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.

279868 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. const StringArray SystemStats::getMACAddressStrings()
  1360. {
  1361. int64 macAddresses [16];
  1362. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1363. StringArray s;
  1364. for (int i = 0; i < numAddresses; ++i)
  1365. {
  1366. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1367. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1368. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1369. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1370. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1371. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1372. }
  1373. return s;
  1374. }
  1375. #ifdef JUCE_DLL
  1376. void* juce_Malloc (const int size)
  1377. {
  1378. return malloc (size);
  1379. }
  1380. void* juce_Calloc (const int size)
  1381. {
  1382. return calloc (1, size);
  1383. }
  1384. void* juce_Realloc (void* const block, const int size)
  1385. {
  1386. return realloc (block, size);
  1387. }
  1388. void juce_Free (void* const block)
  1389. {
  1390. free (block);
  1391. }
  1392. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1393. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1394. {
  1395. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1396. }
  1397. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1398. {
  1399. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1400. }
  1401. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1402. {
  1403. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1404. }
  1405. void juce_DebugFree (void* const block)
  1406. {
  1407. _free_dbg (block, _NORMAL_BLOCK);
  1408. }
  1409. #endif
  1410. #endif
  1411. END_JUCE_NAMESPACE
  1412. /*** End of inlined file: juce_SystemStats.cpp ***/
  1413. /*** Start of inlined file: juce_Time.cpp ***/
  1414. #if JUCE_MSVC
  1415. #pragma warning (push)
  1416. #pragma warning (disable: 4514)
  1417. #endif
  1418. #ifndef JUCE_WINDOWS
  1419. #include <sys/time.h>
  1420. #else
  1421. #include <ctime>
  1422. #endif
  1423. #include <sys/timeb.h>
  1424. #if JUCE_MSVC
  1425. #pragma warning (pop)
  1426. #ifdef _INC_TIME_INL
  1427. #define USE_NEW_SECURE_TIME_FNS
  1428. #endif
  1429. #endif
  1430. BEGIN_JUCE_NAMESPACE
  1431. namespace TimeHelpers
  1432. {
  1433. static struct tm millisToLocal (const int64 millis) throw()
  1434. {
  1435. struct tm result;
  1436. const int64 seconds = millis / 1000;
  1437. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1438. {
  1439. // use extended maths for dates beyond 1970 to 2037..
  1440. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1441. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1442. const int days = (int) (jdm / literal64bit (86400));
  1443. const int a = 32044 + days;
  1444. const int b = (4 * a + 3) / 146097;
  1445. const int c = a - (b * 146097) / 4;
  1446. const int d = (4 * c + 3) / 1461;
  1447. const int e = c - (d * 1461) / 4;
  1448. const int m = (5 * e + 2) / 153;
  1449. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1450. result.tm_mon = m + 2 - 12 * (m / 10);
  1451. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1452. result.tm_wday = (days + 1) % 7;
  1453. result.tm_yday = -1;
  1454. int t = (int) (jdm % literal64bit (86400));
  1455. result.tm_hour = t / 3600;
  1456. t %= 3600;
  1457. result.tm_min = t / 60;
  1458. result.tm_sec = t % 60;
  1459. result.tm_isdst = -1;
  1460. }
  1461. else
  1462. {
  1463. time_t now = static_cast <time_t> (seconds);
  1464. #if JUCE_WINDOWS
  1465. #ifdef USE_NEW_SECURE_TIME_FNS
  1466. if (now >= 0 && now <= 0x793406fff)
  1467. localtime_s (&result, &now);
  1468. else
  1469. zeromem (&result, sizeof (result));
  1470. #else
  1471. result = *localtime (&now);
  1472. #endif
  1473. #else
  1474. // more thread-safe
  1475. localtime_r (&now, &result);
  1476. #endif
  1477. }
  1478. return result;
  1479. }
  1480. static int extendedModulo (const int64 value, const int modulo) throw()
  1481. {
  1482. return (int) (value >= 0 ? (value % modulo)
  1483. : (value - ((value / modulo) + 1) * modulo));
  1484. }
  1485. static uint32 lastMSCounterValue = 0;
  1486. }
  1487. Time::Time() throw()
  1488. : millisSinceEpoch (0)
  1489. {
  1490. }
  1491. Time::Time (const Time& other) throw()
  1492. : millisSinceEpoch (other.millisSinceEpoch)
  1493. {
  1494. }
  1495. Time::Time (const int64 ms) throw()
  1496. : millisSinceEpoch (ms)
  1497. {
  1498. }
  1499. Time::Time (const int year,
  1500. const int month,
  1501. const int day,
  1502. const int hours,
  1503. const int minutes,
  1504. const int seconds,
  1505. const int milliseconds,
  1506. const bool useLocalTime) throw()
  1507. {
  1508. jassert (year > 100); // year must be a 4-digit version
  1509. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1510. {
  1511. // use extended maths for dates beyond 1970 to 2037..
  1512. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1513. : 0;
  1514. const int a = (13 - month) / 12;
  1515. const int y = year + 4800 - a;
  1516. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1517. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1518. - 32045;
  1519. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1520. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1521. + milliseconds;
  1522. }
  1523. else
  1524. {
  1525. struct tm t;
  1526. t.tm_year = year - 1900;
  1527. t.tm_mon = month;
  1528. t.tm_mday = day;
  1529. t.tm_hour = hours;
  1530. t.tm_min = minutes;
  1531. t.tm_sec = seconds;
  1532. t.tm_isdst = -1;
  1533. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1534. if (millisSinceEpoch < 0)
  1535. millisSinceEpoch = 0;
  1536. else
  1537. millisSinceEpoch += milliseconds;
  1538. }
  1539. }
  1540. Time::~Time() throw()
  1541. {
  1542. }
  1543. Time& Time::operator= (const Time& other) throw()
  1544. {
  1545. millisSinceEpoch = other.millisSinceEpoch;
  1546. return *this;
  1547. }
  1548. int64 Time::currentTimeMillis() throw()
  1549. {
  1550. static uint32 lastCounterResult = 0xffffffff;
  1551. static int64 correction = 0;
  1552. const uint32 now = getMillisecondCounter();
  1553. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1554. if (now < lastCounterResult)
  1555. {
  1556. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1557. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1558. {
  1559. // get the time once using normal library calls, and store the difference needed to
  1560. // turn the millisecond counter into a real time.
  1561. #if JUCE_WINDOWS
  1562. struct _timeb t;
  1563. #ifdef USE_NEW_SECURE_TIME_FNS
  1564. _ftime_s (&t);
  1565. #else
  1566. _ftime (&t);
  1567. #endif
  1568. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1569. #else
  1570. struct timeval tv;
  1571. struct timezone tz;
  1572. gettimeofday (&tv, &tz);
  1573. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1574. #endif
  1575. }
  1576. }
  1577. lastCounterResult = now;
  1578. return correction + now;
  1579. }
  1580. uint32 juce_millisecondsSinceStartup() throw();
  1581. uint32 Time::getMillisecondCounter() throw()
  1582. {
  1583. const uint32 now = juce_millisecondsSinceStartup();
  1584. if (now < TimeHelpers::lastMSCounterValue)
  1585. {
  1586. // in multi-threaded apps this might be called concurrently, so
  1587. // make sure that our last counter value only increases and doesn't
  1588. // go backwards..
  1589. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1590. TimeHelpers::lastMSCounterValue = now;
  1591. }
  1592. else
  1593. {
  1594. TimeHelpers::lastMSCounterValue = now;
  1595. }
  1596. return now;
  1597. }
  1598. uint32 Time::getApproximateMillisecondCounter() throw()
  1599. {
  1600. jassert (TimeHelpers::lastMSCounterValue != 0);
  1601. return TimeHelpers::lastMSCounterValue;
  1602. }
  1603. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1604. {
  1605. for (;;)
  1606. {
  1607. const uint32 now = getMillisecondCounter();
  1608. if (now >= targetTime)
  1609. break;
  1610. const int toWait = targetTime - now;
  1611. if (toWait > 2)
  1612. {
  1613. Thread::sleep (jmin (20, toWait >> 1));
  1614. }
  1615. else
  1616. {
  1617. // xxx should consider using mutex_pause on the mac as it apparently
  1618. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1619. for (int i = 10; --i >= 0;)
  1620. Thread::yield();
  1621. }
  1622. }
  1623. }
  1624. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1625. {
  1626. return ticks / (double) getHighResolutionTicksPerSecond();
  1627. }
  1628. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1629. {
  1630. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1631. }
  1632. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1633. {
  1634. return Time (currentTimeMillis());
  1635. }
  1636. const String Time::toString (const bool includeDate,
  1637. const bool includeTime,
  1638. const bool includeSeconds,
  1639. const bool use24HourClock) const throw()
  1640. {
  1641. String result;
  1642. if (includeDate)
  1643. {
  1644. result << getDayOfMonth() << ' '
  1645. << getMonthName (true) << ' '
  1646. << getYear();
  1647. if (includeTime)
  1648. result << ' ';
  1649. }
  1650. if (includeTime)
  1651. {
  1652. const int mins = getMinutes();
  1653. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1654. << (mins < 10 ? ":0" : ":") << mins;
  1655. if (includeSeconds)
  1656. {
  1657. const int secs = getSeconds();
  1658. result << (secs < 10 ? ":0" : ":") << secs;
  1659. }
  1660. if (! use24HourClock)
  1661. result << (isAfternoon() ? "pm" : "am");
  1662. }
  1663. return result.trimEnd();
  1664. }
  1665. const String Time::formatted (const String& format) const
  1666. {
  1667. String buffer;
  1668. int bufferSize = 128;
  1669. buffer.preallocateStorage (bufferSize);
  1670. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1671. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1672. {
  1673. bufferSize += 128;
  1674. buffer.preallocateStorage (bufferSize);
  1675. }
  1676. return buffer;
  1677. }
  1678. int Time::getYear() const throw()
  1679. {
  1680. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1681. }
  1682. int Time::getMonth() const throw()
  1683. {
  1684. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1685. }
  1686. int Time::getDayOfMonth() const throw()
  1687. {
  1688. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1689. }
  1690. int Time::getDayOfWeek() const throw()
  1691. {
  1692. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1693. }
  1694. int Time::getHours() const throw()
  1695. {
  1696. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1697. }
  1698. int Time::getHoursInAmPmFormat() const throw()
  1699. {
  1700. const int hours = getHours();
  1701. if (hours == 0)
  1702. return 12;
  1703. else if (hours <= 12)
  1704. return hours;
  1705. else
  1706. return hours - 12;
  1707. }
  1708. bool Time::isAfternoon() const throw()
  1709. {
  1710. return getHours() >= 12;
  1711. }
  1712. int Time::getMinutes() const throw()
  1713. {
  1714. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1715. }
  1716. int Time::getSeconds() const throw()
  1717. {
  1718. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1719. }
  1720. int Time::getMilliseconds() const throw()
  1721. {
  1722. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1723. }
  1724. bool Time::isDaylightSavingTime() const throw()
  1725. {
  1726. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1727. }
  1728. const String Time::getTimeZone() const throw()
  1729. {
  1730. String zone[2];
  1731. #if JUCE_WINDOWS
  1732. _tzset();
  1733. #ifdef USE_NEW_SECURE_TIME_FNS
  1734. {
  1735. char name [128];
  1736. size_t length;
  1737. for (int i = 0; i < 2; ++i)
  1738. {
  1739. zeromem (name, sizeof (name));
  1740. _get_tzname (&length, name, 127, i);
  1741. zone[i] = name;
  1742. }
  1743. }
  1744. #else
  1745. const char** const zonePtr = (const char**) _tzname;
  1746. zone[0] = zonePtr[0];
  1747. zone[1] = zonePtr[1];
  1748. #endif
  1749. #else
  1750. tzset();
  1751. const char** const zonePtr = (const char**) tzname;
  1752. zone[0] = zonePtr[0];
  1753. zone[1] = zonePtr[1];
  1754. #endif
  1755. if (isDaylightSavingTime())
  1756. {
  1757. zone[0] = zone[1];
  1758. if (zone[0].length() > 3
  1759. && zone[0].containsIgnoreCase ("daylight")
  1760. && zone[0].contains ("GMT"))
  1761. zone[0] = "BST";
  1762. }
  1763. return zone[0].substring (0, 3);
  1764. }
  1765. const String Time::getMonthName (const bool threeLetterVersion) const
  1766. {
  1767. return getMonthName (getMonth(), threeLetterVersion);
  1768. }
  1769. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1770. {
  1771. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1772. }
  1773. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1774. {
  1775. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1776. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1777. monthNumber %= 12;
  1778. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1779. : longMonthNames [monthNumber]);
  1780. }
  1781. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1782. {
  1783. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1784. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1785. day %= 7;
  1786. return TRANS (threeLetterVersion ? shortDayNames [day]
  1787. : longDayNames [day]);
  1788. }
  1789. END_JUCE_NAMESPACE
  1790. /*** End of inlined file: juce_Time.cpp ***/
  1791. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1792. BEGIN_JUCE_NAMESPACE
  1793. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1794. #endif
  1795. #if JUCE_WINDOWS
  1796. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1797. #endif
  1798. #if JUCE_DEBUG
  1799. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1800. #endif
  1801. static bool juceInitialisedNonGUI = false;
  1802. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1803. {
  1804. if (! juceInitialisedNonGUI)
  1805. {
  1806. juceInitialisedNonGUI = true;
  1807. JUCE_AUTORELEASEPOOL
  1808. DBG (SystemStats::getJUCEVersion());
  1809. SystemStats::initialiseStats();
  1810. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1811. }
  1812. // Some basic tests, to keep an eye on things and make sure these types work ok
  1813. // on all platforms. Let me know if any of these assertions fail on your system!
  1814. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1815. static_jassert (sizeof (int8) == 1);
  1816. static_jassert (sizeof (uint8) == 1);
  1817. static_jassert (sizeof (int16) == 2);
  1818. static_jassert (sizeof (uint16) == 2);
  1819. static_jassert (sizeof (int32) == 4);
  1820. static_jassert (sizeof (uint32) == 4);
  1821. static_jassert (sizeof (int64) == 8);
  1822. static_jassert (sizeof (uint64) == 8);
  1823. }
  1824. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1825. {
  1826. if (juceInitialisedNonGUI)
  1827. {
  1828. juceInitialisedNonGUI = false;
  1829. JUCE_AUTORELEASEPOOL
  1830. LocalisedStrings::setCurrentMappings (0);
  1831. Thread::stopAllThreads (3000);
  1832. #if JUCE_WINDOWS
  1833. juce_shutdownWin32Sockets();
  1834. #endif
  1835. #if JUCE_DEBUG
  1836. juce_CheckForDanglingStreams();
  1837. #endif
  1838. }
  1839. }
  1840. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1841. void juce_setCurrentThreadName (const String& name);
  1842. static bool juceInitialisedGUI = false;
  1843. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1844. {
  1845. if (! juceInitialisedGUI)
  1846. {
  1847. juceInitialisedGUI = true;
  1848. JUCE_AUTORELEASEPOOL
  1849. initialiseJuce_NonGUI();
  1850. MessageManager::getInstance();
  1851. LookAndFeel::setDefaultLookAndFeel (0);
  1852. juce_setCurrentThreadName ("Juce Message Thread");
  1853. #if JUCE_DEBUG
  1854. // This section is just for catching people who mess up their project settings and
  1855. // turn RTTI off..
  1856. try
  1857. {
  1858. TextButton tb (String::empty);
  1859. Component* c = &tb;
  1860. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1861. c = dynamic_cast <Button*> (c);
  1862. }
  1863. catch (...)
  1864. {
  1865. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1866. jassertfalse;
  1867. }
  1868. #endif
  1869. }
  1870. }
  1871. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1872. {
  1873. if (juceInitialisedGUI)
  1874. {
  1875. juceInitialisedGUI = false;
  1876. JUCE_AUTORELEASEPOOL
  1877. DeletedAtShutdown::deleteAll();
  1878. LookAndFeel::clearDefaultLookAndFeel();
  1879. delete MessageManager::getInstance();
  1880. shutdownJuce_NonGUI();
  1881. }
  1882. }
  1883. #endif
  1884. #if JUCE_UNIT_TESTS
  1885. class AtomicTests : public UnitTest
  1886. {
  1887. public:
  1888. AtomicTests() : UnitTest ("Atomics") {}
  1889. void runTest()
  1890. {
  1891. beginTest ("Misc");
  1892. char a1[7];
  1893. expect (numElementsInArray(a1) == 7);
  1894. int a2[3];
  1895. expect (numElementsInArray(a2) == 3);
  1896. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1897. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1898. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1899. beginTest ("Atomic types");
  1900. AtomicTester <int>::testInteger (*this);
  1901. AtomicTester <unsigned int>::testInteger (*this);
  1902. AtomicTester <int32>::testInteger (*this);
  1903. AtomicTester <uint32>::testInteger (*this);
  1904. AtomicTester <long>::testInteger (*this);
  1905. AtomicTester <void*>::testInteger (*this);
  1906. AtomicTester <int*>::testInteger (*this);
  1907. AtomicTester <float>::testFloat (*this);
  1908. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1909. AtomicTester <int64>::testInteger (*this);
  1910. AtomicTester <uint64>::testInteger (*this);
  1911. AtomicTester <double>::testFloat (*this);
  1912. #endif
  1913. }
  1914. template <typename Type>
  1915. class AtomicTester
  1916. {
  1917. public:
  1918. AtomicTester() {}
  1919. static void testInteger (UnitTest& test)
  1920. {
  1921. Atomic<Type> a, b;
  1922. a.set ((Type) 10);
  1923. a += (Type) 15;
  1924. a.memoryBarrier();
  1925. a -= (Type) 5;
  1926. ++a; ++a; --a;
  1927. a.memoryBarrier();
  1928. testFloat (test);
  1929. }
  1930. static void testFloat (UnitTest& test)
  1931. {
  1932. Atomic<Type> a, b;
  1933. a = (Type) 21;
  1934. a.memoryBarrier();
  1935. /* These are some simple test cases to check the atomics - let me know
  1936. if any of these assertions fail on your system!
  1937. */
  1938. test.expect (a.get() == (Type) 21);
  1939. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1940. test.expect (a.get() == (Type) 21);
  1941. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1942. test.expect (a.get() == (Type) 101);
  1943. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1944. test.expect (a.get() == (Type) 101);
  1945. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1946. test.expect (a.get() == (Type) 200);
  1947. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1948. test.expect (a.get() == (Type) 300);
  1949. b = a;
  1950. test.expect (b.get() == a.get());
  1951. }
  1952. };
  1953. };
  1954. static AtomicTests atomicUnitTests;
  1955. #endif
  1956. END_JUCE_NAMESPACE
  1957. /*** End of inlined file: juce_Initialisation.cpp ***/
  1958. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1959. BEGIN_JUCE_NAMESPACE
  1960. AbstractFifo::AbstractFifo (const int capacity) throw()
  1961. : bufferSize (capacity)
  1962. {
  1963. jassert (bufferSize > 0);
  1964. }
  1965. AbstractFifo::~AbstractFifo() {}
  1966. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1967. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1968. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1969. void AbstractFifo::reset() throw()
  1970. {
  1971. validEnd = 0;
  1972. validStart = 0;
  1973. }
  1974. void AbstractFifo::setTotalSize (int newSize) throw()
  1975. {
  1976. jassert (newSize > 0);
  1977. reset();
  1978. bufferSize = newSize;
  1979. }
  1980. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1981. {
  1982. const int vs = validStart.get();
  1983. const int ve = validEnd.get();
  1984. const int freeSpace = bufferSize - (ve - vs);
  1985. numToWrite = jmin (numToWrite, freeSpace);
  1986. if (numToWrite <= 0)
  1987. {
  1988. startIndex1 = 0;
  1989. startIndex2 = 0;
  1990. blockSize1 = 0;
  1991. blockSize2 = 0;
  1992. }
  1993. else
  1994. {
  1995. startIndex1 = (int) (ve % bufferSize);
  1996. startIndex2 = 0;
  1997. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1998. numToWrite -= blockSize1;
  1999. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  2000. }
  2001. }
  2002. void AbstractFifo::finishedWrite (int numWritten) throw()
  2003. {
  2004. jassert (numWritten >= 0 && numWritten < bufferSize);
  2005. validEnd += numWritten;
  2006. }
  2007. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  2008. {
  2009. const int vs = validStart.get();
  2010. const int ve = validEnd.get();
  2011. const int numReady = ve - vs;
  2012. numWanted = jmin (numWanted, numReady);
  2013. if (numWanted <= 0)
  2014. {
  2015. startIndex1 = 0;
  2016. startIndex2 = 0;
  2017. blockSize1 = 0;
  2018. blockSize2 = 0;
  2019. }
  2020. else
  2021. {
  2022. startIndex1 = (int) (vs % bufferSize);
  2023. startIndex2 = 0;
  2024. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  2025. numWanted -= blockSize1;
  2026. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  2027. }
  2028. }
  2029. void AbstractFifo::finishedRead (int numRead) throw()
  2030. {
  2031. jassert (numRead >= 0 && numRead < bufferSize);
  2032. validStart += numRead;
  2033. }
  2034. END_JUCE_NAMESPACE
  2035. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2036. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2037. BEGIN_JUCE_NAMESPACE
  2038. BigInteger::BigInteger()
  2039. : numValues (4),
  2040. highestBit (-1),
  2041. negative (false)
  2042. {
  2043. values.calloc (numValues + 1);
  2044. }
  2045. BigInteger::BigInteger (const int32 value)
  2046. : numValues (4),
  2047. highestBit (31),
  2048. negative (value < 0)
  2049. {
  2050. values.calloc (numValues + 1);
  2051. values[0] = abs (value);
  2052. highestBit = getHighestBit();
  2053. }
  2054. BigInteger::BigInteger (const uint32 value)
  2055. : numValues (4),
  2056. highestBit (31),
  2057. negative (false)
  2058. {
  2059. values.calloc (numValues + 1);
  2060. values[0] = value;
  2061. highestBit = getHighestBit();
  2062. }
  2063. BigInteger::BigInteger (int64 value)
  2064. : numValues (4),
  2065. highestBit (63),
  2066. negative (value < 0)
  2067. {
  2068. values.calloc (numValues + 1);
  2069. if (value < 0)
  2070. value = -value;
  2071. values[0] = (uint32) value;
  2072. values[1] = (uint32) (value >> 32);
  2073. highestBit = getHighestBit();
  2074. }
  2075. BigInteger::BigInteger (const BigInteger& other)
  2076. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2077. highestBit (other.getHighestBit()),
  2078. negative (other.negative)
  2079. {
  2080. values.malloc (numValues + 1);
  2081. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2082. }
  2083. BigInteger::~BigInteger()
  2084. {
  2085. }
  2086. void BigInteger::swapWith (BigInteger& other) throw()
  2087. {
  2088. values.swapWith (other.values);
  2089. swapVariables (numValues, other.numValues);
  2090. swapVariables (highestBit, other.highestBit);
  2091. swapVariables (negative, other.negative);
  2092. }
  2093. BigInteger& BigInteger::operator= (const BigInteger& other)
  2094. {
  2095. if (this != &other)
  2096. {
  2097. highestBit = other.getHighestBit();
  2098. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2099. negative = other.negative;
  2100. values.malloc (numValues + 1);
  2101. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2102. }
  2103. return *this;
  2104. }
  2105. void BigInteger::ensureSize (const int numVals)
  2106. {
  2107. if (numVals + 2 >= numValues)
  2108. {
  2109. int oldSize = numValues;
  2110. numValues = ((numVals + 2) * 3) / 2;
  2111. values.realloc (numValues + 1);
  2112. while (oldSize < numValues)
  2113. values [oldSize++] = 0;
  2114. }
  2115. }
  2116. bool BigInteger::operator[] (const int bit) const throw()
  2117. {
  2118. return bit <= highestBit && bit >= 0
  2119. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2120. }
  2121. int BigInteger::toInteger() const throw()
  2122. {
  2123. const int n = (int) (values[0] & 0x7fffffff);
  2124. return negative ? -n : n;
  2125. }
  2126. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2127. {
  2128. BigInteger r;
  2129. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2130. r.ensureSize (bitToIndex (numBits));
  2131. r.highestBit = numBits;
  2132. int i = 0;
  2133. while (numBits > 0)
  2134. {
  2135. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2136. numBits -= 32;
  2137. startBit += 32;
  2138. }
  2139. r.highestBit = r.getHighestBit();
  2140. return r;
  2141. }
  2142. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2143. {
  2144. if (numBits > 32)
  2145. {
  2146. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2147. numBits = 32;
  2148. }
  2149. numBits = jmin (numBits, highestBit + 1 - startBit);
  2150. if (numBits <= 0)
  2151. return 0;
  2152. const int pos = bitToIndex (startBit);
  2153. const int offset = startBit & 31;
  2154. const int endSpace = 32 - numBits;
  2155. uint32 n = ((uint32) values [pos]) >> offset;
  2156. if (offset > endSpace)
  2157. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2158. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2159. }
  2160. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2161. {
  2162. if (numBits > 32)
  2163. {
  2164. jassertfalse;
  2165. numBits = 32;
  2166. }
  2167. for (int i = 0; i < numBits; ++i)
  2168. {
  2169. setBit (startBit + i, (valueToSet & 1) != 0);
  2170. valueToSet >>= 1;
  2171. }
  2172. }
  2173. void BigInteger::clear()
  2174. {
  2175. if (numValues > 16)
  2176. {
  2177. numValues = 4;
  2178. values.calloc (numValues + 1);
  2179. }
  2180. else
  2181. {
  2182. zeromem (values, sizeof (uint32) * (numValues + 1));
  2183. }
  2184. highestBit = -1;
  2185. negative = false;
  2186. }
  2187. void BigInteger::setBit (const int bit)
  2188. {
  2189. if (bit >= 0)
  2190. {
  2191. if (bit > highestBit)
  2192. {
  2193. ensureSize (bitToIndex (bit));
  2194. highestBit = bit;
  2195. }
  2196. values [bitToIndex (bit)] |= bitToMask (bit);
  2197. }
  2198. }
  2199. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2200. {
  2201. if (shouldBeSet)
  2202. setBit (bit);
  2203. else
  2204. clearBit (bit);
  2205. }
  2206. void BigInteger::clearBit (const int bit) throw()
  2207. {
  2208. if (bit >= 0 && bit <= highestBit)
  2209. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2210. }
  2211. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2212. {
  2213. while (--numBits >= 0)
  2214. setBit (startBit++, shouldBeSet);
  2215. }
  2216. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2217. {
  2218. if (bit >= 0)
  2219. shiftBits (1, bit);
  2220. setBit (bit, shouldBeSet);
  2221. }
  2222. bool BigInteger::isZero() const throw()
  2223. {
  2224. return getHighestBit() < 0;
  2225. }
  2226. bool BigInteger::isOne() const throw()
  2227. {
  2228. return getHighestBit() == 0 && ! negative;
  2229. }
  2230. bool BigInteger::isNegative() const throw()
  2231. {
  2232. return negative && ! isZero();
  2233. }
  2234. void BigInteger::setNegative (const bool neg) throw()
  2235. {
  2236. negative = neg;
  2237. }
  2238. void BigInteger::negate() throw()
  2239. {
  2240. negative = (! negative) && ! isZero();
  2241. }
  2242. int BigInteger::countNumberOfSetBits() const throw()
  2243. {
  2244. int total = 0;
  2245. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2246. {
  2247. uint32 n = values[i];
  2248. if (n == 0xffffffff)
  2249. {
  2250. total += 32;
  2251. }
  2252. else
  2253. {
  2254. while (n != 0)
  2255. {
  2256. total += (n & 1);
  2257. n >>= 1;
  2258. }
  2259. }
  2260. }
  2261. return total;
  2262. }
  2263. int BigInteger::getHighestBit() const throw()
  2264. {
  2265. for (int i = highestBit + 1; --i >= 0;)
  2266. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2267. return i;
  2268. return -1;
  2269. }
  2270. int BigInteger::findNextSetBit (int i) const throw()
  2271. {
  2272. for (; i <= highestBit; ++i)
  2273. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2274. return i;
  2275. return -1;
  2276. }
  2277. int BigInteger::findNextClearBit (int i) const throw()
  2278. {
  2279. for (; i <= highestBit; ++i)
  2280. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2281. break;
  2282. return i;
  2283. }
  2284. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2285. {
  2286. if (other.isNegative())
  2287. return operator-= (-other);
  2288. if (isNegative())
  2289. {
  2290. if (compareAbsolute (other) < 0)
  2291. {
  2292. BigInteger temp (*this);
  2293. temp.negate();
  2294. *this = other;
  2295. operator-= (temp);
  2296. }
  2297. else
  2298. {
  2299. negate();
  2300. operator-= (other);
  2301. negate();
  2302. }
  2303. }
  2304. else
  2305. {
  2306. if (other.highestBit > highestBit)
  2307. highestBit = other.highestBit;
  2308. ++highestBit;
  2309. const int numInts = bitToIndex (highestBit) + 1;
  2310. ensureSize (numInts);
  2311. int64 remainder = 0;
  2312. for (int i = 0; i <= numInts; ++i)
  2313. {
  2314. if (i < numValues)
  2315. remainder += values[i];
  2316. if (i < other.numValues)
  2317. remainder += other.values[i];
  2318. values[i] = (uint32) remainder;
  2319. remainder >>= 32;
  2320. }
  2321. jassert (remainder == 0);
  2322. highestBit = getHighestBit();
  2323. }
  2324. return *this;
  2325. }
  2326. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2327. {
  2328. if (other.isNegative())
  2329. return operator+= (-other);
  2330. if (! isNegative())
  2331. {
  2332. if (compareAbsolute (other) < 0)
  2333. {
  2334. BigInteger temp (other);
  2335. swapWith (temp);
  2336. operator-= (temp);
  2337. negate();
  2338. return *this;
  2339. }
  2340. }
  2341. else
  2342. {
  2343. negate();
  2344. operator+= (other);
  2345. negate();
  2346. return *this;
  2347. }
  2348. const int numInts = bitToIndex (highestBit) + 1;
  2349. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2350. int64 amountToSubtract = 0;
  2351. for (int i = 0; i <= numInts; ++i)
  2352. {
  2353. if (i <= maxOtherInts)
  2354. amountToSubtract += (int64) other.values[i];
  2355. if (values[i] >= amountToSubtract)
  2356. {
  2357. values[i] = (uint32) (values[i] - amountToSubtract);
  2358. amountToSubtract = 0;
  2359. }
  2360. else
  2361. {
  2362. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2363. values[i] = (uint32) n;
  2364. amountToSubtract = 1;
  2365. }
  2366. }
  2367. return *this;
  2368. }
  2369. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2370. {
  2371. BigInteger total;
  2372. highestBit = getHighestBit();
  2373. const bool wasNegative = isNegative();
  2374. setNegative (false);
  2375. for (int i = 0; i <= highestBit; ++i)
  2376. {
  2377. if (operator[](i))
  2378. {
  2379. BigInteger n (other);
  2380. n.setNegative (false);
  2381. n <<= i;
  2382. total += n;
  2383. }
  2384. }
  2385. total.setNegative (wasNegative ^ other.isNegative());
  2386. swapWith (total);
  2387. return *this;
  2388. }
  2389. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2390. {
  2391. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2392. const int divHB = divisor.getHighestBit();
  2393. const int ourHB = getHighestBit();
  2394. if (divHB < 0 || ourHB < 0)
  2395. {
  2396. // division by zero
  2397. remainder.clear();
  2398. clear();
  2399. }
  2400. else
  2401. {
  2402. const bool wasNegative = isNegative();
  2403. swapWith (remainder);
  2404. remainder.setNegative (false);
  2405. clear();
  2406. BigInteger temp (divisor);
  2407. temp.setNegative (false);
  2408. int leftShift = ourHB - divHB;
  2409. temp <<= leftShift;
  2410. while (leftShift >= 0)
  2411. {
  2412. if (remainder.compareAbsolute (temp) >= 0)
  2413. {
  2414. remainder -= temp;
  2415. setBit (leftShift);
  2416. }
  2417. if (--leftShift >= 0)
  2418. temp >>= 1;
  2419. }
  2420. negative = wasNegative ^ divisor.isNegative();
  2421. remainder.setNegative (wasNegative);
  2422. }
  2423. }
  2424. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2425. {
  2426. BigInteger remainder;
  2427. divideBy (other, remainder);
  2428. return *this;
  2429. }
  2430. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2431. {
  2432. // this operation doesn't take into account negative values..
  2433. jassert (isNegative() == other.isNegative());
  2434. if (other.highestBit >= 0)
  2435. {
  2436. ensureSize (bitToIndex (other.highestBit));
  2437. int n = bitToIndex (other.highestBit) + 1;
  2438. while (--n >= 0)
  2439. values[n] |= other.values[n];
  2440. if (other.highestBit > highestBit)
  2441. highestBit = other.highestBit;
  2442. highestBit = getHighestBit();
  2443. }
  2444. return *this;
  2445. }
  2446. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2447. {
  2448. // this operation doesn't take into account negative values..
  2449. jassert (isNegative() == other.isNegative());
  2450. int n = numValues;
  2451. while (n > other.numValues)
  2452. values[--n] = 0;
  2453. while (--n >= 0)
  2454. values[n] &= other.values[n];
  2455. if (other.highestBit < highestBit)
  2456. highestBit = other.highestBit;
  2457. highestBit = getHighestBit();
  2458. return *this;
  2459. }
  2460. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2461. {
  2462. // this operation will only work with the absolute values
  2463. jassert (isNegative() == other.isNegative());
  2464. if (other.highestBit >= 0)
  2465. {
  2466. ensureSize (bitToIndex (other.highestBit));
  2467. int n = bitToIndex (other.highestBit) + 1;
  2468. while (--n >= 0)
  2469. values[n] ^= other.values[n];
  2470. if (other.highestBit > highestBit)
  2471. highestBit = other.highestBit;
  2472. highestBit = getHighestBit();
  2473. }
  2474. return *this;
  2475. }
  2476. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2477. {
  2478. BigInteger remainder;
  2479. divideBy (divisor, remainder);
  2480. swapWith (remainder);
  2481. return *this;
  2482. }
  2483. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2484. {
  2485. shiftBits (numBitsToShift, 0);
  2486. return *this;
  2487. }
  2488. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2489. {
  2490. return operator<<= (-numBitsToShift);
  2491. }
  2492. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2493. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2494. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2495. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2496. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2497. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2498. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2499. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2500. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2501. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2502. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2503. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2504. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2505. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2506. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2507. int BigInteger::compare (const BigInteger& other) const throw()
  2508. {
  2509. if (isNegative() == other.isNegative())
  2510. {
  2511. const int absComp = compareAbsolute (other);
  2512. return isNegative() ? -absComp : absComp;
  2513. }
  2514. else
  2515. {
  2516. return isNegative() ? -1 : 1;
  2517. }
  2518. }
  2519. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2520. {
  2521. const int h1 = getHighestBit();
  2522. const int h2 = other.getHighestBit();
  2523. if (h1 > h2)
  2524. return 1;
  2525. else if (h1 < h2)
  2526. return -1;
  2527. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2528. if (values[i] != other.values[i])
  2529. return (values[i] > other.values[i]) ? 1 : -1;
  2530. return 0;
  2531. }
  2532. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2533. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2534. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2535. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2536. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2537. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2538. void BigInteger::shiftBits (int bits, const int startBit)
  2539. {
  2540. if (highestBit < 0)
  2541. return;
  2542. if (startBit > 0)
  2543. {
  2544. if (bits < 0)
  2545. {
  2546. // right shift
  2547. for (int i = startBit; i <= highestBit; ++i)
  2548. setBit (i, operator[] (i - bits));
  2549. highestBit = getHighestBit();
  2550. }
  2551. else if (bits > 0)
  2552. {
  2553. // left shift
  2554. for (int i = highestBit + 1; --i >= startBit;)
  2555. setBit (i + bits, operator[] (i));
  2556. while (--bits >= 0)
  2557. clearBit (bits + startBit);
  2558. }
  2559. }
  2560. else
  2561. {
  2562. if (bits < 0)
  2563. {
  2564. // right shift
  2565. bits = -bits;
  2566. if (bits > highestBit)
  2567. {
  2568. clear();
  2569. }
  2570. else
  2571. {
  2572. const int wordsToMove = bitToIndex (bits);
  2573. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2574. highestBit -= bits;
  2575. if (wordsToMove > 0)
  2576. {
  2577. int i;
  2578. for (i = 0; i < top; ++i)
  2579. values [i] = values [i + wordsToMove];
  2580. for (i = 0; i < wordsToMove; ++i)
  2581. values [top + i] = 0;
  2582. bits &= 31;
  2583. }
  2584. if (bits != 0)
  2585. {
  2586. const int invBits = 32 - bits;
  2587. --top;
  2588. for (int i = 0; i < top; ++i)
  2589. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2590. values[top] = (values[top] >> bits);
  2591. }
  2592. highestBit = getHighestBit();
  2593. }
  2594. }
  2595. else if (bits > 0)
  2596. {
  2597. // left shift
  2598. ensureSize (bitToIndex (highestBit + bits) + 1);
  2599. const int wordsToMove = bitToIndex (bits);
  2600. int top = 1 + bitToIndex (highestBit);
  2601. highestBit += bits;
  2602. if (wordsToMove > 0)
  2603. {
  2604. int i;
  2605. for (i = top; --i >= 0;)
  2606. values [i + wordsToMove] = values [i];
  2607. for (i = 0; i < wordsToMove; ++i)
  2608. values [i] = 0;
  2609. bits &= 31;
  2610. }
  2611. if (bits != 0)
  2612. {
  2613. const int invBits = 32 - bits;
  2614. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2615. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2616. values [wordsToMove] = values [wordsToMove] << bits;
  2617. }
  2618. highestBit = getHighestBit();
  2619. }
  2620. }
  2621. }
  2622. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2623. {
  2624. while (! m->isZero())
  2625. {
  2626. if (n->compareAbsolute (*m) > 0)
  2627. swapVariables (m, n);
  2628. *m -= *n;
  2629. }
  2630. return *n;
  2631. }
  2632. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2633. {
  2634. BigInteger m (*this);
  2635. while (! n.isZero())
  2636. {
  2637. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2638. return simpleGCD (&m, &n);
  2639. BigInteger temp1 (m), temp2;
  2640. temp1.divideBy (n, temp2);
  2641. m = n;
  2642. n = temp2;
  2643. }
  2644. return m;
  2645. }
  2646. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2647. {
  2648. BigInteger exp (exponent);
  2649. exp %= modulus;
  2650. BigInteger value (1);
  2651. swapWith (value);
  2652. value %= modulus;
  2653. while (! exp.isZero())
  2654. {
  2655. if (exp [0])
  2656. {
  2657. operator*= (value);
  2658. operator%= (modulus);
  2659. }
  2660. value *= value;
  2661. value %= modulus;
  2662. exp >>= 1;
  2663. }
  2664. }
  2665. void BigInteger::inverseModulo (const BigInteger& modulus)
  2666. {
  2667. if (modulus.isOne() || modulus.isNegative())
  2668. {
  2669. clear();
  2670. return;
  2671. }
  2672. if (isNegative() || compareAbsolute (modulus) >= 0)
  2673. operator%= (modulus);
  2674. if (isOne())
  2675. return;
  2676. if (! (*this)[0])
  2677. {
  2678. // not invertible
  2679. clear();
  2680. return;
  2681. }
  2682. BigInteger a1 (modulus);
  2683. BigInteger a2 (*this);
  2684. BigInteger b1 (modulus);
  2685. BigInteger b2 (1);
  2686. while (! a2.isOne())
  2687. {
  2688. BigInteger temp1, temp2, multiplier (a1);
  2689. multiplier.divideBy (a2, temp1);
  2690. temp1 = a2;
  2691. temp1 *= multiplier;
  2692. temp2 = a1;
  2693. temp2 -= temp1;
  2694. a1 = a2;
  2695. a2 = temp2;
  2696. temp1 = b2;
  2697. temp1 *= multiplier;
  2698. temp2 = b1;
  2699. temp2 -= temp1;
  2700. b1 = b2;
  2701. b2 = temp2;
  2702. }
  2703. while (b2.isNegative())
  2704. b2 += modulus;
  2705. b2 %= modulus;
  2706. swapWith (b2);
  2707. }
  2708. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2709. {
  2710. return stream << value.toString (10);
  2711. }
  2712. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2713. {
  2714. String s;
  2715. BigInteger v (*this);
  2716. if (base == 2 || base == 8 || base == 16)
  2717. {
  2718. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2719. static const char* const hexDigits = "0123456789abcdef";
  2720. for (;;)
  2721. {
  2722. const int remainder = v.getBitRangeAsInt (0, bits);
  2723. v >>= bits;
  2724. if (remainder == 0 && v.isZero())
  2725. break;
  2726. s = String::charToString (hexDigits [remainder]) + s;
  2727. }
  2728. }
  2729. else if (base == 10)
  2730. {
  2731. const BigInteger ten (10);
  2732. BigInteger remainder;
  2733. for (;;)
  2734. {
  2735. v.divideBy (ten, remainder);
  2736. if (remainder.isZero() && v.isZero())
  2737. break;
  2738. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2739. }
  2740. }
  2741. else
  2742. {
  2743. jassertfalse; // can't do the specified base!
  2744. return String::empty;
  2745. }
  2746. s = s.paddedLeft ('0', minimumNumCharacters);
  2747. return isNegative() ? "-" + s : s;
  2748. }
  2749. void BigInteger::parseString (const String& text, const int base)
  2750. {
  2751. clear();
  2752. const juce_wchar* t = text;
  2753. if (base == 2 || base == 8 || base == 16)
  2754. {
  2755. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2756. for (;;)
  2757. {
  2758. const juce_wchar c = *t++;
  2759. const int digit = CharacterFunctions::getHexDigitValue (c);
  2760. if (((uint32) digit) < (uint32) base)
  2761. {
  2762. operator<<= (bits);
  2763. operator+= (digit);
  2764. }
  2765. else if (c == 0)
  2766. {
  2767. break;
  2768. }
  2769. }
  2770. }
  2771. else if (base == 10)
  2772. {
  2773. const BigInteger ten ((uint32) 10);
  2774. for (;;)
  2775. {
  2776. const juce_wchar c = *t++;
  2777. if (c >= '0' && c <= '9')
  2778. {
  2779. operator*= (ten);
  2780. operator+= ((int) (c - '0'));
  2781. }
  2782. else if (c == 0)
  2783. {
  2784. break;
  2785. }
  2786. }
  2787. }
  2788. setNegative (text.trimStart().startsWithChar ('-'));
  2789. }
  2790. const MemoryBlock BigInteger::toMemoryBlock() const
  2791. {
  2792. const int numBytes = (getHighestBit() + 8) >> 3;
  2793. MemoryBlock mb ((size_t) numBytes);
  2794. for (int i = 0; i < numBytes; ++i)
  2795. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2796. return mb;
  2797. }
  2798. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2799. {
  2800. clear();
  2801. for (int i = (int) data.getSize(); --i >= 0;)
  2802. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2803. }
  2804. END_JUCE_NAMESPACE
  2805. /*** End of inlined file: juce_BigInteger.cpp ***/
  2806. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2807. BEGIN_JUCE_NAMESPACE
  2808. MemoryBlock::MemoryBlock() throw()
  2809. : size (0)
  2810. {
  2811. }
  2812. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2813. {
  2814. if (initialSize > 0)
  2815. {
  2816. size = initialSize;
  2817. data.allocate (initialSize, initialiseToZero);
  2818. }
  2819. else
  2820. {
  2821. size = 0;
  2822. }
  2823. }
  2824. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2825. : size (other.size)
  2826. {
  2827. if (size > 0)
  2828. {
  2829. jassert (other.data != 0);
  2830. data.malloc (size);
  2831. memcpy (data, other.data, size);
  2832. }
  2833. }
  2834. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2835. : size (jmax ((size_t) 0, sizeInBytes))
  2836. {
  2837. jassert (sizeInBytes >= 0);
  2838. if (size > 0)
  2839. {
  2840. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2841. data.malloc (size);
  2842. if (dataToInitialiseFrom != 0)
  2843. memcpy (data, dataToInitialiseFrom, size);
  2844. }
  2845. }
  2846. MemoryBlock::~MemoryBlock() throw()
  2847. {
  2848. jassert (size >= 0); // should never happen
  2849. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2850. }
  2851. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2852. {
  2853. if (this != &other)
  2854. {
  2855. setSize (other.size, false);
  2856. memcpy (data, other.data, size);
  2857. }
  2858. return *this;
  2859. }
  2860. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2861. {
  2862. return matches (other.data, other.size);
  2863. }
  2864. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2865. {
  2866. return ! operator== (other);
  2867. }
  2868. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2869. {
  2870. return size == dataSize
  2871. && memcmp (data, dataToCompare, size) == 0;
  2872. }
  2873. // this will resize the block to this size
  2874. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2875. {
  2876. if (size != newSize)
  2877. {
  2878. if (newSize <= 0)
  2879. {
  2880. data.free();
  2881. size = 0;
  2882. }
  2883. else
  2884. {
  2885. if (data != 0)
  2886. {
  2887. data.realloc (newSize);
  2888. if (initialiseToZero && (newSize > size))
  2889. zeromem (data + size, newSize - size);
  2890. }
  2891. else
  2892. {
  2893. data.allocate (newSize, initialiseToZero);
  2894. }
  2895. size = newSize;
  2896. }
  2897. }
  2898. }
  2899. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2900. {
  2901. if (size < minimumSize)
  2902. setSize (minimumSize, initialiseToZero);
  2903. }
  2904. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2905. {
  2906. swapVariables (size, other.size);
  2907. data.swapWith (other.data);
  2908. }
  2909. void MemoryBlock::fillWith (const uint8 value) throw()
  2910. {
  2911. memset (data, (int) value, size);
  2912. }
  2913. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2914. {
  2915. if (numBytes > 0)
  2916. {
  2917. const size_t oldSize = size;
  2918. setSize (size + numBytes);
  2919. memcpy (data + oldSize, srcData, numBytes);
  2920. }
  2921. }
  2922. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2923. {
  2924. const char* d = static_cast<const char*> (src);
  2925. if (offset < 0)
  2926. {
  2927. d -= offset;
  2928. num -= offset;
  2929. offset = 0;
  2930. }
  2931. if (offset + num > size)
  2932. num = size - offset;
  2933. if (num > 0)
  2934. memcpy (data + offset, d, num);
  2935. }
  2936. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2937. {
  2938. char* d = static_cast<char*> (dst);
  2939. if (offset < 0)
  2940. {
  2941. zeromem (d, -offset);
  2942. d -= offset;
  2943. num += offset;
  2944. offset = 0;
  2945. }
  2946. if (offset + num > size)
  2947. {
  2948. const size_t newNum = size - offset;
  2949. zeromem (d + newNum, num - newNum);
  2950. num = newNum;
  2951. }
  2952. if (num > 0)
  2953. memcpy (d, data + offset, num);
  2954. }
  2955. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2956. {
  2957. if (startByte < 0)
  2958. {
  2959. numBytesToRemove += startByte;
  2960. startByte = 0;
  2961. }
  2962. if (startByte + numBytesToRemove >= size)
  2963. {
  2964. setSize (startByte);
  2965. }
  2966. else if (numBytesToRemove > 0)
  2967. {
  2968. memmove (data + startByte,
  2969. data + startByte + numBytesToRemove,
  2970. size - (startByte + numBytesToRemove));
  2971. setSize (size - numBytesToRemove);
  2972. }
  2973. }
  2974. const String MemoryBlock::toString() const
  2975. {
  2976. return String (static_cast <const char*> (getData()), size);
  2977. }
  2978. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2979. {
  2980. int res = 0;
  2981. size_t byte = bitRangeStart >> 3;
  2982. int offsetInByte = (int) bitRangeStart & 7;
  2983. size_t bitsSoFar = 0;
  2984. while (numBits > 0 && (size_t) byte < size)
  2985. {
  2986. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2987. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2988. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2989. bitsSoFar += bitsThisTime;
  2990. numBits -= bitsThisTime;
  2991. ++byte;
  2992. offsetInByte = 0;
  2993. }
  2994. return res;
  2995. }
  2996. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2997. {
  2998. size_t byte = bitRangeStart >> 3;
  2999. int offsetInByte = (int) bitRangeStart & 7;
  3000. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3001. while (numBits > 0 && (size_t) byte < size)
  3002. {
  3003. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3004. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3005. const unsigned int tempBits = bitsToSet << offsetInByte;
  3006. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3007. ++byte;
  3008. numBits -= bitsThisTime;
  3009. bitsToSet >>= bitsThisTime;
  3010. mask >>= bitsThisTime;
  3011. offsetInByte = 0;
  3012. }
  3013. }
  3014. void MemoryBlock::loadFromHexString (const String& hex)
  3015. {
  3016. ensureSize (hex.length() >> 1);
  3017. char* dest = data;
  3018. int i = 0;
  3019. for (;;)
  3020. {
  3021. int byte = 0;
  3022. for (int loop = 2; --loop >= 0;)
  3023. {
  3024. byte <<= 4;
  3025. for (;;)
  3026. {
  3027. const juce_wchar c = hex [i++];
  3028. if (c >= '0' && c <= '9')
  3029. {
  3030. byte |= c - '0';
  3031. break;
  3032. }
  3033. else if (c >= 'a' && c <= 'z')
  3034. {
  3035. byte |= c - ('a' - 10);
  3036. break;
  3037. }
  3038. else if (c >= 'A' && c <= 'Z')
  3039. {
  3040. byte |= c - ('A' - 10);
  3041. break;
  3042. }
  3043. else if (c == 0)
  3044. {
  3045. setSize (static_cast <size_t> (dest - data));
  3046. return;
  3047. }
  3048. }
  3049. }
  3050. *dest++ = (char) byte;
  3051. }
  3052. }
  3053. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3054. const String MemoryBlock::toBase64Encoding() const
  3055. {
  3056. const size_t numChars = ((size << 3) + 5) / 6;
  3057. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3058. const int initialLen = destString.length();
  3059. destString.preallocateStorage (initialLen + 2 + numChars);
  3060. juce_wchar* d = destString;
  3061. d += initialLen;
  3062. *d++ = '.';
  3063. for (size_t i = 0; i < numChars; ++i)
  3064. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3065. *d++ = 0;
  3066. return destString;
  3067. }
  3068. bool MemoryBlock::fromBase64Encoding (const String& s)
  3069. {
  3070. const int startPos = s.indexOfChar ('.') + 1;
  3071. if (startPos <= 0)
  3072. return false;
  3073. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3074. setSize (numBytesNeeded, true);
  3075. const int numChars = s.length() - startPos;
  3076. const juce_wchar* srcChars = s;
  3077. srcChars += startPos;
  3078. int pos = 0;
  3079. for (int i = 0; i < numChars; ++i)
  3080. {
  3081. const char c = (char) srcChars[i];
  3082. for (int j = 0; j < 64; ++j)
  3083. {
  3084. if (encodingTable[j] == c)
  3085. {
  3086. setBitRange (pos, 6, j);
  3087. pos += 6;
  3088. break;
  3089. }
  3090. }
  3091. }
  3092. return true;
  3093. }
  3094. END_JUCE_NAMESPACE
  3095. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3096. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3097. BEGIN_JUCE_NAMESPACE
  3098. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3099. : properties (ignoreCaseOfKeyNames),
  3100. fallbackProperties (0),
  3101. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3102. {
  3103. }
  3104. PropertySet::PropertySet (const PropertySet& other)
  3105. : properties (other.properties),
  3106. fallbackProperties (other.fallbackProperties),
  3107. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3108. {
  3109. }
  3110. PropertySet& PropertySet::operator= (const PropertySet& other)
  3111. {
  3112. properties = other.properties;
  3113. fallbackProperties = other.fallbackProperties;
  3114. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3115. propertyChanged();
  3116. return *this;
  3117. }
  3118. PropertySet::~PropertySet()
  3119. {
  3120. }
  3121. void PropertySet::clear()
  3122. {
  3123. const ScopedLock sl (lock);
  3124. if (properties.size() > 0)
  3125. {
  3126. properties.clear();
  3127. propertyChanged();
  3128. }
  3129. }
  3130. const String PropertySet::getValue (const String& keyName,
  3131. const String& defaultValue) const throw()
  3132. {
  3133. const ScopedLock sl (lock);
  3134. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3135. if (index >= 0)
  3136. return properties.getAllValues() [index];
  3137. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3138. : defaultValue;
  3139. }
  3140. int PropertySet::getIntValue (const String& keyName,
  3141. const int defaultValue) const throw()
  3142. {
  3143. const ScopedLock sl (lock);
  3144. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3145. if (index >= 0)
  3146. return properties.getAllValues() [index].getIntValue();
  3147. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3148. : defaultValue;
  3149. }
  3150. double PropertySet::getDoubleValue (const String& keyName,
  3151. const double defaultValue) const throw()
  3152. {
  3153. const ScopedLock sl (lock);
  3154. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3155. if (index >= 0)
  3156. return properties.getAllValues()[index].getDoubleValue();
  3157. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3158. : defaultValue;
  3159. }
  3160. bool PropertySet::getBoolValue (const String& keyName,
  3161. const bool defaultValue) const throw()
  3162. {
  3163. const ScopedLock sl (lock);
  3164. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3165. if (index >= 0)
  3166. return properties.getAllValues() [index].getIntValue() != 0;
  3167. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3168. : defaultValue;
  3169. }
  3170. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3171. {
  3172. XmlDocument doc (getValue (keyName));
  3173. return doc.getDocumentElement();
  3174. }
  3175. void PropertySet::setValue (const String& keyName, const var& v)
  3176. {
  3177. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3178. if (keyName.isNotEmpty())
  3179. {
  3180. const String value (v.toString());
  3181. const ScopedLock sl (lock);
  3182. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3183. if (index < 0 || properties.getAllValues() [index] != value)
  3184. {
  3185. properties.set (keyName, value);
  3186. propertyChanged();
  3187. }
  3188. }
  3189. }
  3190. void PropertySet::removeValue (const String& keyName)
  3191. {
  3192. if (keyName.isNotEmpty())
  3193. {
  3194. const ScopedLock sl (lock);
  3195. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3196. if (index >= 0)
  3197. {
  3198. properties.remove (keyName);
  3199. propertyChanged();
  3200. }
  3201. }
  3202. }
  3203. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3204. {
  3205. setValue (keyName, xml == 0 ? var::null
  3206. : var (xml->createDocument (String::empty, true)));
  3207. }
  3208. bool PropertySet::containsKey (const String& keyName) const throw()
  3209. {
  3210. const ScopedLock sl (lock);
  3211. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3212. }
  3213. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3214. {
  3215. const ScopedLock sl (lock);
  3216. fallbackProperties = fallbackProperties_;
  3217. }
  3218. XmlElement* PropertySet::createXml (const String& nodeName) const
  3219. {
  3220. const ScopedLock sl (lock);
  3221. XmlElement* const xml = new XmlElement (nodeName);
  3222. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3223. {
  3224. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3225. e->setAttribute ("name", properties.getAllKeys()[i]);
  3226. e->setAttribute ("val", properties.getAllValues()[i]);
  3227. }
  3228. return xml;
  3229. }
  3230. void PropertySet::restoreFromXml (const XmlElement& xml)
  3231. {
  3232. const ScopedLock sl (lock);
  3233. clear();
  3234. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3235. {
  3236. if (e->hasAttribute ("name")
  3237. && e->hasAttribute ("val"))
  3238. {
  3239. properties.set (e->getStringAttribute ("name"),
  3240. e->getStringAttribute ("val"));
  3241. }
  3242. }
  3243. if (properties.size() > 0)
  3244. propertyChanged();
  3245. }
  3246. void PropertySet::propertyChanged()
  3247. {
  3248. }
  3249. END_JUCE_NAMESPACE
  3250. /*** End of inlined file: juce_PropertySet.cpp ***/
  3251. /*** Start of inlined file: juce_Identifier.cpp ***/
  3252. BEGIN_JUCE_NAMESPACE
  3253. StringPool& Identifier::getPool()
  3254. {
  3255. static StringPool pool;
  3256. return pool;
  3257. }
  3258. Identifier::Identifier() throw()
  3259. : name (0)
  3260. {
  3261. }
  3262. Identifier::Identifier (const Identifier& other) throw()
  3263. : name (other.name)
  3264. {
  3265. }
  3266. Identifier& Identifier::operator= (const Identifier& other) throw()
  3267. {
  3268. name = other.name;
  3269. return *this;
  3270. }
  3271. Identifier::Identifier (const String& name_)
  3272. : name (Identifier::getPool().getPooledString (name_))
  3273. {
  3274. /* An Identifier string must be suitable for use as a script variable or XML
  3275. attribute, so it can only contain this limited set of characters.. */
  3276. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3277. }
  3278. Identifier::Identifier (const char* const name_)
  3279. : name (Identifier::getPool().getPooledString (name_))
  3280. {
  3281. /* An Identifier string must be suitable for use as a script variable or XML
  3282. attribute, so it can only contain this limited set of characters.. */
  3283. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3284. }
  3285. Identifier::~Identifier()
  3286. {
  3287. }
  3288. END_JUCE_NAMESPACE
  3289. /*** End of inlined file: juce_Identifier.cpp ***/
  3290. /*** Start of inlined file: juce_Variant.cpp ***/
  3291. BEGIN_JUCE_NAMESPACE
  3292. class var::VariantType
  3293. {
  3294. public:
  3295. VariantType() {}
  3296. virtual ~VariantType() {}
  3297. virtual int toInt (const ValueUnion&) const { return 0; }
  3298. virtual double toDouble (const ValueUnion&) const { return 0; }
  3299. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3300. virtual bool toBool (const ValueUnion&) const { return false; }
  3301. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3302. virtual bool isVoid() const throw() { return false; }
  3303. virtual bool isInt() const throw() { return false; }
  3304. virtual bool isBool() const throw() { return false; }
  3305. virtual bool isDouble() const throw() { return false; }
  3306. virtual bool isString() const throw() { return false; }
  3307. virtual bool isObject() const throw() { return false; }
  3308. virtual bool isMethod() const throw() { return false; }
  3309. virtual void cleanUp (ValueUnion&) const throw() {}
  3310. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3311. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3312. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3313. };
  3314. class var::VariantType_Void : public var::VariantType
  3315. {
  3316. public:
  3317. VariantType_Void() {}
  3318. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3319. bool isVoid() const throw() { return true; }
  3320. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3321. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3322. };
  3323. class var::VariantType_Int : public var::VariantType
  3324. {
  3325. public:
  3326. VariantType_Int() {}
  3327. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3328. int toInt (const ValueUnion& data) const { return data.intValue; };
  3329. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3330. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3331. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3332. bool isInt() const throw() { return true; }
  3333. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3334. {
  3335. return otherType.toInt (otherData) == data.intValue;
  3336. }
  3337. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3338. {
  3339. output.writeCompressedInt (5);
  3340. output.writeByte (1);
  3341. output.writeInt (data.intValue);
  3342. }
  3343. };
  3344. class var::VariantType_Double : public var::VariantType
  3345. {
  3346. public:
  3347. VariantType_Double() {}
  3348. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3349. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3350. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3351. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3352. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3353. bool isDouble() const throw() { return true; }
  3354. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3355. {
  3356. return otherType.toDouble (otherData) == data.doubleValue;
  3357. }
  3358. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3359. {
  3360. output.writeCompressedInt (9);
  3361. output.writeByte (4);
  3362. output.writeDouble (data.doubleValue);
  3363. }
  3364. };
  3365. class var::VariantType_Bool : public var::VariantType
  3366. {
  3367. public:
  3368. VariantType_Bool() {}
  3369. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3370. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3371. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3372. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3373. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3374. bool isBool() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toBool (otherData) == data.boolValue;
  3378. }
  3379. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3380. {
  3381. output.writeCompressedInt (1);
  3382. output.writeByte (data.boolValue ? 2 : 3);
  3383. }
  3384. };
  3385. class var::VariantType_String : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_String() {}
  3389. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3390. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3391. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3392. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3393. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3394. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3395. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3396. || data.stringValue->trim().equalsIgnoreCase ("true")
  3397. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3398. bool isString() const throw() { return true; }
  3399. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3400. {
  3401. return otherType.toString (otherData) == *data.stringValue;
  3402. }
  3403. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3404. {
  3405. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3406. output.writeCompressedInt (len + 1);
  3407. output.writeByte (5);
  3408. HeapBlock<char> temp (len);
  3409. data.stringValue->copyToUTF8 (temp, len);
  3410. output.write (temp, len);
  3411. }
  3412. };
  3413. class var::VariantType_Object : public var::VariantType
  3414. {
  3415. public:
  3416. VariantType_Object() {}
  3417. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3418. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3419. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3420. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3421. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3422. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3423. bool isObject() const throw() { return true; }
  3424. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3425. {
  3426. return otherType.toObject (otherData) == data.objectValue;
  3427. }
  3428. void writeToStream (const ValueUnion&, OutputStream& output) const
  3429. {
  3430. jassertfalse; // Can't write an object to a stream!
  3431. output.writeCompressedInt (0);
  3432. }
  3433. };
  3434. class var::VariantType_Method : public var::VariantType
  3435. {
  3436. public:
  3437. VariantType_Method() {}
  3438. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3439. const String toString (const ValueUnion&) const { return "Method"; }
  3440. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3441. bool isMethod() const throw() { return true; }
  3442. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3443. {
  3444. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3445. }
  3446. void writeToStream (const ValueUnion&, OutputStream& output) const
  3447. {
  3448. jassertfalse; // Can't write a method to a stream!
  3449. output.writeCompressedInt (0);
  3450. }
  3451. };
  3452. var::var() throw()
  3453. : type (VariantType_Void::getInstance())
  3454. {
  3455. }
  3456. var::~var() throw()
  3457. {
  3458. type->cleanUp (value);
  3459. }
  3460. const var var::null;
  3461. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3462. {
  3463. type->createCopy (value, valueToCopy.value);
  3464. }
  3465. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3466. {
  3467. value.intValue = value_;
  3468. }
  3469. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3470. {
  3471. value.boolValue = value_;
  3472. }
  3473. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3474. {
  3475. value.doubleValue = value_;
  3476. }
  3477. var::var (const String& value_) : type (VariantType_String::getInstance())
  3478. {
  3479. value.stringValue = new String (value_);
  3480. }
  3481. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3482. {
  3483. value.stringValue = new String (value_);
  3484. }
  3485. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3486. {
  3487. value.stringValue = new String (value_);
  3488. }
  3489. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3490. {
  3491. value.objectValue = object;
  3492. if (object != 0)
  3493. object->incReferenceCount();
  3494. }
  3495. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3496. {
  3497. value.methodValue = method_;
  3498. }
  3499. bool var::isVoid() const throw() { return type->isVoid(); }
  3500. bool var::isInt() const throw() { return type->isInt(); }
  3501. bool var::isBool() const throw() { return type->isBool(); }
  3502. bool var::isDouble() const throw() { return type->isDouble(); }
  3503. bool var::isString() const throw() { return type->isString(); }
  3504. bool var::isObject() const throw() { return type->isObject(); }
  3505. bool var::isMethod() const throw() { return type->isMethod(); }
  3506. var::operator int() const { return type->toInt (value); }
  3507. var::operator bool() const { return type->toBool (value); }
  3508. var::operator float() const { return (float) type->toDouble (value); }
  3509. var::operator double() const { return type->toDouble (value); }
  3510. const String var::toString() const { return type->toString (value); }
  3511. var::operator const String() const { return type->toString (value); }
  3512. DynamicObject* var::getObject() const { return type->toObject (value); }
  3513. void var::swapWith (var& other) throw()
  3514. {
  3515. swapVariables (type, other.type);
  3516. swapVariables (value, other.value);
  3517. }
  3518. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3519. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3520. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3521. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3522. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3523. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3524. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3525. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3526. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3527. bool var::equals (const var& other) const throw()
  3528. {
  3529. return type->equals (value, other.value, *other.type);
  3530. }
  3531. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3532. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3533. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3534. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3535. void var::writeToStream (OutputStream& output) const
  3536. {
  3537. type->writeToStream (value, output);
  3538. }
  3539. const var var::readFromStream (InputStream& input)
  3540. {
  3541. const int numBytes = input.readCompressedInt();
  3542. if (numBytes > 0)
  3543. {
  3544. switch (input.readByte())
  3545. {
  3546. case 1: return var (input.readInt());
  3547. case 2: return var (true);
  3548. case 3: return var (false);
  3549. case 4: return var (input.readDouble());
  3550. case 5:
  3551. {
  3552. MemoryOutputStream mo;
  3553. mo.writeFromInputStream (input, numBytes - 1);
  3554. return var (mo.toUTF8());
  3555. }
  3556. default: input.skipNextBytes (numBytes - 1); break;
  3557. }
  3558. }
  3559. return var::null;
  3560. }
  3561. const var var::operator[] (const Identifier& propertyName) const
  3562. {
  3563. DynamicObject* const o = getObject();
  3564. return o != 0 ? o->getProperty (propertyName) : var::null;
  3565. }
  3566. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3567. {
  3568. DynamicObject* const o = getObject();
  3569. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3570. }
  3571. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3572. {
  3573. if (isMethod())
  3574. {
  3575. DynamicObject* const target = targetObject.getObject();
  3576. if (target != 0)
  3577. return (target->*(value.methodValue)) (arguments, numArguments);
  3578. }
  3579. return var::null;
  3580. }
  3581. const var var::call (const Identifier& method) const
  3582. {
  3583. return invoke (method, 0, 0);
  3584. }
  3585. const var var::call (const Identifier& method, const var& arg1) const
  3586. {
  3587. return invoke (method, &arg1, 1);
  3588. }
  3589. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3590. {
  3591. var args[] = { arg1, arg2 };
  3592. return invoke (method, args, 2);
  3593. }
  3594. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3595. {
  3596. var args[] = { arg1, arg2, arg3 };
  3597. return invoke (method, args, 3);
  3598. }
  3599. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3600. {
  3601. var args[] = { arg1, arg2, arg3, arg4 };
  3602. return invoke (method, args, 4);
  3603. }
  3604. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3605. {
  3606. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3607. return invoke (method, args, 5);
  3608. }
  3609. END_JUCE_NAMESPACE
  3610. /*** End of inlined file: juce_Variant.cpp ***/
  3611. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3612. BEGIN_JUCE_NAMESPACE
  3613. NamedValueSet::NamedValue::NamedValue() throw()
  3614. {
  3615. }
  3616. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3617. : name (name_), value (value_)
  3618. {
  3619. }
  3620. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3621. {
  3622. return name == other.name && value == other.value;
  3623. }
  3624. NamedValueSet::NamedValueSet() throw()
  3625. {
  3626. }
  3627. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3628. : values (other.values)
  3629. {
  3630. }
  3631. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3632. {
  3633. values = other.values;
  3634. return *this;
  3635. }
  3636. NamedValueSet::~NamedValueSet()
  3637. {
  3638. }
  3639. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3640. {
  3641. return values == other.values;
  3642. }
  3643. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3644. {
  3645. return ! operator== (other);
  3646. }
  3647. int NamedValueSet::size() const throw()
  3648. {
  3649. return values.size();
  3650. }
  3651. const var& NamedValueSet::operator[] (const Identifier& name) const
  3652. {
  3653. for (int i = values.size(); --i >= 0;)
  3654. {
  3655. const NamedValue& v = values.getReference(i);
  3656. if (v.name == name)
  3657. return v.value;
  3658. }
  3659. return var::null;
  3660. }
  3661. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3662. {
  3663. const var* v = getItem (name);
  3664. return v != 0 ? *v : defaultReturnValue;
  3665. }
  3666. var* NamedValueSet::getItem (const Identifier& name) const
  3667. {
  3668. for (int i = values.size(); --i >= 0;)
  3669. {
  3670. NamedValue& v = values.getReference(i);
  3671. if (v.name == name)
  3672. return &(v.value);
  3673. }
  3674. return 0;
  3675. }
  3676. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3677. {
  3678. for (int i = values.size(); --i >= 0;)
  3679. {
  3680. NamedValue& v = values.getReference(i);
  3681. if (v.name == name)
  3682. {
  3683. if (v.value == newValue)
  3684. return false;
  3685. v.value = newValue;
  3686. return true;
  3687. }
  3688. }
  3689. values.add (NamedValue (name, newValue));
  3690. return true;
  3691. }
  3692. bool NamedValueSet::contains (const Identifier& name) const
  3693. {
  3694. return getItem (name) != 0;
  3695. }
  3696. bool NamedValueSet::remove (const Identifier& name)
  3697. {
  3698. for (int i = values.size(); --i >= 0;)
  3699. {
  3700. if (values.getReference(i).name == name)
  3701. {
  3702. values.remove (i);
  3703. return true;
  3704. }
  3705. }
  3706. return false;
  3707. }
  3708. const Identifier NamedValueSet::getName (const int index) const
  3709. {
  3710. jassert (((unsigned int) index) < (unsigned int) values.size());
  3711. return values [index].name;
  3712. }
  3713. const var NamedValueSet::getValueAt (const int index) const
  3714. {
  3715. jassert (((unsigned int) index) < (unsigned int) values.size());
  3716. return values [index].value;
  3717. }
  3718. void NamedValueSet::clear()
  3719. {
  3720. values.clear();
  3721. }
  3722. END_JUCE_NAMESPACE
  3723. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3724. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3725. BEGIN_JUCE_NAMESPACE
  3726. DynamicObject::DynamicObject()
  3727. {
  3728. }
  3729. DynamicObject::~DynamicObject()
  3730. {
  3731. }
  3732. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3733. {
  3734. var* const v = properties.getItem (propertyName);
  3735. return v != 0 && ! v->isMethod();
  3736. }
  3737. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3738. {
  3739. return properties [propertyName];
  3740. }
  3741. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3742. {
  3743. properties.set (propertyName, newValue);
  3744. }
  3745. void DynamicObject::removeProperty (const Identifier& propertyName)
  3746. {
  3747. properties.remove (propertyName);
  3748. }
  3749. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3750. {
  3751. return getProperty (methodName).isMethod();
  3752. }
  3753. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3754. const var* parameters,
  3755. int numParameters)
  3756. {
  3757. return properties [methodName].invoke (var (this), parameters, numParameters);
  3758. }
  3759. void DynamicObject::setMethod (const Identifier& name,
  3760. var::MethodFunction methodFunction)
  3761. {
  3762. properties.set (name, var (methodFunction));
  3763. }
  3764. void DynamicObject::clear()
  3765. {
  3766. properties.clear();
  3767. }
  3768. END_JUCE_NAMESPACE
  3769. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3770. /*** Start of inlined file: juce_Expression.cpp ***/
  3771. BEGIN_JUCE_NAMESPACE
  3772. class Expression::Helpers
  3773. {
  3774. public:
  3775. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3776. class Constant : public Term
  3777. {
  3778. public:
  3779. Constant (const double value_, bool isResolutionTarget_)
  3780. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3781. Type getType() const throw() { return constantType; }
  3782. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3783. double evaluate (const EvaluationContext&, int) const { return value; }
  3784. int getNumInputs() const { return 0; }
  3785. Term* getInput (int) const { return 0; }
  3786. const TermPtr negated()
  3787. {
  3788. return new Constant (-value, isResolutionTarget);
  3789. }
  3790. const String toString() const
  3791. {
  3792. if (isResolutionTarget)
  3793. return "@" + String (value);
  3794. return String (value);
  3795. }
  3796. double value;
  3797. bool isResolutionTarget;
  3798. };
  3799. class Symbol : public Term
  3800. {
  3801. public:
  3802. explicit Symbol (const String& symbol_)
  3803. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3804. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3805. {}
  3806. Symbol (const String& symbol_, const String& member_)
  3807. : mainSymbol (symbol_),
  3808. member (member_)
  3809. {}
  3810. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3811. {
  3812. if (++recursionDepth > 256)
  3813. throw EvaluationError ("Recursive symbol references");
  3814. try
  3815. {
  3816. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3817. }
  3818. catch (...)
  3819. {}
  3820. return 0;
  3821. }
  3822. Type getType() const throw() { return symbolType; }
  3823. Term* clone() const { return new Symbol (mainSymbol, member); }
  3824. int getNumInputs() const { return 0; }
  3825. Term* getInput (int) const { return 0; }
  3826. const String getSymbolName() const { return toString(); }
  3827. const String toString() const
  3828. {
  3829. return member.isEmpty() ? mainSymbol
  3830. : mainSymbol + "." + member;
  3831. }
  3832. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3833. {
  3834. if (s == mainSymbol)
  3835. return true;
  3836. if (++recursionDepth > 256)
  3837. throw EvaluationError ("Recursive symbol references");
  3838. try
  3839. {
  3840. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3841. }
  3842. catch (EvaluationError&)
  3843. {
  3844. return false;
  3845. }
  3846. }
  3847. String mainSymbol, member;
  3848. };
  3849. class Function : public Term
  3850. {
  3851. public:
  3852. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3853. : functionName (functionName_), parameters (parameters_)
  3854. {}
  3855. Term* clone() const { return new Function (functionName, parameters); }
  3856. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3857. {
  3858. HeapBlock <double> params (parameters.size());
  3859. for (int i = 0; i < parameters.size(); ++i)
  3860. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3861. return c.evaluateFunction (functionName, params, parameters.size());
  3862. }
  3863. Type getType() const throw() { return functionType; }
  3864. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3865. int getNumInputs() const { return parameters.size(); }
  3866. Term* getInput (int i) const { return parameters [i]; }
  3867. const String getFunctionName() const { return functionName; }
  3868. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3869. {
  3870. for (int i = 0; i < parameters.size(); ++i)
  3871. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3872. return true;
  3873. return false;
  3874. }
  3875. const String toString() const
  3876. {
  3877. if (parameters.size() == 0)
  3878. return functionName + "()";
  3879. String s (functionName + " (");
  3880. for (int i = 0; i < parameters.size(); ++i)
  3881. {
  3882. s << parameters.getUnchecked(i)->toString();
  3883. if (i < parameters.size() - 1)
  3884. s << ", ";
  3885. }
  3886. s << ')';
  3887. return s;
  3888. }
  3889. const String functionName;
  3890. ReferenceCountedArray<Term> parameters;
  3891. };
  3892. class Negate : public Term
  3893. {
  3894. public:
  3895. Negate (const TermPtr& input_) : input (input_)
  3896. {
  3897. jassert (input_ != 0);
  3898. }
  3899. Type getType() const throw() { return operatorType; }
  3900. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3901. int getNumInputs() const { return 1; }
  3902. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3903. Term* clone() const { return new Negate (input->clone()); }
  3904. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3905. const String getFunctionName() const { return "-"; }
  3906. const TermPtr negated()
  3907. {
  3908. return input;
  3909. }
  3910. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3911. {
  3912. (void) input_;
  3913. jassert (input_ == input);
  3914. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3915. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3916. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3917. }
  3918. const String toString() const
  3919. {
  3920. if (input->getOperatorPrecedence() > 0)
  3921. return "-(" + input->toString() + ")";
  3922. else
  3923. return "-" + input->toString();
  3924. }
  3925. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3926. {
  3927. return input->referencesSymbol (s, c, recursionDepth);
  3928. }
  3929. private:
  3930. const TermPtr input;
  3931. };
  3932. class BinaryTerm : public Term
  3933. {
  3934. public:
  3935. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3936. {
  3937. jassert (left_ != 0 && right_ != 0);
  3938. }
  3939. int getInputIndexFor (const Term* possibleInput) const
  3940. {
  3941. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3942. }
  3943. Type getType() const throw() { return operatorType; }
  3944. int getNumInputs() const { return 2; }
  3945. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3946. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3947. {
  3948. return left->referencesSymbol (s, c, recursionDepth)
  3949. || right->referencesSymbol (s, c, recursionDepth);
  3950. }
  3951. const String toString() const
  3952. {
  3953. String s;
  3954. const int ourPrecendence = getOperatorPrecedence();
  3955. if (left->getOperatorPrecedence() > ourPrecendence)
  3956. s << '(' << left->toString() << ')';
  3957. else
  3958. s = left->toString();
  3959. s << ' ' << getFunctionName() << ' ';
  3960. if (right->getOperatorPrecedence() >= ourPrecendence)
  3961. s << '(' << right->toString() << ')';
  3962. else
  3963. s << right->toString();
  3964. return s;
  3965. }
  3966. protected:
  3967. const TermPtr left, right;
  3968. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3969. {
  3970. jassert (input == left || input == right);
  3971. if (input != left && input != right)
  3972. return 0;
  3973. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3974. if (dest == 0)
  3975. return new Constant (overallTarget, false);
  3976. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3977. }
  3978. };
  3979. class Add : public BinaryTerm
  3980. {
  3981. public:
  3982. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3983. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3984. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3985. int getOperatorPrecedence() const { return 2; }
  3986. const String getFunctionName() const { return "+"; }
  3987. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3988. {
  3989. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3990. if (newDest == 0)
  3991. return 0;
  3992. return new Subtract (newDest, (input == left ? right : left)->clone());
  3993. }
  3994. private:
  3995. Add (const Add&);
  3996. Add& operator= (const Add&);
  3997. };
  3998. class Subtract : public BinaryTerm
  3999. {
  4000. public:
  4001. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4002. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4003. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4004. int getOperatorPrecedence() const { return 2; }
  4005. const String getFunctionName() const { return "-"; }
  4006. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4007. {
  4008. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4009. if (newDest == 0)
  4010. return 0;
  4011. if (input == left)
  4012. return new Add (newDest, right->clone());
  4013. else
  4014. return new Subtract (left->clone(), newDest);
  4015. }
  4016. private:
  4017. Subtract (const Subtract&);
  4018. Subtract& operator= (const Subtract&);
  4019. };
  4020. class Multiply : public BinaryTerm
  4021. {
  4022. public:
  4023. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4024. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4025. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4026. const String getFunctionName() const { return "*"; }
  4027. int getOperatorPrecedence() const { return 1; }
  4028. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4029. {
  4030. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4031. if (newDest == 0)
  4032. return 0;
  4033. return new Divide (newDest, (input == left ? right : left)->clone());
  4034. }
  4035. private:
  4036. Multiply (const Multiply&);
  4037. Multiply& operator= (const Multiply&);
  4038. };
  4039. class Divide : public BinaryTerm
  4040. {
  4041. public:
  4042. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4043. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4044. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4045. const String getFunctionName() const { return "/"; }
  4046. int getOperatorPrecedence() const { return 1; }
  4047. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4048. {
  4049. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4050. if (newDest == 0)
  4051. return 0;
  4052. if (input == left)
  4053. return new Multiply (newDest, right->clone());
  4054. else
  4055. return new Divide (left->clone(), newDest);
  4056. }
  4057. private:
  4058. Divide (const Divide&);
  4059. Divide& operator= (const Divide&);
  4060. };
  4061. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4062. {
  4063. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4064. if (inputIndex >= 0)
  4065. return topLevel;
  4066. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4067. {
  4068. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4069. if (t != 0)
  4070. return t;
  4071. }
  4072. return 0;
  4073. }
  4074. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4075. {
  4076. Constant* c = dynamic_cast<Constant*> (term);
  4077. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4078. return c;
  4079. if (dynamic_cast<Function*> (term) != 0)
  4080. return 0;
  4081. int i;
  4082. const int numIns = term->getNumInputs();
  4083. for (i = 0; i < numIns; ++i)
  4084. {
  4085. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4086. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4087. return c;
  4088. }
  4089. for (i = 0; i < numIns; ++i)
  4090. {
  4091. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4092. if (c != 0)
  4093. return c;
  4094. }
  4095. return 0;
  4096. }
  4097. static bool containsAnySymbols (const Term* const t)
  4098. {
  4099. if (dynamic_cast <const Symbol*> (t) != 0)
  4100. return true;
  4101. for (int i = t->getNumInputs(); --i >= 0;)
  4102. if (containsAnySymbols (t->getInput (i)))
  4103. return true;
  4104. return false;
  4105. }
  4106. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4107. {
  4108. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4109. if (sym != 0 && sym->mainSymbol == oldName)
  4110. {
  4111. sym->mainSymbol = newName;
  4112. return true;
  4113. }
  4114. bool anyChanged = false;
  4115. for (int i = t->getNumInputs(); --i >= 0;)
  4116. if (renameSymbol (t->getInput (i), oldName, newName))
  4117. anyChanged = true;
  4118. return anyChanged;
  4119. }
  4120. class Parser
  4121. {
  4122. public:
  4123. Parser (const String& stringToParse, int& textIndex_)
  4124. : textString (stringToParse), textIndex (textIndex_)
  4125. {
  4126. text = textString;
  4127. }
  4128. const TermPtr readExpression()
  4129. {
  4130. TermPtr lhs (readMultiplyOrDivideExpression());
  4131. char opType;
  4132. while (lhs != 0 && readOperator ("+-", &opType))
  4133. {
  4134. TermPtr rhs (readMultiplyOrDivideExpression());
  4135. if (rhs == 0)
  4136. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4137. if (opType == '+')
  4138. lhs = new Add (lhs, rhs);
  4139. else
  4140. lhs = new Subtract (lhs, rhs);
  4141. }
  4142. return lhs;
  4143. }
  4144. private:
  4145. const String textString;
  4146. const juce_wchar* text;
  4147. int& textIndex;
  4148. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4149. {
  4150. return c >= '0' && c <= '9';
  4151. }
  4152. void skipWhitespace (int& i)
  4153. {
  4154. while (CharacterFunctions::isWhitespace (text [i]))
  4155. ++i;
  4156. }
  4157. bool readChar (const juce_wchar required)
  4158. {
  4159. if (text[textIndex] == required)
  4160. {
  4161. ++textIndex;
  4162. return true;
  4163. }
  4164. return false;
  4165. }
  4166. bool readOperator (const char* ops, char* const opType = 0)
  4167. {
  4168. skipWhitespace (textIndex);
  4169. while (*ops != 0)
  4170. {
  4171. if (readChar (*ops))
  4172. {
  4173. if (opType != 0)
  4174. *opType = *ops;
  4175. return true;
  4176. }
  4177. ++ops;
  4178. }
  4179. return false;
  4180. }
  4181. bool readIdentifier (String& identifier)
  4182. {
  4183. skipWhitespace (textIndex);
  4184. int i = textIndex;
  4185. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4186. {
  4187. ++i;
  4188. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4189. ++i;
  4190. }
  4191. if (i > textIndex)
  4192. {
  4193. identifier = String (text + textIndex, i - textIndex);
  4194. textIndex = i;
  4195. return true;
  4196. }
  4197. return false;
  4198. }
  4199. Term* readNumber()
  4200. {
  4201. skipWhitespace (textIndex);
  4202. int i = textIndex;
  4203. const bool isResolutionTarget = (text[i] == '@');
  4204. if (isResolutionTarget)
  4205. {
  4206. ++i;
  4207. skipWhitespace (i);
  4208. textIndex = i;
  4209. }
  4210. if (text[i] == '-')
  4211. {
  4212. ++i;
  4213. skipWhitespace (i);
  4214. }
  4215. int numDigits = 0;
  4216. while (isDecimalDigit (text[i]))
  4217. {
  4218. ++i;
  4219. ++numDigits;
  4220. }
  4221. const bool hasPoint = (text[i] == '.');
  4222. if (hasPoint)
  4223. {
  4224. ++i;
  4225. while (isDecimalDigit (text[i]))
  4226. {
  4227. ++i;
  4228. ++numDigits;
  4229. }
  4230. }
  4231. if (numDigits == 0)
  4232. return 0;
  4233. juce_wchar c = text[i];
  4234. const bool hasExponent = (c == 'e' || c == 'E');
  4235. if (hasExponent)
  4236. {
  4237. ++i;
  4238. c = text[i];
  4239. if (c == '+' || c == '-')
  4240. ++i;
  4241. int numExpDigits = 0;
  4242. while (isDecimalDigit (text[i]))
  4243. {
  4244. ++i;
  4245. ++numExpDigits;
  4246. }
  4247. if (numExpDigits == 0)
  4248. return 0;
  4249. }
  4250. const int start = textIndex;
  4251. textIndex = i;
  4252. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4253. }
  4254. const TermPtr readMultiplyOrDivideExpression()
  4255. {
  4256. TermPtr lhs (readUnaryExpression());
  4257. char opType;
  4258. while (lhs != 0 && readOperator ("*/", &opType))
  4259. {
  4260. TermPtr rhs (readUnaryExpression());
  4261. if (rhs == 0)
  4262. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4263. if (opType == '*')
  4264. lhs = new Multiply (lhs, rhs);
  4265. else
  4266. lhs = new Divide (lhs, rhs);
  4267. }
  4268. return lhs;
  4269. }
  4270. const TermPtr readUnaryExpression()
  4271. {
  4272. char opType;
  4273. if (readOperator ("+-", &opType))
  4274. {
  4275. TermPtr term (readUnaryExpression());
  4276. if (term == 0)
  4277. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4278. if (opType == '-')
  4279. term = term->negated();
  4280. return term;
  4281. }
  4282. return readPrimaryExpression();
  4283. }
  4284. const TermPtr readPrimaryExpression()
  4285. {
  4286. TermPtr e (readParenthesisedExpression());
  4287. if (e != 0)
  4288. return e;
  4289. e = readNumber();
  4290. if (e != 0)
  4291. return e;
  4292. String identifier;
  4293. if (readIdentifier (identifier))
  4294. {
  4295. if (readOperator ("(")) // method call...
  4296. {
  4297. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4298. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4299. TermPtr param (readExpression());
  4300. if (param == 0)
  4301. {
  4302. if (readOperator (")"))
  4303. return func.release();
  4304. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4305. }
  4306. f->parameters.add (param);
  4307. while (readOperator (","))
  4308. {
  4309. param = readExpression();
  4310. if (param == 0)
  4311. throw ParseError ("Expected expression after \",\"");
  4312. f->parameters.add (param);
  4313. }
  4314. if (readOperator (")"))
  4315. return func.release();
  4316. throw ParseError ("Expected \")\"");
  4317. }
  4318. else // just a symbol..
  4319. {
  4320. return new Symbol (identifier);
  4321. }
  4322. }
  4323. return 0;
  4324. }
  4325. const TermPtr readParenthesisedExpression()
  4326. {
  4327. if (! readOperator ("("))
  4328. return 0;
  4329. const TermPtr e (readExpression());
  4330. if (e == 0 || ! readOperator (")"))
  4331. return 0;
  4332. return e;
  4333. }
  4334. Parser (const Parser&);
  4335. Parser& operator= (const Parser&);
  4336. };
  4337. };
  4338. Expression::Expression()
  4339. : term (new Expression::Helpers::Constant (0, false))
  4340. {
  4341. }
  4342. Expression::~Expression()
  4343. {
  4344. }
  4345. Expression::Expression (Term* const term_)
  4346. : term (term_)
  4347. {
  4348. jassert (term != 0);
  4349. }
  4350. Expression::Expression (const double constant)
  4351. : term (new Expression::Helpers::Constant (constant, false))
  4352. {
  4353. }
  4354. Expression::Expression (const Expression& other)
  4355. : term (other.term)
  4356. {
  4357. }
  4358. Expression& Expression::operator= (const Expression& other)
  4359. {
  4360. term = other.term;
  4361. return *this;
  4362. }
  4363. Expression::Expression (const String& stringToParse)
  4364. {
  4365. int i = 0;
  4366. Helpers::Parser parser (stringToParse, i);
  4367. term = parser.readExpression();
  4368. if (term == 0)
  4369. term = new Helpers::Constant (0, false);
  4370. }
  4371. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4372. {
  4373. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4374. const Helpers::TermPtr term (parser.readExpression());
  4375. if (term != 0)
  4376. return Expression (term);
  4377. return Expression();
  4378. }
  4379. double Expression::evaluate() const
  4380. {
  4381. return evaluate (Expression::EvaluationContext());
  4382. }
  4383. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4384. {
  4385. return term->evaluate (context, 0);
  4386. }
  4387. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4388. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4389. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4390. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4391. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4392. const String Expression::toString() const
  4393. {
  4394. return term->toString();
  4395. }
  4396. const Expression Expression::symbol (const String& symbol)
  4397. {
  4398. return Expression (new Helpers::Symbol (symbol));
  4399. }
  4400. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4401. {
  4402. ReferenceCountedArray<Term> params;
  4403. for (int i = 0; i < parameters.size(); ++i)
  4404. params.add (parameters.getReference(i).term);
  4405. return Expression (new Helpers::Function (functionName, params));
  4406. }
  4407. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4408. const Expression::EvaluationContext& context) const
  4409. {
  4410. ScopedPointer<Term> newTerm (term->clone());
  4411. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4412. if (termToAdjust == 0)
  4413. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4414. if (termToAdjust == 0)
  4415. {
  4416. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4417. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4418. }
  4419. jassert (termToAdjust != 0);
  4420. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4421. if (parent == 0)
  4422. {
  4423. termToAdjust->value = targetValue;
  4424. }
  4425. else
  4426. {
  4427. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4428. if (reverseTerm == 0)
  4429. return Expression (targetValue);
  4430. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4431. }
  4432. return Expression (newTerm.release());
  4433. }
  4434. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4435. {
  4436. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4437. Expression newExpression (term->clone());
  4438. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4439. return newExpression;
  4440. }
  4441. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4442. {
  4443. return term->referencesSymbol (symbol, context, 0);
  4444. }
  4445. bool Expression::usesAnySymbols() const
  4446. {
  4447. return Helpers::containsAnySymbols (term);
  4448. }
  4449. Expression::Type Expression::getType() const throw()
  4450. {
  4451. return term->getType();
  4452. }
  4453. const String Expression::getSymbol() const
  4454. {
  4455. return term->getSymbolName();
  4456. }
  4457. const String Expression::getFunction() const
  4458. {
  4459. return term->getFunctionName();
  4460. }
  4461. const String Expression::getOperator() const
  4462. {
  4463. return term->getFunctionName();
  4464. }
  4465. int Expression::getNumInputs() const
  4466. {
  4467. return term->getNumInputs();
  4468. }
  4469. const Expression Expression::getInput (int index) const
  4470. {
  4471. return Expression (term->getInput (index));
  4472. }
  4473. int Expression::Term::getOperatorPrecedence() const
  4474. {
  4475. return 0;
  4476. }
  4477. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4478. {
  4479. return false;
  4480. }
  4481. int Expression::Term::getInputIndexFor (const Term*) const
  4482. {
  4483. return -1;
  4484. }
  4485. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4486. {
  4487. jassertfalse;
  4488. return 0;
  4489. }
  4490. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4491. {
  4492. return new Helpers::Negate (this);
  4493. }
  4494. const String Expression::Term::getSymbolName() const
  4495. {
  4496. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4497. return String::empty;
  4498. }
  4499. const String Expression::Term::getFunctionName() const
  4500. {
  4501. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4502. return String::empty;
  4503. }
  4504. Expression::ParseError::ParseError (const String& message)
  4505. : description (message)
  4506. {
  4507. DBG ("Expression::ParseError: " + message);
  4508. }
  4509. Expression::EvaluationError::EvaluationError (const String& message)
  4510. : description (message)
  4511. {
  4512. DBG ("Expression::EvaluationError: " + description);
  4513. }
  4514. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4515. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4516. {
  4517. DBG ("Expression::EvaluationError: " + description);
  4518. }
  4519. Expression::EvaluationContext::EvaluationContext() {}
  4520. Expression::EvaluationContext::~EvaluationContext() {}
  4521. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4522. {
  4523. throw EvaluationError (symbol, member);
  4524. }
  4525. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4526. {
  4527. if (numParams > 0)
  4528. {
  4529. if (functionName == "min")
  4530. {
  4531. double v = parameters[0];
  4532. for (int i = 1; i < numParams; ++i)
  4533. v = jmin (v, parameters[i]);
  4534. return v;
  4535. }
  4536. else if (functionName == "max")
  4537. {
  4538. double v = parameters[0];
  4539. for (int i = 1; i < numParams; ++i)
  4540. v = jmax (v, parameters[i]);
  4541. return v;
  4542. }
  4543. else if (numParams == 1)
  4544. {
  4545. if (functionName == "sin") return sin (parameters[0]);
  4546. else if (functionName == "cos") return cos (parameters[0]);
  4547. else if (functionName == "tan") return tan (parameters[0]);
  4548. else if (functionName == "abs") return std::abs (parameters[0]);
  4549. }
  4550. }
  4551. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4552. }
  4553. END_JUCE_NAMESPACE
  4554. /*** End of inlined file: juce_Expression.cpp ***/
  4555. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4556. BEGIN_JUCE_NAMESPACE
  4557. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4558. {
  4559. jassert (keyData != 0);
  4560. jassert (keyBytes > 0);
  4561. static const uint32 initialPValues [18] =
  4562. {
  4563. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4564. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4565. 0x9216d5d9, 0x8979fb1b
  4566. };
  4567. static const uint32 initialSValues [4 * 256] =
  4568. {
  4569. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4570. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4571. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4572. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4573. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4574. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4575. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4576. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4577. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4578. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4579. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4580. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4581. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4582. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4583. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4584. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4585. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4586. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4587. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4588. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4589. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4590. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4591. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4592. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4593. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4594. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4595. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4596. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4597. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4598. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4599. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4600. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4601. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4602. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4603. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4604. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4605. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4606. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4607. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4608. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4609. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4610. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4611. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4612. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4613. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4614. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4615. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4616. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4617. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4618. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4619. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4620. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4621. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4622. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4623. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4624. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4625. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4626. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4627. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4628. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4629. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4630. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4631. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4632. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4633. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4634. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4635. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4636. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4637. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4638. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4639. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4640. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4641. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4642. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4643. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4644. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4645. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4646. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4647. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4648. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4649. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4650. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4651. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4652. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4653. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4654. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4655. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4656. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4657. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4658. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4659. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4660. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4661. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4662. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4663. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4664. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4665. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4666. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4667. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4668. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4669. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4670. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4671. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4672. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4673. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4674. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4675. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4676. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4677. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4678. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4679. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4680. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4681. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4682. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4683. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4684. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4685. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4686. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4687. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4688. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4689. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4690. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4691. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4692. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4693. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4694. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4695. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4696. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4697. };
  4698. memcpy (p, initialPValues, sizeof (p));
  4699. int i, j = 0;
  4700. for (i = 4; --i >= 0;)
  4701. {
  4702. s[i].malloc (256);
  4703. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4704. }
  4705. for (i = 0; i < 18; ++i)
  4706. {
  4707. uint32 d = 0;
  4708. for (int k = 0; k < 4; ++k)
  4709. {
  4710. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4711. if (++j >= keyBytes)
  4712. j = 0;
  4713. }
  4714. p[i] = initialPValues[i] ^ d;
  4715. }
  4716. uint32 l = 0, r = 0;
  4717. for (i = 0; i < 18; i += 2)
  4718. {
  4719. encrypt (l, r);
  4720. p[i] = l;
  4721. p[i + 1] = r;
  4722. }
  4723. for (i = 0; i < 4; ++i)
  4724. {
  4725. for (j = 0; j < 256; j += 2)
  4726. {
  4727. encrypt (l, r);
  4728. s[i][j] = l;
  4729. s[i][j + 1] = r;
  4730. }
  4731. }
  4732. }
  4733. BlowFish::BlowFish (const BlowFish& other)
  4734. {
  4735. for (int i = 4; --i >= 0;)
  4736. s[i].malloc (256);
  4737. operator= (other);
  4738. }
  4739. BlowFish& BlowFish::operator= (const BlowFish& other)
  4740. {
  4741. memcpy (p, other.p, sizeof (p));
  4742. for (int i = 4; --i >= 0;)
  4743. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4744. return *this;
  4745. }
  4746. BlowFish::~BlowFish()
  4747. {
  4748. }
  4749. uint32 BlowFish::F (const uint32 x) const throw()
  4750. {
  4751. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4752. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4753. }
  4754. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4755. {
  4756. uint32 l = data1;
  4757. uint32 r = data2;
  4758. for (int i = 0; i < 16; ++i)
  4759. {
  4760. l ^= p[i];
  4761. r ^= F(l);
  4762. swapVariables (l, r);
  4763. }
  4764. data1 = r ^ p[17];
  4765. data2 = l ^ p[16];
  4766. }
  4767. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4768. {
  4769. uint32 l = data1;
  4770. uint32 r = data2;
  4771. for (int i = 17; i > 1; --i)
  4772. {
  4773. l ^= p[i];
  4774. r ^= F(l);
  4775. swapVariables (l, r);
  4776. }
  4777. data1 = r ^ p[0];
  4778. data2 = l ^ p[1];
  4779. }
  4780. END_JUCE_NAMESPACE
  4781. /*** End of inlined file: juce_BlowFish.cpp ***/
  4782. /*** Start of inlined file: juce_MD5.cpp ***/
  4783. BEGIN_JUCE_NAMESPACE
  4784. MD5::MD5()
  4785. {
  4786. zerostruct (result);
  4787. }
  4788. MD5::MD5 (const MD5& other)
  4789. {
  4790. memcpy (result, other.result, sizeof (result));
  4791. }
  4792. MD5& MD5::operator= (const MD5& other)
  4793. {
  4794. memcpy (result, other.result, sizeof (result));
  4795. return *this;
  4796. }
  4797. MD5::MD5 (const MemoryBlock& data)
  4798. {
  4799. ProcessContext context;
  4800. context.processBlock (data.getData(), data.getSize());
  4801. context.finish (result);
  4802. }
  4803. MD5::MD5 (const void* data, const size_t numBytes)
  4804. {
  4805. ProcessContext context;
  4806. context.processBlock (data, numBytes);
  4807. context.finish (result);
  4808. }
  4809. MD5::MD5 (const String& text)
  4810. {
  4811. ProcessContext context;
  4812. const int len = text.length();
  4813. const juce_wchar* const t = text;
  4814. for (int i = 0; i < len; ++i)
  4815. {
  4816. // force the string into integer-sized unicode characters, to try to make it
  4817. // get the same results on all platforms + compilers.
  4818. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4819. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4820. }
  4821. context.finish (result);
  4822. }
  4823. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4824. {
  4825. ProcessContext context;
  4826. if (numBytesToRead < 0)
  4827. numBytesToRead = std::numeric_limits<int64>::max();
  4828. while (numBytesToRead > 0)
  4829. {
  4830. uint8 tempBuffer [512];
  4831. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4832. if (bytesRead <= 0)
  4833. break;
  4834. numBytesToRead -= bytesRead;
  4835. context.processBlock (tempBuffer, bytesRead);
  4836. }
  4837. context.finish (result);
  4838. }
  4839. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4840. {
  4841. processStream (input, numBytesToRead);
  4842. }
  4843. MD5::MD5 (const File& file)
  4844. {
  4845. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4846. if (fin != 0)
  4847. processStream (*fin, -1);
  4848. else
  4849. zerostruct (result);
  4850. }
  4851. MD5::~MD5()
  4852. {
  4853. }
  4854. namespace MD5Functions
  4855. {
  4856. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4857. {
  4858. for (int i = 0; i < (numBytes >> 2); ++i)
  4859. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4860. }
  4861. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4862. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4863. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4864. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4865. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4866. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4867. {
  4868. a += F (b, c, d) + x + ac;
  4869. a = rotateLeft (a, s) + b;
  4870. }
  4871. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4872. {
  4873. a += G (b, c, d) + x + ac;
  4874. a = rotateLeft (a, s) + b;
  4875. }
  4876. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4877. {
  4878. a += H (b, c, d) + x + ac;
  4879. a = rotateLeft (a, s) + b;
  4880. }
  4881. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4882. {
  4883. a += I (b, c, d) + x + ac;
  4884. a = rotateLeft (a, s) + b;
  4885. }
  4886. }
  4887. MD5::ProcessContext::ProcessContext()
  4888. {
  4889. state[0] = 0x67452301;
  4890. state[1] = 0xefcdab89;
  4891. state[2] = 0x98badcfe;
  4892. state[3] = 0x10325476;
  4893. count[0] = 0;
  4894. count[1] = 0;
  4895. }
  4896. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4897. {
  4898. int bufferPos = ((count[0] >> 3) & 0x3F);
  4899. count[0] += (uint32) (dataSize << 3);
  4900. if (count[0] < ((uint32) dataSize << 3))
  4901. count[1]++;
  4902. count[1] += (uint32) (dataSize >> 29);
  4903. const size_t spaceLeft = 64 - bufferPos;
  4904. size_t i = 0;
  4905. if (dataSize >= spaceLeft)
  4906. {
  4907. memcpy (buffer + bufferPos, data, spaceLeft);
  4908. transform (buffer);
  4909. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4910. transform (static_cast <const char*> (data) + i);
  4911. bufferPos = 0;
  4912. }
  4913. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4914. }
  4915. void MD5::ProcessContext::finish (void* const result)
  4916. {
  4917. unsigned char encodedLength[8];
  4918. MD5Functions::encode (encodedLength, count, 8);
  4919. // Pad out to 56 mod 64.
  4920. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4921. const int paddingLength = (index < 56) ? (56 - index)
  4922. : (120 - index);
  4923. uint8 paddingBuffer [64];
  4924. zeromem (paddingBuffer, paddingLength);
  4925. paddingBuffer [0] = 0x80;
  4926. processBlock (paddingBuffer, paddingLength);
  4927. processBlock (encodedLength, 8);
  4928. MD5Functions::encode (result, state, 16);
  4929. zerostruct (buffer);
  4930. }
  4931. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4932. {
  4933. using namespace MD5Functions;
  4934. uint32 a = state[0];
  4935. uint32 b = state[1];
  4936. uint32 c = state[2];
  4937. uint32 d = state[3];
  4938. uint32 x[16];
  4939. encode (x, bufferToTransform, 64);
  4940. enum Constants
  4941. {
  4942. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4943. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4944. };
  4945. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4946. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4947. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4948. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4949. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4950. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4951. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4952. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4953. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4954. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4955. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4956. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4957. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4958. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4959. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4960. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4961. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4962. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4963. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4964. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4965. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4966. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4967. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4968. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4969. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4970. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4971. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4972. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4973. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4974. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4975. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4976. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4977. state[0] += a;
  4978. state[1] += b;
  4979. state[2] += c;
  4980. state[3] += d;
  4981. zerostruct (x);
  4982. }
  4983. const MemoryBlock MD5::getRawChecksumData() const
  4984. {
  4985. return MemoryBlock (result, sizeof (result));
  4986. }
  4987. const String MD5::toHexString() const
  4988. {
  4989. return String::toHexString (result, sizeof (result), 0);
  4990. }
  4991. bool MD5::operator== (const MD5& other) const
  4992. {
  4993. return memcmp (result, other.result, sizeof (result)) == 0;
  4994. }
  4995. bool MD5::operator!= (const MD5& other) const
  4996. {
  4997. return ! operator== (other);
  4998. }
  4999. END_JUCE_NAMESPACE
  5000. /*** End of inlined file: juce_MD5.cpp ***/
  5001. /*** Start of inlined file: juce_Primes.cpp ***/
  5002. BEGIN_JUCE_NAMESPACE
  5003. namespace PrimesHelpers
  5004. {
  5005. static void createSmallSieve (const int numBits, BigInteger& result)
  5006. {
  5007. result.setBit (numBits);
  5008. result.clearBit (numBits); // to enlarge the array
  5009. result.setBit (0);
  5010. int n = 2;
  5011. do
  5012. {
  5013. for (int i = n + n; i < numBits; i += n)
  5014. result.setBit (i);
  5015. n = result.findNextClearBit (n + 1);
  5016. }
  5017. while (n <= (numBits >> 1));
  5018. }
  5019. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5020. const BigInteger& smallSieve, const int smallSieveSize)
  5021. {
  5022. jassert (! base[0]); // must be even!
  5023. result.setBit (numBits);
  5024. result.clearBit (numBits); // to enlarge the array
  5025. int index = smallSieve.findNextClearBit (0);
  5026. do
  5027. {
  5028. const int prime = (index << 1) + 1;
  5029. BigInteger r (base), remainder;
  5030. r.divideBy (prime, remainder);
  5031. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5032. if (r.isZero())
  5033. i += prime;
  5034. if ((i & 1) == 0)
  5035. i += prime;
  5036. i = (i - 1) >> 1;
  5037. while (i < numBits)
  5038. {
  5039. result.setBit (i);
  5040. i += prime;
  5041. }
  5042. index = smallSieve.findNextClearBit (index + 1);
  5043. }
  5044. while (index < smallSieveSize);
  5045. }
  5046. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5047. const int numBits, BigInteger& result, const int certainty)
  5048. {
  5049. for (int i = 0; i < numBits; ++i)
  5050. {
  5051. if (! sieve[i])
  5052. {
  5053. result = base + (unsigned int) ((i << 1) + 1);
  5054. if (Primes::isProbablyPrime (result, certainty))
  5055. return true;
  5056. }
  5057. }
  5058. return false;
  5059. }
  5060. static bool passesMillerRabin (const BigInteger& n, int iterations)
  5061. {
  5062. const BigInteger one (1), two (2);
  5063. const BigInteger nMinusOne (n - one);
  5064. BigInteger d (nMinusOne);
  5065. const int s = d.findNextSetBit (0);
  5066. d >>= s;
  5067. BigInteger smallPrimes;
  5068. int numBitsInSmallPrimes = 0;
  5069. for (;;)
  5070. {
  5071. numBitsInSmallPrimes += 256;
  5072. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5073. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5074. if (numPrimesFound > iterations + 1)
  5075. break;
  5076. }
  5077. int smallPrime = 2;
  5078. while (--iterations >= 0)
  5079. {
  5080. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5081. BigInteger r (smallPrime);
  5082. r.exponentModulo (d, n);
  5083. if (r != one && r != nMinusOne)
  5084. {
  5085. for (int j = 0; j < s; ++j)
  5086. {
  5087. r.exponentModulo (two, n);
  5088. if (r == nMinusOne)
  5089. break;
  5090. }
  5091. if (r != nMinusOne)
  5092. return false;
  5093. }
  5094. }
  5095. return true;
  5096. }
  5097. }
  5098. const BigInteger Primes::createProbablePrime (const int bitLength,
  5099. const int certainty,
  5100. const int* randomSeeds,
  5101. int numRandomSeeds)
  5102. {
  5103. using namespace PrimesHelpers;
  5104. int defaultSeeds [16];
  5105. if (numRandomSeeds <= 0)
  5106. {
  5107. randomSeeds = defaultSeeds;
  5108. numRandomSeeds = numElementsInArray (defaultSeeds);
  5109. Random r (0);
  5110. for (int j = 10; --j >= 0;)
  5111. {
  5112. r.setSeedRandomly();
  5113. for (int i = numRandomSeeds; --i >= 0;)
  5114. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5115. }
  5116. }
  5117. BigInteger smallSieve;
  5118. const int smallSieveSize = 15000;
  5119. createSmallSieve (smallSieveSize, smallSieve);
  5120. BigInteger p;
  5121. for (int i = numRandomSeeds; --i >= 0;)
  5122. {
  5123. BigInteger p2;
  5124. Random r (randomSeeds[i]);
  5125. r.fillBitsRandomly (p2, 0, bitLength);
  5126. p ^= p2;
  5127. }
  5128. p.setBit (bitLength - 1);
  5129. p.clearBit (0);
  5130. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5131. while (p.getHighestBit() < bitLength)
  5132. {
  5133. p += 2 * searchLen;
  5134. BigInteger sieve;
  5135. bigSieve (p, searchLen, sieve,
  5136. smallSieve, smallSieveSize);
  5137. BigInteger candidate;
  5138. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5139. return candidate;
  5140. }
  5141. jassertfalse;
  5142. return BigInteger();
  5143. }
  5144. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5145. {
  5146. using namespace PrimesHelpers;
  5147. if (! number[0])
  5148. return false;
  5149. if (number.getHighestBit() <= 10)
  5150. {
  5151. const int num = number.getBitRangeAsInt (0, 10);
  5152. for (int i = num / 2; --i > 1;)
  5153. if (num % i == 0)
  5154. return false;
  5155. return true;
  5156. }
  5157. else
  5158. {
  5159. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5160. return false;
  5161. return passesMillerRabin (number, certainty);
  5162. }
  5163. }
  5164. END_JUCE_NAMESPACE
  5165. /*** End of inlined file: juce_Primes.cpp ***/
  5166. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5167. BEGIN_JUCE_NAMESPACE
  5168. RSAKey::RSAKey()
  5169. {
  5170. }
  5171. RSAKey::RSAKey (const String& s)
  5172. {
  5173. if (s.containsChar (','))
  5174. {
  5175. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5176. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5177. }
  5178. else
  5179. {
  5180. // the string needs to be two hex numbers, comma-separated..
  5181. jassertfalse;
  5182. }
  5183. }
  5184. RSAKey::~RSAKey()
  5185. {
  5186. }
  5187. bool RSAKey::operator== (const RSAKey& other) const throw()
  5188. {
  5189. return part1 == other.part1 && part2 == other.part2;
  5190. }
  5191. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5192. {
  5193. return ! operator== (other);
  5194. }
  5195. const String RSAKey::toString() const
  5196. {
  5197. return part1.toString (16) + "," + part2.toString (16);
  5198. }
  5199. bool RSAKey::applyToValue (BigInteger& value) const
  5200. {
  5201. if (part1.isZero() || part2.isZero() || value <= 0)
  5202. {
  5203. jassertfalse; // using an uninitialised key
  5204. value.clear();
  5205. return false;
  5206. }
  5207. BigInteger result;
  5208. while (! value.isZero())
  5209. {
  5210. result *= part2;
  5211. BigInteger remainder;
  5212. value.divideBy (part2, remainder);
  5213. remainder.exponentModulo (part1, part2);
  5214. result += remainder;
  5215. }
  5216. value.swapWith (result);
  5217. return true;
  5218. }
  5219. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5220. {
  5221. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5222. // are fast to divide + multiply
  5223. for (int i = 2; i <= 65536; i *= 2)
  5224. {
  5225. const BigInteger e (1 + i);
  5226. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5227. return e;
  5228. }
  5229. BigInteger e (4);
  5230. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5231. ++e;
  5232. return e;
  5233. }
  5234. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5235. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5236. {
  5237. jassert (numBits > 16); // not much point using less than this..
  5238. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5239. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5240. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5241. const BigInteger n (p * q);
  5242. const BigInteger m (--p * --q);
  5243. const BigInteger e (findBestCommonDivisor (p, q));
  5244. BigInteger d (e);
  5245. d.inverseModulo (m);
  5246. publicKey.part1 = e;
  5247. publicKey.part2 = n;
  5248. privateKey.part1 = d;
  5249. privateKey.part2 = n;
  5250. }
  5251. END_JUCE_NAMESPACE
  5252. /*** End of inlined file: juce_RSAKey.cpp ***/
  5253. /*** Start of inlined file: juce_InputStream.cpp ***/
  5254. BEGIN_JUCE_NAMESPACE
  5255. char InputStream::readByte()
  5256. {
  5257. char temp = 0;
  5258. read (&temp, 1);
  5259. return temp;
  5260. }
  5261. bool InputStream::readBool()
  5262. {
  5263. return readByte() != 0;
  5264. }
  5265. short InputStream::readShort()
  5266. {
  5267. char temp[2];
  5268. if (read (temp, 2) == 2)
  5269. return (short) ByteOrder::littleEndianShort (temp);
  5270. return 0;
  5271. }
  5272. short InputStream::readShortBigEndian()
  5273. {
  5274. char temp[2];
  5275. if (read (temp, 2) == 2)
  5276. return (short) ByteOrder::bigEndianShort (temp);
  5277. return 0;
  5278. }
  5279. int InputStream::readInt()
  5280. {
  5281. char temp[4];
  5282. if (read (temp, 4) == 4)
  5283. return (int) ByteOrder::littleEndianInt (temp);
  5284. return 0;
  5285. }
  5286. int InputStream::readIntBigEndian()
  5287. {
  5288. char temp[4];
  5289. if (read (temp, 4) == 4)
  5290. return (int) ByteOrder::bigEndianInt (temp);
  5291. return 0;
  5292. }
  5293. int InputStream::readCompressedInt()
  5294. {
  5295. const unsigned char sizeByte = readByte();
  5296. if (sizeByte == 0)
  5297. return 0;
  5298. const int numBytes = (sizeByte & 0x7f);
  5299. if (numBytes > 4)
  5300. {
  5301. jassertfalse; // trying to read corrupt data - this method must only be used
  5302. // to read data that was written by OutputStream::writeCompressedInt()
  5303. return 0;
  5304. }
  5305. char bytes[4] = { 0, 0, 0, 0 };
  5306. if (read (bytes, numBytes) != numBytes)
  5307. return 0;
  5308. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5309. return (sizeByte >> 7) ? -num : num;
  5310. }
  5311. int64 InputStream::readInt64()
  5312. {
  5313. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5314. if (read (n.asBytes, 8) == 8)
  5315. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5316. return 0;
  5317. }
  5318. int64 InputStream::readInt64BigEndian()
  5319. {
  5320. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5321. if (read (n.asBytes, 8) == 8)
  5322. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5323. return 0;
  5324. }
  5325. float InputStream::readFloat()
  5326. {
  5327. // the union below relies on these types being the same size...
  5328. static_jassert (sizeof (int32) == sizeof (float));
  5329. union { int32 asInt; float asFloat; } n;
  5330. n.asInt = (int32) readInt();
  5331. return n.asFloat;
  5332. }
  5333. float InputStream::readFloatBigEndian()
  5334. {
  5335. union { int32 asInt; float asFloat; } n;
  5336. n.asInt = (int32) readIntBigEndian();
  5337. return n.asFloat;
  5338. }
  5339. double InputStream::readDouble()
  5340. {
  5341. union { int64 asInt; double asDouble; } n;
  5342. n.asInt = readInt64();
  5343. return n.asDouble;
  5344. }
  5345. double InputStream::readDoubleBigEndian()
  5346. {
  5347. union { int64 asInt; double asDouble; } n;
  5348. n.asInt = readInt64BigEndian();
  5349. return n.asDouble;
  5350. }
  5351. const String InputStream::readString()
  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 (++i >= buffer.getSize())
  5359. {
  5360. buffer.setSize (buffer.getSize() + 512);
  5361. data = static_cast<char*> (buffer.getData());
  5362. }
  5363. }
  5364. return String::fromUTF8 (data, (int) i);
  5365. }
  5366. const String InputStream::readNextLine()
  5367. {
  5368. MemoryBlock buffer (256);
  5369. char* data = static_cast<char*> (buffer.getData());
  5370. size_t i = 0;
  5371. while ((data[i] = readByte()) != 0)
  5372. {
  5373. if (data[i] == '\n')
  5374. break;
  5375. if (data[i] == '\r')
  5376. {
  5377. const int64 lastPos = getPosition();
  5378. if (readByte() != '\n')
  5379. setPosition (lastPos);
  5380. break;
  5381. }
  5382. if (++i >= buffer.getSize())
  5383. {
  5384. buffer.setSize (buffer.getSize() + 512);
  5385. data = static_cast<char*> (buffer.getData());
  5386. }
  5387. }
  5388. return String::fromUTF8 (data, (int) i);
  5389. }
  5390. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5391. {
  5392. MemoryOutputStream mo (block, true);
  5393. return mo.writeFromInputStream (*this, numBytes);
  5394. }
  5395. const String InputStream::readEntireStreamAsString()
  5396. {
  5397. MemoryOutputStream mo;
  5398. mo.writeFromInputStream (*this, -1);
  5399. return mo.toString();
  5400. }
  5401. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5402. {
  5403. if (numBytesToSkip > 0)
  5404. {
  5405. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5406. HeapBlock<char> temp (skipBufferSize);
  5407. while (numBytesToSkip > 0 && ! isExhausted())
  5408. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5409. }
  5410. }
  5411. END_JUCE_NAMESPACE
  5412. /*** End of inlined file: juce_InputStream.cpp ***/
  5413. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5414. BEGIN_JUCE_NAMESPACE
  5415. #if JUCE_DEBUG
  5416. static Array<void*, CriticalSection> activeStreams;
  5417. void juce_CheckForDanglingStreams()
  5418. {
  5419. /*
  5420. It's always a bad idea to leak any object, but if you're leaking output
  5421. streams, then there's a good chance that you're failing to flush a file
  5422. to disk properly, which could result in corrupted data and other similar
  5423. nastiness..
  5424. */
  5425. jassert (activeStreams.size() == 0);
  5426. };
  5427. #endif
  5428. OutputStream::OutputStream()
  5429. {
  5430. #if JUCE_DEBUG
  5431. activeStreams.add (this);
  5432. #endif
  5433. }
  5434. OutputStream::~OutputStream()
  5435. {
  5436. #if JUCE_DEBUG
  5437. activeStreams.removeValue (this);
  5438. #endif
  5439. }
  5440. void OutputStream::writeBool (const bool b)
  5441. {
  5442. writeByte (b ? (char) 1
  5443. : (char) 0);
  5444. }
  5445. void OutputStream::writeByte (char byte)
  5446. {
  5447. write (&byte, 1);
  5448. }
  5449. void OutputStream::writeShort (short value)
  5450. {
  5451. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5452. write (&v, 2);
  5453. }
  5454. void OutputStream::writeShortBigEndian (short value)
  5455. {
  5456. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5457. write (&v, 2);
  5458. }
  5459. void OutputStream::writeInt (int value)
  5460. {
  5461. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5462. write (&v, 4);
  5463. }
  5464. void OutputStream::writeIntBigEndian (int value)
  5465. {
  5466. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5467. write (&v, 4);
  5468. }
  5469. void OutputStream::writeCompressedInt (int value)
  5470. {
  5471. unsigned int un = (value < 0) ? (unsigned int) -value
  5472. : (unsigned int) value;
  5473. uint8 data[5];
  5474. int num = 0;
  5475. while (un > 0)
  5476. {
  5477. data[++num] = (uint8) un;
  5478. un >>= 8;
  5479. }
  5480. data[0] = (uint8) num;
  5481. if (value < 0)
  5482. data[0] |= 0x80;
  5483. write (data, num + 1);
  5484. }
  5485. void OutputStream::writeInt64 (int64 value)
  5486. {
  5487. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5488. write (&v, 8);
  5489. }
  5490. void OutputStream::writeInt64BigEndian (int64 value)
  5491. {
  5492. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5493. write (&v, 8);
  5494. }
  5495. void OutputStream::writeFloat (float value)
  5496. {
  5497. union { int asInt; float asFloat; } n;
  5498. n.asFloat = value;
  5499. writeInt (n.asInt);
  5500. }
  5501. void OutputStream::writeFloatBigEndian (float value)
  5502. {
  5503. union { int asInt; float asFloat; } n;
  5504. n.asFloat = value;
  5505. writeIntBigEndian (n.asInt);
  5506. }
  5507. void OutputStream::writeDouble (double value)
  5508. {
  5509. union { int64 asInt; double asDouble; } n;
  5510. n.asDouble = value;
  5511. writeInt64 (n.asInt);
  5512. }
  5513. void OutputStream::writeDoubleBigEndian (double value)
  5514. {
  5515. union { int64 asInt; double asDouble; } n;
  5516. n.asDouble = value;
  5517. writeInt64BigEndian (n.asInt);
  5518. }
  5519. void OutputStream::writeString (const String& text)
  5520. {
  5521. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5522. // if lots of large, persistent strings were to be written to streams).
  5523. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5524. HeapBlock<char> temp (numBytes);
  5525. text.copyToUTF8 (temp, numBytes);
  5526. write (temp, numBytes);
  5527. }
  5528. void OutputStream::writeText (const String& text, const bool asUnicode,
  5529. const bool writeUnicodeHeaderBytes)
  5530. {
  5531. if (asUnicode)
  5532. {
  5533. if (writeUnicodeHeaderBytes)
  5534. write ("\x0ff\x0fe", 2);
  5535. const juce_wchar* src = text;
  5536. bool lastCharWasReturn = false;
  5537. while (*src != 0)
  5538. {
  5539. if (*src == L'\n' && ! lastCharWasReturn)
  5540. writeShort ((short) L'\r');
  5541. lastCharWasReturn = (*src == L'\r');
  5542. writeShort ((short) *src++);
  5543. }
  5544. }
  5545. else
  5546. {
  5547. const char* src = text.toUTF8();
  5548. const char* t = src;
  5549. for (;;)
  5550. {
  5551. if (*t == '\n')
  5552. {
  5553. if (t > src)
  5554. write (src, (int) (t - src));
  5555. write ("\r\n", 2);
  5556. src = t + 1;
  5557. }
  5558. else if (*t == '\r')
  5559. {
  5560. if (t[1] == '\n')
  5561. ++t;
  5562. }
  5563. else if (*t == 0)
  5564. {
  5565. if (t > src)
  5566. write (src, (int) (t - src));
  5567. break;
  5568. }
  5569. ++t;
  5570. }
  5571. }
  5572. }
  5573. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5574. {
  5575. if (numBytesToWrite < 0)
  5576. numBytesToWrite = std::numeric_limits<int64>::max();
  5577. int numWritten = 0;
  5578. while (numBytesToWrite > 0 && ! source.isExhausted())
  5579. {
  5580. char buffer [8192];
  5581. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5582. if (num <= 0)
  5583. break;
  5584. write (buffer, num);
  5585. numBytesToWrite -= num;
  5586. numWritten += num;
  5587. }
  5588. return numWritten;
  5589. }
  5590. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5591. {
  5592. return stream << String (number);
  5593. }
  5594. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5595. {
  5596. return stream << String (number);
  5597. }
  5598. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5599. {
  5600. stream.writeByte (character);
  5601. return stream;
  5602. }
  5603. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5604. {
  5605. stream.write (text, (int) strlen (text));
  5606. return stream;
  5607. }
  5608. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5609. {
  5610. stream.write (data.getData(), (int) data.getSize());
  5611. return stream;
  5612. }
  5613. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5614. {
  5615. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5616. if (in != 0)
  5617. stream.writeFromInputStream (*in, -1);
  5618. return stream;
  5619. }
  5620. END_JUCE_NAMESPACE
  5621. /*** End of inlined file: juce_OutputStream.cpp ***/
  5622. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5623. BEGIN_JUCE_NAMESPACE
  5624. DirectoryIterator::DirectoryIterator (const File& directory,
  5625. bool isRecursive_,
  5626. const String& wildCard_,
  5627. const int whatToLookFor_)
  5628. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5629. wildCard (wildCard_),
  5630. path (File::addTrailingSeparator (directory.getFullPathName())),
  5631. index (-1),
  5632. totalNumFiles (-1),
  5633. whatToLookFor (whatToLookFor_),
  5634. isRecursive (isRecursive_),
  5635. hasBeenAdvanced (false)
  5636. {
  5637. // you have to specify the type of files you're looking for!
  5638. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5639. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5640. }
  5641. DirectoryIterator::~DirectoryIterator()
  5642. {
  5643. }
  5644. bool DirectoryIterator::next()
  5645. {
  5646. return next (0, 0, 0, 0, 0, 0);
  5647. }
  5648. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5649. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5650. {
  5651. hasBeenAdvanced = true;
  5652. if (subIterator != 0)
  5653. {
  5654. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5655. return true;
  5656. subIterator = 0;
  5657. }
  5658. String filename;
  5659. bool isDirectory, isHidden;
  5660. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5661. {
  5662. ++index;
  5663. if (! filename.containsOnly ("."))
  5664. {
  5665. const File fileFound (path + filename, 0);
  5666. bool matches = false;
  5667. if (isDirectory)
  5668. {
  5669. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5670. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5671. matches = (whatToLookFor & File::findDirectories) != 0;
  5672. }
  5673. else
  5674. {
  5675. matches = (whatToLookFor & File::findFiles) != 0;
  5676. }
  5677. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5678. if (matches && isRecursive)
  5679. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5680. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5681. matches = ! isHidden;
  5682. if (matches)
  5683. {
  5684. currentFile = fileFound;
  5685. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5686. if (isDirResult != 0) *isDirResult = isDirectory;
  5687. return true;
  5688. }
  5689. else if (subIterator != 0)
  5690. {
  5691. return next();
  5692. }
  5693. }
  5694. }
  5695. return false;
  5696. }
  5697. const File DirectoryIterator::getFile() const
  5698. {
  5699. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5700. return subIterator->getFile();
  5701. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5702. jassert (hasBeenAdvanced);
  5703. return currentFile;
  5704. }
  5705. float DirectoryIterator::getEstimatedProgress() const
  5706. {
  5707. if (totalNumFiles < 0)
  5708. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5709. if (totalNumFiles <= 0)
  5710. return 0.0f;
  5711. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5712. : (float) index;
  5713. return detailedIndex / totalNumFiles;
  5714. }
  5715. END_JUCE_NAMESPACE
  5716. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5717. /*** Start of inlined file: juce_File.cpp ***/
  5718. #if ! JUCE_WINDOWS
  5719. #include <pwd.h>
  5720. #endif
  5721. BEGIN_JUCE_NAMESPACE
  5722. File::File (const String& fullPathName)
  5723. : fullPath (parseAbsolutePath (fullPathName))
  5724. {
  5725. }
  5726. File::File (const String& path, int)
  5727. : fullPath (path)
  5728. {
  5729. }
  5730. const File File::createFileWithoutCheckingPath (const String& path)
  5731. {
  5732. return File (path, 0);
  5733. }
  5734. File::File (const File& other)
  5735. : fullPath (other.fullPath)
  5736. {
  5737. }
  5738. File& File::operator= (const String& newPath)
  5739. {
  5740. fullPath = parseAbsolutePath (newPath);
  5741. return *this;
  5742. }
  5743. File& File::operator= (const File& other)
  5744. {
  5745. fullPath = other.fullPath;
  5746. return *this;
  5747. }
  5748. const File File::nonexistent;
  5749. const String File::parseAbsolutePath (const String& p)
  5750. {
  5751. if (p.isEmpty())
  5752. return String::empty;
  5753. #if JUCE_WINDOWS
  5754. // Windows..
  5755. String path (p.replaceCharacter ('/', '\\'));
  5756. if (path.startsWithChar (File::separator))
  5757. {
  5758. if (path[1] != File::separator)
  5759. {
  5760. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5761. If you're trying to parse a string that may be either a relative path or an absolute path,
  5762. you MUST provide a context against which the partial path can be evaluated - you can do
  5763. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5764. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5765. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5766. */
  5767. jassertfalse;
  5768. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5769. }
  5770. }
  5771. else if (! path.containsChar (':'))
  5772. {
  5773. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5774. If you're trying to parse a string that may be either a relative path or an absolute path,
  5775. you MUST provide a context against which the partial path can be evaluated - you can do
  5776. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5777. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5778. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5779. */
  5780. jassertfalse;
  5781. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5782. }
  5783. #else
  5784. // Mac or Linux..
  5785. String path (p.replaceCharacter ('\\', '/'));
  5786. if (path.startsWithChar ('~'))
  5787. {
  5788. if (path[1] == File::separator || path[1] == 0)
  5789. {
  5790. // expand a name of the form "~/abc"
  5791. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5792. + path.substring (1);
  5793. }
  5794. else
  5795. {
  5796. // expand a name of type "~dave/abc"
  5797. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5798. struct passwd* const pw = getpwnam (userName.toUTF8());
  5799. if (pw != 0)
  5800. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5801. }
  5802. }
  5803. else if (! path.startsWithChar (File::separator))
  5804. {
  5805. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5806. If you're trying to parse a string that may be either a relative path or an absolute path,
  5807. you MUST provide a context against which the partial path can be evaluated - you can do
  5808. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5809. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5810. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5811. */
  5812. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5813. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5814. }
  5815. #endif
  5816. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5817. path = path.dropLastCharacters (1);
  5818. return path;
  5819. }
  5820. const String File::addTrailingSeparator (const String& path)
  5821. {
  5822. return path.endsWithChar (File::separator) ? path
  5823. : path + File::separator;
  5824. }
  5825. #if JUCE_LINUX
  5826. #define NAMES_ARE_CASE_SENSITIVE 1
  5827. #endif
  5828. bool File::areFileNamesCaseSensitive()
  5829. {
  5830. #if NAMES_ARE_CASE_SENSITIVE
  5831. return true;
  5832. #else
  5833. return false;
  5834. #endif
  5835. }
  5836. bool File::operator== (const File& other) const
  5837. {
  5838. #if NAMES_ARE_CASE_SENSITIVE
  5839. return fullPath == other.fullPath;
  5840. #else
  5841. return fullPath.equalsIgnoreCase (other.fullPath);
  5842. #endif
  5843. }
  5844. bool File::operator!= (const File& other) const
  5845. {
  5846. return ! operator== (other);
  5847. }
  5848. bool File::operator< (const File& other) const
  5849. {
  5850. #if NAMES_ARE_CASE_SENSITIVE
  5851. return fullPath < other.fullPath;
  5852. #else
  5853. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5854. #endif
  5855. }
  5856. bool File::operator> (const File& other) const
  5857. {
  5858. #if NAMES_ARE_CASE_SENSITIVE
  5859. return fullPath > other.fullPath;
  5860. #else
  5861. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5862. #endif
  5863. }
  5864. bool File::setReadOnly (const bool shouldBeReadOnly,
  5865. const bool applyRecursively) const
  5866. {
  5867. bool worked = true;
  5868. if (applyRecursively && isDirectory())
  5869. {
  5870. Array <File> subFiles;
  5871. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5872. for (int i = subFiles.size(); --i >= 0;)
  5873. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5874. }
  5875. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5876. }
  5877. bool File::deleteRecursively() const
  5878. {
  5879. bool worked = true;
  5880. if (isDirectory())
  5881. {
  5882. Array<File> subFiles;
  5883. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5884. for (int i = subFiles.size(); --i >= 0;)
  5885. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5886. }
  5887. return deleteFile() && worked;
  5888. }
  5889. bool File::moveFileTo (const File& newFile) const
  5890. {
  5891. if (newFile.fullPath == fullPath)
  5892. return true;
  5893. #if ! NAMES_ARE_CASE_SENSITIVE
  5894. if (*this != newFile)
  5895. #endif
  5896. if (! newFile.deleteFile())
  5897. return false;
  5898. return moveInternal (newFile);
  5899. }
  5900. bool File::copyFileTo (const File& newFile) const
  5901. {
  5902. return (*this == newFile)
  5903. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5904. }
  5905. bool File::copyDirectoryTo (const File& newDirectory) const
  5906. {
  5907. if (isDirectory() && newDirectory.createDirectory())
  5908. {
  5909. Array<File> subFiles;
  5910. findChildFiles (subFiles, File::findFiles, false);
  5911. int i;
  5912. for (i = 0; i < subFiles.size(); ++i)
  5913. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5914. return false;
  5915. subFiles.clear();
  5916. findChildFiles (subFiles, File::findDirectories, false);
  5917. for (i = 0; i < subFiles.size(); ++i)
  5918. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5919. return false;
  5920. return true;
  5921. }
  5922. return false;
  5923. }
  5924. const String File::getPathUpToLastSlash() const
  5925. {
  5926. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5927. if (lastSlash > 0)
  5928. return fullPath.substring (0, lastSlash);
  5929. else if (lastSlash == 0)
  5930. return separatorString;
  5931. else
  5932. return fullPath;
  5933. }
  5934. const File File::getParentDirectory() const
  5935. {
  5936. return File (getPathUpToLastSlash(), (int) 0);
  5937. }
  5938. const String File::getFileName() const
  5939. {
  5940. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5941. }
  5942. int File::hashCode() const
  5943. {
  5944. return fullPath.hashCode();
  5945. }
  5946. int64 File::hashCode64() const
  5947. {
  5948. return fullPath.hashCode64();
  5949. }
  5950. const String File::getFileNameWithoutExtension() const
  5951. {
  5952. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5953. const int lastDot = fullPath.lastIndexOfChar ('.');
  5954. if (lastDot > lastSlash)
  5955. return fullPath.substring (lastSlash, lastDot);
  5956. else
  5957. return fullPath.substring (lastSlash);
  5958. }
  5959. bool File::isAChildOf (const File& potentialParent) const
  5960. {
  5961. if (potentialParent == File::nonexistent)
  5962. return false;
  5963. const String ourPath (getPathUpToLastSlash());
  5964. #if NAMES_ARE_CASE_SENSITIVE
  5965. if (potentialParent.fullPath == ourPath)
  5966. #else
  5967. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5968. #endif
  5969. {
  5970. return true;
  5971. }
  5972. else if (potentialParent.fullPath.length() >= ourPath.length())
  5973. {
  5974. return false;
  5975. }
  5976. else
  5977. {
  5978. return getParentDirectory().isAChildOf (potentialParent);
  5979. }
  5980. }
  5981. bool File::isAbsolutePath (const String& path)
  5982. {
  5983. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5984. #if JUCE_WINDOWS
  5985. || (path.isNotEmpty() && path[1] == ':');
  5986. #else
  5987. || path.startsWithChar ('~');
  5988. #endif
  5989. }
  5990. const File File::getChildFile (String relativePath) const
  5991. {
  5992. if (isAbsolutePath (relativePath))
  5993. {
  5994. // the path is really absolute..
  5995. return File (relativePath);
  5996. }
  5997. else
  5998. {
  5999. // it's relative, so remove any ../ or ./ bits at the start.
  6000. String path (fullPath);
  6001. if (relativePath[0] == '.')
  6002. {
  6003. #if JUCE_WINDOWS
  6004. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6005. #else
  6006. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6007. #endif
  6008. while (relativePath[0] == '.')
  6009. {
  6010. if (relativePath[1] == '.')
  6011. {
  6012. if (relativePath [2] == 0 || relativePath[2] == separator)
  6013. {
  6014. const int lastSlash = path.lastIndexOfChar (separator);
  6015. if (lastSlash >= 0)
  6016. path = path.substring (0, lastSlash);
  6017. relativePath = relativePath.substring (3);
  6018. }
  6019. else
  6020. {
  6021. break;
  6022. }
  6023. }
  6024. else if (relativePath[1] == separator)
  6025. {
  6026. relativePath = relativePath.substring (2);
  6027. }
  6028. else
  6029. {
  6030. break;
  6031. }
  6032. }
  6033. }
  6034. return File (addTrailingSeparator (path) + relativePath);
  6035. }
  6036. }
  6037. const File File::getSiblingFile (const String& fileName) const
  6038. {
  6039. return getParentDirectory().getChildFile (fileName);
  6040. }
  6041. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6042. {
  6043. if (bytes == 1)
  6044. {
  6045. return "1 byte";
  6046. }
  6047. else if (bytes < 1024)
  6048. {
  6049. return String ((int) bytes) + " bytes";
  6050. }
  6051. else if (bytes < 1024 * 1024)
  6052. {
  6053. return String (bytes / 1024.0, 1) + " KB";
  6054. }
  6055. else if (bytes < 1024 * 1024 * 1024)
  6056. {
  6057. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6058. }
  6059. else
  6060. {
  6061. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6062. }
  6063. }
  6064. bool File::create() const
  6065. {
  6066. if (exists())
  6067. return true;
  6068. {
  6069. const File parentDir (getParentDirectory());
  6070. if (parentDir == *this || ! parentDir.createDirectory())
  6071. return false;
  6072. FileOutputStream fo (*this, 8);
  6073. }
  6074. return exists();
  6075. }
  6076. bool File::createDirectory() const
  6077. {
  6078. if (! isDirectory())
  6079. {
  6080. const File parentDir (getParentDirectory());
  6081. if (parentDir == *this || ! parentDir.createDirectory())
  6082. return false;
  6083. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6084. return isDirectory();
  6085. }
  6086. return true;
  6087. }
  6088. const Time File::getCreationTime() const
  6089. {
  6090. int64 m, a, c;
  6091. getFileTimesInternal (m, a, c);
  6092. return Time (c);
  6093. }
  6094. const Time File::getLastModificationTime() const
  6095. {
  6096. int64 m, a, c;
  6097. getFileTimesInternal (m, a, c);
  6098. return Time (m);
  6099. }
  6100. const Time File::getLastAccessTime() const
  6101. {
  6102. int64 m, a, c;
  6103. getFileTimesInternal (m, a, c);
  6104. return Time (a);
  6105. }
  6106. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6107. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6108. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6109. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6110. {
  6111. if (! existsAsFile())
  6112. return false;
  6113. FileInputStream in (*this);
  6114. return getSize() == in.readIntoMemoryBlock (destBlock);
  6115. }
  6116. const String File::loadFileAsString() const
  6117. {
  6118. if (! existsAsFile())
  6119. return String::empty;
  6120. FileInputStream in (*this);
  6121. return in.readEntireStreamAsString();
  6122. }
  6123. int File::findChildFiles (Array<File>& results,
  6124. const int whatToLookFor,
  6125. const bool searchRecursively,
  6126. const String& wildCardPattern) const
  6127. {
  6128. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6129. int total = 0;
  6130. while (di.next())
  6131. {
  6132. results.add (di.getFile());
  6133. ++total;
  6134. }
  6135. return total;
  6136. }
  6137. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6138. {
  6139. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6140. int total = 0;
  6141. while (di.next())
  6142. ++total;
  6143. return total;
  6144. }
  6145. bool File::containsSubDirectories() const
  6146. {
  6147. if (isDirectory())
  6148. {
  6149. DirectoryIterator di (*this, false, "*", findDirectories);
  6150. return di.next();
  6151. }
  6152. return false;
  6153. }
  6154. const File File::getNonexistentChildFile (const String& prefix_,
  6155. const String& suffix,
  6156. bool putNumbersInBrackets) const
  6157. {
  6158. File f (getChildFile (prefix_ + suffix));
  6159. if (f.exists())
  6160. {
  6161. int num = 2;
  6162. String prefix (prefix_);
  6163. // remove any bracketed numbers that may already be on the end..
  6164. if (prefix.trim().endsWithChar (')'))
  6165. {
  6166. putNumbersInBrackets = true;
  6167. const int openBracks = prefix.lastIndexOfChar ('(');
  6168. const int closeBracks = prefix.lastIndexOfChar (')');
  6169. if (openBracks > 0
  6170. && closeBracks > openBracks
  6171. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6172. {
  6173. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6174. prefix = prefix.substring (0, openBracks);
  6175. }
  6176. }
  6177. // also use brackets if it ends in a digit.
  6178. putNumbersInBrackets = putNumbersInBrackets
  6179. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6180. do
  6181. {
  6182. if (putNumbersInBrackets)
  6183. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6184. else
  6185. f = getChildFile (prefix + String (num++) + suffix);
  6186. } while (f.exists());
  6187. }
  6188. return f;
  6189. }
  6190. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6191. {
  6192. if (exists())
  6193. {
  6194. return getParentDirectory()
  6195. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6196. getFileExtension(),
  6197. putNumbersInBrackets);
  6198. }
  6199. else
  6200. {
  6201. return *this;
  6202. }
  6203. }
  6204. const String File::getFileExtension() const
  6205. {
  6206. String ext;
  6207. if (! isDirectory())
  6208. {
  6209. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6210. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6211. ext = fullPath.substring (indexOfDot);
  6212. }
  6213. return ext;
  6214. }
  6215. bool File::hasFileExtension (const String& possibleSuffix) const
  6216. {
  6217. if (possibleSuffix.isEmpty())
  6218. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6219. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6220. if (semicolon >= 0)
  6221. {
  6222. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6223. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6224. }
  6225. else
  6226. {
  6227. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6228. {
  6229. if (possibleSuffix.startsWithChar ('.'))
  6230. return true;
  6231. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6232. if (dotPos >= 0)
  6233. return fullPath [dotPos] == '.';
  6234. }
  6235. }
  6236. return false;
  6237. }
  6238. const File File::withFileExtension (const String& newExtension) const
  6239. {
  6240. if (fullPath.isEmpty())
  6241. return File::nonexistent;
  6242. String filePart (getFileName());
  6243. int i = filePart.lastIndexOfChar ('.');
  6244. if (i >= 0)
  6245. filePart = filePart.substring (0, i);
  6246. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6247. filePart << '.';
  6248. return getSiblingFile (filePart + newExtension);
  6249. }
  6250. bool File::startAsProcess (const String& parameters) const
  6251. {
  6252. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6253. }
  6254. FileInputStream* File::createInputStream() const
  6255. {
  6256. if (existsAsFile())
  6257. return new FileInputStream (*this);
  6258. return 0;
  6259. }
  6260. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6261. {
  6262. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6263. if (out->failedToOpen())
  6264. return 0;
  6265. return out.release();
  6266. }
  6267. bool File::appendData (const void* const dataToAppend,
  6268. const int numberOfBytes) const
  6269. {
  6270. if (numberOfBytes > 0)
  6271. {
  6272. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6273. if (out == 0)
  6274. return false;
  6275. out->write (dataToAppend, numberOfBytes);
  6276. }
  6277. return true;
  6278. }
  6279. bool File::replaceWithData (const void* const dataToWrite,
  6280. const int numberOfBytes) const
  6281. {
  6282. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6283. if (numberOfBytes <= 0)
  6284. return deleteFile();
  6285. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6286. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6287. return tempFile.overwriteTargetFileWithTemporary();
  6288. }
  6289. bool File::appendText (const String& text,
  6290. const bool asUnicode,
  6291. const bool writeUnicodeHeaderBytes) const
  6292. {
  6293. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6294. if (out != 0)
  6295. {
  6296. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6297. return true;
  6298. }
  6299. return false;
  6300. }
  6301. bool File::replaceWithText (const String& textToWrite,
  6302. const bool asUnicode,
  6303. const bool writeUnicodeHeaderBytes) const
  6304. {
  6305. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6306. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6307. return tempFile.overwriteTargetFileWithTemporary();
  6308. }
  6309. bool File::hasIdenticalContentTo (const File& other) const
  6310. {
  6311. if (other == *this)
  6312. return true;
  6313. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6314. {
  6315. FileInputStream in1 (*this), in2 (other);
  6316. const int bufferSize = 4096;
  6317. HeapBlock <char> buffer1, buffer2;
  6318. buffer1.malloc (bufferSize);
  6319. buffer2.malloc (bufferSize);
  6320. for (;;)
  6321. {
  6322. const int num1 = in1.read (buffer1, bufferSize);
  6323. const int num2 = in2.read (buffer2, bufferSize);
  6324. if (num1 != num2)
  6325. break;
  6326. if (num1 <= 0)
  6327. return true;
  6328. if (memcmp (buffer1, buffer2, num1) != 0)
  6329. break;
  6330. }
  6331. }
  6332. return false;
  6333. }
  6334. const String File::createLegalPathName (const String& original)
  6335. {
  6336. String s (original);
  6337. String start;
  6338. if (s[1] == ':')
  6339. {
  6340. start = s.substring (0, 2);
  6341. s = s.substring (2);
  6342. }
  6343. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6344. .substring (0, 1024);
  6345. }
  6346. const String File::createLegalFileName (const String& original)
  6347. {
  6348. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6349. const int maxLength = 128; // only the length of the filename, not the whole path
  6350. const int len = s.length();
  6351. if (len > maxLength)
  6352. {
  6353. const int lastDot = s.lastIndexOfChar ('.');
  6354. if (lastDot > jmax (0, len - 12))
  6355. {
  6356. s = s.substring (0, maxLength - (len - lastDot))
  6357. + s.substring (lastDot);
  6358. }
  6359. else
  6360. {
  6361. s = s.substring (0, maxLength);
  6362. }
  6363. }
  6364. return s;
  6365. }
  6366. const String File::getRelativePathFrom (const File& dir) const
  6367. {
  6368. String thisPath (fullPath);
  6369. {
  6370. int len = thisPath.length();
  6371. while (--len >= 0 && thisPath [len] == File::separator)
  6372. thisPath [len] = 0;
  6373. }
  6374. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6375. : dir.fullPath));
  6376. const int len = jmin (thisPath.length(), dirPath.length());
  6377. int commonBitLength = 0;
  6378. for (int i = 0; i < len; ++i)
  6379. {
  6380. #if NAMES_ARE_CASE_SENSITIVE
  6381. if (thisPath[i] != dirPath[i])
  6382. #else
  6383. if (CharacterFunctions::toLowerCase (thisPath[i])
  6384. != CharacterFunctions::toLowerCase (dirPath[i]))
  6385. #endif
  6386. {
  6387. break;
  6388. }
  6389. ++commonBitLength;
  6390. }
  6391. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6392. --commonBitLength;
  6393. // if the only common bit is the root, then just return the full path..
  6394. if (commonBitLength <= 0
  6395. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6396. return fullPath;
  6397. thisPath = thisPath.substring (commonBitLength);
  6398. dirPath = dirPath.substring (commonBitLength);
  6399. while (dirPath.isNotEmpty())
  6400. {
  6401. #if JUCE_WINDOWS
  6402. thisPath = "..\\" + thisPath;
  6403. #else
  6404. thisPath = "../" + thisPath;
  6405. #endif
  6406. const int sep = dirPath.indexOfChar (separator);
  6407. if (sep >= 0)
  6408. dirPath = dirPath.substring (sep + 1);
  6409. else
  6410. dirPath = String::empty;
  6411. }
  6412. return thisPath;
  6413. }
  6414. const File File::createTempFile (const String& fileNameEnding)
  6415. {
  6416. const File tempFile (getSpecialLocation (tempDirectory)
  6417. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6418. .withFileExtension (fileNameEnding));
  6419. if (tempFile.exists())
  6420. return createTempFile (fileNameEnding);
  6421. else
  6422. return tempFile;
  6423. }
  6424. #if JUCE_UNIT_TESTS
  6425. class FileTests : public UnitTest
  6426. {
  6427. public:
  6428. FileTests() : UnitTest ("Files") {}
  6429. void runTest()
  6430. {
  6431. beginTest ("Reading");
  6432. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6433. const File temp (File::getSpecialLocation (File::tempDirectory));
  6434. expect (! File::nonexistent.exists());
  6435. expect (home.isDirectory());
  6436. expect (home.exists());
  6437. expect (! home.existsAsFile());
  6438. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6439. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6440. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6441. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6442. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6443. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6444. expect (home.getBytesFreeOnVolume() > 0);
  6445. expect (! home.isHidden());
  6446. expect (home.isOnHardDisk());
  6447. expect (! home.isOnCDRomDrive());
  6448. expect (File::getCurrentWorkingDirectory().exists());
  6449. expect (home.setAsCurrentWorkingDirectory());
  6450. expect (File::getCurrentWorkingDirectory() == home);
  6451. {
  6452. Array<File> roots;
  6453. File::findFileSystemRoots (roots);
  6454. expect (roots.size() > 0);
  6455. int numRootsExisting = 0;
  6456. for (int i = 0; i < roots.size(); ++i)
  6457. if (roots[i].exists())
  6458. ++numRootsExisting;
  6459. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6460. expect (numRootsExisting > 0);
  6461. }
  6462. beginTest ("Writing");
  6463. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6464. expect (demoFolder.deleteRecursively());
  6465. expect (demoFolder.createDirectory());
  6466. expect (demoFolder.isDirectory());
  6467. expect (demoFolder.getParentDirectory() == temp);
  6468. expect (temp.isDirectory());
  6469. {
  6470. Array<File> files;
  6471. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6472. expect (files.contains (demoFolder));
  6473. }
  6474. {
  6475. Array<File> files;
  6476. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6477. expect (files.contains (demoFolder));
  6478. }
  6479. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6480. expect (tempFile.getFileExtension() == ".txt");
  6481. expect (tempFile.hasFileExtension (".txt"));
  6482. expect (tempFile.hasFileExtension ("txt"));
  6483. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6484. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6485. expect (tempFile.hasWriteAccess());
  6486. {
  6487. FileOutputStream fo (tempFile);
  6488. fo.write ("0123456789", 10);
  6489. }
  6490. expect (tempFile.exists());
  6491. expect (tempFile.getSize() == 10);
  6492. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6493. expect (tempFile.loadFileAsString() == "0123456789");
  6494. expect (! demoFolder.containsSubDirectories());
  6495. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6496. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6497. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6498. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6499. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6500. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6501. expect (demoFolder.containsSubDirectories());
  6502. expect (tempFile.hasWriteAccess());
  6503. tempFile.setReadOnly (true);
  6504. expect (! tempFile.hasWriteAccess());
  6505. tempFile.setReadOnly (false);
  6506. expect (tempFile.hasWriteAccess());
  6507. Time t (Time::getCurrentTime());
  6508. tempFile.setLastModificationTime (t);
  6509. Time t2 = tempFile.getLastModificationTime();
  6510. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6511. {
  6512. MemoryBlock mb;
  6513. tempFile.loadFileAsData (mb);
  6514. expect (mb.getSize() == 10);
  6515. expect (mb[0] == '0');
  6516. }
  6517. expect (tempFile.appendData ("abcdefghij", 10));
  6518. expect (tempFile.getSize() == 20);
  6519. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6520. expect (tempFile.getSize() == 10);
  6521. File tempFile2 (tempFile.getNonexistentSibling (false));
  6522. expect (tempFile.copyFileTo (tempFile2));
  6523. expect (tempFile2.exists());
  6524. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6525. expect (tempFile.deleteFile());
  6526. expect (! tempFile.exists());
  6527. expect (tempFile2.moveFileTo (tempFile));
  6528. expect (tempFile.exists());
  6529. expect (! tempFile2.exists());
  6530. expect (demoFolder.deleteRecursively());
  6531. expect (! demoFolder.exists());
  6532. }
  6533. };
  6534. static FileTests fileUnitTests;
  6535. #endif
  6536. END_JUCE_NAMESPACE
  6537. /*** End of inlined file: juce_File.cpp ***/
  6538. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6539. BEGIN_JUCE_NAMESPACE
  6540. int64 juce_fileSetPosition (void* handle, int64 pos);
  6541. FileInputStream::FileInputStream (const File& f)
  6542. : file (f),
  6543. fileHandle (0),
  6544. currentPosition (0),
  6545. totalSize (0),
  6546. needToSeek (true)
  6547. {
  6548. openHandle();
  6549. }
  6550. FileInputStream::~FileInputStream()
  6551. {
  6552. closeHandle();
  6553. }
  6554. int64 FileInputStream::getTotalLength()
  6555. {
  6556. return totalSize;
  6557. }
  6558. int FileInputStream::read (void* buffer, int bytesToRead)
  6559. {
  6560. int num = 0;
  6561. if (needToSeek)
  6562. {
  6563. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6564. return 0;
  6565. needToSeek = false;
  6566. }
  6567. num = readInternal (buffer, bytesToRead);
  6568. currentPosition += num;
  6569. return num;
  6570. }
  6571. bool FileInputStream::isExhausted()
  6572. {
  6573. return currentPosition >= totalSize;
  6574. }
  6575. int64 FileInputStream::getPosition()
  6576. {
  6577. return currentPosition;
  6578. }
  6579. bool FileInputStream::setPosition (int64 pos)
  6580. {
  6581. pos = jlimit ((int64) 0, totalSize, pos);
  6582. needToSeek |= (currentPosition != pos);
  6583. currentPosition = pos;
  6584. return true;
  6585. }
  6586. END_JUCE_NAMESPACE
  6587. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6588. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6589. BEGIN_JUCE_NAMESPACE
  6590. int64 juce_fileSetPosition (void* handle, int64 pos);
  6591. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6592. : file (f),
  6593. fileHandle (0),
  6594. currentPosition (0),
  6595. bufferSize (bufferSize_),
  6596. bytesInBuffer (0),
  6597. buffer (jmax (bufferSize_, 16))
  6598. {
  6599. openHandle();
  6600. }
  6601. FileOutputStream::~FileOutputStream()
  6602. {
  6603. flush();
  6604. closeHandle();
  6605. }
  6606. int64 FileOutputStream::getPosition()
  6607. {
  6608. return currentPosition;
  6609. }
  6610. bool FileOutputStream::setPosition (int64 newPosition)
  6611. {
  6612. if (newPosition != currentPosition)
  6613. {
  6614. flush();
  6615. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6616. }
  6617. return newPosition == currentPosition;
  6618. }
  6619. void FileOutputStream::flush()
  6620. {
  6621. if (bytesInBuffer > 0)
  6622. {
  6623. writeInternal (buffer, bytesInBuffer);
  6624. bytesInBuffer = 0;
  6625. }
  6626. flushInternal();
  6627. }
  6628. bool FileOutputStream::write (const void* const src, const int numBytes)
  6629. {
  6630. if (bytesInBuffer + numBytes < bufferSize)
  6631. {
  6632. memcpy (buffer + bytesInBuffer, src, numBytes);
  6633. bytesInBuffer += numBytes;
  6634. currentPosition += numBytes;
  6635. }
  6636. else
  6637. {
  6638. if (bytesInBuffer > 0)
  6639. {
  6640. // flush the reservoir
  6641. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6642. bytesInBuffer = 0;
  6643. if (! wroteOk)
  6644. return false;
  6645. }
  6646. if (numBytes < bufferSize)
  6647. {
  6648. memcpy (buffer + bytesInBuffer, src, numBytes);
  6649. bytesInBuffer += numBytes;
  6650. currentPosition += numBytes;
  6651. }
  6652. else
  6653. {
  6654. const int bytesWritten = writeInternal (src, numBytes);
  6655. if (bytesWritten < 0)
  6656. return false;
  6657. currentPosition += bytesWritten;
  6658. return bytesWritten == numBytes;
  6659. }
  6660. }
  6661. return true;
  6662. }
  6663. END_JUCE_NAMESPACE
  6664. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6665. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6666. BEGIN_JUCE_NAMESPACE
  6667. FileSearchPath::FileSearchPath()
  6668. {
  6669. }
  6670. FileSearchPath::FileSearchPath (const String& path)
  6671. {
  6672. init (path);
  6673. }
  6674. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6675. : directories (other.directories)
  6676. {
  6677. }
  6678. FileSearchPath::~FileSearchPath()
  6679. {
  6680. }
  6681. FileSearchPath& FileSearchPath::operator= (const String& path)
  6682. {
  6683. init (path);
  6684. return *this;
  6685. }
  6686. void FileSearchPath::init (const String& path)
  6687. {
  6688. directories.clear();
  6689. directories.addTokens (path, ";", "\"");
  6690. directories.trim();
  6691. directories.removeEmptyStrings();
  6692. for (int i = directories.size(); --i >= 0;)
  6693. directories.set (i, directories[i].unquoted());
  6694. }
  6695. int FileSearchPath::getNumPaths() const
  6696. {
  6697. return directories.size();
  6698. }
  6699. const File FileSearchPath::operator[] (const int index) const
  6700. {
  6701. return File (directories [index]);
  6702. }
  6703. const String FileSearchPath::toString() const
  6704. {
  6705. StringArray directories2 (directories);
  6706. for (int i = directories2.size(); --i >= 0;)
  6707. if (directories2[i].containsChar (';'))
  6708. directories2.set (i, directories2[i].quoted());
  6709. return directories2.joinIntoString (";");
  6710. }
  6711. void FileSearchPath::add (const File& dir, const int insertIndex)
  6712. {
  6713. directories.insert (insertIndex, dir.getFullPathName());
  6714. }
  6715. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6716. {
  6717. for (int i = 0; i < directories.size(); ++i)
  6718. if (File (directories[i]) == dir)
  6719. return;
  6720. add (dir);
  6721. }
  6722. void FileSearchPath::remove (const int index)
  6723. {
  6724. directories.remove (index);
  6725. }
  6726. void FileSearchPath::addPath (const FileSearchPath& other)
  6727. {
  6728. for (int i = 0; i < other.getNumPaths(); ++i)
  6729. addIfNotAlreadyThere (other[i]);
  6730. }
  6731. void FileSearchPath::removeRedundantPaths()
  6732. {
  6733. for (int i = directories.size(); --i >= 0;)
  6734. {
  6735. const File d1 (directories[i]);
  6736. for (int j = directories.size(); --j >= 0;)
  6737. {
  6738. const File d2 (directories[j]);
  6739. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6740. {
  6741. directories.remove (i);
  6742. break;
  6743. }
  6744. }
  6745. }
  6746. }
  6747. void FileSearchPath::removeNonExistentPaths()
  6748. {
  6749. for (int i = directories.size(); --i >= 0;)
  6750. if (! File (directories[i]).isDirectory())
  6751. directories.remove (i);
  6752. }
  6753. int FileSearchPath::findChildFiles (Array<File>& results,
  6754. const int whatToLookFor,
  6755. const bool searchRecursively,
  6756. const String& wildCardPattern) const
  6757. {
  6758. int total = 0;
  6759. for (int i = 0; i < directories.size(); ++i)
  6760. total += operator[] (i).findChildFiles (results,
  6761. whatToLookFor,
  6762. searchRecursively,
  6763. wildCardPattern);
  6764. return total;
  6765. }
  6766. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6767. const bool checkRecursively) const
  6768. {
  6769. for (int i = directories.size(); --i >= 0;)
  6770. {
  6771. const File d (directories[i]);
  6772. if (checkRecursively)
  6773. {
  6774. if (fileToCheck.isAChildOf (d))
  6775. return true;
  6776. }
  6777. else
  6778. {
  6779. if (fileToCheck.getParentDirectory() == d)
  6780. return true;
  6781. }
  6782. }
  6783. return false;
  6784. }
  6785. END_JUCE_NAMESPACE
  6786. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6787. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6788. BEGIN_JUCE_NAMESPACE
  6789. NamedPipe::NamedPipe()
  6790. : internal (0)
  6791. {
  6792. }
  6793. NamedPipe::~NamedPipe()
  6794. {
  6795. close();
  6796. }
  6797. bool NamedPipe::openExisting (const String& pipeName)
  6798. {
  6799. currentPipeName = pipeName;
  6800. return openInternal (pipeName, false);
  6801. }
  6802. bool NamedPipe::createNewPipe (const String& pipeName)
  6803. {
  6804. currentPipeName = pipeName;
  6805. return openInternal (pipeName, true);
  6806. }
  6807. bool NamedPipe::isOpen() const
  6808. {
  6809. return internal != 0;
  6810. }
  6811. const String NamedPipe::getName() const
  6812. {
  6813. return currentPipeName;
  6814. }
  6815. // other methods for this class are implemented in the platform-specific files
  6816. END_JUCE_NAMESPACE
  6817. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6818. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6819. BEGIN_JUCE_NAMESPACE
  6820. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6821. {
  6822. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6823. "temp_" + String (Random::getSystemRandom().nextInt()),
  6824. suffix,
  6825. optionFlags);
  6826. }
  6827. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6828. : targetFile (targetFile_)
  6829. {
  6830. // If you use this constructor, you need to give it a valid target file!
  6831. jassert (targetFile != File::nonexistent);
  6832. createTempFile (targetFile.getParentDirectory(),
  6833. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6834. targetFile.getFileExtension(),
  6835. optionFlags);
  6836. }
  6837. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6838. const String& suffix, const int optionFlags)
  6839. {
  6840. if ((optionFlags & useHiddenFile) != 0)
  6841. name = "." + name;
  6842. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6843. }
  6844. TemporaryFile::~TemporaryFile()
  6845. {
  6846. if (! deleteTemporaryFile())
  6847. {
  6848. /* Failed to delete our temporary file! The most likely reason for this would be
  6849. that you've not closed an output stream that was being used to write to file.
  6850. If you find that something beyond your control is changing permissions on
  6851. your temporary files and preventing them from being deleted, you may want to
  6852. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6853. handle them appropriately.
  6854. */
  6855. jassertfalse;
  6856. }
  6857. }
  6858. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6859. {
  6860. // This method only works if you created this object with the constructor
  6861. // that takes a target file!
  6862. jassert (targetFile != File::nonexistent);
  6863. if (temporaryFile.exists())
  6864. {
  6865. // Have a few attempts at overwriting the file before giving up..
  6866. for (int i = 5; --i >= 0;)
  6867. {
  6868. if (temporaryFile.moveFileTo (targetFile))
  6869. return true;
  6870. Thread::sleep (100);
  6871. }
  6872. }
  6873. else
  6874. {
  6875. // There's no temporary file to use. If your write failed, you should
  6876. // probably check, and not bother calling this method.
  6877. jassertfalse;
  6878. }
  6879. return false;
  6880. }
  6881. bool TemporaryFile::deleteTemporaryFile() const
  6882. {
  6883. // Have a few attempts at deleting the file before giving up..
  6884. for (int i = 5; --i >= 0;)
  6885. {
  6886. if (temporaryFile.deleteFile())
  6887. return true;
  6888. Thread::sleep (50);
  6889. }
  6890. return false;
  6891. }
  6892. END_JUCE_NAMESPACE
  6893. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6894. /*** Start of inlined file: juce_Socket.cpp ***/
  6895. #if JUCE_WINDOWS
  6896. #include <winsock2.h>
  6897. #if JUCE_MSVC
  6898. #pragma warning (push)
  6899. #pragma warning (disable : 4127 4389 4018)
  6900. #endif
  6901. #else
  6902. #if JUCE_LINUX
  6903. #include <sys/types.h>
  6904. #include <sys/socket.h>
  6905. #include <sys/errno.h>
  6906. #include <unistd.h>
  6907. #include <netinet/in.h>
  6908. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6909. #include <CoreServices/CoreServices.h>
  6910. #endif
  6911. #include <fcntl.h>
  6912. #include <netdb.h>
  6913. #include <arpa/inet.h>
  6914. #include <netinet/tcp.h>
  6915. #endif
  6916. BEGIN_JUCE_NAMESPACE
  6917. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6918. typedef socklen_t juce_socklen_t;
  6919. #else
  6920. typedef int juce_socklen_t;
  6921. #endif
  6922. #if JUCE_WINDOWS
  6923. namespace SocketHelpers
  6924. {
  6925. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6926. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6927. }
  6928. static void initWin32Sockets()
  6929. {
  6930. static CriticalSection lock;
  6931. const ScopedLock sl (lock);
  6932. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6933. {
  6934. WSADATA wsaData;
  6935. const WORD wVersionRequested = MAKEWORD (1, 1);
  6936. WSAStartup (wVersionRequested, &wsaData);
  6937. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6938. }
  6939. }
  6940. void juce_shutdownWin32Sockets()
  6941. {
  6942. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6943. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6944. }
  6945. #endif
  6946. namespace SocketHelpers
  6947. {
  6948. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6949. {
  6950. const int sndBufSize = 65536;
  6951. const int rcvBufSize = 65536;
  6952. const int one = 1;
  6953. return handle > 0
  6954. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6955. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6956. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6957. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6958. }
  6959. static bool bindSocketToPort (const int handle, const int port) throw()
  6960. {
  6961. if (handle <= 0 || port <= 0)
  6962. return false;
  6963. struct sockaddr_in servTmpAddr;
  6964. zerostruct (servTmpAddr);
  6965. servTmpAddr.sin_family = PF_INET;
  6966. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6967. servTmpAddr.sin_port = htons ((uint16) port);
  6968. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6969. }
  6970. static int readSocket (const int handle,
  6971. void* const destBuffer, const int maxBytesToRead,
  6972. bool volatile& connected,
  6973. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6974. {
  6975. int bytesRead = 0;
  6976. while (bytesRead < maxBytesToRead)
  6977. {
  6978. int bytesThisTime;
  6979. #if JUCE_WINDOWS
  6980. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6981. #else
  6982. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6983. && errno == EINTR
  6984. && connected)
  6985. {
  6986. }
  6987. #endif
  6988. if (bytesThisTime <= 0 || ! connected)
  6989. {
  6990. if (bytesRead == 0)
  6991. bytesRead = -1;
  6992. break;
  6993. }
  6994. bytesRead += bytesThisTime;
  6995. if (! blockUntilSpecifiedAmountHasArrived)
  6996. break;
  6997. }
  6998. return bytesRead;
  6999. }
  7000. static int waitForReadiness (const int handle, const bool forReading,
  7001. const int timeoutMsecs) throw()
  7002. {
  7003. struct timeval timeout;
  7004. struct timeval* timeoutp;
  7005. if (timeoutMsecs >= 0)
  7006. {
  7007. timeout.tv_sec = timeoutMsecs / 1000;
  7008. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7009. timeoutp = &timeout;
  7010. }
  7011. else
  7012. {
  7013. timeoutp = 0;
  7014. }
  7015. fd_set rset, wset;
  7016. FD_ZERO (&rset);
  7017. FD_SET (handle, &rset);
  7018. FD_ZERO (&wset);
  7019. FD_SET (handle, &wset);
  7020. fd_set* const prset = forReading ? &rset : 0;
  7021. fd_set* const pwset = forReading ? 0 : &wset;
  7022. #if JUCE_WINDOWS
  7023. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7024. return -1;
  7025. #else
  7026. {
  7027. int result;
  7028. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7029. && errno == EINTR)
  7030. {
  7031. }
  7032. if (result < 0)
  7033. return -1;
  7034. }
  7035. #endif
  7036. {
  7037. int opt;
  7038. juce_socklen_t len = sizeof (opt);
  7039. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7040. || opt != 0)
  7041. return -1;
  7042. }
  7043. if ((forReading && FD_ISSET (handle, &rset))
  7044. || ((! forReading) && FD_ISSET (handle, &wset)))
  7045. return 1;
  7046. return 0;
  7047. }
  7048. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7049. {
  7050. #if JUCE_WINDOWS
  7051. u_long nonBlocking = shouldBlock ? 0 : 1;
  7052. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7053. return false;
  7054. #else
  7055. int socketFlags = fcntl (handle, F_GETFL, 0);
  7056. if (socketFlags == -1)
  7057. return false;
  7058. if (shouldBlock)
  7059. socketFlags &= ~O_NONBLOCK;
  7060. else
  7061. socketFlags |= O_NONBLOCK;
  7062. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7063. return false;
  7064. #endif
  7065. return true;
  7066. }
  7067. static bool connectSocket (int volatile& handle,
  7068. const bool isDatagram,
  7069. void** serverAddress,
  7070. const String& hostName,
  7071. const int portNumber,
  7072. const int timeOutMillisecs) throw()
  7073. {
  7074. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7075. if (hostEnt == 0)
  7076. return false;
  7077. struct in_addr targetAddress;
  7078. memcpy (&targetAddress.s_addr,
  7079. *(hostEnt->h_addr_list),
  7080. sizeof (targetAddress.s_addr));
  7081. struct sockaddr_in servTmpAddr;
  7082. zerostruct (servTmpAddr);
  7083. servTmpAddr.sin_family = PF_INET;
  7084. servTmpAddr.sin_addr = targetAddress;
  7085. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7086. if (handle < 0)
  7087. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7088. if (handle < 0)
  7089. return false;
  7090. if (isDatagram)
  7091. {
  7092. *serverAddress = new struct sockaddr_in();
  7093. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7094. return true;
  7095. }
  7096. setSocketBlockingState (handle, false);
  7097. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7098. if (result < 0)
  7099. {
  7100. #if JUCE_WINDOWS
  7101. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7102. #else
  7103. if (errno == EINPROGRESS)
  7104. #endif
  7105. {
  7106. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7107. {
  7108. setSocketBlockingState (handle, true);
  7109. return false;
  7110. }
  7111. }
  7112. }
  7113. setSocketBlockingState (handle, true);
  7114. resetSocketOptions (handle, false, false);
  7115. return true;
  7116. }
  7117. }
  7118. StreamingSocket::StreamingSocket()
  7119. : portNumber (0),
  7120. handle (-1),
  7121. connected (false),
  7122. isListener (false)
  7123. {
  7124. #if JUCE_WINDOWS
  7125. initWin32Sockets();
  7126. #endif
  7127. }
  7128. StreamingSocket::StreamingSocket (const String& hostName_,
  7129. const int portNumber_,
  7130. const int handle_)
  7131. : hostName (hostName_),
  7132. portNumber (portNumber_),
  7133. handle (handle_),
  7134. connected (true),
  7135. isListener (false)
  7136. {
  7137. #if JUCE_WINDOWS
  7138. initWin32Sockets();
  7139. #endif
  7140. SocketHelpers::resetSocketOptions (handle_, false, false);
  7141. }
  7142. StreamingSocket::~StreamingSocket()
  7143. {
  7144. close();
  7145. }
  7146. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7147. {
  7148. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7149. : -1;
  7150. }
  7151. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7152. {
  7153. if (isListener || ! connected)
  7154. return -1;
  7155. #if JUCE_WINDOWS
  7156. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7157. #else
  7158. int result;
  7159. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7160. && errno == EINTR)
  7161. {
  7162. }
  7163. return result;
  7164. #endif
  7165. }
  7166. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7167. const int timeoutMsecs) const
  7168. {
  7169. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7170. : -1;
  7171. }
  7172. bool StreamingSocket::bindToPort (const int port)
  7173. {
  7174. return SocketHelpers::bindSocketToPort (handle, port);
  7175. }
  7176. bool StreamingSocket::connect (const String& remoteHostName,
  7177. const int remotePortNumber,
  7178. const int timeOutMillisecs)
  7179. {
  7180. if (isListener)
  7181. {
  7182. jassertfalse; // a listener socket can't connect to another one!
  7183. return false;
  7184. }
  7185. if (connected)
  7186. close();
  7187. hostName = remoteHostName;
  7188. portNumber = remotePortNumber;
  7189. isListener = false;
  7190. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7191. remotePortNumber, timeOutMillisecs);
  7192. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7193. {
  7194. close();
  7195. return false;
  7196. }
  7197. return true;
  7198. }
  7199. void StreamingSocket::close()
  7200. {
  7201. #if JUCE_WINDOWS
  7202. if (handle != SOCKET_ERROR || connected)
  7203. closesocket (handle);
  7204. connected = false;
  7205. #else
  7206. if (connected)
  7207. {
  7208. connected = false;
  7209. if (isListener)
  7210. {
  7211. // need to do this to interrupt the accept() function..
  7212. StreamingSocket temp;
  7213. temp.connect ("localhost", portNumber, 1000);
  7214. }
  7215. }
  7216. if (handle != -1)
  7217. ::close (handle);
  7218. #endif
  7219. hostName = String::empty;
  7220. portNumber = 0;
  7221. handle = -1;
  7222. isListener = false;
  7223. }
  7224. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7225. {
  7226. if (connected)
  7227. close();
  7228. hostName = "listener";
  7229. portNumber = newPortNumber;
  7230. isListener = true;
  7231. struct sockaddr_in servTmpAddr;
  7232. zerostruct (servTmpAddr);
  7233. servTmpAddr.sin_family = PF_INET;
  7234. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7235. if (localHostName.isNotEmpty())
  7236. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7237. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7238. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7239. if (handle < 0)
  7240. return false;
  7241. const int reuse = 1;
  7242. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7243. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7244. || listen (handle, SOMAXCONN) < 0)
  7245. {
  7246. close();
  7247. return false;
  7248. }
  7249. connected = true;
  7250. return true;
  7251. }
  7252. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7253. {
  7254. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7255. // prepare this socket as a listener.
  7256. if (connected && isListener)
  7257. {
  7258. struct sockaddr address;
  7259. juce_socklen_t len = sizeof (sockaddr);
  7260. const int newSocket = (int) accept (handle, &address, &len);
  7261. if (newSocket >= 0 && connected)
  7262. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7263. portNumber, newSocket);
  7264. }
  7265. return 0;
  7266. }
  7267. bool StreamingSocket::isLocal() const throw()
  7268. {
  7269. return hostName == "127.0.0.1";
  7270. }
  7271. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7272. : portNumber (0),
  7273. handle (-1),
  7274. connected (true),
  7275. allowBroadcast (allowBroadcast_),
  7276. serverAddress (0)
  7277. {
  7278. #if JUCE_WINDOWS
  7279. initWin32Sockets();
  7280. #endif
  7281. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7282. bindToPort (localPortNumber);
  7283. }
  7284. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7285. const int handle_, const int localPortNumber)
  7286. : hostName (hostName_),
  7287. portNumber (portNumber_),
  7288. handle (handle_),
  7289. connected (true),
  7290. allowBroadcast (false),
  7291. serverAddress (0)
  7292. {
  7293. #if JUCE_WINDOWS
  7294. initWin32Sockets();
  7295. #endif
  7296. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7297. bindToPort (localPortNumber);
  7298. }
  7299. DatagramSocket::~DatagramSocket()
  7300. {
  7301. close();
  7302. delete static_cast <struct sockaddr_in*> (serverAddress);
  7303. serverAddress = 0;
  7304. }
  7305. void DatagramSocket::close()
  7306. {
  7307. #if JUCE_WINDOWS
  7308. closesocket (handle);
  7309. connected = false;
  7310. #else
  7311. connected = false;
  7312. ::close (handle);
  7313. #endif
  7314. hostName = String::empty;
  7315. portNumber = 0;
  7316. handle = -1;
  7317. }
  7318. bool DatagramSocket::bindToPort (const int port)
  7319. {
  7320. return SocketHelpers::bindSocketToPort (handle, port);
  7321. }
  7322. bool DatagramSocket::connect (const String& remoteHostName,
  7323. const int remotePortNumber,
  7324. const int timeOutMillisecs)
  7325. {
  7326. if (connected)
  7327. close();
  7328. hostName = remoteHostName;
  7329. portNumber = remotePortNumber;
  7330. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7331. remoteHostName, remotePortNumber,
  7332. timeOutMillisecs);
  7333. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7334. {
  7335. close();
  7336. return false;
  7337. }
  7338. return true;
  7339. }
  7340. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7341. {
  7342. struct sockaddr address;
  7343. juce_socklen_t len = sizeof (sockaddr);
  7344. while (waitUntilReady (true, -1) == 1)
  7345. {
  7346. char buf[1];
  7347. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7348. {
  7349. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7350. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7351. -1, -1);
  7352. }
  7353. }
  7354. return 0;
  7355. }
  7356. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7357. const int timeoutMsecs) const
  7358. {
  7359. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7360. : -1;
  7361. }
  7362. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7363. {
  7364. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7365. : -1;
  7366. }
  7367. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7368. {
  7369. // You need to call connect() first to set the server address..
  7370. jassert (serverAddress != 0 && connected);
  7371. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7372. numBytesToWrite, 0,
  7373. (const struct sockaddr*) serverAddress,
  7374. sizeof (struct sockaddr_in))
  7375. : -1;
  7376. }
  7377. bool DatagramSocket::isLocal() const throw()
  7378. {
  7379. return hostName == "127.0.0.1";
  7380. }
  7381. #if JUCE_MSVC
  7382. #pragma warning (pop)
  7383. #endif
  7384. END_JUCE_NAMESPACE
  7385. /*** End of inlined file: juce_Socket.cpp ***/
  7386. /*** Start of inlined file: juce_URL.cpp ***/
  7387. BEGIN_JUCE_NAMESPACE
  7388. URL::URL()
  7389. {
  7390. }
  7391. URL::URL (const String& url_)
  7392. : url (url_)
  7393. {
  7394. int i = url.indexOfChar ('?');
  7395. if (i >= 0)
  7396. {
  7397. do
  7398. {
  7399. const int nextAmp = url.indexOfChar (i + 1, '&');
  7400. const int equalsPos = url.indexOfChar (i + 1, '=');
  7401. if (equalsPos > i + 1)
  7402. {
  7403. if (nextAmp < 0)
  7404. {
  7405. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7406. removeEscapeChars (url.substring (equalsPos + 1)));
  7407. }
  7408. else if (nextAmp > 0 && equalsPos < nextAmp)
  7409. {
  7410. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7411. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7412. }
  7413. }
  7414. i = nextAmp;
  7415. }
  7416. while (i >= 0);
  7417. url = url.upToFirstOccurrenceOf ("?", false, false);
  7418. }
  7419. }
  7420. URL::URL (const URL& other)
  7421. : url (other.url),
  7422. postData (other.postData),
  7423. parameters (other.parameters),
  7424. filesToUpload (other.filesToUpload),
  7425. mimeTypes (other.mimeTypes)
  7426. {
  7427. }
  7428. URL& URL::operator= (const URL& other)
  7429. {
  7430. url = other.url;
  7431. postData = other.postData;
  7432. parameters = other.parameters;
  7433. filesToUpload = other.filesToUpload;
  7434. mimeTypes = other.mimeTypes;
  7435. return *this;
  7436. }
  7437. URL::~URL()
  7438. {
  7439. }
  7440. static const String getMangledParameters (const StringPairArray& parameters)
  7441. {
  7442. String p;
  7443. for (int i = 0; i < parameters.size(); ++i)
  7444. {
  7445. if (i > 0)
  7446. p << '&';
  7447. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7448. << '='
  7449. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7450. }
  7451. return p;
  7452. }
  7453. const String URL::toString (const bool includeGetParameters) const
  7454. {
  7455. if (includeGetParameters && parameters.size() > 0)
  7456. return url + "?" + getMangledParameters (parameters);
  7457. else
  7458. return url;
  7459. }
  7460. bool URL::isWellFormed() const
  7461. {
  7462. //xxx TODO
  7463. return url.isNotEmpty();
  7464. }
  7465. static int findStartOfDomain (const String& url)
  7466. {
  7467. int i = 0;
  7468. while (CharacterFunctions::isLetterOrDigit (url[i])
  7469. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7470. ++i;
  7471. return url[i] == ':' ? i + 1 : 0;
  7472. }
  7473. const String URL::getDomain() const
  7474. {
  7475. int start = findStartOfDomain (url);
  7476. while (url[start] == '/')
  7477. ++start;
  7478. const int end1 = url.indexOfChar (start, '/');
  7479. const int end2 = url.indexOfChar (start, ':');
  7480. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7481. : jmin (end1, end2);
  7482. return url.substring (start, end);
  7483. }
  7484. const String URL::getSubPath() const
  7485. {
  7486. int start = findStartOfDomain (url);
  7487. while (url[start] == '/')
  7488. ++start;
  7489. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7490. return startOfPath <= 0 ? String::empty
  7491. : url.substring (startOfPath);
  7492. }
  7493. const String URL::getScheme() const
  7494. {
  7495. return url.substring (0, findStartOfDomain (url) - 1);
  7496. }
  7497. const URL URL::withNewSubPath (const String& newPath) const
  7498. {
  7499. int start = findStartOfDomain (url);
  7500. while (url[start] == '/')
  7501. ++start;
  7502. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7503. URL u (*this);
  7504. if (startOfPath > 0)
  7505. u.url = url.substring (0, startOfPath);
  7506. if (! u.url.endsWithChar ('/'))
  7507. u.url << '/';
  7508. if (newPath.startsWithChar ('/'))
  7509. u.url << newPath.substring (1);
  7510. else
  7511. u.url << newPath;
  7512. return u;
  7513. }
  7514. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7515. {
  7516. if (possibleURL.startsWithIgnoreCase ("http:")
  7517. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7518. return true;
  7519. if (possibleURL.startsWithIgnoreCase ("file:")
  7520. || possibleURL.containsChar ('@')
  7521. || possibleURL.endsWithChar ('.')
  7522. || (! possibleURL.containsChar ('.')))
  7523. return false;
  7524. if (possibleURL.startsWithIgnoreCase ("www.")
  7525. && possibleURL.substring (5).containsChar ('.'))
  7526. return true;
  7527. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7528. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7529. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7530. return true;
  7531. return false;
  7532. }
  7533. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7534. {
  7535. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7536. return atSign > 0
  7537. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7538. && (! possibleEmailAddress.endsWithChar ('.'));
  7539. }
  7540. void* juce_openInternetFile (const String& url,
  7541. const String& headers,
  7542. const MemoryBlock& optionalPostData,
  7543. const bool isPost,
  7544. URL::OpenStreamProgressCallback* callback,
  7545. void* callbackContext,
  7546. int timeOutMs);
  7547. void juce_closeInternetFile (void* handle);
  7548. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7549. int juce_seekInInternetFile (void* handle, int newPosition);
  7550. int64 juce_getInternetFileContentLength (void* handle);
  7551. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7552. class WebInputStream : public InputStream
  7553. {
  7554. public:
  7555. WebInputStream (const URL& url,
  7556. const bool isPost_,
  7557. URL::OpenStreamProgressCallback* const progressCallback_,
  7558. void* const progressCallbackContext_,
  7559. const String& extraHeaders,
  7560. const int timeOutMs_,
  7561. StringPairArray* const responseHeaders)
  7562. : position (0),
  7563. finished (false),
  7564. isPost (isPost_),
  7565. progressCallback (progressCallback_),
  7566. progressCallbackContext (progressCallbackContext_),
  7567. timeOutMs (timeOutMs_)
  7568. {
  7569. server = url.toString (! isPost);
  7570. if (isPost_)
  7571. createHeadersAndPostData (url);
  7572. headers += extraHeaders;
  7573. if (! headers.endsWithChar ('\n'))
  7574. headers << "\r\n";
  7575. handle = juce_openInternetFile (server, headers, postData, isPost,
  7576. progressCallback_, progressCallbackContext_,
  7577. timeOutMs);
  7578. if (responseHeaders != 0)
  7579. juce_getInternetFileHeaders (handle, *responseHeaders);
  7580. }
  7581. ~WebInputStream()
  7582. {
  7583. juce_closeInternetFile (handle);
  7584. }
  7585. bool isError() const { return handle == 0; }
  7586. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7587. bool isExhausted() { return finished; }
  7588. int64 getPosition() { return position; }
  7589. int read (void* dest, int bytes)
  7590. {
  7591. if (finished || isError())
  7592. {
  7593. return 0;
  7594. }
  7595. else
  7596. {
  7597. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7598. position += bytesRead;
  7599. if (bytesRead == 0)
  7600. finished = true;
  7601. return bytesRead;
  7602. }
  7603. }
  7604. bool setPosition (int64 wantedPos)
  7605. {
  7606. if (wantedPos != position)
  7607. {
  7608. finished = false;
  7609. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7610. if (actualPos == wantedPos)
  7611. {
  7612. position = wantedPos;
  7613. }
  7614. else
  7615. {
  7616. if (wantedPos < position)
  7617. {
  7618. juce_closeInternetFile (handle);
  7619. position = 0;
  7620. finished = false;
  7621. handle = juce_openInternetFile (server, headers, postData, isPost,
  7622. progressCallback, progressCallbackContext,
  7623. timeOutMs);
  7624. }
  7625. skipNextBytes (wantedPos - position);
  7626. }
  7627. }
  7628. return true;
  7629. }
  7630. juce_UseDebuggingNewOperator
  7631. private:
  7632. String server, headers;
  7633. MemoryBlock postData;
  7634. int64 position;
  7635. bool finished;
  7636. const bool isPost;
  7637. void* handle;
  7638. URL::OpenStreamProgressCallback* const progressCallback;
  7639. void* const progressCallbackContext;
  7640. const int timeOutMs;
  7641. void createHeadersAndPostData (const URL& url)
  7642. {
  7643. MemoryOutputStream data (postData, false);
  7644. if (url.getFilesToUpload().size() > 0)
  7645. {
  7646. // need to upload some files, so do it as multi-part...
  7647. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7648. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7649. data << "--" << boundary;
  7650. int i;
  7651. for (i = 0; i < url.getParameters().size(); ++i)
  7652. {
  7653. data << "\r\nContent-Disposition: form-data; name=\""
  7654. << url.getParameters().getAllKeys() [i]
  7655. << "\"\r\n\r\n"
  7656. << url.getParameters().getAllValues() [i]
  7657. << "\r\n--"
  7658. << boundary;
  7659. }
  7660. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7661. {
  7662. const File file (url.getFilesToUpload().getAllValues() [i]);
  7663. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7664. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7665. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7666. const String mimeType (url.getMimeTypesOfUploadFiles()
  7667. .getValue (paramName, String::empty));
  7668. if (mimeType.isNotEmpty())
  7669. data << "Content-Type: " << mimeType << "\r\n";
  7670. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7671. << file << "\r\n--" << boundary;
  7672. }
  7673. data << "--\r\n";
  7674. data.flush();
  7675. }
  7676. else
  7677. {
  7678. data << getMangledParameters (url.getParameters())
  7679. << url.getPostData();
  7680. data.flush();
  7681. // just a short text attachment, so use simple url encoding..
  7682. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7683. + String ((unsigned int) postData.getSize())
  7684. + "\r\n";
  7685. }
  7686. }
  7687. WebInputStream (const WebInputStream&);
  7688. WebInputStream& operator= (const WebInputStream&);
  7689. };
  7690. InputStream* URL::createInputStream (const bool usePostCommand,
  7691. OpenStreamProgressCallback* const progressCallback,
  7692. void* const progressCallbackContext,
  7693. const String& extraHeaders,
  7694. const int timeOutMs,
  7695. StringPairArray* const responseHeaders) const
  7696. {
  7697. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7698. progressCallback, progressCallbackContext,
  7699. extraHeaders, timeOutMs, responseHeaders));
  7700. return wi->isError() ? 0 : wi.release();
  7701. }
  7702. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7703. const bool usePostCommand) const
  7704. {
  7705. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7706. if (in != 0)
  7707. {
  7708. in->readIntoMemoryBlock (destData);
  7709. return true;
  7710. }
  7711. return false;
  7712. }
  7713. const String URL::readEntireTextStream (const bool usePostCommand) const
  7714. {
  7715. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7716. if (in != 0)
  7717. return in->readEntireStreamAsString();
  7718. return String::empty;
  7719. }
  7720. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7721. {
  7722. XmlDocument doc (readEntireTextStream (usePostCommand));
  7723. return doc.getDocumentElement();
  7724. }
  7725. const URL URL::withParameter (const String& parameterName,
  7726. const String& parameterValue) const
  7727. {
  7728. URL u (*this);
  7729. u.parameters.set (parameterName, parameterValue);
  7730. return u;
  7731. }
  7732. const URL URL::withFileToUpload (const String& parameterName,
  7733. const File& fileToUpload,
  7734. const String& mimeType) const
  7735. {
  7736. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7737. URL u (*this);
  7738. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7739. u.mimeTypes.set (parameterName, mimeType);
  7740. return u;
  7741. }
  7742. const URL URL::withPOSTData (const String& postData_) const
  7743. {
  7744. URL u (*this);
  7745. u.postData = postData_;
  7746. return u;
  7747. }
  7748. const StringPairArray& URL::getParameters() const
  7749. {
  7750. return parameters;
  7751. }
  7752. const StringPairArray& URL::getFilesToUpload() const
  7753. {
  7754. return filesToUpload;
  7755. }
  7756. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7757. {
  7758. return mimeTypes;
  7759. }
  7760. const String URL::removeEscapeChars (const String& s)
  7761. {
  7762. String result (s.replaceCharacter ('+', ' '));
  7763. if (! result.containsChar ('%'))
  7764. return result;
  7765. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7766. // after all the replacements have been made, so that multi-byte chars are handled.
  7767. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7768. for (int i = 0; i < utf8.size(); ++i)
  7769. {
  7770. if (utf8.getUnchecked(i) == '%')
  7771. {
  7772. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7773. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7774. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7775. {
  7776. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7777. utf8.removeRange (i + 1, 2);
  7778. }
  7779. }
  7780. }
  7781. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7782. }
  7783. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7784. {
  7785. const char* const legalChars = isParameter ? "_-.*!'()"
  7786. : ",$_-.*!'()";
  7787. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7788. for (int i = 0; i < utf8.size(); ++i)
  7789. {
  7790. const char c = utf8.getUnchecked(i);
  7791. if (! (CharacterFunctions::isLetterOrDigit (c)
  7792. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7793. {
  7794. if (c == ' ')
  7795. {
  7796. utf8.set (i, '+');
  7797. }
  7798. else
  7799. {
  7800. static const char* const hexDigits = "0123456789abcdef";
  7801. utf8.set (i, '%');
  7802. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7803. utf8.insert (++i, hexDigits [c & 15]);
  7804. }
  7805. }
  7806. }
  7807. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7808. }
  7809. bool URL::launchInDefaultBrowser() const
  7810. {
  7811. String u (toString (true));
  7812. if (u.containsChar ('@') && ! u.containsChar (':'))
  7813. u = "mailto:" + u;
  7814. return PlatformUtilities::openDocument (u, String::empty);
  7815. }
  7816. END_JUCE_NAMESPACE
  7817. /*** End of inlined file: juce_URL.cpp ***/
  7818. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7819. BEGIN_JUCE_NAMESPACE
  7820. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7821. const int bufferSize_,
  7822. const bool deleteSourceWhenDestroyed)
  7823. : source (source_),
  7824. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7825. bufferSize (jmax (256, bufferSize_)),
  7826. position (source_->getPosition()),
  7827. lastReadPos (0),
  7828. bufferOverlap (128)
  7829. {
  7830. const int sourceSize = (int) source_->getTotalLength();
  7831. if (sourceSize >= 0)
  7832. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7833. bufferStart = position;
  7834. buffer.malloc (bufferSize);
  7835. }
  7836. BufferedInputStream::~BufferedInputStream()
  7837. {
  7838. }
  7839. int64 BufferedInputStream::getTotalLength()
  7840. {
  7841. return source->getTotalLength();
  7842. }
  7843. int64 BufferedInputStream::getPosition()
  7844. {
  7845. return position;
  7846. }
  7847. bool BufferedInputStream::setPosition (int64 newPosition)
  7848. {
  7849. position = jmax ((int64) 0, newPosition);
  7850. return true;
  7851. }
  7852. bool BufferedInputStream::isExhausted()
  7853. {
  7854. return (position >= lastReadPos)
  7855. && source->isExhausted();
  7856. }
  7857. void BufferedInputStream::ensureBuffered()
  7858. {
  7859. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7860. if (position < bufferStart || position >= bufferEndOverlap)
  7861. {
  7862. int bytesRead;
  7863. if (position < lastReadPos
  7864. && position >= bufferEndOverlap
  7865. && position >= bufferStart)
  7866. {
  7867. const int bytesToKeep = (int) (lastReadPos - position);
  7868. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7869. bufferStart = position;
  7870. bytesRead = source->read (buffer + bytesToKeep,
  7871. bufferSize - bytesToKeep);
  7872. lastReadPos += bytesRead;
  7873. bytesRead += bytesToKeep;
  7874. }
  7875. else
  7876. {
  7877. bufferStart = position;
  7878. source->setPosition (bufferStart);
  7879. bytesRead = source->read (buffer, bufferSize);
  7880. lastReadPos = bufferStart + bytesRead;
  7881. }
  7882. while (bytesRead < bufferSize)
  7883. buffer [bytesRead++] = 0;
  7884. }
  7885. }
  7886. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7887. {
  7888. if (position >= bufferStart
  7889. && position + maxBytesToRead <= lastReadPos)
  7890. {
  7891. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7892. position += maxBytesToRead;
  7893. return maxBytesToRead;
  7894. }
  7895. else
  7896. {
  7897. if (position < bufferStart || position >= lastReadPos)
  7898. ensureBuffered();
  7899. int bytesRead = 0;
  7900. while (maxBytesToRead > 0)
  7901. {
  7902. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7903. if (bytesAvailable > 0)
  7904. {
  7905. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7906. maxBytesToRead -= bytesAvailable;
  7907. bytesRead += bytesAvailable;
  7908. position += bytesAvailable;
  7909. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7910. }
  7911. const int64 oldLastReadPos = lastReadPos;
  7912. ensureBuffered();
  7913. if (oldLastReadPos == lastReadPos)
  7914. break; // if ensureBuffered() failed to read any more data, bail out
  7915. if (isExhausted())
  7916. break;
  7917. }
  7918. return bytesRead;
  7919. }
  7920. }
  7921. const String BufferedInputStream::readString()
  7922. {
  7923. if (position >= bufferStart
  7924. && position < lastReadPos)
  7925. {
  7926. const int maxChars = (int) (lastReadPos - position);
  7927. const char* const src = buffer + (int) (position - bufferStart);
  7928. for (int i = 0; i < maxChars; ++i)
  7929. {
  7930. if (src[i] == 0)
  7931. {
  7932. position += i + 1;
  7933. return String::fromUTF8 (src, i);
  7934. }
  7935. }
  7936. }
  7937. return InputStream::readString();
  7938. }
  7939. END_JUCE_NAMESPACE
  7940. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7941. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7942. BEGIN_JUCE_NAMESPACE
  7943. FileInputSource::FileInputSource (const File& file_)
  7944. : file (file_)
  7945. {
  7946. }
  7947. FileInputSource::~FileInputSource()
  7948. {
  7949. }
  7950. InputStream* FileInputSource::createInputStream()
  7951. {
  7952. return file.createInputStream();
  7953. }
  7954. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7955. {
  7956. return file.getSiblingFile (relatedItemPath).createInputStream();
  7957. }
  7958. int64 FileInputSource::hashCode() const
  7959. {
  7960. return file.hashCode();
  7961. }
  7962. END_JUCE_NAMESPACE
  7963. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7964. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7965. BEGIN_JUCE_NAMESPACE
  7966. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7967. const size_t sourceDataSize,
  7968. const bool keepInternalCopy)
  7969. : data (static_cast <const char*> (sourceData)),
  7970. dataSize (sourceDataSize),
  7971. position (0)
  7972. {
  7973. if (keepInternalCopy)
  7974. {
  7975. internalCopy.append (data, sourceDataSize);
  7976. data = static_cast <const char*> (internalCopy.getData());
  7977. }
  7978. }
  7979. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7980. const bool keepInternalCopy)
  7981. : data (static_cast <const char*> (sourceData.getData())),
  7982. dataSize (sourceData.getSize()),
  7983. position (0)
  7984. {
  7985. if (keepInternalCopy)
  7986. {
  7987. internalCopy = sourceData;
  7988. data = static_cast <const char*> (internalCopy.getData());
  7989. }
  7990. }
  7991. MemoryInputStream::~MemoryInputStream()
  7992. {
  7993. }
  7994. int64 MemoryInputStream::getTotalLength()
  7995. {
  7996. return dataSize;
  7997. }
  7998. int MemoryInputStream::read (void* const buffer, const int howMany)
  7999. {
  8000. jassert (howMany >= 0);
  8001. const int num = jmin (howMany, (int) (dataSize - position));
  8002. memcpy (buffer, data + position, num);
  8003. position += num;
  8004. return (int) num;
  8005. }
  8006. bool MemoryInputStream::isExhausted()
  8007. {
  8008. return (position >= dataSize);
  8009. }
  8010. bool MemoryInputStream::setPosition (const int64 pos)
  8011. {
  8012. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8013. return true;
  8014. }
  8015. int64 MemoryInputStream::getPosition()
  8016. {
  8017. return position;
  8018. }
  8019. #if JUCE_UNIT_TESTS
  8020. class MemoryStreamTests : public UnitTest
  8021. {
  8022. public:
  8023. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8024. void runTest()
  8025. {
  8026. beginTest ("Basics");
  8027. int randomInt = Random::getSystemRandom().nextInt();
  8028. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8029. double randomDouble = Random::getSystemRandom().nextDouble();
  8030. String randomString;
  8031. for (int i = 50; --i >= 0;)
  8032. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8033. MemoryOutputStream mo;
  8034. mo.writeInt (randomInt);
  8035. mo.writeIntBigEndian (randomInt);
  8036. mo.writeCompressedInt (randomInt);
  8037. mo.writeString (randomString);
  8038. mo.writeInt64 (randomInt64);
  8039. mo.writeInt64BigEndian (randomInt64);
  8040. mo.writeDouble (randomDouble);
  8041. mo.writeDoubleBigEndian (randomDouble);
  8042. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8043. expect (mi.readInt() == randomInt);
  8044. expect (mi.readIntBigEndian() == randomInt);
  8045. expect (mi.readCompressedInt() == randomInt);
  8046. expect (mi.readString() == randomString);
  8047. expect (mi.readInt64() == randomInt64);
  8048. expect (mi.readInt64BigEndian() == randomInt64);
  8049. expect (mi.readDouble() == randomDouble);
  8050. expect (mi.readDoubleBigEndian() == randomDouble);
  8051. }
  8052. };
  8053. static MemoryStreamTests memoryInputStreamUnitTests;
  8054. #endif
  8055. END_JUCE_NAMESPACE
  8056. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8057. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8058. BEGIN_JUCE_NAMESPACE
  8059. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8060. : data (internalBlock),
  8061. position (0),
  8062. size (0)
  8063. {
  8064. internalBlock.setSize (initialSize, false);
  8065. }
  8066. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8067. const bool appendToExistingBlockContent)
  8068. : data (memoryBlockToWriteTo),
  8069. position (0),
  8070. size (0)
  8071. {
  8072. if (appendToExistingBlockContent)
  8073. position = size = memoryBlockToWriteTo.getSize();
  8074. }
  8075. MemoryOutputStream::~MemoryOutputStream()
  8076. {
  8077. flush();
  8078. }
  8079. void MemoryOutputStream::flush()
  8080. {
  8081. if (&data != &internalBlock)
  8082. data.setSize (size, false);
  8083. }
  8084. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8085. {
  8086. data.ensureSize (bytesToPreallocate + 1);
  8087. }
  8088. void MemoryOutputStream::reset() throw()
  8089. {
  8090. position = 0;
  8091. size = 0;
  8092. }
  8093. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8094. {
  8095. if (howMany > 0)
  8096. {
  8097. const size_t storageNeeded = position + howMany;
  8098. if (storageNeeded >= data.getSize())
  8099. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8100. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8101. position += howMany;
  8102. size = jmax (size, position);
  8103. }
  8104. return true;
  8105. }
  8106. const void* MemoryOutputStream::getData() const throw()
  8107. {
  8108. void* const d = data.getData();
  8109. if (data.getSize() > size)
  8110. static_cast <char*> (d) [size] = 0;
  8111. return d;
  8112. }
  8113. bool MemoryOutputStream::setPosition (int64 newPosition)
  8114. {
  8115. if (newPosition <= (int64) size)
  8116. {
  8117. // ok to seek backwards
  8118. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8119. return true;
  8120. }
  8121. else
  8122. {
  8123. // trying to make it bigger isn't a good thing to do..
  8124. return false;
  8125. }
  8126. }
  8127. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8128. {
  8129. // before writing from an input, see if we can preallocate to make it more efficient..
  8130. int64 availableData = source.getTotalLength() - source.getPosition();
  8131. if (availableData > 0)
  8132. {
  8133. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8134. availableData = maxNumBytesToWrite;
  8135. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8136. }
  8137. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8138. }
  8139. const String MemoryOutputStream::toUTF8() const
  8140. {
  8141. return String (static_cast <const char*> (getData()), getDataSize());
  8142. }
  8143. const String MemoryOutputStream::toString() const
  8144. {
  8145. return String::createStringFromData (getData(), getDataSize());
  8146. }
  8147. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8148. {
  8149. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8150. return stream;
  8151. }
  8152. END_JUCE_NAMESPACE
  8153. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8154. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8155. BEGIN_JUCE_NAMESPACE
  8156. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8157. const int64 startPositionInSourceStream_,
  8158. const int64 lengthOfSourceStream_,
  8159. const bool deleteSourceWhenDestroyed)
  8160. : source (sourceStream),
  8161. startPositionInSourceStream (startPositionInSourceStream_),
  8162. lengthOfSourceStream (lengthOfSourceStream_)
  8163. {
  8164. if (deleteSourceWhenDestroyed)
  8165. sourceToDelete = source;
  8166. setPosition (0);
  8167. }
  8168. SubregionStream::~SubregionStream()
  8169. {
  8170. }
  8171. int64 SubregionStream::getTotalLength()
  8172. {
  8173. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8174. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8175. : srcLen;
  8176. }
  8177. int64 SubregionStream::getPosition()
  8178. {
  8179. return source->getPosition() - startPositionInSourceStream;
  8180. }
  8181. bool SubregionStream::setPosition (int64 newPosition)
  8182. {
  8183. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8184. }
  8185. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8186. {
  8187. if (lengthOfSourceStream < 0)
  8188. {
  8189. return source->read (destBuffer, maxBytesToRead);
  8190. }
  8191. else
  8192. {
  8193. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8194. if (maxBytesToRead <= 0)
  8195. return 0;
  8196. return source->read (destBuffer, maxBytesToRead);
  8197. }
  8198. }
  8199. bool SubregionStream::isExhausted()
  8200. {
  8201. if (lengthOfSourceStream >= 0)
  8202. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8203. else
  8204. return source->isExhausted();
  8205. }
  8206. END_JUCE_NAMESPACE
  8207. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8208. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8209. BEGIN_JUCE_NAMESPACE
  8210. PerformanceCounter::PerformanceCounter (const String& name_,
  8211. int runsPerPrintout,
  8212. const File& loggingFile)
  8213. : name (name_),
  8214. numRuns (0),
  8215. runsPerPrint (runsPerPrintout),
  8216. totalTime (0),
  8217. outputFile (loggingFile)
  8218. {
  8219. if (outputFile != File::nonexistent)
  8220. {
  8221. String s ("**** Counter for \"");
  8222. s << name_ << "\" started at: "
  8223. << Time::getCurrentTime().toString (true, true)
  8224. << "\r\n";
  8225. outputFile.appendText (s, false, false);
  8226. }
  8227. }
  8228. PerformanceCounter::~PerformanceCounter()
  8229. {
  8230. printStatistics();
  8231. }
  8232. void PerformanceCounter::start()
  8233. {
  8234. started = Time::getHighResolutionTicks();
  8235. }
  8236. void PerformanceCounter::stop()
  8237. {
  8238. const int64 now = Time::getHighResolutionTicks();
  8239. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8240. if (++numRuns == runsPerPrint)
  8241. printStatistics();
  8242. }
  8243. void PerformanceCounter::printStatistics()
  8244. {
  8245. if (numRuns > 0)
  8246. {
  8247. String s ("Performance count for \"");
  8248. s << name << "\" - average over " << numRuns << " run(s) = ";
  8249. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8250. if (micros > 10000)
  8251. s << (micros/1000) << " millisecs";
  8252. else
  8253. s << micros << " microsecs";
  8254. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8255. Logger::outputDebugString (s);
  8256. s << "\r\n";
  8257. if (outputFile != File::nonexistent)
  8258. outputFile.appendText (s, false, false);
  8259. numRuns = 0;
  8260. totalTime = 0;
  8261. }
  8262. }
  8263. END_JUCE_NAMESPACE
  8264. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8265. /*** Start of inlined file: juce_Uuid.cpp ***/
  8266. BEGIN_JUCE_NAMESPACE
  8267. Uuid::Uuid()
  8268. {
  8269. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8270. // to make it very very unlikely that two UUIDs will ever be the same..
  8271. static int64 macAddresses[2];
  8272. static bool hasCheckedMacAddresses = false;
  8273. if (! hasCheckedMacAddresses)
  8274. {
  8275. hasCheckedMacAddresses = true;
  8276. SystemStats::getMACAddresses (macAddresses, 2);
  8277. }
  8278. value.asInt64[0] = macAddresses[0];
  8279. value.asInt64[1] = macAddresses[1];
  8280. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8281. // whose seed will carry over between calls to this method.
  8282. Random r (macAddresses[0] ^ macAddresses[1]
  8283. ^ Random::getSystemRandom().nextInt64());
  8284. for (int i = 4; --i >= 0;)
  8285. {
  8286. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8287. value.asInt[i] ^= r.nextInt();
  8288. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8289. }
  8290. }
  8291. Uuid::~Uuid() throw()
  8292. {
  8293. }
  8294. Uuid::Uuid (const Uuid& other)
  8295. : value (other.value)
  8296. {
  8297. }
  8298. Uuid& Uuid::operator= (const Uuid& other)
  8299. {
  8300. value = other.value;
  8301. return *this;
  8302. }
  8303. bool Uuid::operator== (const Uuid& other) const
  8304. {
  8305. return value.asInt64[0] == other.value.asInt64[0]
  8306. && value.asInt64[1] == other.value.asInt64[1];
  8307. }
  8308. bool Uuid::operator!= (const Uuid& other) const
  8309. {
  8310. return ! operator== (other);
  8311. }
  8312. bool Uuid::isNull() const throw()
  8313. {
  8314. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8315. }
  8316. const String Uuid::toString() const
  8317. {
  8318. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8319. }
  8320. Uuid::Uuid (const String& uuidString)
  8321. {
  8322. operator= (uuidString);
  8323. }
  8324. Uuid& Uuid::operator= (const String& uuidString)
  8325. {
  8326. MemoryBlock mb;
  8327. mb.loadFromHexString (uuidString);
  8328. mb.ensureSize (sizeof (value.asBytes), true);
  8329. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8330. return *this;
  8331. }
  8332. Uuid::Uuid (const uint8* const rawData)
  8333. {
  8334. operator= (rawData);
  8335. }
  8336. Uuid& Uuid::operator= (const uint8* const rawData)
  8337. {
  8338. if (rawData != 0)
  8339. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8340. else
  8341. zeromem (value.asBytes, sizeof (value.asBytes));
  8342. return *this;
  8343. }
  8344. END_JUCE_NAMESPACE
  8345. /*** End of inlined file: juce_Uuid.cpp ***/
  8346. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8347. BEGIN_JUCE_NAMESPACE
  8348. class ZipFile::ZipEntryInfo
  8349. {
  8350. public:
  8351. ZipFile::ZipEntry entry;
  8352. int streamOffset;
  8353. int compressedSize;
  8354. bool compressed;
  8355. };
  8356. class ZipFile::ZipInputStream : public InputStream
  8357. {
  8358. public:
  8359. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8360. : file (file_),
  8361. zipEntryInfo (zei),
  8362. pos (0),
  8363. headerSize (0),
  8364. inputStream (0)
  8365. {
  8366. inputStream = file_.inputStream;
  8367. if (file_.inputSource != 0)
  8368. {
  8369. inputStream = file.inputSource->createInputStream();
  8370. }
  8371. else
  8372. {
  8373. #if JUCE_DEBUG
  8374. file_.numOpenStreams++;
  8375. #endif
  8376. }
  8377. char buffer [30];
  8378. if (inputStream != 0
  8379. && inputStream->setPosition (zei.streamOffset)
  8380. && inputStream->read (buffer, 30) == 30
  8381. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8382. {
  8383. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8384. + ByteOrder::littleEndianShort (buffer + 28);
  8385. }
  8386. }
  8387. ~ZipInputStream()
  8388. {
  8389. #if JUCE_DEBUG
  8390. if (inputStream != 0 && inputStream == file.inputStream)
  8391. file.numOpenStreams--;
  8392. #endif
  8393. if (inputStream != file.inputStream)
  8394. delete inputStream;
  8395. }
  8396. int64 getTotalLength()
  8397. {
  8398. return zipEntryInfo.compressedSize;
  8399. }
  8400. int read (void* buffer, int howMany)
  8401. {
  8402. if (headerSize <= 0)
  8403. return 0;
  8404. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8405. if (inputStream == 0)
  8406. return 0;
  8407. int num;
  8408. if (inputStream == file.inputStream)
  8409. {
  8410. const ScopedLock sl (file.lock);
  8411. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8412. num = inputStream->read (buffer, howMany);
  8413. }
  8414. else
  8415. {
  8416. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8417. num = inputStream->read (buffer, howMany);
  8418. }
  8419. pos += num;
  8420. return num;
  8421. }
  8422. bool isExhausted()
  8423. {
  8424. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8425. }
  8426. int64 getPosition()
  8427. {
  8428. return pos;
  8429. }
  8430. bool setPosition (int64 newPos)
  8431. {
  8432. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8433. return true;
  8434. }
  8435. private:
  8436. ZipFile& file;
  8437. ZipEntryInfo zipEntryInfo;
  8438. int64 pos;
  8439. int headerSize;
  8440. InputStream* inputStream;
  8441. ZipInputStream (const ZipInputStream&);
  8442. ZipInputStream& operator= (const ZipInputStream&);
  8443. };
  8444. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8445. : inputStream (source_)
  8446. #if JUCE_DEBUG
  8447. , numOpenStreams (0)
  8448. #endif
  8449. {
  8450. if (deleteStreamWhenDestroyed)
  8451. streamToDelete = inputStream;
  8452. init();
  8453. }
  8454. ZipFile::ZipFile (const File& file)
  8455. : inputStream (0)
  8456. #if JUCE_DEBUG
  8457. , numOpenStreams (0)
  8458. #endif
  8459. {
  8460. inputSource = new FileInputSource (file);
  8461. init();
  8462. }
  8463. ZipFile::ZipFile (InputSource* const inputSource_)
  8464. : inputStream (0),
  8465. inputSource (inputSource_)
  8466. #if JUCE_DEBUG
  8467. , numOpenStreams (0)
  8468. #endif
  8469. {
  8470. init();
  8471. }
  8472. ZipFile::~ZipFile()
  8473. {
  8474. #if JUCE_DEBUG
  8475. entries.clear();
  8476. // If you hit this assertion, it means you've created a stream to read
  8477. // one of the items in the zipfile, but you've forgotten to delete that
  8478. // stream object before deleting the file.. Streams can't be kept open
  8479. // after the file is deleted because they need to share the input
  8480. // stream that the file uses to read itself.
  8481. jassert (numOpenStreams == 0);
  8482. #endif
  8483. }
  8484. int ZipFile::getNumEntries() const throw()
  8485. {
  8486. return entries.size();
  8487. }
  8488. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8489. {
  8490. ZipEntryInfo* const zei = entries [index];
  8491. return zei != 0 ? &(zei->entry) : 0;
  8492. }
  8493. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8494. {
  8495. for (int i = 0; i < entries.size(); ++i)
  8496. if (entries.getUnchecked (i)->entry.filename == fileName)
  8497. return i;
  8498. return -1;
  8499. }
  8500. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8501. {
  8502. return getEntry (getIndexOfFileName (fileName));
  8503. }
  8504. InputStream* ZipFile::createStreamForEntry (const int index)
  8505. {
  8506. ZipEntryInfo* const zei = entries[index];
  8507. InputStream* stream = 0;
  8508. if (zei != 0)
  8509. {
  8510. stream = new ZipInputStream (*this, *zei);
  8511. if (zei->compressed)
  8512. {
  8513. stream = new GZIPDecompressorInputStream (stream, true, true,
  8514. zei->entry.uncompressedSize);
  8515. // (much faster to unzip in big blocks using a buffer..)
  8516. stream = new BufferedInputStream (stream, 32768, true);
  8517. }
  8518. }
  8519. return stream;
  8520. }
  8521. class ZipFile::ZipFilenameComparator
  8522. {
  8523. public:
  8524. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8525. {
  8526. return first->entry.filename.compare (second->entry.filename);
  8527. }
  8528. };
  8529. void ZipFile::sortEntriesByFilename()
  8530. {
  8531. ZipFilenameComparator sorter;
  8532. entries.sort (sorter);
  8533. }
  8534. void ZipFile::init()
  8535. {
  8536. ScopedPointer <InputStream> toDelete;
  8537. InputStream* in = inputStream;
  8538. if (inputSource != 0)
  8539. {
  8540. in = inputSource->createInputStream();
  8541. toDelete = in;
  8542. }
  8543. if (in != 0)
  8544. {
  8545. int numEntries = 0;
  8546. int pos = findEndOfZipEntryTable (in, numEntries);
  8547. if (pos >= 0 && pos < in->getTotalLength())
  8548. {
  8549. const int size = (int) (in->getTotalLength() - pos);
  8550. in->setPosition (pos);
  8551. MemoryBlock headerData;
  8552. if (in->readIntoMemoryBlock (headerData, size) == size)
  8553. {
  8554. pos = 0;
  8555. for (int i = 0; i < numEntries; ++i)
  8556. {
  8557. if (pos + 46 > size)
  8558. break;
  8559. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8560. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8561. if (pos + 46 + fileNameLen > size)
  8562. break;
  8563. ZipEntryInfo* const zei = new ZipEntryInfo();
  8564. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8565. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8566. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8567. const int year = 1980 + (date >> 9);
  8568. const int month = ((date >> 5) & 15) - 1;
  8569. const int day = date & 31;
  8570. const int hours = time >> 11;
  8571. const int minutes = (time >> 5) & 63;
  8572. const int seconds = (time & 31) << 1;
  8573. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8574. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8575. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8576. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8577. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8578. entries.add (zei);
  8579. pos += 46 + fileNameLen
  8580. + ByteOrder::littleEndianShort (buffer + 30)
  8581. + ByteOrder::littleEndianShort (buffer + 32);
  8582. }
  8583. }
  8584. }
  8585. }
  8586. }
  8587. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8588. {
  8589. BufferedInputStream in (input, 8192, false);
  8590. in.setPosition (in.getTotalLength());
  8591. int64 pos = in.getPosition();
  8592. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8593. char buffer [32];
  8594. zeromem (buffer, sizeof (buffer));
  8595. while (pos > lowestPos)
  8596. {
  8597. in.setPosition (pos - 22);
  8598. pos = in.getPosition();
  8599. memcpy (buffer + 22, buffer, 4);
  8600. if (in.read (buffer, 22) != 22)
  8601. return 0;
  8602. for (int i = 0; i < 22; ++i)
  8603. {
  8604. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8605. {
  8606. in.setPosition (pos + i);
  8607. in.read (buffer, 22);
  8608. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8609. return ByteOrder::littleEndianInt (buffer + 16);
  8610. }
  8611. }
  8612. }
  8613. return 0;
  8614. }
  8615. bool ZipFile::uncompressTo (const File& targetDirectory,
  8616. const bool shouldOverwriteFiles)
  8617. {
  8618. for (int i = 0; i < entries.size(); ++i)
  8619. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8620. return false;
  8621. return true;
  8622. }
  8623. bool ZipFile::uncompressEntry (const int index,
  8624. const File& targetDirectory,
  8625. bool shouldOverwriteFiles)
  8626. {
  8627. const ZipEntryInfo* zei = entries [index];
  8628. if (zei != 0)
  8629. {
  8630. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8631. if (zei->entry.filename.endsWithChar ('/'))
  8632. {
  8633. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8634. }
  8635. else
  8636. {
  8637. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8638. if (in != 0)
  8639. {
  8640. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8641. return false;
  8642. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8643. {
  8644. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8645. if (out != 0)
  8646. {
  8647. out->writeFromInputStream (*in, -1);
  8648. out = 0;
  8649. targetFile.setCreationTime (zei->entry.fileTime);
  8650. targetFile.setLastModificationTime (zei->entry.fileTime);
  8651. targetFile.setLastAccessTime (zei->entry.fileTime);
  8652. return true;
  8653. }
  8654. }
  8655. }
  8656. }
  8657. }
  8658. return false;
  8659. }
  8660. END_JUCE_NAMESPACE
  8661. /*** End of inlined file: juce_ZipFile.cpp ***/
  8662. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8663. #if JUCE_MSVC
  8664. #pragma warning (push)
  8665. #pragma warning (disable: 4514 4996)
  8666. #endif
  8667. #include <cwctype>
  8668. #include <cctype>
  8669. #include <ctime>
  8670. BEGIN_JUCE_NAMESPACE
  8671. int CharacterFunctions::length (const char* const s) throw()
  8672. {
  8673. return (int) strlen (s);
  8674. }
  8675. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8676. {
  8677. return (int) wcslen (s);
  8678. }
  8679. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8680. {
  8681. strncpy (dest, src, maxChars);
  8682. }
  8683. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8684. {
  8685. wcsncpy (dest, src, maxChars);
  8686. }
  8687. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8688. {
  8689. mbstowcs (dest, src, maxChars);
  8690. }
  8691. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8692. {
  8693. wcstombs (dest, src, maxChars);
  8694. }
  8695. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8696. {
  8697. return (int) wcstombs (0, src, 0);
  8698. }
  8699. void CharacterFunctions::append (char* dest, const char* src) throw()
  8700. {
  8701. strcat (dest, src);
  8702. }
  8703. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8704. {
  8705. wcscat (dest, src);
  8706. }
  8707. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8708. {
  8709. return strcmp (s1, s2);
  8710. }
  8711. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8712. {
  8713. jassert (s1 != 0 && s2 != 0);
  8714. return wcscmp (s1, s2);
  8715. }
  8716. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8717. {
  8718. jassert (s1 != 0 && s2 != 0);
  8719. return strncmp (s1, s2, maxChars);
  8720. }
  8721. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8722. {
  8723. jassert (s1 != 0 && s2 != 0);
  8724. return wcsncmp (s1, s2, maxChars);
  8725. }
  8726. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8727. {
  8728. jassert (s1 != 0 && s2 != 0);
  8729. for (;;)
  8730. {
  8731. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8732. if (diff != 0)
  8733. return diff;
  8734. else if (*s1 == 0)
  8735. break;
  8736. ++s1;
  8737. ++s2;
  8738. }
  8739. return 0;
  8740. }
  8741. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8742. {
  8743. return -compare (s2, s1);
  8744. }
  8745. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8746. {
  8747. jassert (s1 != 0 && s2 != 0);
  8748. #if JUCE_WINDOWS
  8749. return stricmp (s1, s2);
  8750. #else
  8751. return strcasecmp (s1, s2);
  8752. #endif
  8753. }
  8754. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8755. {
  8756. jassert (s1 != 0 && s2 != 0);
  8757. #if JUCE_WINDOWS
  8758. return _wcsicmp (s1, s2);
  8759. #else
  8760. for (;;)
  8761. {
  8762. if (*s1 != *s2)
  8763. {
  8764. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8765. if (diff != 0)
  8766. return diff < 0 ? -1 : 1;
  8767. }
  8768. else if (*s1 == 0)
  8769. break;
  8770. ++s1;
  8771. ++s2;
  8772. }
  8773. return 0;
  8774. #endif
  8775. }
  8776. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8777. {
  8778. jassert (s1 != 0 && s2 != 0);
  8779. for (;;)
  8780. {
  8781. if (*s1 != *s2)
  8782. {
  8783. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8784. if (diff != 0)
  8785. return diff < 0 ? -1 : 1;
  8786. }
  8787. else if (*s1 == 0)
  8788. break;
  8789. ++s1;
  8790. ++s2;
  8791. }
  8792. return 0;
  8793. }
  8794. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8795. {
  8796. jassert (s1 != 0 && s2 != 0);
  8797. #if JUCE_WINDOWS
  8798. return strnicmp (s1, s2, maxChars);
  8799. #else
  8800. return strncasecmp (s1, s2, maxChars);
  8801. #endif
  8802. }
  8803. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8804. {
  8805. jassert (s1 != 0 && s2 != 0);
  8806. #if JUCE_WINDOWS
  8807. return _wcsnicmp (s1, s2, maxChars);
  8808. #else
  8809. while (--maxChars >= 0)
  8810. {
  8811. if (*s1 != *s2)
  8812. {
  8813. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8814. if (diff != 0)
  8815. return diff < 0 ? -1 : 1;
  8816. }
  8817. else if (*s1 == 0)
  8818. break;
  8819. ++s1;
  8820. ++s2;
  8821. }
  8822. return 0;
  8823. #endif
  8824. }
  8825. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8826. {
  8827. return strstr (haystack, needle);
  8828. }
  8829. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8830. {
  8831. return wcsstr (haystack, needle);
  8832. }
  8833. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8834. {
  8835. if (haystack != 0)
  8836. {
  8837. int i = 0;
  8838. if (ignoreCase)
  8839. {
  8840. const char n1 = toLowerCase (needle);
  8841. const char n2 = toUpperCase (needle);
  8842. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8843. {
  8844. while (haystack[i] != 0)
  8845. {
  8846. if (haystack[i] == n1 || haystack[i] == n2)
  8847. return i;
  8848. ++i;
  8849. }
  8850. return -1;
  8851. }
  8852. jassert (n1 == needle);
  8853. }
  8854. while (haystack[i] != 0)
  8855. {
  8856. if (haystack[i] == needle)
  8857. return i;
  8858. ++i;
  8859. }
  8860. }
  8861. return -1;
  8862. }
  8863. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8864. {
  8865. if (haystack != 0)
  8866. {
  8867. int i = 0;
  8868. if (ignoreCase)
  8869. {
  8870. const juce_wchar n1 = toLowerCase (needle);
  8871. const juce_wchar n2 = toUpperCase (needle);
  8872. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8873. {
  8874. while (haystack[i] != 0)
  8875. {
  8876. if (haystack[i] == n1 || haystack[i] == n2)
  8877. return i;
  8878. ++i;
  8879. }
  8880. return -1;
  8881. }
  8882. jassert (n1 == needle);
  8883. }
  8884. while (haystack[i] != 0)
  8885. {
  8886. if (haystack[i] == needle)
  8887. return i;
  8888. ++i;
  8889. }
  8890. }
  8891. return -1;
  8892. }
  8893. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8894. {
  8895. jassert (haystack != 0);
  8896. int i = 0;
  8897. while (haystack[i] != 0)
  8898. {
  8899. if (haystack[i] == needle)
  8900. return i;
  8901. ++i;
  8902. }
  8903. return -1;
  8904. }
  8905. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8906. {
  8907. jassert (haystack != 0);
  8908. int i = 0;
  8909. while (haystack[i] != 0)
  8910. {
  8911. if (haystack[i] == needle)
  8912. return i;
  8913. ++i;
  8914. }
  8915. return -1;
  8916. }
  8917. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8918. {
  8919. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8920. }
  8921. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8922. {
  8923. if (allowedChars == 0)
  8924. return 0;
  8925. int i = 0;
  8926. for (;;)
  8927. {
  8928. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8929. break;
  8930. ++i;
  8931. }
  8932. return i;
  8933. }
  8934. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8935. {
  8936. return (int) strftime (dest, maxChars, format, tm);
  8937. }
  8938. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8939. {
  8940. return (int) wcsftime (dest, maxChars, format, tm);
  8941. }
  8942. int CharacterFunctions::getIntValue (const char* const s) throw()
  8943. {
  8944. return atoi (s);
  8945. }
  8946. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8947. {
  8948. #if JUCE_WINDOWS
  8949. return _wtoi (s);
  8950. #else
  8951. int v = 0;
  8952. while (isWhitespace (*s))
  8953. ++s;
  8954. const bool isNeg = *s == '-';
  8955. if (isNeg)
  8956. ++s;
  8957. for (;;)
  8958. {
  8959. const wchar_t c = *s++;
  8960. if (c >= '0' && c <= '9')
  8961. v = v * 10 + (int) (c - '0');
  8962. else
  8963. break;
  8964. }
  8965. return isNeg ? -v : v;
  8966. #endif
  8967. }
  8968. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8969. {
  8970. #if JUCE_LINUX
  8971. return atoll (s);
  8972. #elif JUCE_WINDOWS
  8973. return _atoi64 (s);
  8974. #else
  8975. int64 v = 0;
  8976. while (isWhitespace (*s))
  8977. ++s;
  8978. const bool isNeg = *s == '-';
  8979. if (isNeg)
  8980. ++s;
  8981. for (;;)
  8982. {
  8983. const char c = *s++;
  8984. if (c >= '0' && c <= '9')
  8985. v = v * 10 + (int64) (c - '0');
  8986. else
  8987. break;
  8988. }
  8989. return isNeg ? -v : v;
  8990. #endif
  8991. }
  8992. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8993. {
  8994. #if JUCE_WINDOWS
  8995. return _wtoi64 (s);
  8996. #else
  8997. int64 v = 0;
  8998. while (isWhitespace (*s))
  8999. ++s;
  9000. const bool isNeg = *s == '-';
  9001. if (isNeg)
  9002. ++s;
  9003. for (;;)
  9004. {
  9005. const juce_wchar c = *s++;
  9006. if (c >= '0' && c <= '9')
  9007. v = v * 10 + (int64) (c - '0');
  9008. else
  9009. break;
  9010. }
  9011. return isNeg ? -v : v;
  9012. #endif
  9013. }
  9014. static double juce_mulexp10 (const double value, int exponent) throw()
  9015. {
  9016. if (exponent == 0)
  9017. return value;
  9018. if (value == 0)
  9019. return 0;
  9020. const bool negative = (exponent < 0);
  9021. if (negative)
  9022. exponent = -exponent;
  9023. double result = 1.0, power = 10.0;
  9024. for (int bit = 1; exponent != 0; bit <<= 1)
  9025. {
  9026. if ((exponent & bit) != 0)
  9027. {
  9028. exponent ^= bit;
  9029. result *= power;
  9030. if (exponent == 0)
  9031. break;
  9032. }
  9033. power *= power;
  9034. }
  9035. return negative ? (value / result) : (value * result);
  9036. }
  9037. template <class CharType>
  9038. double juce_atof (const CharType* const original) throw()
  9039. {
  9040. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9041. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9042. int exponent = 0, decPointIndex = 0, digit = 0;
  9043. int lastDigit = 0, numSignificantDigits = 0;
  9044. bool isNegative = false, digitsFound = false;
  9045. const int maxSignificantDigits = 15 + 2;
  9046. const CharType* s = original;
  9047. while (CharacterFunctions::isWhitespace (*s))
  9048. ++s;
  9049. switch (*s)
  9050. {
  9051. case '-': isNegative = true; // fall-through..
  9052. case '+': ++s;
  9053. }
  9054. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9055. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9056. for (;;)
  9057. {
  9058. if (CharacterFunctions::isDigit (*s))
  9059. {
  9060. lastDigit = digit;
  9061. digit = *s++ - '0';
  9062. digitsFound = true;
  9063. if (decPointIndex != 0)
  9064. exponentAdjustment[1]++;
  9065. if (numSignificantDigits == 0 && digit == 0)
  9066. continue;
  9067. if (++numSignificantDigits > maxSignificantDigits)
  9068. {
  9069. if (digit > 5)
  9070. ++accumulator [decPointIndex];
  9071. else if (digit == 5 && (lastDigit & 1) != 0)
  9072. ++accumulator [decPointIndex];
  9073. if (decPointIndex > 0)
  9074. exponentAdjustment[1]--;
  9075. else
  9076. exponentAdjustment[0]++;
  9077. while (CharacterFunctions::isDigit (*s))
  9078. {
  9079. ++s;
  9080. if (decPointIndex == 0)
  9081. exponentAdjustment[0]++;
  9082. }
  9083. }
  9084. else
  9085. {
  9086. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9087. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9088. {
  9089. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9090. + accumulator [decPointIndex];
  9091. accumulator [decPointIndex] = 0;
  9092. exponentAccumulator [decPointIndex] = 0;
  9093. }
  9094. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9095. exponentAccumulator [decPointIndex]++;
  9096. }
  9097. }
  9098. else if (decPointIndex == 0 && *s == '.')
  9099. {
  9100. ++s;
  9101. decPointIndex = 1;
  9102. if (numSignificantDigits > maxSignificantDigits)
  9103. {
  9104. while (CharacterFunctions::isDigit (*s))
  9105. ++s;
  9106. break;
  9107. }
  9108. }
  9109. else
  9110. {
  9111. break;
  9112. }
  9113. }
  9114. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9115. if (decPointIndex != 0)
  9116. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9117. if ((*s == 'e' || *s == 'E') && digitsFound)
  9118. {
  9119. bool negativeExponent = false;
  9120. switch (*++s)
  9121. {
  9122. case '-': negativeExponent = true; // fall-through..
  9123. case '+': ++s;
  9124. }
  9125. while (CharacterFunctions::isDigit (*s))
  9126. exponent = (exponent * 10) + (*s++ - '0');
  9127. if (negativeExponent)
  9128. exponent = -exponent;
  9129. }
  9130. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9131. if (decPointIndex != 0)
  9132. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9133. return isNegative ? -r : r;
  9134. }
  9135. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9136. {
  9137. return juce_atof <char> (s);
  9138. }
  9139. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9140. {
  9141. return juce_atof <juce_wchar> (s);
  9142. }
  9143. char CharacterFunctions::toUpperCase (const char character) throw()
  9144. {
  9145. return (char) toupper (character);
  9146. }
  9147. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9148. {
  9149. return towupper (character);
  9150. }
  9151. void CharacterFunctions::toUpperCase (char* s) throw()
  9152. {
  9153. #if JUCE_WINDOWS
  9154. strupr (s);
  9155. #else
  9156. while (*s != 0)
  9157. {
  9158. *s = toUpperCase (*s);
  9159. ++s;
  9160. }
  9161. #endif
  9162. }
  9163. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9164. {
  9165. #if JUCE_WINDOWS
  9166. _wcsupr (s);
  9167. #else
  9168. while (*s != 0)
  9169. {
  9170. *s = toUpperCase (*s);
  9171. ++s;
  9172. }
  9173. #endif
  9174. }
  9175. bool CharacterFunctions::isUpperCase (const char character) throw()
  9176. {
  9177. return isupper (character) != 0;
  9178. }
  9179. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9180. {
  9181. #if JUCE_WINDOWS
  9182. return iswupper (character) != 0;
  9183. #else
  9184. return toLowerCase (character) != character;
  9185. #endif
  9186. }
  9187. char CharacterFunctions::toLowerCase (const char character) throw()
  9188. {
  9189. return (char) tolower (character);
  9190. }
  9191. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9192. {
  9193. return towlower (character);
  9194. }
  9195. void CharacterFunctions::toLowerCase (char* s) throw()
  9196. {
  9197. #if JUCE_WINDOWS
  9198. strlwr (s);
  9199. #else
  9200. while (*s != 0)
  9201. {
  9202. *s = toLowerCase (*s);
  9203. ++s;
  9204. }
  9205. #endif
  9206. }
  9207. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9208. {
  9209. #if JUCE_WINDOWS
  9210. _wcslwr (s);
  9211. #else
  9212. while (*s != 0)
  9213. {
  9214. *s = toLowerCase (*s);
  9215. ++s;
  9216. }
  9217. #endif
  9218. }
  9219. bool CharacterFunctions::isLowerCase (const char character) throw()
  9220. {
  9221. return islower (character) != 0;
  9222. }
  9223. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9224. {
  9225. #if JUCE_WINDOWS
  9226. return iswlower (character) != 0;
  9227. #else
  9228. return toUpperCase (character) != character;
  9229. #endif
  9230. }
  9231. bool CharacterFunctions::isWhitespace (const char character) throw()
  9232. {
  9233. return character == ' ' || (character <= 13 && character >= 9);
  9234. }
  9235. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9236. {
  9237. return iswspace (character) != 0;
  9238. }
  9239. bool CharacterFunctions::isDigit (const char character) throw()
  9240. {
  9241. return (character >= '0' && character <= '9');
  9242. }
  9243. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9244. {
  9245. return iswdigit (character) != 0;
  9246. }
  9247. bool CharacterFunctions::isLetter (const char character) throw()
  9248. {
  9249. return (character >= 'a' && character <= 'z')
  9250. || (character >= 'A' && character <= 'Z');
  9251. }
  9252. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9253. {
  9254. return iswalpha (character) != 0;
  9255. }
  9256. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9257. {
  9258. return (character >= 'a' && character <= 'z')
  9259. || (character >= 'A' && character <= 'Z')
  9260. || (character >= '0' && character <= '9');
  9261. }
  9262. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9263. {
  9264. return iswalnum (character) != 0;
  9265. }
  9266. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9267. {
  9268. unsigned int d = digit - '0';
  9269. if (d < (unsigned int) 10)
  9270. return (int) d;
  9271. d += (unsigned int) ('0' - 'a');
  9272. if (d < (unsigned int) 6)
  9273. return (int) d + 10;
  9274. d += (unsigned int) ('a' - 'A');
  9275. if (d < (unsigned int) 6)
  9276. return (int) d + 10;
  9277. return -1;
  9278. }
  9279. #if JUCE_MSVC
  9280. #pragma warning (pop)
  9281. #endif
  9282. END_JUCE_NAMESPACE
  9283. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9284. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9285. BEGIN_JUCE_NAMESPACE
  9286. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9287. {
  9288. loadFromText (fileContents);
  9289. }
  9290. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9291. {
  9292. loadFromText (fileToLoad.loadFileAsString());
  9293. }
  9294. LocalisedStrings::~LocalisedStrings()
  9295. {
  9296. }
  9297. const String LocalisedStrings::translate (const String& text) const
  9298. {
  9299. return translations.getValue (text, text);
  9300. }
  9301. static int findCloseQuote (const String& text, int startPos)
  9302. {
  9303. juce_wchar lastChar = 0;
  9304. for (;;)
  9305. {
  9306. const juce_wchar c = text [startPos];
  9307. if (c == 0 || (c == '"' && lastChar != '\\'))
  9308. break;
  9309. lastChar = c;
  9310. ++startPos;
  9311. }
  9312. return startPos;
  9313. }
  9314. static const String unescapeString (const String& s)
  9315. {
  9316. return s.replace ("\\\"", "\"")
  9317. .replace ("\\\'", "\'")
  9318. .replace ("\\t", "\t")
  9319. .replace ("\\r", "\r")
  9320. .replace ("\\n", "\n");
  9321. }
  9322. void LocalisedStrings::loadFromText (const String& fileContents)
  9323. {
  9324. StringArray lines;
  9325. lines.addLines (fileContents);
  9326. for (int i = 0; i < lines.size(); ++i)
  9327. {
  9328. String line (lines[i].trim());
  9329. if (line.startsWithChar ('"'))
  9330. {
  9331. int closeQuote = findCloseQuote (line, 1);
  9332. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9333. if (originalText.isNotEmpty())
  9334. {
  9335. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9336. closeQuote = findCloseQuote (line, openingQuote + 1);
  9337. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9338. if (newText.isNotEmpty())
  9339. translations.set (originalText, newText);
  9340. }
  9341. }
  9342. else if (line.startsWithIgnoreCase ("language:"))
  9343. {
  9344. languageName = line.substring (9).trim();
  9345. }
  9346. else if (line.startsWithIgnoreCase ("countries:"))
  9347. {
  9348. countryCodes.addTokens (line.substring (10).trim(), true);
  9349. countryCodes.trim();
  9350. countryCodes.removeEmptyStrings();
  9351. }
  9352. }
  9353. }
  9354. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9355. {
  9356. translations.setIgnoresCase (shouldIgnoreCase);
  9357. }
  9358. static CriticalSection currentMappingsLock;
  9359. static LocalisedStrings* currentMappings = 0;
  9360. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9361. {
  9362. const ScopedLock sl (currentMappingsLock);
  9363. delete currentMappings;
  9364. currentMappings = newTranslations;
  9365. }
  9366. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9367. {
  9368. return currentMappings;
  9369. }
  9370. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9371. {
  9372. const ScopedLock sl (currentMappingsLock);
  9373. if (currentMappings != 0)
  9374. return currentMappings->translate (text);
  9375. return text;
  9376. }
  9377. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9378. {
  9379. return translateWithCurrentMappings (String (text));
  9380. }
  9381. END_JUCE_NAMESPACE
  9382. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9383. /*** Start of inlined file: juce_String.cpp ***/
  9384. #if JUCE_MSVC
  9385. #pragma warning (push)
  9386. #pragma warning (disable: 4514)
  9387. #endif
  9388. #include <locale>
  9389. BEGIN_JUCE_NAMESPACE
  9390. #if JUCE_MSVC
  9391. #pragma warning (pop)
  9392. #endif
  9393. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9394. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9395. #endif
  9396. class StringHolder
  9397. {
  9398. public:
  9399. StringHolder()
  9400. : refCount (0x3fffffff), allocatedNumChars (0)
  9401. {
  9402. text[0] = 0;
  9403. }
  9404. static juce_wchar* createUninitialised (const size_t numChars)
  9405. {
  9406. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9407. s->refCount.value = 0;
  9408. s->allocatedNumChars = numChars;
  9409. return &(s->text[0]);
  9410. }
  9411. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9412. {
  9413. juce_wchar* const dest = createUninitialised (numChars);
  9414. copyChars (dest, src, numChars);
  9415. return dest;
  9416. }
  9417. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9418. {
  9419. juce_wchar* const dest = createUninitialised (numChars);
  9420. CharacterFunctions::copy (dest, src, (int) numChars);
  9421. dest [numChars] = 0;
  9422. return dest;
  9423. }
  9424. static inline juce_wchar* getEmpty() throw()
  9425. {
  9426. return &(empty.text[0]);
  9427. }
  9428. static void retain (juce_wchar* const text) throw()
  9429. {
  9430. ++(bufferFromText (text)->refCount);
  9431. }
  9432. static inline void release (StringHolder* const b) throw()
  9433. {
  9434. if (--(b->refCount) == -1 && b != &empty)
  9435. delete[] reinterpret_cast <char*> (b);
  9436. }
  9437. static void release (juce_wchar* const text) throw()
  9438. {
  9439. release (bufferFromText (text));
  9440. }
  9441. static juce_wchar* makeUnique (juce_wchar* const text)
  9442. {
  9443. StringHolder* const b = bufferFromText (text);
  9444. if (b->refCount.get() <= 0)
  9445. return text;
  9446. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9447. release (b);
  9448. return newText;
  9449. }
  9450. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9451. {
  9452. StringHolder* const b = bufferFromText (text);
  9453. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9454. return text;
  9455. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9456. copyChars (newText, text, b->allocatedNumChars);
  9457. release (b);
  9458. return newText;
  9459. }
  9460. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9461. {
  9462. return bufferFromText (text)->allocatedNumChars;
  9463. }
  9464. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9465. {
  9466. jassert (src != 0 && dest != 0);
  9467. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9468. dest [numChars] = 0;
  9469. }
  9470. Atomic<int> refCount;
  9471. size_t allocatedNumChars;
  9472. juce_wchar text[1];
  9473. static StringHolder empty;
  9474. private:
  9475. static inline StringHolder* bufferFromText (void* const text) throw()
  9476. {
  9477. // (Can't use offsetof() here because of warnings about this not being a POD)
  9478. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9479. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9480. }
  9481. };
  9482. StringHolder StringHolder::empty;
  9483. const String String::empty;
  9484. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9485. {
  9486. jassert (t[numChars] == 0); // must have a null terminator
  9487. text = StringHolder::createCopy (t, numChars);
  9488. }
  9489. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9490. {
  9491. if (numExtraChars > 0)
  9492. {
  9493. const int oldLen = length();
  9494. const int newTotalLen = oldLen + numExtraChars;
  9495. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9496. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9497. }
  9498. }
  9499. void String::preallocateStorage (const size_t numChars)
  9500. {
  9501. text = StringHolder::makeUniqueWithSize (text, numChars);
  9502. }
  9503. String::String() throw()
  9504. : text (StringHolder::getEmpty())
  9505. {
  9506. }
  9507. String::~String() throw()
  9508. {
  9509. StringHolder::release (text);
  9510. }
  9511. String::String (const String& other) throw()
  9512. : text (other.text)
  9513. {
  9514. StringHolder::retain (text);
  9515. }
  9516. void String::swapWith (String& other) throw()
  9517. {
  9518. swapVariables (text, other.text);
  9519. }
  9520. String& String::operator= (const String& other) throw()
  9521. {
  9522. juce_wchar* const newText = other.text;
  9523. StringHolder::retain (newText);
  9524. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9525. return *this;
  9526. }
  9527. String::String (const size_t numChars, const int /*dummyVariable*/)
  9528. : text (StringHolder::createUninitialised (numChars))
  9529. {
  9530. }
  9531. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9532. {
  9533. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9534. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9535. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9536. }
  9537. String::String (const char* const t)
  9538. {
  9539. if (t != 0 && *t != 0)
  9540. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9541. else
  9542. text = StringHolder::getEmpty();
  9543. }
  9544. String::String (const juce_wchar* const t)
  9545. {
  9546. if (t != 0 && *t != 0)
  9547. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9548. else
  9549. text = StringHolder::getEmpty();
  9550. }
  9551. String::String (const char* const t, const size_t maxChars)
  9552. {
  9553. int i;
  9554. for (i = 0; (size_t) i < maxChars; ++i)
  9555. if (t[i] == 0)
  9556. break;
  9557. if (i > 0)
  9558. text = StringHolder::createCopy (t, i);
  9559. else
  9560. text = StringHolder::getEmpty();
  9561. }
  9562. String::String (const juce_wchar* const t, const size_t maxChars)
  9563. {
  9564. int i;
  9565. for (i = 0; (size_t) i < maxChars; ++i)
  9566. if (t[i] == 0)
  9567. break;
  9568. if (i > 0)
  9569. text = StringHolder::createCopy (t, i);
  9570. else
  9571. text = StringHolder::getEmpty();
  9572. }
  9573. const String String::charToString (const juce_wchar character)
  9574. {
  9575. String result ((size_t) 1, (int) 0);
  9576. result.text[0] = character;
  9577. result.text[1] = 0;
  9578. return result;
  9579. }
  9580. namespace NumberToStringConverters
  9581. {
  9582. // pass in a pointer to the END of a buffer..
  9583. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9584. {
  9585. *--t = 0;
  9586. int64 v = (n >= 0) ? n : -n;
  9587. do
  9588. {
  9589. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9590. v /= 10;
  9591. } while (v > 0);
  9592. if (n < 0)
  9593. *--t = '-';
  9594. return t;
  9595. }
  9596. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9597. {
  9598. *--t = 0;
  9599. do
  9600. {
  9601. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9602. v /= 10;
  9603. } while (v > 0);
  9604. return t;
  9605. }
  9606. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9607. {
  9608. if (n == (int) 0x80000000) // (would cause an overflow)
  9609. return int64ToString (t, n);
  9610. *--t = 0;
  9611. int v = abs (n);
  9612. do
  9613. {
  9614. *--t = (juce_wchar) ('0' + (v % 10));
  9615. v /= 10;
  9616. } while (v > 0);
  9617. if (n < 0)
  9618. *--t = '-';
  9619. return t;
  9620. }
  9621. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9622. {
  9623. *--t = 0;
  9624. do
  9625. {
  9626. *--t = (juce_wchar) ('0' + (v % 10));
  9627. v /= 10;
  9628. } while (v > 0);
  9629. return t;
  9630. }
  9631. static juce_wchar getDecimalPoint()
  9632. {
  9633. #if JUCE_MSVC && _MSC_VER < 1400
  9634. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9635. #else
  9636. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9637. #endif
  9638. return dp;
  9639. }
  9640. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9641. {
  9642. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9643. {
  9644. juce_wchar* const end = buffer + numChars;
  9645. juce_wchar* t = end;
  9646. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9647. *--t = (juce_wchar) 0;
  9648. while (numDecPlaces >= 0 || v > 0)
  9649. {
  9650. if (numDecPlaces == 0)
  9651. *--t = getDecimalPoint();
  9652. *--t = (juce_wchar) ('0' + (v % 10));
  9653. v /= 10;
  9654. --numDecPlaces;
  9655. }
  9656. if (n < 0)
  9657. *--t = '-';
  9658. len = end - t - 1;
  9659. return t;
  9660. }
  9661. else
  9662. {
  9663. #if JUCE_WINDOWS
  9664. #if JUCE_MSVC && _MSC_VER <= 1400
  9665. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9666. #else
  9667. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9668. #endif
  9669. #else
  9670. len = swprintf (buffer, numChars, L"%.9g", n);
  9671. #endif
  9672. return buffer;
  9673. }
  9674. }
  9675. }
  9676. String::String (const int number)
  9677. {
  9678. juce_wchar buffer [16];
  9679. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9680. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9681. createInternal (start, end - start - 1);
  9682. }
  9683. String::String (const unsigned int number)
  9684. {
  9685. juce_wchar buffer [16];
  9686. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9687. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9688. createInternal (start, end - start - 1);
  9689. }
  9690. String::String (const short number)
  9691. {
  9692. juce_wchar buffer [16];
  9693. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9694. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9695. createInternal (start, end - start - 1);
  9696. }
  9697. String::String (const unsigned short number)
  9698. {
  9699. juce_wchar buffer [16];
  9700. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9701. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9702. createInternal (start, end - start - 1);
  9703. }
  9704. String::String (const int64 number)
  9705. {
  9706. juce_wchar buffer [32];
  9707. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9708. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9709. createInternal (start, end - start - 1);
  9710. }
  9711. String::String (const uint64 number)
  9712. {
  9713. juce_wchar buffer [32];
  9714. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9715. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9716. createInternal (start, end - start - 1);
  9717. }
  9718. String::String (const float number, const int numberOfDecimalPlaces)
  9719. {
  9720. juce_wchar buffer [48];
  9721. size_t len;
  9722. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9723. createInternal (start, len);
  9724. }
  9725. String::String (const double number, const int numberOfDecimalPlaces)
  9726. {
  9727. juce_wchar buffer [48];
  9728. size_t len;
  9729. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9730. createInternal (start, len);
  9731. }
  9732. int String::length() const throw()
  9733. {
  9734. return CharacterFunctions::length (text);
  9735. }
  9736. int String::hashCode() const throw()
  9737. {
  9738. const juce_wchar* t = text;
  9739. int result = 0;
  9740. while (*t != (juce_wchar) 0)
  9741. result = 31 * result + *t++;
  9742. return result;
  9743. }
  9744. int64 String::hashCode64() const throw()
  9745. {
  9746. const juce_wchar* t = text;
  9747. int64 result = 0;
  9748. while (*t != (juce_wchar) 0)
  9749. result = 101 * result + *t++;
  9750. return result;
  9751. }
  9752. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9753. {
  9754. return string1.compare (string2) == 0;
  9755. }
  9756. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9757. {
  9758. return string1.compare (string2) == 0;
  9759. }
  9760. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9761. {
  9762. return string1.compare (string2) == 0;
  9763. }
  9764. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9765. {
  9766. return string1.compare (string2) != 0;
  9767. }
  9768. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9769. {
  9770. return string1.compare (string2) != 0;
  9771. }
  9772. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9773. {
  9774. return string1.compare (string2) != 0;
  9775. }
  9776. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9777. {
  9778. return string1.compare (string2) > 0;
  9779. }
  9780. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9781. {
  9782. return string1.compare (string2) < 0;
  9783. }
  9784. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9785. {
  9786. return string1.compare (string2) >= 0;
  9787. }
  9788. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9789. {
  9790. return string1.compare (string2) <= 0;
  9791. }
  9792. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9793. {
  9794. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9795. : isEmpty();
  9796. }
  9797. bool String::equalsIgnoreCase (const char* t) const throw()
  9798. {
  9799. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9800. : isEmpty();
  9801. }
  9802. bool String::equalsIgnoreCase (const String& other) const throw()
  9803. {
  9804. return text == other.text
  9805. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9806. }
  9807. int String::compare (const String& other) const throw()
  9808. {
  9809. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9810. }
  9811. int String::compare (const char* other) const throw()
  9812. {
  9813. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9814. }
  9815. int String::compare (const juce_wchar* other) const throw()
  9816. {
  9817. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9818. }
  9819. int String::compareIgnoreCase (const String& other) const throw()
  9820. {
  9821. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9822. }
  9823. int String::compareLexicographically (const String& other) const throw()
  9824. {
  9825. const juce_wchar* s1 = text;
  9826. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9827. ++s1;
  9828. const juce_wchar* s2 = other.text;
  9829. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9830. ++s2;
  9831. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9832. }
  9833. String& String::operator+= (const juce_wchar* const t)
  9834. {
  9835. if (t != 0)
  9836. appendInternal (t, CharacterFunctions::length (t));
  9837. return *this;
  9838. }
  9839. String& String::operator+= (const String& other)
  9840. {
  9841. if (isEmpty())
  9842. operator= (other);
  9843. else
  9844. appendInternal (other.text, other.length());
  9845. return *this;
  9846. }
  9847. String& String::operator+= (const char ch)
  9848. {
  9849. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9850. return operator+= (static_cast <const juce_wchar*> (asString));
  9851. }
  9852. String& String::operator+= (const juce_wchar ch)
  9853. {
  9854. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9855. return operator+= (static_cast <const juce_wchar*> (asString));
  9856. }
  9857. String& String::operator+= (const int number)
  9858. {
  9859. juce_wchar buffer [16];
  9860. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9861. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9862. appendInternal (start, (int) (end - start));
  9863. return *this;
  9864. }
  9865. String& String::operator+= (const unsigned int number)
  9866. {
  9867. juce_wchar buffer [16];
  9868. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9869. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9870. appendInternal (start, (int) (end - start));
  9871. return *this;
  9872. }
  9873. void String::append (const juce_wchar* const other, const int howMany)
  9874. {
  9875. if (howMany > 0)
  9876. {
  9877. int i;
  9878. for (i = 0; i < howMany; ++i)
  9879. if (other[i] == 0)
  9880. break;
  9881. appendInternal (other, i);
  9882. }
  9883. }
  9884. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9885. {
  9886. String s (string1);
  9887. return s += string2;
  9888. }
  9889. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9890. {
  9891. String s (string1);
  9892. return s += string2;
  9893. }
  9894. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9895. {
  9896. return String::charToString (string1) + string2;
  9897. }
  9898. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9899. {
  9900. return String::charToString (string1) + string2;
  9901. }
  9902. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9903. {
  9904. return string1 += string2;
  9905. }
  9906. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9907. {
  9908. return string1 += string2;
  9909. }
  9910. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9911. {
  9912. return string1 += string2;
  9913. }
  9914. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9915. {
  9916. return string1 += string2;
  9917. }
  9918. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9919. {
  9920. return string1 += string2;
  9921. }
  9922. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9923. {
  9924. return string1 += characterToAppend;
  9925. }
  9926. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9927. {
  9928. return string1 += characterToAppend;
  9929. }
  9930. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9931. {
  9932. return string1 += string2;
  9933. }
  9934. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9935. {
  9936. return string1 += string2;
  9937. }
  9938. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9939. {
  9940. return string1 += string2;
  9941. }
  9942. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9943. {
  9944. return string1 += (int) number;
  9945. }
  9946. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9947. {
  9948. return string1 += number;
  9949. }
  9950. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  9951. {
  9952. return string1 += number;
  9953. }
  9954. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9955. {
  9956. return string1 += (int) number;
  9957. }
  9958. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  9959. {
  9960. return string1 += (unsigned int) number;
  9961. }
  9962. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9963. {
  9964. return string1 += String (number);
  9965. }
  9966. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9967. {
  9968. return string1 += String (number);
  9969. }
  9970. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9971. {
  9972. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9973. // if lots of large, persistent strings were to be written to streams).
  9974. const int numBytes = text.getNumBytesAsUTF8();
  9975. HeapBlock<char> temp (numBytes + 1);
  9976. text.copyToUTF8 (temp, numBytes + 1);
  9977. stream.write (temp, numBytes);
  9978. return stream;
  9979. }
  9980. int String::indexOfChar (const juce_wchar character) const throw()
  9981. {
  9982. const juce_wchar* t = text;
  9983. for (;;)
  9984. {
  9985. if (*t == character)
  9986. return (int) (t - text);
  9987. if (*t++ == 0)
  9988. return -1;
  9989. }
  9990. }
  9991. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9992. {
  9993. for (int i = length(); --i >= 0;)
  9994. if (text[i] == character)
  9995. return i;
  9996. return -1;
  9997. }
  9998. int String::indexOf (const String& t) const throw()
  9999. {
  10000. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  10001. return r == 0 ? -1 : (int) (r - text);
  10002. }
  10003. int String::indexOfChar (const int startIndex,
  10004. const juce_wchar character) const throw()
  10005. {
  10006. if (startIndex > 0 && startIndex >= length())
  10007. return -1;
  10008. const juce_wchar* t = text + jmax (0, startIndex);
  10009. for (;;)
  10010. {
  10011. if (*t == character)
  10012. return (int) (t - text);
  10013. if (*t == 0)
  10014. return -1;
  10015. ++t;
  10016. }
  10017. }
  10018. int String::indexOfAnyOf (const String& charactersToLookFor,
  10019. const int startIndex,
  10020. const bool ignoreCase) const throw()
  10021. {
  10022. if (startIndex > 0 && startIndex >= length())
  10023. return -1;
  10024. const juce_wchar* t = text + jmax (0, startIndex);
  10025. while (*t != 0)
  10026. {
  10027. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10028. return (int) (t - text);
  10029. ++t;
  10030. }
  10031. return -1;
  10032. }
  10033. int String::indexOf (const int startIndex, const String& other) const throw()
  10034. {
  10035. if (startIndex > 0 && startIndex >= length())
  10036. return -1;
  10037. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10038. return found == 0 ? -1 : (int) (found - text);
  10039. }
  10040. int String::indexOfIgnoreCase (const String& other) const throw()
  10041. {
  10042. if (other.isNotEmpty())
  10043. {
  10044. const int len = other.length();
  10045. const int end = length() - len;
  10046. for (int i = 0; i <= end; ++i)
  10047. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10048. return i;
  10049. }
  10050. return -1;
  10051. }
  10052. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10053. {
  10054. if (other.isNotEmpty())
  10055. {
  10056. const int len = other.length();
  10057. const int end = length() - len;
  10058. for (int i = jmax (0, startIndex); i <= end; ++i)
  10059. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10060. return i;
  10061. }
  10062. return -1;
  10063. }
  10064. int String::lastIndexOf (const String& other) const throw()
  10065. {
  10066. if (other.isNotEmpty())
  10067. {
  10068. const int len = other.length();
  10069. int i = length() - len;
  10070. if (i >= 0)
  10071. {
  10072. const juce_wchar* n = text + i;
  10073. while (i >= 0)
  10074. {
  10075. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10076. return i;
  10077. --i;
  10078. }
  10079. }
  10080. }
  10081. return -1;
  10082. }
  10083. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10084. {
  10085. if (other.isNotEmpty())
  10086. {
  10087. const int len = other.length();
  10088. int i = length() - len;
  10089. if (i >= 0)
  10090. {
  10091. const juce_wchar* n = text + i;
  10092. while (i >= 0)
  10093. {
  10094. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10095. return i;
  10096. --i;
  10097. }
  10098. }
  10099. }
  10100. return -1;
  10101. }
  10102. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10103. {
  10104. for (int i = length(); --i >= 0;)
  10105. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10106. return i;
  10107. return -1;
  10108. }
  10109. bool String::contains (const String& other) const throw()
  10110. {
  10111. return indexOf (other) >= 0;
  10112. }
  10113. bool String::containsChar (const juce_wchar character) const throw()
  10114. {
  10115. const juce_wchar* t = text;
  10116. for (;;)
  10117. {
  10118. if (*t == 0)
  10119. return false;
  10120. if (*t == character)
  10121. return true;
  10122. ++t;
  10123. }
  10124. }
  10125. bool String::containsIgnoreCase (const String& t) const throw()
  10126. {
  10127. return indexOfIgnoreCase (t) >= 0;
  10128. }
  10129. int String::indexOfWholeWord (const String& word) const throw()
  10130. {
  10131. if (word.isNotEmpty())
  10132. {
  10133. const int wordLen = word.length();
  10134. const int end = length() - wordLen;
  10135. const juce_wchar* t = text;
  10136. for (int i = 0; i <= end; ++i)
  10137. {
  10138. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10139. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10140. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10141. {
  10142. return i;
  10143. }
  10144. ++t;
  10145. }
  10146. }
  10147. return -1;
  10148. }
  10149. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10150. {
  10151. if (word.isNotEmpty())
  10152. {
  10153. const int wordLen = word.length();
  10154. const int end = length() - wordLen;
  10155. const juce_wchar* t = text;
  10156. for (int i = 0; i <= end; ++i)
  10157. {
  10158. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10159. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10160. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10161. {
  10162. return i;
  10163. }
  10164. ++t;
  10165. }
  10166. }
  10167. return -1;
  10168. }
  10169. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10170. {
  10171. return indexOfWholeWord (wordToLookFor) >= 0;
  10172. }
  10173. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10174. {
  10175. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10176. }
  10177. static int indexOfMatch (const juce_wchar* const wildcard,
  10178. const juce_wchar* const test,
  10179. const bool ignoreCase) throw()
  10180. {
  10181. int start = 0;
  10182. while (test [start] != 0)
  10183. {
  10184. int i = 0;
  10185. for (;;)
  10186. {
  10187. const juce_wchar wc = wildcard [i];
  10188. const juce_wchar c = test [i + start];
  10189. if (wc == c
  10190. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10191. || (wc == '?' && c != 0))
  10192. {
  10193. if (wc == 0)
  10194. return start;
  10195. ++i;
  10196. }
  10197. else
  10198. {
  10199. if (wc == '*' && (wildcard [i + 1] == 0
  10200. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10201. {
  10202. return start;
  10203. }
  10204. break;
  10205. }
  10206. }
  10207. ++start;
  10208. }
  10209. return -1;
  10210. }
  10211. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10212. {
  10213. int i = 0;
  10214. for (;;)
  10215. {
  10216. const juce_wchar wc = wildcard.text [i];
  10217. const juce_wchar c = text [i];
  10218. if (wc == c
  10219. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10220. || (wc == '?' && c != 0))
  10221. {
  10222. if (wc == 0)
  10223. return true;
  10224. ++i;
  10225. }
  10226. else
  10227. {
  10228. return wc == '*' && (wildcard [i + 1] == 0
  10229. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10230. }
  10231. }
  10232. }
  10233. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10234. {
  10235. const int len = stringToRepeat.length();
  10236. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10237. juce_wchar* n = result.text;
  10238. *n = 0;
  10239. while (--numberOfTimesToRepeat >= 0)
  10240. {
  10241. StringHolder::copyChars (n, stringToRepeat.text, len);
  10242. n += len;
  10243. }
  10244. return result;
  10245. }
  10246. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10247. {
  10248. jassert (padCharacter != 0);
  10249. const int len = length();
  10250. if (len >= minimumLength || padCharacter == 0)
  10251. return *this;
  10252. String result ((size_t) minimumLength + 1, (int) 0);
  10253. juce_wchar* n = result.text;
  10254. minimumLength -= len;
  10255. while (--minimumLength >= 0)
  10256. *n++ = padCharacter;
  10257. StringHolder::copyChars (n, text, len);
  10258. return result;
  10259. }
  10260. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10261. {
  10262. jassert (padCharacter != 0);
  10263. const int len = length();
  10264. if (len >= minimumLength || padCharacter == 0)
  10265. return *this;
  10266. String result (*this, (size_t) minimumLength);
  10267. juce_wchar* n = result.text + len;
  10268. minimumLength -= len;
  10269. while (--minimumLength >= 0)
  10270. *n++ = padCharacter;
  10271. *n = 0;
  10272. return result;
  10273. }
  10274. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10275. {
  10276. if (index < 0)
  10277. {
  10278. // a negative index to replace from?
  10279. jassertfalse;
  10280. index = 0;
  10281. }
  10282. if (numCharsToReplace < 0)
  10283. {
  10284. // replacing a negative number of characters?
  10285. numCharsToReplace = 0;
  10286. jassertfalse;
  10287. }
  10288. const int len = length();
  10289. if (index + numCharsToReplace > len)
  10290. {
  10291. if (index > len)
  10292. {
  10293. // replacing beyond the end of the string?
  10294. index = len;
  10295. jassertfalse;
  10296. }
  10297. numCharsToReplace = len - index;
  10298. }
  10299. const int newStringLen = stringToInsert.length();
  10300. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10301. if (newTotalLen <= 0)
  10302. return String::empty;
  10303. String result ((size_t) newTotalLen, (int) 0);
  10304. StringHolder::copyChars (result.text, text, index);
  10305. if (newStringLen > 0)
  10306. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10307. const int endStringLen = newTotalLen - (index + newStringLen);
  10308. if (endStringLen > 0)
  10309. StringHolder::copyChars (result.text + (index + newStringLen),
  10310. text + (index + numCharsToReplace),
  10311. endStringLen);
  10312. return result;
  10313. }
  10314. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10315. {
  10316. const int stringToReplaceLen = stringToReplace.length();
  10317. const int stringToInsertLen = stringToInsert.length();
  10318. int i = 0;
  10319. String result (*this);
  10320. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10321. : result.indexOf (i, stringToReplace))) >= 0)
  10322. {
  10323. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10324. i += stringToInsertLen;
  10325. }
  10326. return result;
  10327. }
  10328. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10329. {
  10330. const int index = indexOfChar (charToReplace);
  10331. if (index < 0)
  10332. return *this;
  10333. String result (*this, size_t());
  10334. juce_wchar* t = result.text + index;
  10335. while (*t != 0)
  10336. {
  10337. if (*t == charToReplace)
  10338. *t = charToInsert;
  10339. ++t;
  10340. }
  10341. return result;
  10342. }
  10343. const String String::replaceCharacters (const String& charactersToReplace,
  10344. const String& charactersToInsertInstead) const
  10345. {
  10346. String result (*this, size_t());
  10347. juce_wchar* t = result.text;
  10348. const int len2 = charactersToInsertInstead.length();
  10349. // the two strings passed in are supposed to be the same length!
  10350. jassert (len2 == charactersToReplace.length());
  10351. while (*t != 0)
  10352. {
  10353. const int index = charactersToReplace.indexOfChar (*t);
  10354. if (((unsigned int) index) < (unsigned int) len2)
  10355. *t = charactersToInsertInstead [index];
  10356. ++t;
  10357. }
  10358. return result;
  10359. }
  10360. bool String::startsWith (const String& other) const throw()
  10361. {
  10362. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10363. }
  10364. bool String::startsWithIgnoreCase (const String& other) const throw()
  10365. {
  10366. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10367. }
  10368. bool String::startsWithChar (const juce_wchar character) const throw()
  10369. {
  10370. jassert (character != 0); // strings can't contain a null character!
  10371. return text[0] == character;
  10372. }
  10373. bool String::endsWithChar (const juce_wchar character) const throw()
  10374. {
  10375. jassert (character != 0); // strings can't contain a null character!
  10376. return text[0] != 0
  10377. && text [length() - 1] == character;
  10378. }
  10379. bool String::endsWith (const String& other) const throw()
  10380. {
  10381. const int thisLen = length();
  10382. const int otherLen = other.length();
  10383. return thisLen >= otherLen
  10384. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10385. }
  10386. bool String::endsWithIgnoreCase (const String& other) const throw()
  10387. {
  10388. const int thisLen = length();
  10389. const int otherLen = other.length();
  10390. return thisLen >= otherLen
  10391. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10392. }
  10393. const String String::toUpperCase() const
  10394. {
  10395. String result (*this, size_t());
  10396. CharacterFunctions::toUpperCase (result.text);
  10397. return result;
  10398. }
  10399. const String String::toLowerCase() const
  10400. {
  10401. String result (*this, size_t());
  10402. CharacterFunctions::toLowerCase (result.text);
  10403. return result;
  10404. }
  10405. juce_wchar& String::operator[] (const int index)
  10406. {
  10407. jassert (((unsigned int) index) <= (unsigned int) length());
  10408. text = StringHolder::makeUnique (text);
  10409. return text [index];
  10410. }
  10411. juce_wchar String::getLastCharacter() const throw()
  10412. {
  10413. return isEmpty() ? juce_wchar() : text [length() - 1];
  10414. }
  10415. const String String::substring (int start, int end) const
  10416. {
  10417. if (start < 0)
  10418. start = 0;
  10419. else if (end <= start)
  10420. return empty;
  10421. int len = 0;
  10422. while (len <= end && text [len] != 0)
  10423. ++len;
  10424. if (end >= len)
  10425. {
  10426. if (start == 0)
  10427. return *this;
  10428. end = len;
  10429. }
  10430. return String (text + start, end - start);
  10431. }
  10432. const String String::substring (const int start) const
  10433. {
  10434. if (start <= 0)
  10435. return *this;
  10436. const int len = length();
  10437. if (start >= len)
  10438. return empty;
  10439. return String (text + start, len - start);
  10440. }
  10441. const String String::dropLastCharacters (const int numberToDrop) const
  10442. {
  10443. return String (text, jmax (0, length() - numberToDrop));
  10444. }
  10445. const String String::getLastCharacters (const int numCharacters) const
  10446. {
  10447. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10448. }
  10449. const String String::fromFirstOccurrenceOf (const String& sub,
  10450. const bool includeSubString,
  10451. const bool ignoreCase) const
  10452. {
  10453. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10454. : indexOf (sub);
  10455. if (i < 0)
  10456. return empty;
  10457. return substring (includeSubString ? i : i + sub.length());
  10458. }
  10459. const String String::fromLastOccurrenceOf (const String& sub,
  10460. const bool includeSubString,
  10461. const bool ignoreCase) const
  10462. {
  10463. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10464. : lastIndexOf (sub);
  10465. if (i < 0)
  10466. return *this;
  10467. return substring (includeSubString ? i : i + sub.length());
  10468. }
  10469. const String String::upToFirstOccurrenceOf (const String& sub,
  10470. const bool includeSubString,
  10471. const bool ignoreCase) const
  10472. {
  10473. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10474. : indexOf (sub);
  10475. if (i < 0)
  10476. return *this;
  10477. return substring (0, includeSubString ? i + sub.length() : i);
  10478. }
  10479. const String String::upToLastOccurrenceOf (const String& sub,
  10480. const bool includeSubString,
  10481. const bool ignoreCase) const
  10482. {
  10483. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10484. : lastIndexOf (sub);
  10485. if (i < 0)
  10486. return *this;
  10487. return substring (0, includeSubString ? i + sub.length() : i);
  10488. }
  10489. bool String::isQuotedString() const
  10490. {
  10491. const String trimmed (trimStart());
  10492. return trimmed[0] == '"'
  10493. || trimmed[0] == '\'';
  10494. }
  10495. const String String::unquoted() const
  10496. {
  10497. String s (*this);
  10498. if (s.text[0] == '"' || s.text[0] == '\'')
  10499. s = s.substring (1);
  10500. const int lastCharIndex = s.length() - 1;
  10501. if (lastCharIndex >= 0
  10502. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10503. s [lastCharIndex] = 0;
  10504. return s;
  10505. }
  10506. const String String::quoted (const juce_wchar quoteCharacter) const
  10507. {
  10508. if (isEmpty())
  10509. return charToString (quoteCharacter) + quoteCharacter;
  10510. String t (*this);
  10511. if (! t.startsWithChar (quoteCharacter))
  10512. t = charToString (quoteCharacter) + t;
  10513. if (! t.endsWithChar (quoteCharacter))
  10514. t += quoteCharacter;
  10515. return t;
  10516. }
  10517. const String String::trim() const
  10518. {
  10519. if (isEmpty())
  10520. return empty;
  10521. int start = 0;
  10522. while (CharacterFunctions::isWhitespace (text [start]))
  10523. ++start;
  10524. const int len = length();
  10525. int end = len - 1;
  10526. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10527. --end;
  10528. ++end;
  10529. if (end <= start)
  10530. return empty;
  10531. else if (start > 0 || end < len)
  10532. return String (text + start, end - start);
  10533. return *this;
  10534. }
  10535. const String String::trimStart() const
  10536. {
  10537. if (isEmpty())
  10538. return empty;
  10539. const juce_wchar* t = text;
  10540. while (CharacterFunctions::isWhitespace (*t))
  10541. ++t;
  10542. if (t == text)
  10543. return *this;
  10544. return String (t);
  10545. }
  10546. const String String::trimEnd() const
  10547. {
  10548. if (isEmpty())
  10549. return empty;
  10550. const juce_wchar* endT = text + (length() - 1);
  10551. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10552. --endT;
  10553. return String (text, (int) (++endT - text));
  10554. }
  10555. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10556. {
  10557. const juce_wchar* t = text;
  10558. while (charactersToTrim.containsChar (*t))
  10559. ++t;
  10560. return t == text ? *this : String (t);
  10561. }
  10562. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10563. {
  10564. if (isEmpty())
  10565. return empty;
  10566. const int len = length();
  10567. const juce_wchar* endT = text + (len - 1);
  10568. int numToRemove = 0;
  10569. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10570. {
  10571. ++numToRemove;
  10572. --endT;
  10573. }
  10574. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10575. }
  10576. const String String::retainCharacters (const String& charactersToRetain) const
  10577. {
  10578. if (isEmpty())
  10579. return empty;
  10580. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10581. juce_wchar* dst = result.text;
  10582. const juce_wchar* src = text;
  10583. while (*src != 0)
  10584. {
  10585. if (charactersToRetain.containsChar (*src))
  10586. *dst++ = *src;
  10587. ++src;
  10588. }
  10589. *dst = 0;
  10590. return result;
  10591. }
  10592. const String String::removeCharacters (const String& charactersToRemove) const
  10593. {
  10594. if (isEmpty())
  10595. return empty;
  10596. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10597. juce_wchar* dst = result.text;
  10598. const juce_wchar* src = text;
  10599. while (*src != 0)
  10600. {
  10601. if (! charactersToRemove.containsChar (*src))
  10602. *dst++ = *src;
  10603. ++src;
  10604. }
  10605. *dst = 0;
  10606. return result;
  10607. }
  10608. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10609. {
  10610. int i = 0;
  10611. for (;;)
  10612. {
  10613. if (! permittedCharacters.containsChar (text[i]))
  10614. break;
  10615. ++i;
  10616. }
  10617. return substring (0, i);
  10618. }
  10619. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10620. {
  10621. const juce_wchar* const t = text;
  10622. int i = 0;
  10623. while (t[i] != 0)
  10624. {
  10625. if (charactersToStopAt.containsChar (t[i]))
  10626. return String (text, i);
  10627. ++i;
  10628. }
  10629. return empty;
  10630. }
  10631. bool String::containsOnly (const String& chars) const throw()
  10632. {
  10633. const juce_wchar* t = text;
  10634. while (*t != 0)
  10635. if (! chars.containsChar (*t++))
  10636. return false;
  10637. return true;
  10638. }
  10639. bool String::containsAnyOf (const String& chars) const throw()
  10640. {
  10641. const juce_wchar* t = text;
  10642. while (*t != 0)
  10643. if (chars.containsChar (*t++))
  10644. return true;
  10645. return false;
  10646. }
  10647. bool String::containsNonWhitespaceChars() const throw()
  10648. {
  10649. const juce_wchar* t = text;
  10650. while (*t != 0)
  10651. if (! CharacterFunctions::isWhitespace (*t++))
  10652. return true;
  10653. return false;
  10654. }
  10655. const String String::formatted (const juce_wchar* const pf, ... )
  10656. {
  10657. jassert (pf != 0);
  10658. va_list args;
  10659. va_start (args, pf);
  10660. size_t bufferSize = 256;
  10661. String result (bufferSize, (int) 0);
  10662. result.text[0] = 0;
  10663. for (;;)
  10664. {
  10665. #if JUCE_LINUX && JUCE_64BIT
  10666. va_list tempArgs;
  10667. va_copy (tempArgs, args);
  10668. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10669. va_end (tempArgs);
  10670. #elif JUCE_WINDOWS
  10671. #if JUCE_MSVC
  10672. #pragma warning (push)
  10673. #pragma warning (disable: 4996)
  10674. #endif
  10675. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10676. #if JUCE_MSVC
  10677. #pragma warning (pop)
  10678. #endif
  10679. #else
  10680. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10681. #endif
  10682. if (num > 0)
  10683. return result;
  10684. bufferSize += 256;
  10685. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10686. break; // returns -1 because of an error rather than because it needs more space.
  10687. result.preallocateStorage (bufferSize);
  10688. }
  10689. return empty;
  10690. }
  10691. int String::getIntValue() const throw()
  10692. {
  10693. return CharacterFunctions::getIntValue (text);
  10694. }
  10695. int String::getTrailingIntValue() const throw()
  10696. {
  10697. int n = 0;
  10698. int mult = 1;
  10699. const juce_wchar* t = text + length();
  10700. while (--t >= text)
  10701. {
  10702. const juce_wchar c = *t;
  10703. if (! CharacterFunctions::isDigit (c))
  10704. {
  10705. if (c == '-')
  10706. n = -n;
  10707. break;
  10708. }
  10709. n += mult * (c - '0');
  10710. mult *= 10;
  10711. }
  10712. return n;
  10713. }
  10714. int64 String::getLargeIntValue() const throw()
  10715. {
  10716. return CharacterFunctions::getInt64Value (text);
  10717. }
  10718. float String::getFloatValue() const throw()
  10719. {
  10720. return (float) CharacterFunctions::getDoubleValue (text);
  10721. }
  10722. double String::getDoubleValue() const throw()
  10723. {
  10724. return CharacterFunctions::getDoubleValue (text);
  10725. }
  10726. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10727. const String String::toHexString (const int number)
  10728. {
  10729. juce_wchar buffer[32];
  10730. juce_wchar* const end = buffer + 32;
  10731. juce_wchar* t = end;
  10732. *--t = 0;
  10733. unsigned int v = (unsigned int) number;
  10734. do
  10735. {
  10736. *--t = hexDigits [v & 15];
  10737. v >>= 4;
  10738. } while (v != 0);
  10739. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10740. }
  10741. const String String::toHexString (const int64 number)
  10742. {
  10743. juce_wchar buffer[32];
  10744. juce_wchar* const end = buffer + 32;
  10745. juce_wchar* t = end;
  10746. *--t = 0;
  10747. uint64 v = (uint64) number;
  10748. do
  10749. {
  10750. *--t = hexDigits [(int) (v & 15)];
  10751. v >>= 4;
  10752. } while (v != 0);
  10753. return String (t, (int) (((char*) end) - (char*) t));
  10754. }
  10755. const String String::toHexString (const short number)
  10756. {
  10757. return toHexString ((int) (unsigned short) number);
  10758. }
  10759. const String String::toHexString (const unsigned char* data,
  10760. const int size,
  10761. const int groupSize)
  10762. {
  10763. if (size <= 0)
  10764. return empty;
  10765. int numChars = (size * 2) + 2;
  10766. if (groupSize > 0)
  10767. numChars += size / groupSize;
  10768. String s ((size_t) numChars, (int) 0);
  10769. juce_wchar* d = s.text;
  10770. for (int i = 0; i < size; ++i)
  10771. {
  10772. *d++ = hexDigits [(*data) >> 4];
  10773. *d++ = hexDigits [(*data) & 0xf];
  10774. ++data;
  10775. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10776. *d++ = ' ';
  10777. }
  10778. *d = 0;
  10779. return s;
  10780. }
  10781. int String::getHexValue32() const throw()
  10782. {
  10783. int result = 0;
  10784. const juce_wchar* c = text;
  10785. for (;;)
  10786. {
  10787. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10788. if (hexValue >= 0)
  10789. result = (result << 4) | hexValue;
  10790. else if (*c == 0)
  10791. break;
  10792. ++c;
  10793. }
  10794. return result;
  10795. }
  10796. int64 String::getHexValue64() const throw()
  10797. {
  10798. int64 result = 0;
  10799. const juce_wchar* c = text;
  10800. for (;;)
  10801. {
  10802. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10803. if (hexValue >= 0)
  10804. result = (result << 4) | hexValue;
  10805. else if (*c == 0)
  10806. break;
  10807. ++c;
  10808. }
  10809. return result;
  10810. }
  10811. const String String::createStringFromData (const void* const data_, const int size)
  10812. {
  10813. const char* const data = static_cast <const char*> (data_);
  10814. if (size <= 0 || data == 0)
  10815. {
  10816. return empty;
  10817. }
  10818. else if (size < 2)
  10819. {
  10820. return charToString (data[0]);
  10821. }
  10822. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10823. || (data[0] == (char)-1 && data[1] == (char)-2))
  10824. {
  10825. // assume it's 16-bit unicode
  10826. const bool bigEndian = (data[0] == (char)-2);
  10827. const int numChars = size / 2 - 1;
  10828. String result;
  10829. result.preallocateStorage (numChars + 2);
  10830. const uint16* const src = (const uint16*) (data + 2);
  10831. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10832. if (bigEndian)
  10833. {
  10834. for (int i = 0; i < numChars; ++i)
  10835. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10836. }
  10837. else
  10838. {
  10839. for (int i = 0; i < numChars; ++i)
  10840. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10841. }
  10842. dst [numChars] = 0;
  10843. return result;
  10844. }
  10845. else
  10846. {
  10847. return String::fromUTF8 (data, size);
  10848. }
  10849. }
  10850. const char* String::toUTF8() const
  10851. {
  10852. if (isEmpty())
  10853. {
  10854. return reinterpret_cast <const char*> (text);
  10855. }
  10856. else
  10857. {
  10858. const int currentLen = length() + 1;
  10859. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10860. String* const mutableThis = const_cast <String*> (this);
  10861. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10862. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10863. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10864. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10865. #endif
  10866. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10867. return otherCopy;
  10868. }
  10869. }
  10870. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10871. {
  10872. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10873. int num = 0, index = 0;
  10874. for (;;)
  10875. {
  10876. const uint32 c = (uint32) text [index++];
  10877. if (c >= 0x80)
  10878. {
  10879. int numExtraBytes = 1;
  10880. if (c >= 0x800)
  10881. {
  10882. ++numExtraBytes;
  10883. if (c >= 0x10000)
  10884. {
  10885. ++numExtraBytes;
  10886. if (c >= 0x200000)
  10887. {
  10888. ++numExtraBytes;
  10889. if (c >= 0x4000000)
  10890. ++numExtraBytes;
  10891. }
  10892. }
  10893. }
  10894. if (buffer != 0)
  10895. {
  10896. if (num + numExtraBytes >= maxBufferSizeBytes)
  10897. {
  10898. buffer [num++] = 0;
  10899. break;
  10900. }
  10901. else
  10902. {
  10903. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10904. while (--numExtraBytes >= 0)
  10905. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10906. }
  10907. }
  10908. else
  10909. {
  10910. num += numExtraBytes + 1;
  10911. }
  10912. }
  10913. else
  10914. {
  10915. if (buffer != 0)
  10916. {
  10917. if (num + 1 >= maxBufferSizeBytes)
  10918. {
  10919. buffer [num++] = 0;
  10920. break;
  10921. }
  10922. buffer [num] = (uint8) c;
  10923. }
  10924. ++num;
  10925. }
  10926. if (c == 0)
  10927. break;
  10928. }
  10929. return num;
  10930. }
  10931. int String::getNumBytesAsUTF8() const throw()
  10932. {
  10933. int num = 0;
  10934. const juce_wchar* t = text;
  10935. for (;;)
  10936. {
  10937. const uint32 c = (uint32) *t;
  10938. if (c >= 0x80)
  10939. {
  10940. ++num;
  10941. if (c >= 0x800)
  10942. {
  10943. ++num;
  10944. if (c >= 0x10000)
  10945. {
  10946. ++num;
  10947. if (c >= 0x200000)
  10948. {
  10949. ++num;
  10950. if (c >= 0x4000000)
  10951. ++num;
  10952. }
  10953. }
  10954. }
  10955. }
  10956. else if (c == 0)
  10957. break;
  10958. ++num;
  10959. ++t;
  10960. }
  10961. return num;
  10962. }
  10963. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10964. {
  10965. if (buffer == 0)
  10966. return empty;
  10967. if (bufferSizeBytes < 0)
  10968. bufferSizeBytes = std::numeric_limits<int>::max();
  10969. size_t numBytes;
  10970. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10971. if (buffer [numBytes] == 0)
  10972. break;
  10973. String result ((size_t) numBytes + 1, (int) 0);
  10974. juce_wchar* dest = result.text;
  10975. size_t i = 0;
  10976. while (i < numBytes)
  10977. {
  10978. const char c = buffer [i++];
  10979. if (c < 0)
  10980. {
  10981. unsigned int mask = 0x7f;
  10982. int bit = 0x40;
  10983. int numExtraValues = 0;
  10984. while (bit != 0 && (c & bit) != 0)
  10985. {
  10986. bit >>= 1;
  10987. mask >>= 1;
  10988. ++numExtraValues;
  10989. }
  10990. int n = (mask & (unsigned char) c);
  10991. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10992. {
  10993. const char nextByte = buffer[i];
  10994. if ((nextByte & 0xc0) != 0x80)
  10995. break;
  10996. n <<= 6;
  10997. n |= (nextByte & 0x3f);
  10998. ++i;
  10999. }
  11000. *dest++ = (juce_wchar) n;
  11001. }
  11002. else
  11003. {
  11004. *dest++ = (juce_wchar) c;
  11005. }
  11006. }
  11007. *dest = 0;
  11008. return result;
  11009. }
  11010. const char* String::toCString() const
  11011. {
  11012. if (isEmpty())
  11013. {
  11014. return reinterpret_cast <const char*> (text);
  11015. }
  11016. else
  11017. {
  11018. const int len = length();
  11019. String* const mutableThis = const_cast <String*> (this);
  11020. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11021. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11022. CharacterFunctions::copy (otherCopy, text, len);
  11023. otherCopy [len] = 0;
  11024. return otherCopy;
  11025. }
  11026. }
  11027. #if JUCE_MSVC
  11028. #pragma warning (push)
  11029. #pragma warning (disable: 4514 4996)
  11030. #endif
  11031. int String::getNumBytesAsCString() const throw()
  11032. {
  11033. return (int) wcstombs (0, text, 0);
  11034. }
  11035. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11036. {
  11037. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11038. if (destBuffer != 0 && numBytes >= 0)
  11039. destBuffer [numBytes] = 0;
  11040. return numBytes;
  11041. }
  11042. #if JUCE_MSVC
  11043. #pragma warning (pop)
  11044. #endif
  11045. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11046. {
  11047. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11048. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11049. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11050. }
  11051. String::Concatenator::Concatenator (String& stringToAppendTo)
  11052. : result (stringToAppendTo),
  11053. nextIndex (stringToAppendTo.length())
  11054. {
  11055. }
  11056. String::Concatenator::~Concatenator()
  11057. {
  11058. }
  11059. void String::Concatenator::append (const String& s)
  11060. {
  11061. const int len = s.length();
  11062. if (len > 0)
  11063. {
  11064. result.preallocateStorage (nextIndex + len);
  11065. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11066. nextIndex += len;
  11067. }
  11068. }
  11069. #if JUCE_UNIT_TESTS
  11070. class StringTests : public UnitTest
  11071. {
  11072. public:
  11073. StringTests() : UnitTest ("String class") {}
  11074. void runTest()
  11075. {
  11076. {
  11077. beginTest ("Basics");
  11078. expect (String().length() == 0);
  11079. expect (String() == String::empty);
  11080. String s1, s2 ("abcd");
  11081. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11082. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11083. expect (s2.length() == 4);
  11084. s1 = "abcd";
  11085. expect (s2 == s1 && s1 == s2);
  11086. expect (s1 == "abcd" && s1 == L"abcd");
  11087. expect (String ("abcd") == String (L"abcd"));
  11088. expect (String ("abcdefg", 4) == L"abcd");
  11089. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11090. expect (String::charToString ('x') == "x");
  11091. expect (String::charToString (0) == String::empty);
  11092. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11093. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11094. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11095. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11096. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11097. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11098. expect (s1.indexOf (String::empty) == 0);
  11099. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11100. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11101. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11102. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11103. }
  11104. {
  11105. beginTest ("Operations");
  11106. String s ("012345678");
  11107. expect (s.hashCode() != 0);
  11108. expect (s.hashCode64() != 0);
  11109. expect (s.hashCode() != (s + s).hashCode());
  11110. expect (s.hashCode64() != (s + s).hashCode64());
  11111. expect (s.compare (String ("012345678")) == 0);
  11112. expect (s.compare (String ("012345679")) < 0);
  11113. expect (s.compare (String ("012345676")) > 0);
  11114. expect (s.substring (2, 3) == String::charToString (s[2]));
  11115. expect (s.substring (0, 1) == String::charToString (s[0]));
  11116. expect (s.getLastCharacter() == s [s.length() - 1]);
  11117. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11118. expect (s.substring (0, 3) == L"012");
  11119. expect (s.substring (0, 100) == s);
  11120. expect (s.substring (-1, 100) == s);
  11121. expect (s.substring (3) == "345678");
  11122. expect (s.indexOf (L"45") == 4);
  11123. expect (String ("444445").indexOf ("45") == 4);
  11124. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11125. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11126. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11127. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11128. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11129. expect (s.indexOfChar (L'4') == 4);
  11130. expect (s + s == "012345678012345678");
  11131. expect (s.startsWith (s));
  11132. expect (s.startsWith (s.substring (0, 4)));
  11133. expect (s.startsWith (s.dropLastCharacters (4)));
  11134. expect (s.endsWith (s.substring (5)));
  11135. expect (s.endsWith (s));
  11136. expect (s.contains (s.substring (3, 6)));
  11137. expect (s.contains (s.substring (3)));
  11138. expect (s.startsWithChar (s[0]));
  11139. expect (s.endsWithChar (s.getLastCharacter()));
  11140. expect (s [s.length()] == 0);
  11141. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11142. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11143. String s2 ("123");
  11144. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11145. s2 += "xyz";
  11146. expect (s2 == "1234567890xyz");
  11147. beginTest ("Numeric conversions");
  11148. expect (String::empty.getIntValue() == 0);
  11149. expect (String::empty.getDoubleValue() == 0.0);
  11150. expect (String::empty.getFloatValue() == 0.0f);
  11151. expect (s.getIntValue() == 12345678);
  11152. expect (s.getLargeIntValue() == (int64) 12345678);
  11153. expect (s.getDoubleValue() == 12345678.0);
  11154. expect (s.getFloatValue() == 12345678.0f);
  11155. expect (String (-1234).getIntValue() == -1234);
  11156. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11157. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11158. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11159. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11160. expect (s.getHexValue32() == 0x12345678);
  11161. expect (s.getHexValue64() == (int64) 0x12345678);
  11162. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11163. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11164. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11165. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11166. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11167. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11168. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11169. beginTest ("Subsections");
  11170. String s3;
  11171. s3 = "abcdeFGHIJ";
  11172. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11173. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11174. expect (s3.containsIgnoreCase (s3.substring (3)));
  11175. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11176. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11177. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11178. expect (s3.containsAnyOf (L"zzzFs"));
  11179. expect (s3.startsWith ("abcd"));
  11180. expect (s3.startsWithIgnoreCase (L"abCD"));
  11181. expect (s3.startsWith (String::empty));
  11182. expect (s3.startsWithChar ('a'));
  11183. expect (s3.endsWith (String ("HIJ")));
  11184. expect (s3.endsWithIgnoreCase (L"Hij"));
  11185. expect (s3.endsWith (String::empty));
  11186. expect (s3.endsWithChar (L'J'));
  11187. expect (s3.indexOf ("HIJ") == 7);
  11188. expect (s3.indexOf (L"HIJK") == -1);
  11189. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11190. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11191. String s4 (s3);
  11192. s4.append (String ("xyz123"), 3);
  11193. expect (s4 == s3 + "xyz");
  11194. expect (String (1234) < String (1235));
  11195. expect (String (1235) > String (1234));
  11196. expect (String (1234) >= String (1234));
  11197. expect (String (1234) <= String (1234));
  11198. expect (String (1235) >= String (1234));
  11199. expect (String (1234) <= String (1235));
  11200. String s5 ("word word2 word3");
  11201. expect (s5.containsWholeWord (String ("word2")));
  11202. expect (s5.indexOfWholeWord ("word2") == 5);
  11203. expect (s5.containsWholeWord (L"word"));
  11204. expect (s5.containsWholeWord ("word3"));
  11205. expect (s5.containsWholeWord (s5));
  11206. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11207. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11208. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11209. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11210. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11211. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11212. expect (s5.containsNonWhitespaceChars());
  11213. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11214. expect (s5.matchesWildcard (L"wor*", false));
  11215. expect (s5.matchesWildcard ("wOr*", true));
  11216. expect (s5.matchesWildcard (L"*word3", true));
  11217. expect (s5.matchesWildcard ("*word?", true));
  11218. expect (s5.matchesWildcard (L"Word*3", true));
  11219. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11220. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11221. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11222. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11223. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11224. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11225. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11226. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11227. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11228. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11229. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11230. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11231. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11232. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11233. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11234. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11235. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11236. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11237. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11238. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11239. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11240. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11241. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11242. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11243. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11244. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11245. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11246. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11247. expect (s5.replace ("Word", "", true) == " 2 3");
  11248. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11249. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11250. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11251. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11252. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11253. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11254. expect (s5.retainCharacters (String::empty).isEmpty());
  11255. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11256. expect (s5.removeCharacters (String::empty) == s5);
  11257. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11258. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11259. expect (! s5.isQuotedString());
  11260. expect (s5.quoted().isQuotedString());
  11261. expect (! s5.quoted().unquoted().isQuotedString());
  11262. expect (! String ("x'").isQuotedString());
  11263. expect (String ("'x").isQuotedString());
  11264. String s6 (" \t xyz \t\r\n");
  11265. expect (s6.trim() == String ("xyz"));
  11266. expect (s6.trim().trim() == "xyz");
  11267. expect (s5.trim() == s5);
  11268. expect (s6.trimStart().trimEnd() == s6.trim());
  11269. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11270. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11271. expect (s6.trimStart() != s6.trimEnd());
  11272. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11273. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11274. }
  11275. {
  11276. beginTest ("UTF8");
  11277. String s ("word word2 word3");
  11278. {
  11279. char buffer [100];
  11280. memset (buffer, 0xff, sizeof (buffer));
  11281. s.copyToUTF8 (buffer, 100);
  11282. expect (String::fromUTF8 (buffer, 100) == s);
  11283. juce_wchar bufferUnicode [100];
  11284. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11285. s.copyToUnicode (bufferUnicode, 100);
  11286. expect (String (bufferUnicode, 100) == s);
  11287. }
  11288. {
  11289. juce_wchar wideBuffer [50];
  11290. zerostruct (wideBuffer);
  11291. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11292. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11293. String wide (wideBuffer);
  11294. expect (wide == (const juce_wchar*) wideBuffer);
  11295. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11296. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11297. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11298. }
  11299. }
  11300. }
  11301. };
  11302. static StringTests stringUnitTests;
  11303. #endif
  11304. END_JUCE_NAMESPACE
  11305. /*** End of inlined file: juce_String.cpp ***/
  11306. /*** Start of inlined file: juce_StringArray.cpp ***/
  11307. BEGIN_JUCE_NAMESPACE
  11308. StringArray::StringArray() throw()
  11309. {
  11310. }
  11311. StringArray::StringArray (const StringArray& other)
  11312. : strings (other.strings)
  11313. {
  11314. }
  11315. StringArray::StringArray (const String& firstValue)
  11316. {
  11317. strings.add (firstValue);
  11318. }
  11319. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11320. const int numberOfStrings)
  11321. {
  11322. for (int i = 0; i < numberOfStrings; ++i)
  11323. strings.add (initialStrings [i]);
  11324. }
  11325. StringArray::StringArray (const char* const* const initialStrings,
  11326. const int numberOfStrings)
  11327. {
  11328. for (int i = 0; i < numberOfStrings; ++i)
  11329. strings.add (initialStrings [i]);
  11330. }
  11331. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11332. {
  11333. int i = 0;
  11334. while (initialStrings[i] != 0)
  11335. strings.add (initialStrings [i++]);
  11336. }
  11337. StringArray::StringArray (const char* const* const initialStrings)
  11338. {
  11339. int i = 0;
  11340. while (initialStrings[i] != 0)
  11341. strings.add (initialStrings [i++]);
  11342. }
  11343. StringArray& StringArray::operator= (const StringArray& other)
  11344. {
  11345. strings = other.strings;
  11346. return *this;
  11347. }
  11348. StringArray::~StringArray()
  11349. {
  11350. }
  11351. bool StringArray::operator== (const StringArray& other) const throw()
  11352. {
  11353. if (other.size() != size())
  11354. return false;
  11355. for (int i = size(); --i >= 0;)
  11356. if (other.strings.getReference(i) != strings.getReference(i))
  11357. return false;
  11358. return true;
  11359. }
  11360. bool StringArray::operator!= (const StringArray& other) const throw()
  11361. {
  11362. return ! operator== (other);
  11363. }
  11364. void StringArray::clear()
  11365. {
  11366. strings.clear();
  11367. }
  11368. const String& StringArray::operator[] (const int index) const throw()
  11369. {
  11370. if (((unsigned int) index) < (unsigned int) strings.size())
  11371. return strings.getReference (index);
  11372. return String::empty;
  11373. }
  11374. String& StringArray::getReference (const int index) throw()
  11375. {
  11376. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11377. return strings.getReference (index);
  11378. }
  11379. void StringArray::add (const String& newString)
  11380. {
  11381. strings.add (newString);
  11382. }
  11383. void StringArray::insert (const int index, const String& newString)
  11384. {
  11385. strings.insert (index, newString);
  11386. }
  11387. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11388. {
  11389. if (! contains (newString, ignoreCase))
  11390. add (newString);
  11391. }
  11392. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11393. {
  11394. if (startIndex < 0)
  11395. {
  11396. jassertfalse;
  11397. startIndex = 0;
  11398. }
  11399. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11400. numElementsToAdd = otherArray.size() - startIndex;
  11401. while (--numElementsToAdd >= 0)
  11402. strings.add (otherArray.strings.getReference (startIndex++));
  11403. }
  11404. void StringArray::set (const int index, const String& newString)
  11405. {
  11406. strings.set (index, newString);
  11407. }
  11408. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11409. {
  11410. if (ignoreCase)
  11411. {
  11412. for (int i = size(); --i >= 0;)
  11413. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11414. return true;
  11415. }
  11416. else
  11417. {
  11418. for (int i = size(); --i >= 0;)
  11419. if (stringToLookFor == strings.getReference(i))
  11420. return true;
  11421. }
  11422. return false;
  11423. }
  11424. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11425. {
  11426. if (i < 0)
  11427. i = 0;
  11428. const int numElements = size();
  11429. if (ignoreCase)
  11430. {
  11431. while (i < numElements)
  11432. {
  11433. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11434. return i;
  11435. ++i;
  11436. }
  11437. }
  11438. else
  11439. {
  11440. while (i < numElements)
  11441. {
  11442. if (stringToLookFor == strings.getReference (i))
  11443. return i;
  11444. ++i;
  11445. }
  11446. }
  11447. return -1;
  11448. }
  11449. void StringArray::remove (const int index)
  11450. {
  11451. strings.remove (index);
  11452. }
  11453. void StringArray::removeString (const String& stringToRemove,
  11454. const bool ignoreCase)
  11455. {
  11456. if (ignoreCase)
  11457. {
  11458. for (int i = size(); --i >= 0;)
  11459. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11460. strings.remove (i);
  11461. }
  11462. else
  11463. {
  11464. for (int i = size(); --i >= 0;)
  11465. if (stringToRemove == strings.getReference (i))
  11466. strings.remove (i);
  11467. }
  11468. }
  11469. void StringArray::removeRange (int startIndex, int numberToRemove)
  11470. {
  11471. strings.removeRange (startIndex, numberToRemove);
  11472. }
  11473. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11474. {
  11475. if (removeWhitespaceStrings)
  11476. {
  11477. for (int i = size(); --i >= 0;)
  11478. if (! strings.getReference(i).containsNonWhitespaceChars())
  11479. strings.remove (i);
  11480. }
  11481. else
  11482. {
  11483. for (int i = size(); --i >= 0;)
  11484. if (strings.getReference(i).isEmpty())
  11485. strings.remove (i);
  11486. }
  11487. }
  11488. void StringArray::trim()
  11489. {
  11490. for (int i = size(); --i >= 0;)
  11491. {
  11492. String& s = strings.getReference(i);
  11493. s = s.trim();
  11494. }
  11495. }
  11496. class InternalStringArrayComparator_CaseSensitive
  11497. {
  11498. public:
  11499. static int compareElements (String& first, String& second) { return first.compare (second); }
  11500. };
  11501. class InternalStringArrayComparator_CaseInsensitive
  11502. {
  11503. public:
  11504. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11505. };
  11506. void StringArray::sort (const bool ignoreCase)
  11507. {
  11508. if (ignoreCase)
  11509. {
  11510. InternalStringArrayComparator_CaseInsensitive comp;
  11511. strings.sort (comp);
  11512. }
  11513. else
  11514. {
  11515. InternalStringArrayComparator_CaseSensitive comp;
  11516. strings.sort (comp);
  11517. }
  11518. }
  11519. void StringArray::move (const int currentIndex, int newIndex) throw()
  11520. {
  11521. strings.move (currentIndex, newIndex);
  11522. }
  11523. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11524. {
  11525. const int last = (numberToJoin < 0) ? size()
  11526. : jmin (size(), start + numberToJoin);
  11527. if (start < 0)
  11528. start = 0;
  11529. if (start >= last)
  11530. return String::empty;
  11531. if (start == last - 1)
  11532. return strings.getReference (start);
  11533. const int separatorLen = separator.length();
  11534. int charsNeeded = separatorLen * (last - start - 1);
  11535. for (int i = start; i < last; ++i)
  11536. charsNeeded += strings.getReference(i).length();
  11537. String result;
  11538. result.preallocateStorage (charsNeeded);
  11539. juce_wchar* dest = result;
  11540. while (start < last)
  11541. {
  11542. const String& s = strings.getReference (start);
  11543. const int len = s.length();
  11544. if (len > 0)
  11545. {
  11546. s.copyToUnicode (dest, len);
  11547. dest += len;
  11548. }
  11549. if (++start < last && separatorLen > 0)
  11550. {
  11551. separator.copyToUnicode (dest, separatorLen);
  11552. dest += separatorLen;
  11553. }
  11554. }
  11555. *dest = 0;
  11556. return result;
  11557. }
  11558. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11559. {
  11560. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11561. }
  11562. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11563. {
  11564. int num = 0;
  11565. if (text.isNotEmpty())
  11566. {
  11567. bool insideQuotes = false;
  11568. juce_wchar currentQuoteChar = 0;
  11569. int i = 0;
  11570. int tokenStart = 0;
  11571. for (;;)
  11572. {
  11573. const juce_wchar c = text[i];
  11574. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11575. if (! isBreak)
  11576. {
  11577. if (quoteCharacters.containsChar (c))
  11578. {
  11579. if (insideQuotes)
  11580. {
  11581. // only break out of quotes-mode if we find a matching quote to the
  11582. // one that we opened with..
  11583. if (currentQuoteChar == c)
  11584. insideQuotes = false;
  11585. }
  11586. else
  11587. {
  11588. insideQuotes = true;
  11589. currentQuoteChar = c;
  11590. }
  11591. }
  11592. }
  11593. else
  11594. {
  11595. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11596. ++num;
  11597. tokenStart = i + 1;
  11598. }
  11599. if (c == 0)
  11600. break;
  11601. ++i;
  11602. }
  11603. }
  11604. return num;
  11605. }
  11606. int StringArray::addLines (const String& sourceText)
  11607. {
  11608. int numLines = 0;
  11609. const juce_wchar* text = sourceText;
  11610. while (*text != 0)
  11611. {
  11612. const juce_wchar* const startOfLine = text;
  11613. while (*text != 0)
  11614. {
  11615. if (*text == '\r')
  11616. {
  11617. ++text;
  11618. if (*text == '\n')
  11619. ++text;
  11620. break;
  11621. }
  11622. if (*text == '\n')
  11623. {
  11624. ++text;
  11625. break;
  11626. }
  11627. ++text;
  11628. }
  11629. const juce_wchar* endOfLine = text;
  11630. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11631. --endOfLine;
  11632. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11633. --endOfLine;
  11634. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11635. ++numLines;
  11636. }
  11637. return numLines;
  11638. }
  11639. void StringArray::removeDuplicates (const bool ignoreCase)
  11640. {
  11641. for (int i = 0; i < size() - 1; ++i)
  11642. {
  11643. const String s (strings.getReference(i));
  11644. int nextIndex = i + 1;
  11645. for (;;)
  11646. {
  11647. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11648. if (nextIndex < 0)
  11649. break;
  11650. strings.remove (nextIndex);
  11651. }
  11652. }
  11653. }
  11654. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11655. const bool appendNumberToFirstInstance,
  11656. const juce_wchar* preNumberString,
  11657. const juce_wchar* postNumberString)
  11658. {
  11659. if (preNumberString == 0)
  11660. preNumberString = L" (";
  11661. if (postNumberString == 0)
  11662. postNumberString = L")";
  11663. for (int i = 0; i < size() - 1; ++i)
  11664. {
  11665. String& s = strings.getReference(i);
  11666. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11667. if (nextIndex >= 0)
  11668. {
  11669. const String original (s);
  11670. int number = 0;
  11671. if (appendNumberToFirstInstance)
  11672. s = original + preNumberString + String (++number) + postNumberString;
  11673. else
  11674. ++number;
  11675. while (nextIndex >= 0)
  11676. {
  11677. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11678. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11679. }
  11680. }
  11681. }
  11682. }
  11683. void StringArray::minimiseStorageOverheads()
  11684. {
  11685. strings.minimiseStorageOverheads();
  11686. }
  11687. END_JUCE_NAMESPACE
  11688. /*** End of inlined file: juce_StringArray.cpp ***/
  11689. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11690. BEGIN_JUCE_NAMESPACE
  11691. StringPairArray::StringPairArray (const bool ignoreCase_)
  11692. : ignoreCase (ignoreCase_)
  11693. {
  11694. }
  11695. StringPairArray::StringPairArray (const StringPairArray& other)
  11696. : keys (other.keys),
  11697. values (other.values),
  11698. ignoreCase (other.ignoreCase)
  11699. {
  11700. }
  11701. StringPairArray::~StringPairArray()
  11702. {
  11703. }
  11704. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11705. {
  11706. keys = other.keys;
  11707. values = other.values;
  11708. return *this;
  11709. }
  11710. bool StringPairArray::operator== (const StringPairArray& other) const
  11711. {
  11712. for (int i = keys.size(); --i >= 0;)
  11713. if (other [keys[i]] != values[i])
  11714. return false;
  11715. return true;
  11716. }
  11717. bool StringPairArray::operator!= (const StringPairArray& other) const
  11718. {
  11719. return ! operator== (other);
  11720. }
  11721. const String& StringPairArray::operator[] (const String& key) const
  11722. {
  11723. return values [keys.indexOf (key, ignoreCase)];
  11724. }
  11725. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11726. {
  11727. const int i = keys.indexOf (key, ignoreCase);
  11728. if (i >= 0)
  11729. return values[i];
  11730. return defaultReturnValue;
  11731. }
  11732. void StringPairArray::set (const String& key, const String& value)
  11733. {
  11734. const int i = keys.indexOf (key, ignoreCase);
  11735. if (i >= 0)
  11736. {
  11737. values.set (i, value);
  11738. }
  11739. else
  11740. {
  11741. keys.add (key);
  11742. values.add (value);
  11743. }
  11744. }
  11745. void StringPairArray::addArray (const StringPairArray& other)
  11746. {
  11747. for (int i = 0; i < other.size(); ++i)
  11748. set (other.keys[i], other.values[i]);
  11749. }
  11750. void StringPairArray::clear()
  11751. {
  11752. keys.clear();
  11753. values.clear();
  11754. }
  11755. void StringPairArray::remove (const String& key)
  11756. {
  11757. remove (keys.indexOf (key, ignoreCase));
  11758. }
  11759. void StringPairArray::remove (const int index)
  11760. {
  11761. keys.remove (index);
  11762. values.remove (index);
  11763. }
  11764. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11765. {
  11766. ignoreCase = shouldIgnoreCase;
  11767. }
  11768. const String StringPairArray::getDescription() const
  11769. {
  11770. String s;
  11771. for (int i = 0; i < keys.size(); ++i)
  11772. {
  11773. s << keys[i] << " = " << values[i];
  11774. if (i < keys.size())
  11775. s << ", ";
  11776. }
  11777. return s;
  11778. }
  11779. void StringPairArray::minimiseStorageOverheads()
  11780. {
  11781. keys.minimiseStorageOverheads();
  11782. values.minimiseStorageOverheads();
  11783. }
  11784. END_JUCE_NAMESPACE
  11785. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11786. /*** Start of inlined file: juce_StringPool.cpp ***/
  11787. BEGIN_JUCE_NAMESPACE
  11788. StringPool::StringPool() throw() {}
  11789. StringPool::~StringPool() {}
  11790. template <class StringType>
  11791. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11792. {
  11793. int start = 0;
  11794. int end = strings.size();
  11795. for (;;)
  11796. {
  11797. if (start >= end)
  11798. {
  11799. jassert (start <= end);
  11800. strings.insert (start, newString);
  11801. return strings.getReference (start);
  11802. }
  11803. else
  11804. {
  11805. const String& startString = strings.getReference (start);
  11806. if (startString == newString)
  11807. return startString;
  11808. const int halfway = (start + end) >> 1;
  11809. if (halfway == start)
  11810. {
  11811. if (startString.compare (newString) < 0)
  11812. ++start;
  11813. strings.insert (start, newString);
  11814. return strings.getReference (start);
  11815. }
  11816. const int comp = strings.getReference (halfway).compare (newString);
  11817. if (comp == 0)
  11818. return strings.getReference (halfway);
  11819. else if (comp < 0)
  11820. start = halfway;
  11821. else
  11822. end = halfway;
  11823. }
  11824. }
  11825. }
  11826. const juce_wchar* StringPool::getPooledString (const String& s)
  11827. {
  11828. if (s.isEmpty())
  11829. return String::empty;
  11830. return getPooledStringFromArray (strings, s);
  11831. }
  11832. const juce_wchar* StringPool::getPooledString (const char* const s)
  11833. {
  11834. if (s == 0 || *s == 0)
  11835. return String::empty;
  11836. return getPooledStringFromArray (strings, s);
  11837. }
  11838. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11839. {
  11840. if (s == 0 || *s == 0)
  11841. return String::empty;
  11842. return getPooledStringFromArray (strings, s);
  11843. }
  11844. int StringPool::size() const throw()
  11845. {
  11846. return strings.size();
  11847. }
  11848. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11849. {
  11850. return strings [index];
  11851. }
  11852. END_JUCE_NAMESPACE
  11853. /*** End of inlined file: juce_StringPool.cpp ***/
  11854. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11855. BEGIN_JUCE_NAMESPACE
  11856. XmlDocument::XmlDocument (const String& documentText)
  11857. : originalText (documentText),
  11858. ignoreEmptyTextElements (true)
  11859. {
  11860. }
  11861. XmlDocument::XmlDocument (const File& file)
  11862. : ignoreEmptyTextElements (true)
  11863. {
  11864. inputSource = new FileInputSource (file);
  11865. }
  11866. XmlDocument::~XmlDocument()
  11867. {
  11868. }
  11869. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11870. {
  11871. inputSource = newSource;
  11872. }
  11873. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11874. {
  11875. ignoreEmptyTextElements = shouldBeIgnored;
  11876. }
  11877. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11878. {
  11879. return CharacterFunctions::isLetterOrDigit (c)
  11880. || c == '_' || c == '-' || c == ':' || c == '.';
  11881. }
  11882. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11883. {
  11884. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11885. : isXmlIdentifierCharSlow (c);
  11886. }
  11887. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11888. {
  11889. String textToParse (originalText);
  11890. if (textToParse.isEmpty() && inputSource != 0)
  11891. {
  11892. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11893. if (in != 0)
  11894. {
  11895. MemoryOutputStream data;
  11896. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11897. textToParse = data.toString();
  11898. if (! onlyReadOuterDocumentElement)
  11899. originalText = textToParse;
  11900. }
  11901. }
  11902. input = textToParse;
  11903. lastError = String::empty;
  11904. errorOccurred = false;
  11905. outOfData = false;
  11906. needToLoadDTD = true;
  11907. for (int i = 0; i < 128; ++i)
  11908. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11909. if (textToParse.isEmpty())
  11910. {
  11911. lastError = "not enough input";
  11912. }
  11913. else
  11914. {
  11915. skipHeader();
  11916. if (input != 0)
  11917. {
  11918. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11919. if (! errorOccurred)
  11920. return result.release();
  11921. }
  11922. else
  11923. {
  11924. lastError = "incorrect xml header";
  11925. }
  11926. }
  11927. return 0;
  11928. }
  11929. const String& XmlDocument::getLastParseError() const throw()
  11930. {
  11931. return lastError;
  11932. }
  11933. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11934. {
  11935. lastError = desc;
  11936. errorOccurred = ! carryOn;
  11937. }
  11938. const String XmlDocument::getFileContents (const String& filename) const
  11939. {
  11940. if (inputSource != 0)
  11941. {
  11942. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11943. if (in != 0)
  11944. return in->readEntireStreamAsString();
  11945. }
  11946. return String::empty;
  11947. }
  11948. juce_wchar XmlDocument::readNextChar() throw()
  11949. {
  11950. if (*input != 0)
  11951. {
  11952. return *input++;
  11953. }
  11954. else
  11955. {
  11956. outOfData = true;
  11957. return 0;
  11958. }
  11959. }
  11960. int XmlDocument::findNextTokenLength() throw()
  11961. {
  11962. int len = 0;
  11963. juce_wchar c = *input;
  11964. while (isXmlIdentifierChar (c))
  11965. c = input [++len];
  11966. return len;
  11967. }
  11968. void XmlDocument::skipHeader()
  11969. {
  11970. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11971. if (found != 0)
  11972. {
  11973. input = found;
  11974. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11975. if (input == 0)
  11976. return;
  11977. input += 2;
  11978. }
  11979. skipNextWhiteSpace();
  11980. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11981. if (docType == 0)
  11982. return;
  11983. input = docType + 9;
  11984. int n = 1;
  11985. while (n > 0)
  11986. {
  11987. const juce_wchar c = readNextChar();
  11988. if (outOfData)
  11989. return;
  11990. if (c == '<')
  11991. ++n;
  11992. else if (c == '>')
  11993. --n;
  11994. }
  11995. docType += 9;
  11996. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11997. }
  11998. void XmlDocument::skipNextWhiteSpace()
  11999. {
  12000. for (;;)
  12001. {
  12002. juce_wchar c = *input;
  12003. while (CharacterFunctions::isWhitespace (c))
  12004. c = *++input;
  12005. if (c == 0)
  12006. {
  12007. outOfData = true;
  12008. break;
  12009. }
  12010. else if (c == '<')
  12011. {
  12012. if (input[1] == '!'
  12013. && input[2] == '-'
  12014. && input[3] == '-')
  12015. {
  12016. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12017. if (closeComment == 0)
  12018. {
  12019. outOfData = true;
  12020. break;
  12021. }
  12022. input = closeComment + 3;
  12023. continue;
  12024. }
  12025. else if (input[1] == '?')
  12026. {
  12027. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12028. if (closeBracket == 0)
  12029. {
  12030. outOfData = true;
  12031. break;
  12032. }
  12033. input = closeBracket + 2;
  12034. continue;
  12035. }
  12036. }
  12037. break;
  12038. }
  12039. }
  12040. void XmlDocument::readQuotedString (String& result)
  12041. {
  12042. const juce_wchar quote = readNextChar();
  12043. while (! outOfData)
  12044. {
  12045. const juce_wchar c = readNextChar();
  12046. if (c == quote)
  12047. break;
  12048. if (c == '&')
  12049. {
  12050. --input;
  12051. readEntity (result);
  12052. }
  12053. else
  12054. {
  12055. --input;
  12056. const juce_wchar* const start = input;
  12057. for (;;)
  12058. {
  12059. const juce_wchar character = *input;
  12060. if (character == quote)
  12061. {
  12062. result.append (start, (int) (input - start));
  12063. ++input;
  12064. return;
  12065. }
  12066. else if (character == '&')
  12067. {
  12068. result.append (start, (int) (input - start));
  12069. break;
  12070. }
  12071. else if (character == 0)
  12072. {
  12073. outOfData = true;
  12074. setLastError ("unmatched quotes", false);
  12075. break;
  12076. }
  12077. ++input;
  12078. }
  12079. }
  12080. }
  12081. }
  12082. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12083. {
  12084. XmlElement* node = 0;
  12085. skipNextWhiteSpace();
  12086. if (outOfData)
  12087. return 0;
  12088. input = CharacterFunctions::find (input, JUCE_T("<"));
  12089. if (input != 0)
  12090. {
  12091. ++input;
  12092. int tagLen = findNextTokenLength();
  12093. if (tagLen == 0)
  12094. {
  12095. // no tag name - but allow for a gap after the '<' before giving an error
  12096. skipNextWhiteSpace();
  12097. tagLen = findNextTokenLength();
  12098. if (tagLen == 0)
  12099. {
  12100. setLastError ("tag name missing", false);
  12101. return node;
  12102. }
  12103. }
  12104. node = new XmlElement (String (input, tagLen));
  12105. input += tagLen;
  12106. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12107. // look for attributes
  12108. for (;;)
  12109. {
  12110. skipNextWhiteSpace();
  12111. const juce_wchar c = *input;
  12112. // empty tag..
  12113. if (c == '/' && input[1] == '>')
  12114. {
  12115. input += 2;
  12116. break;
  12117. }
  12118. // parse the guts of the element..
  12119. if (c == '>')
  12120. {
  12121. ++input;
  12122. if (alsoParseSubElements)
  12123. readChildElements (node);
  12124. break;
  12125. }
  12126. // get an attribute..
  12127. if (isXmlIdentifierChar (c))
  12128. {
  12129. const int attNameLen = findNextTokenLength();
  12130. if (attNameLen > 0)
  12131. {
  12132. const juce_wchar* attNameStart = input;
  12133. input += attNameLen;
  12134. skipNextWhiteSpace();
  12135. if (readNextChar() == '=')
  12136. {
  12137. skipNextWhiteSpace();
  12138. const juce_wchar nextChar = *input;
  12139. if (nextChar == '"' || nextChar == '\'')
  12140. {
  12141. XmlElement::XmlAttributeNode* const newAtt
  12142. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12143. String::empty);
  12144. readQuotedString (newAtt->value);
  12145. if (lastAttribute == 0)
  12146. node->attributes = newAtt;
  12147. else
  12148. lastAttribute->next = newAtt;
  12149. lastAttribute = newAtt;
  12150. continue;
  12151. }
  12152. }
  12153. }
  12154. }
  12155. else
  12156. {
  12157. if (! outOfData)
  12158. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12159. }
  12160. break;
  12161. }
  12162. }
  12163. return node;
  12164. }
  12165. void XmlDocument::readChildElements (XmlElement* parent)
  12166. {
  12167. XmlElement* lastChildNode = 0;
  12168. for (;;)
  12169. {
  12170. const juce_wchar* const preWhitespaceInput = input;
  12171. skipNextWhiteSpace();
  12172. if (outOfData)
  12173. {
  12174. setLastError ("unmatched tags", false);
  12175. break;
  12176. }
  12177. if (*input == '<')
  12178. {
  12179. if (input[1] == '/')
  12180. {
  12181. // our close tag..
  12182. input = CharacterFunctions::find (input, JUCE_T(">"));
  12183. ++input;
  12184. break;
  12185. }
  12186. else if (input[1] == '!'
  12187. && input[2] == '['
  12188. && input[3] == 'C'
  12189. && input[4] == 'D'
  12190. && input[5] == 'A'
  12191. && input[6] == 'T'
  12192. && input[7] == 'A'
  12193. && input[8] == '[')
  12194. {
  12195. input += 9;
  12196. const juce_wchar* const inputStart = input;
  12197. int len = 0;
  12198. for (;;)
  12199. {
  12200. if (*input == 0)
  12201. {
  12202. setLastError ("unterminated CDATA section", false);
  12203. outOfData = true;
  12204. break;
  12205. }
  12206. else if (input[0] == ']'
  12207. && input[1] == ']'
  12208. && input[2] == '>')
  12209. {
  12210. input += 3;
  12211. break;
  12212. }
  12213. ++input;
  12214. ++len;
  12215. }
  12216. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12217. if (lastChildNode != 0)
  12218. lastChildNode->nextElement = e;
  12219. else
  12220. parent->addChildElement (e);
  12221. lastChildNode = e;
  12222. }
  12223. else
  12224. {
  12225. // this is some other element, so parse and add it..
  12226. XmlElement* const n = readNextElement (true);
  12227. if (n != 0)
  12228. {
  12229. if (lastChildNode == 0)
  12230. parent->addChildElement (n);
  12231. else
  12232. lastChildNode->nextElement = n;
  12233. lastChildNode = n;
  12234. }
  12235. else
  12236. {
  12237. return;
  12238. }
  12239. }
  12240. }
  12241. else // must be a character block
  12242. {
  12243. input = preWhitespaceInput; // roll back to include the leading whitespace
  12244. String textElementContent;
  12245. for (;;)
  12246. {
  12247. const juce_wchar c = *input;
  12248. if (c == '<')
  12249. break;
  12250. if (c == 0)
  12251. {
  12252. setLastError ("unmatched tags", false);
  12253. outOfData = true;
  12254. return;
  12255. }
  12256. if (c == '&')
  12257. {
  12258. String entity;
  12259. readEntity (entity);
  12260. if (entity.startsWithChar ('<') && entity [1] != 0)
  12261. {
  12262. const juce_wchar* const oldInput = input;
  12263. const bool oldOutOfData = outOfData;
  12264. input = entity;
  12265. outOfData = false;
  12266. for (;;)
  12267. {
  12268. XmlElement* const n = readNextElement (true);
  12269. if (n == 0)
  12270. break;
  12271. if (lastChildNode == 0)
  12272. parent->addChildElement (n);
  12273. else
  12274. lastChildNode->nextElement = n;
  12275. lastChildNode = n;
  12276. }
  12277. input = oldInput;
  12278. outOfData = oldOutOfData;
  12279. }
  12280. else
  12281. {
  12282. textElementContent += entity;
  12283. }
  12284. }
  12285. else
  12286. {
  12287. const juce_wchar* start = input;
  12288. int len = 0;
  12289. for (;;)
  12290. {
  12291. const juce_wchar nextChar = *input;
  12292. if (nextChar == '<' || nextChar == '&')
  12293. {
  12294. break;
  12295. }
  12296. else if (nextChar == 0)
  12297. {
  12298. setLastError ("unmatched tags", false);
  12299. outOfData = true;
  12300. return;
  12301. }
  12302. ++input;
  12303. ++len;
  12304. }
  12305. textElementContent.append (start, len);
  12306. }
  12307. }
  12308. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12309. {
  12310. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12311. if (lastChildNode != 0)
  12312. lastChildNode->nextElement = textElement;
  12313. else
  12314. parent->addChildElement (textElement);
  12315. lastChildNode = textElement;
  12316. }
  12317. }
  12318. }
  12319. }
  12320. void XmlDocument::readEntity (String& result)
  12321. {
  12322. // skip over the ampersand
  12323. ++input;
  12324. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12325. {
  12326. input += 4;
  12327. result += '&';
  12328. }
  12329. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12330. {
  12331. input += 5;
  12332. result += '"';
  12333. }
  12334. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12335. {
  12336. input += 5;
  12337. result += '\'';
  12338. }
  12339. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12340. {
  12341. input += 3;
  12342. result += '<';
  12343. }
  12344. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12345. {
  12346. input += 3;
  12347. result += '>';
  12348. }
  12349. else if (*input == '#')
  12350. {
  12351. int charCode = 0;
  12352. ++input;
  12353. if (*input == 'x' || *input == 'X')
  12354. {
  12355. ++input;
  12356. int numChars = 0;
  12357. while (input[0] != ';')
  12358. {
  12359. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12360. if (hexValue < 0 || ++numChars > 8)
  12361. {
  12362. setLastError ("illegal escape sequence", true);
  12363. break;
  12364. }
  12365. charCode = (charCode << 4) | hexValue;
  12366. ++input;
  12367. }
  12368. ++input;
  12369. }
  12370. else if (input[0] >= '0' && input[0] <= '9')
  12371. {
  12372. int numChars = 0;
  12373. while (input[0] != ';')
  12374. {
  12375. if (++numChars > 12)
  12376. {
  12377. setLastError ("illegal escape sequence", true);
  12378. break;
  12379. }
  12380. charCode = charCode * 10 + (input[0] - '0');
  12381. ++input;
  12382. }
  12383. ++input;
  12384. }
  12385. else
  12386. {
  12387. setLastError ("illegal escape sequence", true);
  12388. result += '&';
  12389. return;
  12390. }
  12391. result << (juce_wchar) charCode;
  12392. }
  12393. else
  12394. {
  12395. const juce_wchar* const entityNameStart = input;
  12396. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12397. if (closingSemiColon == 0)
  12398. {
  12399. outOfData = true;
  12400. result += '&';
  12401. }
  12402. else
  12403. {
  12404. input = closingSemiColon + 1;
  12405. result += expandExternalEntity (String (entityNameStart,
  12406. (int) (closingSemiColon - entityNameStart)));
  12407. }
  12408. }
  12409. }
  12410. const String XmlDocument::expandEntity (const String& ent)
  12411. {
  12412. if (ent.equalsIgnoreCase ("amp"))
  12413. return String::charToString ('&');
  12414. if (ent.equalsIgnoreCase ("quot"))
  12415. return String::charToString ('"');
  12416. if (ent.equalsIgnoreCase ("apos"))
  12417. return String::charToString ('\'');
  12418. if (ent.equalsIgnoreCase ("lt"))
  12419. return String::charToString ('<');
  12420. if (ent.equalsIgnoreCase ("gt"))
  12421. return String::charToString ('>');
  12422. if (ent[0] == '#')
  12423. {
  12424. if (ent[1] == 'x' || ent[1] == 'X')
  12425. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12426. if (ent[1] >= '0' && ent[1] <= '9')
  12427. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12428. setLastError ("illegal escape sequence", false);
  12429. return String::charToString ('&');
  12430. }
  12431. return expandExternalEntity (ent);
  12432. }
  12433. const String XmlDocument::expandExternalEntity (const String& entity)
  12434. {
  12435. if (needToLoadDTD)
  12436. {
  12437. if (dtdText.isNotEmpty())
  12438. {
  12439. dtdText = dtdText.trimCharactersAtEnd (">");
  12440. tokenisedDTD.addTokens (dtdText, true);
  12441. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12442. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12443. {
  12444. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12445. tokenisedDTD.clear();
  12446. tokenisedDTD.addTokens (getFileContents (fn), true);
  12447. }
  12448. else
  12449. {
  12450. tokenisedDTD.clear();
  12451. const int openBracket = dtdText.indexOfChar ('[');
  12452. if (openBracket > 0)
  12453. {
  12454. const int closeBracket = dtdText.lastIndexOfChar (']');
  12455. if (closeBracket > openBracket)
  12456. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12457. closeBracket), true);
  12458. }
  12459. }
  12460. for (int i = tokenisedDTD.size(); --i >= 0;)
  12461. {
  12462. if (tokenisedDTD[i].startsWithChar ('%')
  12463. && tokenisedDTD[i].endsWithChar (';'))
  12464. {
  12465. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12466. StringArray newToks;
  12467. newToks.addTokens (parsed, true);
  12468. tokenisedDTD.remove (i);
  12469. for (int j = newToks.size(); --j >= 0;)
  12470. tokenisedDTD.insert (i, newToks[j]);
  12471. }
  12472. }
  12473. }
  12474. needToLoadDTD = false;
  12475. }
  12476. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12477. {
  12478. if (tokenisedDTD[i] == entity)
  12479. {
  12480. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12481. {
  12482. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12483. // check for sub-entities..
  12484. int ampersand = ent.indexOfChar ('&');
  12485. while (ampersand >= 0)
  12486. {
  12487. const int semiColon = ent.indexOf (i + 1, ";");
  12488. if (semiColon < 0)
  12489. {
  12490. setLastError ("entity without terminating semi-colon", false);
  12491. break;
  12492. }
  12493. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12494. ent = ent.substring (0, ampersand)
  12495. + resolved
  12496. + ent.substring (semiColon + 1);
  12497. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12498. }
  12499. return ent;
  12500. }
  12501. }
  12502. }
  12503. setLastError ("unknown entity", true);
  12504. return entity;
  12505. }
  12506. const String XmlDocument::getParameterEntity (const String& entity)
  12507. {
  12508. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12509. {
  12510. if (tokenisedDTD[i] == entity)
  12511. {
  12512. if (tokenisedDTD [i - 1] == "%"
  12513. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12514. {
  12515. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12516. if (ent.equalsIgnoreCase ("system"))
  12517. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12518. else
  12519. return ent.trim().unquoted();
  12520. }
  12521. }
  12522. }
  12523. return entity;
  12524. }
  12525. END_JUCE_NAMESPACE
  12526. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12527. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12528. BEGIN_JUCE_NAMESPACE
  12529. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12530. : name (other.name),
  12531. value (other.value),
  12532. next (0)
  12533. {
  12534. }
  12535. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12536. : name (name_),
  12537. value (value_),
  12538. next (0)
  12539. {
  12540. }
  12541. XmlElement::XmlElement (const String& tagName_) throw()
  12542. : tagName (tagName_),
  12543. firstChildElement (0),
  12544. nextElement (0),
  12545. attributes (0)
  12546. {
  12547. // the tag name mustn't be empty, or it'll look like a text element!
  12548. jassert (tagName_.containsNonWhitespaceChars())
  12549. // The tag can't contain spaces or other characters that would create invalid XML!
  12550. jassert (! tagName_.containsAnyOf (" <>/&"));
  12551. }
  12552. XmlElement::XmlElement (int /*dummy*/) throw()
  12553. : firstChildElement (0),
  12554. nextElement (0),
  12555. attributes (0)
  12556. {
  12557. }
  12558. XmlElement::XmlElement (const XmlElement& other)
  12559. : tagName (other.tagName),
  12560. firstChildElement (0),
  12561. nextElement (0),
  12562. attributes (0)
  12563. {
  12564. copyChildrenAndAttributesFrom (other);
  12565. }
  12566. XmlElement& XmlElement::operator= (const XmlElement& other)
  12567. {
  12568. if (this != &other)
  12569. {
  12570. removeAllAttributes();
  12571. deleteAllChildElements();
  12572. tagName = other.tagName;
  12573. copyChildrenAndAttributesFrom (other);
  12574. }
  12575. return *this;
  12576. }
  12577. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12578. {
  12579. XmlElement* child = other.firstChildElement;
  12580. XmlElement* lastChild = 0;
  12581. while (child != 0)
  12582. {
  12583. XmlElement* const copiedChild = new XmlElement (*child);
  12584. if (lastChild != 0)
  12585. lastChild->nextElement = copiedChild;
  12586. else
  12587. firstChildElement = copiedChild;
  12588. lastChild = copiedChild;
  12589. child = child->nextElement;
  12590. }
  12591. const XmlAttributeNode* att = other.attributes;
  12592. XmlAttributeNode* lastAtt = 0;
  12593. while (att != 0)
  12594. {
  12595. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12596. if (lastAtt != 0)
  12597. lastAtt->next = newAtt;
  12598. else
  12599. attributes = newAtt;
  12600. lastAtt = newAtt;
  12601. att = att->next;
  12602. }
  12603. }
  12604. XmlElement::~XmlElement() throw()
  12605. {
  12606. XmlElement* child = firstChildElement;
  12607. while (child != 0)
  12608. {
  12609. XmlElement* const nextChild = child->nextElement;
  12610. delete child;
  12611. child = nextChild;
  12612. }
  12613. XmlAttributeNode* att = attributes;
  12614. while (att != 0)
  12615. {
  12616. XmlAttributeNode* const nextAtt = att->next;
  12617. delete att;
  12618. att = nextAtt;
  12619. }
  12620. }
  12621. namespace XmlOutputFunctions
  12622. {
  12623. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12624. {
  12625. if ((character >= 'a' && character <= 'z')
  12626. || (character >= 'A' && character <= 'Z')
  12627. || (character >= '0' && character <= '9'))
  12628. return true;
  12629. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12630. do
  12631. {
  12632. if (((juce_wchar) (uint8) *t) == character)
  12633. return true;
  12634. }
  12635. while (*++t != 0);
  12636. return false;
  12637. }
  12638. static void generateLegalCharConstants()
  12639. {
  12640. uint8 n[32];
  12641. zerostruct (n);
  12642. for (int i = 0; i < 256; ++i)
  12643. if (isLegalXmlCharSlow (i))
  12644. n[i >> 3] |= (1 << (i & 7));
  12645. String s;
  12646. for (int i = 0; i < 32; ++i)
  12647. s << (int) n[i] << ", ";
  12648. DBG (s);
  12649. }*/
  12650. static bool isLegalXmlChar (const uint32 c) throw()
  12651. {
  12652. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12653. return c < sizeof (legalChars) * 8
  12654. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12655. }
  12656. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12657. {
  12658. const juce_wchar* t = text;
  12659. for (;;)
  12660. {
  12661. const juce_wchar character = *t++;
  12662. if (character == 0)
  12663. break;
  12664. if (isLegalXmlChar ((uint32) character))
  12665. {
  12666. outputStream << (char) character;
  12667. }
  12668. else
  12669. {
  12670. switch (character)
  12671. {
  12672. case '&': outputStream << "&amp;"; break;
  12673. case '"': outputStream << "&quot;"; break;
  12674. case '>': outputStream << "&gt;"; break;
  12675. case '<': outputStream << "&lt;"; break;
  12676. case '\n':
  12677. if (changeNewLines)
  12678. outputStream << "&#10;";
  12679. else
  12680. outputStream << (char) character;
  12681. break;
  12682. case '\r':
  12683. if (changeNewLines)
  12684. outputStream << "&#13;";
  12685. else
  12686. outputStream << (char) character;
  12687. break;
  12688. default:
  12689. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12690. break;
  12691. }
  12692. }
  12693. }
  12694. }
  12695. static void writeSpaces (OutputStream& out, int numSpaces)
  12696. {
  12697. if (numSpaces > 0)
  12698. {
  12699. const char blanks[] = " ";
  12700. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12701. while (numSpaces > blankSize)
  12702. {
  12703. out.write (blanks, blankSize);
  12704. numSpaces -= blankSize;
  12705. }
  12706. out.write (blanks, numSpaces);
  12707. }
  12708. }
  12709. static void writeNewLine (OutputStream& out)
  12710. {
  12711. out.write ("\r\n", 2);
  12712. }
  12713. }
  12714. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12715. const int indentationLevel,
  12716. const int lineWrapLength) const
  12717. {
  12718. using namespace XmlOutputFunctions;
  12719. writeSpaces (outputStream, indentationLevel);
  12720. if (! isTextElement())
  12721. {
  12722. outputStream.writeByte ('<');
  12723. outputStream << tagName;
  12724. {
  12725. const int attIndent = indentationLevel + tagName.length() + 1;
  12726. int lineLen = 0;
  12727. const XmlAttributeNode* att = attributes;
  12728. while (att != 0)
  12729. {
  12730. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12731. {
  12732. writeNewLine (outputStream);
  12733. writeSpaces (outputStream, attIndent);
  12734. lineLen = 0;
  12735. }
  12736. const int64 startPos = outputStream.getPosition();
  12737. outputStream.writeByte (' ');
  12738. outputStream << att->name;
  12739. outputStream.write ("=\"", 2);
  12740. escapeIllegalXmlChars (outputStream, att->value, true);
  12741. outputStream.writeByte ('"');
  12742. lineLen += (int) (outputStream.getPosition() - startPos);
  12743. att = att->next;
  12744. }
  12745. }
  12746. if (firstChildElement != 0)
  12747. {
  12748. outputStream.writeByte ('>');
  12749. XmlElement* child = firstChildElement;
  12750. bool lastWasTextNode = false;
  12751. while (child != 0)
  12752. {
  12753. if (child->isTextElement())
  12754. {
  12755. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12756. lastWasTextNode = true;
  12757. }
  12758. else
  12759. {
  12760. if (indentationLevel >= 0 && ! lastWasTextNode)
  12761. writeNewLine (outputStream);
  12762. child->writeElementAsText (outputStream,
  12763. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12764. lastWasTextNode = false;
  12765. }
  12766. child = child->nextElement;
  12767. }
  12768. if (indentationLevel >= 0 && ! lastWasTextNode)
  12769. {
  12770. writeNewLine (outputStream);
  12771. writeSpaces (outputStream, indentationLevel);
  12772. }
  12773. outputStream.write ("</", 2);
  12774. outputStream << tagName;
  12775. outputStream.writeByte ('>');
  12776. }
  12777. else
  12778. {
  12779. outputStream.write ("/>", 2);
  12780. }
  12781. }
  12782. else
  12783. {
  12784. escapeIllegalXmlChars (outputStream, getText(), false);
  12785. }
  12786. }
  12787. const String XmlElement::createDocument (const String& dtdToUse,
  12788. const bool allOnOneLine,
  12789. const bool includeXmlHeader,
  12790. const String& encodingType,
  12791. const int lineWrapLength) const
  12792. {
  12793. MemoryOutputStream mem (2048);
  12794. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12795. return mem.toUTF8();
  12796. }
  12797. void XmlElement::writeToStream (OutputStream& output,
  12798. const String& dtdToUse,
  12799. const bool allOnOneLine,
  12800. const bool includeXmlHeader,
  12801. const String& encodingType,
  12802. const int lineWrapLength) const
  12803. {
  12804. using namespace XmlOutputFunctions;
  12805. if (includeXmlHeader)
  12806. {
  12807. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12808. if (allOnOneLine)
  12809. {
  12810. output.writeByte (' ');
  12811. }
  12812. else
  12813. {
  12814. writeNewLine (output);
  12815. writeNewLine (output);
  12816. }
  12817. }
  12818. if (dtdToUse.isNotEmpty())
  12819. {
  12820. output << dtdToUse;
  12821. if (allOnOneLine)
  12822. output.writeByte (' ');
  12823. else
  12824. writeNewLine (output);
  12825. }
  12826. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12827. if (! allOnOneLine)
  12828. writeNewLine (output);
  12829. }
  12830. bool XmlElement::writeToFile (const File& file,
  12831. const String& dtdToUse,
  12832. const String& encodingType,
  12833. const int lineWrapLength) const
  12834. {
  12835. if (file.hasWriteAccess())
  12836. {
  12837. TemporaryFile tempFile (file);
  12838. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12839. if (out != 0)
  12840. {
  12841. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12842. out = 0;
  12843. return tempFile.overwriteTargetFileWithTemporary();
  12844. }
  12845. }
  12846. return false;
  12847. }
  12848. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12849. {
  12850. #if JUCE_DEBUG
  12851. // if debugging, check that the case is actually the same, because
  12852. // valid xml is case-sensitive, and although this lets it pass, it's
  12853. // better not to..
  12854. if (tagName.equalsIgnoreCase (tagNameWanted))
  12855. {
  12856. jassert (tagName == tagNameWanted);
  12857. return true;
  12858. }
  12859. else
  12860. {
  12861. return false;
  12862. }
  12863. #else
  12864. return tagName.equalsIgnoreCase (tagNameWanted);
  12865. #endif
  12866. }
  12867. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12868. {
  12869. XmlElement* e = nextElement;
  12870. while (e != 0 && ! e->hasTagName (requiredTagName))
  12871. e = e->nextElement;
  12872. return e;
  12873. }
  12874. int XmlElement::getNumAttributes() const throw()
  12875. {
  12876. const XmlAttributeNode* att = attributes;
  12877. int count = 0;
  12878. while (att != 0)
  12879. {
  12880. att = att->next;
  12881. ++count;
  12882. }
  12883. return count;
  12884. }
  12885. const String& XmlElement::getAttributeName (const int index) const throw()
  12886. {
  12887. const XmlAttributeNode* att = attributes;
  12888. int count = 0;
  12889. while (att != 0)
  12890. {
  12891. if (count == index)
  12892. return att->name;
  12893. att = att->next;
  12894. ++count;
  12895. }
  12896. return String::empty;
  12897. }
  12898. const String& XmlElement::getAttributeValue (const int index) const throw()
  12899. {
  12900. const XmlAttributeNode* att = attributes;
  12901. int count = 0;
  12902. while (att != 0)
  12903. {
  12904. if (count == index)
  12905. return att->value;
  12906. att = att->next;
  12907. ++count;
  12908. }
  12909. return String::empty;
  12910. }
  12911. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12912. {
  12913. const XmlAttributeNode* att = attributes;
  12914. while (att != 0)
  12915. {
  12916. if (att->name.equalsIgnoreCase (attributeName))
  12917. return true;
  12918. att = att->next;
  12919. }
  12920. return false;
  12921. }
  12922. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12923. {
  12924. const XmlAttributeNode* att = attributes;
  12925. while (att != 0)
  12926. {
  12927. if (att->name.equalsIgnoreCase (attributeName))
  12928. return att->value;
  12929. att = att->next;
  12930. }
  12931. return String::empty;
  12932. }
  12933. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12934. {
  12935. const XmlAttributeNode* att = attributes;
  12936. while (att != 0)
  12937. {
  12938. if (att->name.equalsIgnoreCase (attributeName))
  12939. return att->value;
  12940. att = att->next;
  12941. }
  12942. return defaultReturnValue;
  12943. }
  12944. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12945. {
  12946. const XmlAttributeNode* att = attributes;
  12947. while (att != 0)
  12948. {
  12949. if (att->name.equalsIgnoreCase (attributeName))
  12950. return att->value.getIntValue();
  12951. att = att->next;
  12952. }
  12953. return defaultReturnValue;
  12954. }
  12955. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12956. {
  12957. const XmlAttributeNode* att = attributes;
  12958. while (att != 0)
  12959. {
  12960. if (att->name.equalsIgnoreCase (attributeName))
  12961. return att->value.getDoubleValue();
  12962. att = att->next;
  12963. }
  12964. return defaultReturnValue;
  12965. }
  12966. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12967. {
  12968. const XmlAttributeNode* att = attributes;
  12969. while (att != 0)
  12970. {
  12971. if (att->name.equalsIgnoreCase (attributeName))
  12972. {
  12973. juce_wchar firstChar = att->value[0];
  12974. if (CharacterFunctions::isWhitespace (firstChar))
  12975. firstChar = att->value.trimStart() [0];
  12976. return firstChar == '1'
  12977. || firstChar == 't'
  12978. || firstChar == 'y'
  12979. || firstChar == 'T'
  12980. || firstChar == 'Y';
  12981. }
  12982. att = att->next;
  12983. }
  12984. return defaultReturnValue;
  12985. }
  12986. bool XmlElement::compareAttribute (const String& attributeName,
  12987. const String& stringToCompareAgainst,
  12988. const bool ignoreCase) const throw()
  12989. {
  12990. const XmlAttributeNode* att = attributes;
  12991. while (att != 0)
  12992. {
  12993. if (att->name.equalsIgnoreCase (attributeName))
  12994. {
  12995. if (ignoreCase)
  12996. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12997. else
  12998. return att->value == stringToCompareAgainst;
  12999. }
  13000. att = att->next;
  13001. }
  13002. return false;
  13003. }
  13004. void XmlElement::setAttribute (const String& attributeName, const String& value)
  13005. {
  13006. #if JUCE_DEBUG
  13007. // check the identifier being passed in is legal..
  13008. const juce_wchar* t = attributeName;
  13009. while (*t != 0)
  13010. {
  13011. jassert (CharacterFunctions::isLetterOrDigit (*t)
  13012. || *t == '_'
  13013. || *t == '-'
  13014. || *t == ':');
  13015. ++t;
  13016. }
  13017. #endif
  13018. if (attributes == 0)
  13019. {
  13020. attributes = new XmlAttributeNode (attributeName, value);
  13021. }
  13022. else
  13023. {
  13024. XmlAttributeNode* att = attributes;
  13025. for (;;)
  13026. {
  13027. if (att->name.equalsIgnoreCase (attributeName))
  13028. {
  13029. att->value = value;
  13030. break;
  13031. }
  13032. else if (att->next == 0)
  13033. {
  13034. att->next = new XmlAttributeNode (attributeName, value);
  13035. break;
  13036. }
  13037. att = att->next;
  13038. }
  13039. }
  13040. }
  13041. void XmlElement::setAttribute (const String& attributeName, const int number)
  13042. {
  13043. setAttribute (attributeName, String (number));
  13044. }
  13045. void XmlElement::setAttribute (const String& attributeName, const double number)
  13046. {
  13047. setAttribute (attributeName, String (number));
  13048. }
  13049. void XmlElement::removeAttribute (const String& attributeName) throw()
  13050. {
  13051. XmlAttributeNode* att = attributes;
  13052. XmlAttributeNode* lastAtt = 0;
  13053. while (att != 0)
  13054. {
  13055. if (att->name.equalsIgnoreCase (attributeName))
  13056. {
  13057. if (lastAtt == 0)
  13058. attributes = att->next;
  13059. else
  13060. lastAtt->next = att->next;
  13061. delete att;
  13062. break;
  13063. }
  13064. lastAtt = att;
  13065. att = att->next;
  13066. }
  13067. }
  13068. void XmlElement::removeAllAttributes() throw()
  13069. {
  13070. while (attributes != 0)
  13071. {
  13072. XmlAttributeNode* const nextAtt = attributes->next;
  13073. delete attributes;
  13074. attributes = nextAtt;
  13075. }
  13076. }
  13077. int XmlElement::getNumChildElements() const throw()
  13078. {
  13079. int count = 0;
  13080. const XmlElement* child = firstChildElement;
  13081. while (child != 0)
  13082. {
  13083. ++count;
  13084. child = child->nextElement;
  13085. }
  13086. return count;
  13087. }
  13088. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13089. {
  13090. int count = 0;
  13091. XmlElement* child = firstChildElement;
  13092. while (child != 0 && count < index)
  13093. {
  13094. child = child->nextElement;
  13095. ++count;
  13096. }
  13097. return child;
  13098. }
  13099. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13100. {
  13101. XmlElement* child = firstChildElement;
  13102. while (child != 0)
  13103. {
  13104. if (child->hasTagName (childName))
  13105. break;
  13106. child = child->nextElement;
  13107. }
  13108. return child;
  13109. }
  13110. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13111. {
  13112. if (newNode != 0)
  13113. {
  13114. if (firstChildElement == 0)
  13115. {
  13116. firstChildElement = newNode;
  13117. }
  13118. else
  13119. {
  13120. XmlElement* child = firstChildElement;
  13121. while (child->nextElement != 0)
  13122. child = child->nextElement;
  13123. child->nextElement = newNode;
  13124. // if this is non-zero, then something's probably
  13125. // gone wrong..
  13126. jassert (newNode->nextElement == 0);
  13127. }
  13128. }
  13129. }
  13130. void XmlElement::insertChildElement (XmlElement* const newNode,
  13131. int indexToInsertAt) throw()
  13132. {
  13133. if (newNode != 0)
  13134. {
  13135. removeChildElement (newNode, false);
  13136. if (indexToInsertAt == 0)
  13137. {
  13138. newNode->nextElement = firstChildElement;
  13139. firstChildElement = newNode;
  13140. }
  13141. else
  13142. {
  13143. if (firstChildElement == 0)
  13144. {
  13145. firstChildElement = newNode;
  13146. }
  13147. else
  13148. {
  13149. if (indexToInsertAt < 0)
  13150. indexToInsertAt = std::numeric_limits<int>::max();
  13151. XmlElement* child = firstChildElement;
  13152. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13153. child = child->nextElement;
  13154. newNode->nextElement = child->nextElement;
  13155. child->nextElement = newNode;
  13156. }
  13157. }
  13158. }
  13159. }
  13160. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13161. {
  13162. XmlElement* const newElement = new XmlElement (childTagName);
  13163. addChildElement (newElement);
  13164. return newElement;
  13165. }
  13166. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13167. XmlElement* const newNode) throw()
  13168. {
  13169. if (newNode != 0)
  13170. {
  13171. XmlElement* child = firstChildElement;
  13172. XmlElement* previousNode = 0;
  13173. while (child != 0)
  13174. {
  13175. if (child == currentChildElement)
  13176. {
  13177. if (child != newNode)
  13178. {
  13179. if (previousNode == 0)
  13180. firstChildElement = newNode;
  13181. else
  13182. previousNode->nextElement = newNode;
  13183. newNode->nextElement = child->nextElement;
  13184. delete child;
  13185. }
  13186. return true;
  13187. }
  13188. previousNode = child;
  13189. child = child->nextElement;
  13190. }
  13191. }
  13192. return false;
  13193. }
  13194. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13195. const bool shouldDeleteTheChild) throw()
  13196. {
  13197. if (childToRemove != 0)
  13198. {
  13199. if (firstChildElement == childToRemove)
  13200. {
  13201. firstChildElement = childToRemove->nextElement;
  13202. childToRemove->nextElement = 0;
  13203. }
  13204. else
  13205. {
  13206. XmlElement* child = firstChildElement;
  13207. XmlElement* last = 0;
  13208. while (child != 0)
  13209. {
  13210. if (child == childToRemove)
  13211. {
  13212. if (last == 0)
  13213. firstChildElement = child->nextElement;
  13214. else
  13215. last->nextElement = child->nextElement;
  13216. childToRemove->nextElement = 0;
  13217. break;
  13218. }
  13219. last = child;
  13220. child = child->nextElement;
  13221. }
  13222. }
  13223. if (shouldDeleteTheChild)
  13224. delete childToRemove;
  13225. }
  13226. }
  13227. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13228. const bool ignoreOrderOfAttributes) const throw()
  13229. {
  13230. if (this != other)
  13231. {
  13232. if (other == 0 || tagName != other->tagName)
  13233. return false;
  13234. if (ignoreOrderOfAttributes)
  13235. {
  13236. int totalAtts = 0;
  13237. const XmlAttributeNode* att = attributes;
  13238. while (att != 0)
  13239. {
  13240. if (! other->compareAttribute (att->name, att->value))
  13241. return false;
  13242. att = att->next;
  13243. ++totalAtts;
  13244. }
  13245. if (totalAtts != other->getNumAttributes())
  13246. return false;
  13247. }
  13248. else
  13249. {
  13250. const XmlAttributeNode* thisAtt = attributes;
  13251. const XmlAttributeNode* otherAtt = other->attributes;
  13252. for (;;)
  13253. {
  13254. if (thisAtt == 0 || otherAtt == 0)
  13255. {
  13256. if (thisAtt == otherAtt) // both 0, so it's a match
  13257. break;
  13258. return false;
  13259. }
  13260. if (thisAtt->name != otherAtt->name
  13261. || thisAtt->value != otherAtt->value)
  13262. {
  13263. return false;
  13264. }
  13265. thisAtt = thisAtt->next;
  13266. otherAtt = otherAtt->next;
  13267. }
  13268. }
  13269. const XmlElement* thisChild = firstChildElement;
  13270. const XmlElement* otherChild = other->firstChildElement;
  13271. for (;;)
  13272. {
  13273. if (thisChild == 0 || otherChild == 0)
  13274. {
  13275. if (thisChild == otherChild) // both 0, so it's a match
  13276. break;
  13277. return false;
  13278. }
  13279. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13280. return false;
  13281. thisChild = thisChild->nextElement;
  13282. otherChild = otherChild->nextElement;
  13283. }
  13284. }
  13285. return true;
  13286. }
  13287. void XmlElement::deleteAllChildElements() throw()
  13288. {
  13289. while (firstChildElement != 0)
  13290. {
  13291. XmlElement* const nextChild = firstChildElement->nextElement;
  13292. delete firstChildElement;
  13293. firstChildElement = nextChild;
  13294. }
  13295. }
  13296. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13297. {
  13298. XmlElement* child = firstChildElement;
  13299. while (child != 0)
  13300. {
  13301. if (child->hasTagName (name))
  13302. {
  13303. XmlElement* const nextChild = child->nextElement;
  13304. removeChildElement (child, true);
  13305. child = nextChild;
  13306. }
  13307. else
  13308. {
  13309. child = child->nextElement;
  13310. }
  13311. }
  13312. }
  13313. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13314. {
  13315. const XmlElement* child = firstChildElement;
  13316. while (child != 0)
  13317. {
  13318. if (child == possibleChild)
  13319. return true;
  13320. child = child->nextElement;
  13321. }
  13322. return false;
  13323. }
  13324. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13325. {
  13326. if (this == elementToLookFor || elementToLookFor == 0)
  13327. return 0;
  13328. XmlElement* child = firstChildElement;
  13329. while (child != 0)
  13330. {
  13331. if (elementToLookFor == child)
  13332. return this;
  13333. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13334. if (found != 0)
  13335. return found;
  13336. child = child->nextElement;
  13337. }
  13338. return 0;
  13339. }
  13340. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13341. {
  13342. XmlElement* e = firstChildElement;
  13343. while (e != 0)
  13344. {
  13345. *elems++ = e;
  13346. e = e->nextElement;
  13347. }
  13348. }
  13349. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13350. {
  13351. XmlElement* e = firstChildElement = elems[0];
  13352. for (int i = 1; i < num; ++i)
  13353. {
  13354. e->nextElement = elems[i];
  13355. e = e->nextElement;
  13356. }
  13357. e->nextElement = 0;
  13358. }
  13359. bool XmlElement::isTextElement() const throw()
  13360. {
  13361. return tagName.isEmpty();
  13362. }
  13363. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13364. const String& XmlElement::getText() const throw()
  13365. {
  13366. jassert (isTextElement()); // you're trying to get the text from an element that
  13367. // isn't actually a text element.. If this contains text sub-nodes, you
  13368. // probably want to use getAllSubText instead.
  13369. return getStringAttribute (juce_xmltextContentAttributeName);
  13370. }
  13371. void XmlElement::setText (const String& newText)
  13372. {
  13373. if (isTextElement())
  13374. setAttribute (juce_xmltextContentAttributeName, newText);
  13375. else
  13376. jassertfalse; // you can only change the text in a text element, not a normal one.
  13377. }
  13378. const String XmlElement::getAllSubText() const
  13379. {
  13380. if (isTextElement())
  13381. return getText();
  13382. String result;
  13383. String::Concatenator concatenator (result);
  13384. const XmlElement* child = firstChildElement;
  13385. while (child != 0)
  13386. {
  13387. concatenator.append (child->getAllSubText());
  13388. child = child->nextElement;
  13389. }
  13390. return result;
  13391. }
  13392. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13393. const String& defaultReturnValue) const
  13394. {
  13395. const XmlElement* const child = getChildByName (childTagName);
  13396. if (child != 0)
  13397. return child->getAllSubText();
  13398. return defaultReturnValue;
  13399. }
  13400. XmlElement* XmlElement::createTextElement (const String& text)
  13401. {
  13402. XmlElement* const e = new XmlElement ((int) 0);
  13403. e->setAttribute (juce_xmltextContentAttributeName, text);
  13404. return e;
  13405. }
  13406. void XmlElement::addTextElement (const String& text)
  13407. {
  13408. addChildElement (createTextElement (text));
  13409. }
  13410. void XmlElement::deleteAllTextElements() throw()
  13411. {
  13412. XmlElement* child = firstChildElement;
  13413. while (child != 0)
  13414. {
  13415. XmlElement* const next = child->nextElement;
  13416. if (child->isTextElement())
  13417. removeChildElement (child, true);
  13418. child = next;
  13419. }
  13420. }
  13421. END_JUCE_NAMESPACE
  13422. /*** End of inlined file: juce_XmlElement.cpp ***/
  13423. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13424. BEGIN_JUCE_NAMESPACE
  13425. ReadWriteLock::ReadWriteLock() throw()
  13426. : numWaitingWriters (0),
  13427. numWriters (0),
  13428. writerThreadId (0)
  13429. {
  13430. }
  13431. ReadWriteLock::~ReadWriteLock() throw()
  13432. {
  13433. jassert (readerThreads.size() == 0);
  13434. jassert (numWriters == 0);
  13435. }
  13436. void ReadWriteLock::enterRead() const throw()
  13437. {
  13438. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13439. const ScopedLock sl (accessLock);
  13440. for (;;)
  13441. {
  13442. jassert (readerThreads.size() % 2 == 0);
  13443. int i;
  13444. for (i = 0; i < readerThreads.size(); i += 2)
  13445. if (readerThreads.getUnchecked(i) == threadId)
  13446. break;
  13447. if (i < readerThreads.size()
  13448. || numWriters + numWaitingWriters == 0
  13449. || (threadId == writerThreadId && numWriters > 0))
  13450. {
  13451. if (i < readerThreads.size())
  13452. {
  13453. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13454. }
  13455. else
  13456. {
  13457. readerThreads.add (threadId);
  13458. readerThreads.add ((Thread::ThreadID) 1);
  13459. }
  13460. return;
  13461. }
  13462. const ScopedUnlock ul (accessLock);
  13463. waitEvent.wait (100);
  13464. }
  13465. }
  13466. void ReadWriteLock::exitRead() const throw()
  13467. {
  13468. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13469. const ScopedLock sl (accessLock);
  13470. for (int i = 0; i < readerThreads.size(); i += 2)
  13471. {
  13472. if (readerThreads.getUnchecked(i) == threadId)
  13473. {
  13474. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13475. if (newCount == 0)
  13476. {
  13477. readerThreads.removeRange (i, 2);
  13478. waitEvent.signal();
  13479. }
  13480. else
  13481. {
  13482. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13483. }
  13484. return;
  13485. }
  13486. }
  13487. jassertfalse; // unlocking a lock that wasn't locked..
  13488. }
  13489. void ReadWriteLock::enterWrite() const throw()
  13490. {
  13491. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13492. const ScopedLock sl (accessLock);
  13493. for (;;)
  13494. {
  13495. if (readerThreads.size() + numWriters == 0
  13496. || threadId == writerThreadId
  13497. || (readerThreads.size() == 2
  13498. && readerThreads.getUnchecked(0) == threadId))
  13499. {
  13500. writerThreadId = threadId;
  13501. ++numWriters;
  13502. break;
  13503. }
  13504. ++numWaitingWriters;
  13505. accessLock.exit();
  13506. waitEvent.wait (100);
  13507. accessLock.enter();
  13508. --numWaitingWriters;
  13509. }
  13510. }
  13511. bool ReadWriteLock::tryEnterWrite() const throw()
  13512. {
  13513. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13514. const ScopedLock sl (accessLock);
  13515. if (readerThreads.size() + numWriters == 0
  13516. || threadId == writerThreadId
  13517. || (readerThreads.size() == 2
  13518. && readerThreads.getUnchecked(0) == threadId))
  13519. {
  13520. writerThreadId = threadId;
  13521. ++numWriters;
  13522. return true;
  13523. }
  13524. return false;
  13525. }
  13526. void ReadWriteLock::exitWrite() const throw()
  13527. {
  13528. const ScopedLock sl (accessLock);
  13529. // check this thread actually had the lock..
  13530. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13531. if (--numWriters == 0)
  13532. {
  13533. writerThreadId = 0;
  13534. waitEvent.signal();
  13535. }
  13536. }
  13537. END_JUCE_NAMESPACE
  13538. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13539. /*** Start of inlined file: juce_Thread.cpp ***/
  13540. BEGIN_JUCE_NAMESPACE
  13541. // these functions are implemented in the platform-specific code.
  13542. void* juce_createThread (void* userData);
  13543. void juce_killThread (void* handle);
  13544. bool juce_setThreadPriority (void* handle, int priority);
  13545. void juce_setCurrentThreadName (const String& name);
  13546. #if JUCE_WINDOWS
  13547. void juce_CloseThreadHandle (void* handle);
  13548. #endif
  13549. void Thread::threadEntryPoint (Thread* const thread)
  13550. {
  13551. {
  13552. const ScopedLock sl (runningThreadsLock);
  13553. runningThreads.add (thread);
  13554. }
  13555. JUCE_TRY
  13556. {
  13557. thread->threadId_ = Thread::getCurrentThreadId();
  13558. if (thread->threadName_.isNotEmpty())
  13559. juce_setCurrentThreadName (thread->threadName_);
  13560. if (thread->startSuspensionEvent_.wait (10000))
  13561. {
  13562. if (thread->affinityMask_ != 0)
  13563. setCurrentThreadAffinityMask (thread->affinityMask_);
  13564. thread->run();
  13565. }
  13566. }
  13567. JUCE_CATCH_ALL_ASSERT
  13568. {
  13569. const ScopedLock sl (runningThreadsLock);
  13570. jassert (runningThreads.contains (thread));
  13571. runningThreads.removeValue (thread);
  13572. }
  13573. #if JUCE_WINDOWS
  13574. juce_CloseThreadHandle (thread->threadHandle_);
  13575. #endif
  13576. thread->threadHandle_ = 0;
  13577. thread->threadId_ = 0;
  13578. }
  13579. // used to wrap the incoming call from the platform-specific code
  13580. void JUCE_API juce_threadEntryPoint (void* userData)
  13581. {
  13582. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13583. }
  13584. Thread::Thread (const String& threadName)
  13585. : threadName_ (threadName),
  13586. threadHandle_ (0),
  13587. threadPriority_ (5),
  13588. threadId_ (0),
  13589. affinityMask_ (0),
  13590. threadShouldExit_ (false)
  13591. {
  13592. }
  13593. Thread::~Thread()
  13594. {
  13595. stopThread (100);
  13596. }
  13597. void Thread::startThread()
  13598. {
  13599. const ScopedLock sl (startStopLock);
  13600. threadShouldExit_ = false;
  13601. if (threadHandle_ == 0)
  13602. {
  13603. threadHandle_ = juce_createThread (this);
  13604. juce_setThreadPriority (threadHandle_, threadPriority_);
  13605. startSuspensionEvent_.signal();
  13606. }
  13607. }
  13608. void Thread::startThread (const int priority)
  13609. {
  13610. const ScopedLock sl (startStopLock);
  13611. if (threadHandle_ == 0)
  13612. {
  13613. threadPriority_ = priority;
  13614. startThread();
  13615. }
  13616. else
  13617. {
  13618. setPriority (priority);
  13619. }
  13620. }
  13621. bool Thread::isThreadRunning() const
  13622. {
  13623. return threadHandle_ != 0;
  13624. }
  13625. void Thread::signalThreadShouldExit()
  13626. {
  13627. threadShouldExit_ = true;
  13628. }
  13629. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13630. {
  13631. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13632. jassert (getThreadId() != getCurrentThreadId());
  13633. const int sleepMsPerIteration = 5;
  13634. int count = timeOutMilliseconds / sleepMsPerIteration;
  13635. while (isThreadRunning())
  13636. {
  13637. if (timeOutMilliseconds > 0 && --count < 0)
  13638. return false;
  13639. sleep (sleepMsPerIteration);
  13640. }
  13641. return true;
  13642. }
  13643. void Thread::stopThread (const int timeOutMilliseconds)
  13644. {
  13645. // agh! You can't stop the thread that's calling this method! How on earth
  13646. // would that work??
  13647. jassert (getCurrentThreadId() != getThreadId());
  13648. const ScopedLock sl (startStopLock);
  13649. if (isThreadRunning())
  13650. {
  13651. signalThreadShouldExit();
  13652. notify();
  13653. if (timeOutMilliseconds != 0)
  13654. waitForThreadToExit (timeOutMilliseconds);
  13655. if (isThreadRunning())
  13656. {
  13657. // very bad karma if this point is reached, as
  13658. // there are bound to be locks and events left in
  13659. // silly states when a thread is killed by force..
  13660. jassertfalse;
  13661. Logger::writeToLog ("!! killing thread by force !!");
  13662. juce_killThread (threadHandle_);
  13663. threadHandle_ = 0;
  13664. threadId_ = 0;
  13665. const ScopedLock sl2 (runningThreadsLock);
  13666. runningThreads.removeValue (this);
  13667. }
  13668. }
  13669. }
  13670. bool Thread::setPriority (const int priority)
  13671. {
  13672. const ScopedLock sl (startStopLock);
  13673. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13674. if (worked)
  13675. threadPriority_ = priority;
  13676. return worked;
  13677. }
  13678. bool Thread::setCurrentThreadPriority (const int priority)
  13679. {
  13680. return juce_setThreadPriority (0, priority);
  13681. }
  13682. void Thread::setAffinityMask (const uint32 affinityMask)
  13683. {
  13684. affinityMask_ = affinityMask;
  13685. }
  13686. bool Thread::wait (const int timeOutMilliseconds) const
  13687. {
  13688. return defaultEvent_.wait (timeOutMilliseconds);
  13689. }
  13690. void Thread::notify() const
  13691. {
  13692. defaultEvent_.signal();
  13693. }
  13694. int Thread::getNumRunningThreads()
  13695. {
  13696. return runningThreads.size();
  13697. }
  13698. Thread* Thread::getCurrentThread()
  13699. {
  13700. const ThreadID thisId = getCurrentThreadId();
  13701. const ScopedLock sl (runningThreadsLock);
  13702. for (int i = runningThreads.size(); --i >= 0;)
  13703. {
  13704. Thread* const t = runningThreads.getUnchecked(i);
  13705. if (t->threadId_ == thisId)
  13706. return t;
  13707. }
  13708. return 0;
  13709. }
  13710. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13711. {
  13712. {
  13713. const ScopedLock sl (runningThreadsLock);
  13714. for (int i = runningThreads.size(); --i >= 0;)
  13715. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13716. }
  13717. for (;;)
  13718. {
  13719. Thread* firstThread;
  13720. {
  13721. const ScopedLock sl (runningThreadsLock);
  13722. firstThread = runningThreads.getFirst();
  13723. }
  13724. if (firstThread == 0)
  13725. break;
  13726. firstThread->stopThread (timeOutMilliseconds);
  13727. }
  13728. }
  13729. Array<Thread*> Thread::runningThreads;
  13730. CriticalSection Thread::runningThreadsLock;
  13731. END_JUCE_NAMESPACE
  13732. /*** End of inlined file: juce_Thread.cpp ***/
  13733. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13734. BEGIN_JUCE_NAMESPACE
  13735. ThreadPoolJob::ThreadPoolJob (const String& name)
  13736. : jobName (name),
  13737. pool (0),
  13738. shouldStop (false),
  13739. isActive (false),
  13740. shouldBeDeleted (false)
  13741. {
  13742. }
  13743. ThreadPoolJob::~ThreadPoolJob()
  13744. {
  13745. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13746. // to remove it first!
  13747. jassert (pool == 0 || ! pool->contains (this));
  13748. }
  13749. const String ThreadPoolJob::getJobName() const
  13750. {
  13751. return jobName;
  13752. }
  13753. void ThreadPoolJob::setJobName (const String& newName)
  13754. {
  13755. jobName = newName;
  13756. }
  13757. void ThreadPoolJob::signalJobShouldExit()
  13758. {
  13759. shouldStop = true;
  13760. }
  13761. class ThreadPool::ThreadPoolThread : public Thread
  13762. {
  13763. public:
  13764. ThreadPoolThread (ThreadPool& pool_)
  13765. : Thread ("Pool"),
  13766. pool (pool_),
  13767. busy (false)
  13768. {
  13769. }
  13770. ~ThreadPoolThread()
  13771. {
  13772. }
  13773. void run()
  13774. {
  13775. while (! threadShouldExit())
  13776. {
  13777. if (! pool.runNextJob())
  13778. wait (500);
  13779. }
  13780. }
  13781. private:
  13782. ThreadPool& pool;
  13783. bool volatile busy;
  13784. ThreadPoolThread (const ThreadPoolThread&);
  13785. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13786. };
  13787. ThreadPool::ThreadPool (const int numThreads,
  13788. const bool startThreadsOnlyWhenNeeded,
  13789. const int stopThreadsWhenNotUsedTimeoutMs)
  13790. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13791. priority (5)
  13792. {
  13793. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13794. for (int i = jmax (1, numThreads); --i >= 0;)
  13795. threads.add (new ThreadPoolThread (*this));
  13796. if (! startThreadsOnlyWhenNeeded)
  13797. for (int i = threads.size(); --i >= 0;)
  13798. threads.getUnchecked(i)->startThread (priority);
  13799. }
  13800. ThreadPool::~ThreadPool()
  13801. {
  13802. removeAllJobs (true, 4000);
  13803. int i;
  13804. for (i = threads.size(); --i >= 0;)
  13805. threads.getUnchecked(i)->signalThreadShouldExit();
  13806. for (i = threads.size(); --i >= 0;)
  13807. threads.getUnchecked(i)->stopThread (500);
  13808. }
  13809. void ThreadPool::addJob (ThreadPoolJob* const job)
  13810. {
  13811. jassert (job != 0);
  13812. jassert (job->pool == 0);
  13813. if (job->pool == 0)
  13814. {
  13815. job->pool = this;
  13816. job->shouldStop = false;
  13817. job->isActive = false;
  13818. {
  13819. const ScopedLock sl (lock);
  13820. jobs.add (job);
  13821. int numRunning = 0;
  13822. for (int i = threads.size(); --i >= 0;)
  13823. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13824. ++numRunning;
  13825. if (numRunning < threads.size())
  13826. {
  13827. bool startedOne = false;
  13828. int n = 1000;
  13829. while (--n >= 0 && ! startedOne)
  13830. {
  13831. for (int i = threads.size(); --i >= 0;)
  13832. {
  13833. if (! threads.getUnchecked(i)->isThreadRunning())
  13834. {
  13835. threads.getUnchecked(i)->startThread (priority);
  13836. startedOne = true;
  13837. break;
  13838. }
  13839. }
  13840. if (! startedOne)
  13841. Thread::sleep (2);
  13842. }
  13843. }
  13844. }
  13845. for (int i = threads.size(); --i >= 0;)
  13846. threads.getUnchecked(i)->notify();
  13847. }
  13848. }
  13849. int ThreadPool::getNumJobs() const
  13850. {
  13851. return jobs.size();
  13852. }
  13853. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13854. {
  13855. const ScopedLock sl (lock);
  13856. return jobs [index];
  13857. }
  13858. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13859. {
  13860. const ScopedLock sl (lock);
  13861. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13862. }
  13863. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13864. {
  13865. const ScopedLock sl (lock);
  13866. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13867. }
  13868. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13869. const int timeOutMs) const
  13870. {
  13871. if (job != 0)
  13872. {
  13873. const uint32 start = Time::getMillisecondCounter();
  13874. while (contains (job))
  13875. {
  13876. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13877. return false;
  13878. jobFinishedSignal.wait (2);
  13879. }
  13880. }
  13881. return true;
  13882. }
  13883. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13884. const bool interruptIfRunning,
  13885. const int timeOutMs)
  13886. {
  13887. bool dontWait = true;
  13888. if (job != 0)
  13889. {
  13890. const ScopedLock sl (lock);
  13891. if (jobs.contains (job))
  13892. {
  13893. if (job->isActive)
  13894. {
  13895. if (interruptIfRunning)
  13896. job->signalJobShouldExit();
  13897. dontWait = false;
  13898. }
  13899. else
  13900. {
  13901. jobs.removeValue (job);
  13902. job->pool = 0;
  13903. }
  13904. }
  13905. }
  13906. return dontWait || waitForJobToFinish (job, timeOutMs);
  13907. }
  13908. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13909. const int timeOutMs,
  13910. const bool deleteInactiveJobs,
  13911. ThreadPool::JobSelector* selectedJobsToRemove)
  13912. {
  13913. Array <ThreadPoolJob*> jobsToWaitFor;
  13914. {
  13915. const ScopedLock sl (lock);
  13916. for (int i = jobs.size(); --i >= 0;)
  13917. {
  13918. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13919. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13920. {
  13921. if (job->isActive)
  13922. {
  13923. jobsToWaitFor.add (job);
  13924. if (interruptRunningJobs)
  13925. job->signalJobShouldExit();
  13926. }
  13927. else
  13928. {
  13929. jobs.remove (i);
  13930. if (deleteInactiveJobs)
  13931. delete job;
  13932. else
  13933. job->pool = 0;
  13934. }
  13935. }
  13936. }
  13937. }
  13938. const uint32 start = Time::getMillisecondCounter();
  13939. for (;;)
  13940. {
  13941. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13942. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13943. jobsToWaitFor.remove (i);
  13944. if (jobsToWaitFor.size() == 0)
  13945. break;
  13946. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13947. return false;
  13948. jobFinishedSignal.wait (20);
  13949. }
  13950. return true;
  13951. }
  13952. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13953. {
  13954. StringArray s;
  13955. const ScopedLock sl (lock);
  13956. for (int i = 0; i < jobs.size(); ++i)
  13957. {
  13958. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13959. if (job->isActive || ! onlyReturnActiveJobs)
  13960. s.add (job->getJobName());
  13961. }
  13962. return s;
  13963. }
  13964. bool ThreadPool::setThreadPriorities (const int newPriority)
  13965. {
  13966. bool ok = true;
  13967. if (priority != newPriority)
  13968. {
  13969. priority = newPriority;
  13970. for (int i = threads.size(); --i >= 0;)
  13971. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13972. ok = false;
  13973. }
  13974. return ok;
  13975. }
  13976. bool ThreadPool::runNextJob()
  13977. {
  13978. ThreadPoolJob* job = 0;
  13979. {
  13980. const ScopedLock sl (lock);
  13981. for (int i = 0; i < jobs.size(); ++i)
  13982. {
  13983. job = jobs[i];
  13984. if (job != 0 && ! (job->isActive || job->shouldStop))
  13985. break;
  13986. job = 0;
  13987. }
  13988. if (job != 0)
  13989. job->isActive = true;
  13990. }
  13991. if (job != 0)
  13992. {
  13993. JUCE_TRY
  13994. {
  13995. ThreadPoolJob::JobStatus result = job->runJob();
  13996. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13997. const ScopedLock sl (lock);
  13998. if (jobs.contains (job))
  13999. {
  14000. job->isActive = false;
  14001. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  14002. {
  14003. job->pool = 0;
  14004. job->shouldStop = true;
  14005. jobs.removeValue (job);
  14006. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  14007. delete job;
  14008. jobFinishedSignal.signal();
  14009. }
  14010. else
  14011. {
  14012. // move the job to the end of the queue if it wants another go
  14013. jobs.move (jobs.indexOf (job), -1);
  14014. }
  14015. }
  14016. }
  14017. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14018. catch (...)
  14019. {
  14020. const ScopedLock sl (lock);
  14021. jobs.removeValue (job);
  14022. }
  14023. #endif
  14024. }
  14025. else
  14026. {
  14027. if (threadStopTimeout > 0
  14028. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14029. {
  14030. const ScopedLock sl (lock);
  14031. if (jobs.size() == 0)
  14032. for (int i = threads.size(); --i >= 0;)
  14033. threads.getUnchecked(i)->signalThreadShouldExit();
  14034. }
  14035. else
  14036. {
  14037. return false;
  14038. }
  14039. }
  14040. return true;
  14041. }
  14042. END_JUCE_NAMESPACE
  14043. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14044. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14045. BEGIN_JUCE_NAMESPACE
  14046. TimeSliceThread::TimeSliceThread (const String& threadName)
  14047. : Thread (threadName),
  14048. index (0),
  14049. clientBeingCalled (0),
  14050. clientsChanged (false)
  14051. {
  14052. }
  14053. TimeSliceThread::~TimeSliceThread()
  14054. {
  14055. stopThread (2000);
  14056. }
  14057. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14058. {
  14059. const ScopedLock sl (listLock);
  14060. clients.addIfNotAlreadyThere (client);
  14061. clientsChanged = true;
  14062. notify();
  14063. }
  14064. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14065. {
  14066. const ScopedLock sl1 (listLock);
  14067. clientsChanged = true;
  14068. // if there's a chance we're in the middle of calling this client, we need to
  14069. // also lock the outer lock..
  14070. if (clientBeingCalled == client)
  14071. {
  14072. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14073. const ScopedLock sl2 (callbackLock);
  14074. const ScopedLock sl3 (listLock);
  14075. clients.removeValue (client);
  14076. }
  14077. else
  14078. {
  14079. clients.removeValue (client);
  14080. }
  14081. }
  14082. int TimeSliceThread::getNumClients() const
  14083. {
  14084. return clients.size();
  14085. }
  14086. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14087. {
  14088. const ScopedLock sl (listLock);
  14089. return clients [i];
  14090. }
  14091. void TimeSliceThread::run()
  14092. {
  14093. int numCallsSinceBusy = 0;
  14094. while (! threadShouldExit())
  14095. {
  14096. int timeToWait = 500;
  14097. {
  14098. const ScopedLock sl (callbackLock);
  14099. {
  14100. const ScopedLock sl2 (listLock);
  14101. if (clients.size() > 0)
  14102. {
  14103. index = (index + 1) % clients.size();
  14104. clientBeingCalled = clients [index];
  14105. }
  14106. else
  14107. {
  14108. index = 0;
  14109. clientBeingCalled = 0;
  14110. }
  14111. if (clientsChanged)
  14112. {
  14113. clientsChanged = false;
  14114. numCallsSinceBusy = 0;
  14115. }
  14116. }
  14117. if (clientBeingCalled != 0)
  14118. {
  14119. if (clientBeingCalled->useTimeSlice())
  14120. numCallsSinceBusy = 0;
  14121. else
  14122. ++numCallsSinceBusy;
  14123. if (numCallsSinceBusy >= clients.size())
  14124. timeToWait = 500;
  14125. else if (index == 0)
  14126. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14127. else
  14128. timeToWait = 0;
  14129. }
  14130. }
  14131. if (timeToWait > 0)
  14132. wait (timeToWait);
  14133. }
  14134. }
  14135. END_JUCE_NAMESPACE
  14136. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14137. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14138. BEGIN_JUCE_NAMESPACE
  14139. DeletedAtShutdown::DeletedAtShutdown()
  14140. {
  14141. const ScopedLock sl (getLock());
  14142. getObjects().add (this);
  14143. }
  14144. DeletedAtShutdown::~DeletedAtShutdown()
  14145. {
  14146. const ScopedLock sl (getLock());
  14147. getObjects().removeValue (this);
  14148. }
  14149. void DeletedAtShutdown::deleteAll()
  14150. {
  14151. // make a local copy of the array, so it can't get into a loop if something
  14152. // creates another DeletedAtShutdown object during its destructor.
  14153. Array <DeletedAtShutdown*> localCopy;
  14154. {
  14155. const ScopedLock sl (getLock());
  14156. localCopy = getObjects();
  14157. }
  14158. for (int i = localCopy.size(); --i >= 0;)
  14159. {
  14160. JUCE_TRY
  14161. {
  14162. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14163. // double-check that it's not already been deleted during another object's destructor.
  14164. {
  14165. const ScopedLock sl (getLock());
  14166. if (! getObjects().contains (deletee))
  14167. deletee = 0;
  14168. }
  14169. delete deletee;
  14170. }
  14171. JUCE_CATCH_EXCEPTION
  14172. }
  14173. // if no objects got re-created during shutdown, this should have been emptied by their
  14174. // destructors
  14175. jassert (getObjects().size() == 0);
  14176. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14177. }
  14178. CriticalSection& DeletedAtShutdown::getLock()
  14179. {
  14180. static CriticalSection lock;
  14181. return lock;
  14182. }
  14183. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14184. {
  14185. static Array <DeletedAtShutdown*> objects;
  14186. return objects;
  14187. }
  14188. END_JUCE_NAMESPACE
  14189. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14190. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14191. BEGIN_JUCE_NAMESPACE
  14192. UnitTest::UnitTest (const String& name_)
  14193. : name (name_), runner (0)
  14194. {
  14195. getAllTests().add (this);
  14196. }
  14197. UnitTest::~UnitTest()
  14198. {
  14199. getAllTests().removeValue (this);
  14200. }
  14201. Array<UnitTest*>& UnitTest::getAllTests()
  14202. {
  14203. static Array<UnitTest*> tests;
  14204. return tests;
  14205. }
  14206. void UnitTest::initialise() {}
  14207. void UnitTest::shutdown() {}
  14208. void UnitTest::performTest (UnitTestRunner* const runner_)
  14209. {
  14210. jassert (runner_ != 0);
  14211. runner = runner_;
  14212. initialise();
  14213. runTest();
  14214. shutdown();
  14215. }
  14216. void UnitTest::logMessage (const String& message)
  14217. {
  14218. runner->logMessage (message);
  14219. }
  14220. void UnitTest::beginTest (const String& testName)
  14221. {
  14222. runner->beginNewTest (this, testName);
  14223. }
  14224. void UnitTest::expect (const bool result, const String& failureMessage)
  14225. {
  14226. if (result)
  14227. runner->addPass();
  14228. else
  14229. runner->addFail (failureMessage);
  14230. }
  14231. UnitTestRunner::UnitTestRunner()
  14232. : currentTest (0), assertOnFailure (false)
  14233. {
  14234. }
  14235. UnitTestRunner::~UnitTestRunner()
  14236. {
  14237. }
  14238. int UnitTestRunner::getNumResults() const throw()
  14239. {
  14240. return results.size();
  14241. }
  14242. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14243. {
  14244. return results [index];
  14245. }
  14246. void UnitTestRunner::resultsUpdated()
  14247. {
  14248. }
  14249. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14250. {
  14251. results.clear();
  14252. assertOnFailure = assertOnFailure_;
  14253. resultsUpdated();
  14254. for (int i = 0; i < tests.size(); ++i)
  14255. {
  14256. try
  14257. {
  14258. tests.getUnchecked(i)->performTest (this);
  14259. }
  14260. catch (...)
  14261. {
  14262. addFail ("An unhandled exception was thrown!");
  14263. }
  14264. }
  14265. endTest();
  14266. }
  14267. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14268. {
  14269. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14270. }
  14271. void UnitTestRunner::logMessage (const String& message)
  14272. {
  14273. Logger::writeToLog (message);
  14274. }
  14275. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14276. {
  14277. endTest();
  14278. currentTest = test;
  14279. TestResult* const r = new TestResult();
  14280. r->unitTestName = test->getName();
  14281. r->subcategoryName = subCategory;
  14282. r->passes = 0;
  14283. r->failures = 0;
  14284. results.add (r);
  14285. logMessage ("-----------------------------------------------------------------");
  14286. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14287. resultsUpdated();
  14288. }
  14289. void UnitTestRunner::endTest()
  14290. {
  14291. if (results.size() > 0)
  14292. {
  14293. TestResult* const r = results.getLast();
  14294. if (r->failures > 0)
  14295. {
  14296. String m ("FAILED!!");
  14297. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14298. << " failed, out of a total of " << (r->passes + r->failures);
  14299. logMessage (String::empty);
  14300. logMessage (m);
  14301. logMessage (String::empty);
  14302. }
  14303. else
  14304. {
  14305. logMessage ("All tests completed successfully");
  14306. }
  14307. }
  14308. }
  14309. void UnitTestRunner::addPass()
  14310. {
  14311. {
  14312. const ScopedLock sl (results.getLock());
  14313. TestResult* const r = results.getLast();
  14314. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14315. r->passes++;
  14316. String message ("Test ");
  14317. message << (r->failures + r->passes) << " passed";
  14318. logMessage (message);
  14319. }
  14320. resultsUpdated();
  14321. }
  14322. void UnitTestRunner::addFail (const String& failureMessage)
  14323. {
  14324. {
  14325. const ScopedLock sl (results.getLock());
  14326. TestResult* const r = results.getLast();
  14327. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14328. r->failures++;
  14329. String message ("!!! Test ");
  14330. message << (r->failures + r->passes) << " failed";
  14331. if (failureMessage.isNotEmpty())
  14332. message << ": " << failureMessage;
  14333. r->messages.add (message);
  14334. logMessage (message);
  14335. }
  14336. resultsUpdated();
  14337. if (assertOnFailure) { jassertfalse }
  14338. }
  14339. END_JUCE_NAMESPACE
  14340. /*** End of inlined file: juce_UnitTest.cpp ***/
  14341. #endif
  14342. #if JUCE_BUILD_MISC
  14343. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14344. BEGIN_JUCE_NAMESPACE
  14345. class ValueTree::SetPropertyAction : public UndoableAction
  14346. {
  14347. public:
  14348. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14349. const var& newValue_, const var& oldValue_,
  14350. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14351. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14352. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14353. {
  14354. }
  14355. ~SetPropertyAction() {}
  14356. bool perform()
  14357. {
  14358. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14359. if (isDeletingProperty)
  14360. target->removeProperty (name, 0);
  14361. else
  14362. target->setProperty (name, newValue, 0);
  14363. return true;
  14364. }
  14365. bool undo()
  14366. {
  14367. if (isAddingNewProperty)
  14368. target->removeProperty (name, 0);
  14369. else
  14370. target->setProperty (name, oldValue, 0);
  14371. return true;
  14372. }
  14373. int getSizeInUnits()
  14374. {
  14375. return (int) sizeof (*this); //xxx should be more accurate
  14376. }
  14377. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14378. {
  14379. if (! (isAddingNewProperty || isDeletingProperty))
  14380. {
  14381. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14382. if (next != 0 && next->target == target && next->name == name
  14383. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14384. {
  14385. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14386. }
  14387. }
  14388. return 0;
  14389. }
  14390. private:
  14391. const SharedObjectPtr target;
  14392. const Identifier name;
  14393. const var newValue;
  14394. var oldValue;
  14395. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14396. SetPropertyAction (const SetPropertyAction&);
  14397. SetPropertyAction& operator= (const SetPropertyAction&);
  14398. };
  14399. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14400. {
  14401. public:
  14402. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14403. const SharedObjectPtr& newChild_)
  14404. : target (target_),
  14405. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14406. childIndex (childIndex_),
  14407. isDeleting (newChild_ == 0)
  14408. {
  14409. jassert (child != 0);
  14410. }
  14411. ~AddOrRemoveChildAction() {}
  14412. bool perform()
  14413. {
  14414. if (isDeleting)
  14415. target->removeChild (childIndex, 0);
  14416. else
  14417. target->addChild (child, childIndex, 0);
  14418. return true;
  14419. }
  14420. bool undo()
  14421. {
  14422. if (isDeleting)
  14423. {
  14424. target->addChild (child, childIndex, 0);
  14425. }
  14426. else
  14427. {
  14428. // If you hit this, it seems that your object's state is getting confused - probably
  14429. // because you've interleaved some undoable and non-undoable operations?
  14430. jassert (childIndex < target->children.size());
  14431. target->removeChild (childIndex, 0);
  14432. }
  14433. return true;
  14434. }
  14435. int getSizeInUnits()
  14436. {
  14437. return (int) sizeof (*this); //xxx should be more accurate
  14438. }
  14439. private:
  14440. const SharedObjectPtr target, child;
  14441. const int childIndex;
  14442. const bool isDeleting;
  14443. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14444. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14445. };
  14446. class ValueTree::MoveChildAction : public UndoableAction
  14447. {
  14448. public:
  14449. MoveChildAction (const SharedObjectPtr& parent_,
  14450. const int startIndex_, const int endIndex_)
  14451. : parent (parent_),
  14452. startIndex (startIndex_),
  14453. endIndex (endIndex_)
  14454. {
  14455. }
  14456. ~MoveChildAction() {}
  14457. bool perform()
  14458. {
  14459. parent->moveChild (startIndex, endIndex, 0);
  14460. return true;
  14461. }
  14462. bool undo()
  14463. {
  14464. parent->moveChild (endIndex, startIndex, 0);
  14465. return true;
  14466. }
  14467. int getSizeInUnits()
  14468. {
  14469. return (int) sizeof (*this); //xxx should be more accurate
  14470. }
  14471. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14472. {
  14473. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14474. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14475. return new MoveChildAction (parent, startIndex, next->endIndex);
  14476. return 0;
  14477. }
  14478. private:
  14479. const SharedObjectPtr parent;
  14480. const int startIndex, endIndex;
  14481. MoveChildAction (const MoveChildAction&);
  14482. MoveChildAction& operator= (const MoveChildAction&);
  14483. };
  14484. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14485. : type (type_), parent (0)
  14486. {
  14487. }
  14488. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14489. : type (other.type), properties (other.properties), parent (0)
  14490. {
  14491. for (int i = 0; i < other.children.size(); ++i)
  14492. {
  14493. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14494. child->parent = this;
  14495. children.add (child);
  14496. }
  14497. }
  14498. ValueTree::SharedObject::~SharedObject()
  14499. {
  14500. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14501. for (int i = children.size(); --i >= 0;)
  14502. {
  14503. const SharedObjectPtr c (children.getUnchecked(i));
  14504. c->parent = 0;
  14505. children.remove (i);
  14506. c->sendParentChangeMessage();
  14507. }
  14508. }
  14509. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14510. {
  14511. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14512. {
  14513. ValueTree* const v = valueTreesWithListeners[i];
  14514. if (v != 0)
  14515. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14516. }
  14517. }
  14518. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14519. {
  14520. ValueTree tree (this);
  14521. ValueTree::SharedObject* t = this;
  14522. while (t != 0)
  14523. {
  14524. t->sendPropertyChangeMessage (tree, property);
  14525. t = t->parent;
  14526. }
  14527. }
  14528. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14529. {
  14530. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14531. {
  14532. ValueTree* const v = valueTreesWithListeners[i];
  14533. if (v != 0)
  14534. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14535. }
  14536. }
  14537. void ValueTree::SharedObject::sendChildChangeMessage()
  14538. {
  14539. ValueTree tree (this);
  14540. ValueTree::SharedObject* t = this;
  14541. while (t != 0)
  14542. {
  14543. t->sendChildChangeMessage (tree);
  14544. t = t->parent;
  14545. }
  14546. }
  14547. void ValueTree::SharedObject::sendParentChangeMessage()
  14548. {
  14549. ValueTree tree (this);
  14550. int i;
  14551. for (i = children.size(); --i >= 0;)
  14552. {
  14553. SharedObject* const t = children[i];
  14554. if (t != 0)
  14555. t->sendParentChangeMessage();
  14556. }
  14557. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14558. {
  14559. ValueTree* const v = valueTreesWithListeners[i];
  14560. if (v != 0)
  14561. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14562. }
  14563. }
  14564. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14565. {
  14566. return properties [name];
  14567. }
  14568. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14569. {
  14570. return properties.getWithDefault (name, defaultReturnValue);
  14571. }
  14572. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14573. {
  14574. if (undoManager == 0)
  14575. {
  14576. if (properties.set (name, newValue))
  14577. sendPropertyChangeMessage (name);
  14578. }
  14579. else
  14580. {
  14581. var* const existingValue = properties.getItem (name);
  14582. if (existingValue != 0)
  14583. {
  14584. if (*existingValue != newValue)
  14585. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14586. }
  14587. else
  14588. {
  14589. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14590. }
  14591. }
  14592. }
  14593. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14594. {
  14595. return properties.contains (name);
  14596. }
  14597. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14598. {
  14599. if (undoManager == 0)
  14600. {
  14601. if (properties.remove (name))
  14602. sendPropertyChangeMessage (name);
  14603. }
  14604. else
  14605. {
  14606. if (properties.contains (name))
  14607. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14608. }
  14609. }
  14610. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14611. {
  14612. if (undoManager == 0)
  14613. {
  14614. while (properties.size() > 0)
  14615. {
  14616. const Identifier name (properties.getName (properties.size() - 1));
  14617. properties.remove (name);
  14618. sendPropertyChangeMessage (name);
  14619. }
  14620. }
  14621. else
  14622. {
  14623. for (int i = properties.size(); --i >= 0;)
  14624. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14625. }
  14626. }
  14627. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14628. {
  14629. for (int i = 0; i < children.size(); ++i)
  14630. if (children.getUnchecked(i)->type == typeToMatch)
  14631. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14632. return ValueTree::invalid;
  14633. }
  14634. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14635. {
  14636. for (int i = 0; i < children.size(); ++i)
  14637. if (children.getUnchecked(i)->type == typeToMatch)
  14638. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14639. SharedObject* const newObject = new SharedObject (typeToMatch);
  14640. addChild (newObject, -1, undoManager);
  14641. return ValueTree (newObject);
  14642. }
  14643. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14644. {
  14645. for (int i = 0; i < children.size(); ++i)
  14646. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14647. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14648. return ValueTree::invalid;
  14649. }
  14650. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14651. {
  14652. const SharedObject* p = parent;
  14653. while (p != 0)
  14654. {
  14655. if (p == possibleParent)
  14656. return true;
  14657. p = p->parent;
  14658. }
  14659. return false;
  14660. }
  14661. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14662. {
  14663. return children.indexOf (child.object);
  14664. }
  14665. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14666. {
  14667. if (child != 0 && child->parent != this)
  14668. {
  14669. if (child != this && ! isAChildOf (child))
  14670. {
  14671. // You should always make sure that a child is removed from its previous parent before
  14672. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14673. // undomanager should be used when removing it from its current parent..
  14674. jassert (child->parent == 0);
  14675. if (child->parent != 0)
  14676. {
  14677. jassert (child->parent->children.indexOf (child) >= 0);
  14678. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14679. }
  14680. if (undoManager == 0)
  14681. {
  14682. children.insert (index, child);
  14683. child->parent = this;
  14684. sendChildChangeMessage();
  14685. child->sendParentChangeMessage();
  14686. }
  14687. else
  14688. {
  14689. if (index < 0)
  14690. index = children.size();
  14691. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14692. }
  14693. }
  14694. else
  14695. {
  14696. // You're attempting to create a recursive loop! A node
  14697. // can't be a child of one of its own children!
  14698. jassertfalse;
  14699. }
  14700. }
  14701. }
  14702. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14703. {
  14704. const SharedObjectPtr child (children [childIndex]);
  14705. if (child != 0)
  14706. {
  14707. if (undoManager == 0)
  14708. {
  14709. children.remove (childIndex);
  14710. child->parent = 0;
  14711. sendChildChangeMessage();
  14712. child->sendParentChangeMessage();
  14713. }
  14714. else
  14715. {
  14716. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14717. }
  14718. }
  14719. }
  14720. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14721. {
  14722. while (children.size() > 0)
  14723. removeChild (children.size() - 1, undoManager);
  14724. }
  14725. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14726. {
  14727. // The source index must be a valid index!
  14728. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14729. if (currentIndex != newIndex
  14730. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14731. {
  14732. if (undoManager == 0)
  14733. {
  14734. children.move (currentIndex, newIndex);
  14735. sendChildChangeMessage();
  14736. }
  14737. else
  14738. {
  14739. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14740. newIndex = children.size() - 1;
  14741. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14742. }
  14743. }
  14744. }
  14745. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14746. {
  14747. jassert (newOrder.size() == children.size());
  14748. if (undoManager == 0)
  14749. {
  14750. children = newOrder;
  14751. sendChildChangeMessage();
  14752. }
  14753. else
  14754. {
  14755. for (int i = 0; i < children.size(); ++i)
  14756. {
  14757. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14758. {
  14759. jassert (children.contains (newOrder.getUnchecked(i)));
  14760. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14761. }
  14762. }
  14763. }
  14764. }
  14765. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14766. {
  14767. if (type != other.type
  14768. || properties.size() != other.properties.size()
  14769. || children.size() != other.children.size()
  14770. || properties != other.properties)
  14771. return false;
  14772. for (int i = 0; i < children.size(); ++i)
  14773. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14774. return false;
  14775. return true;
  14776. }
  14777. ValueTree::ValueTree() throw()
  14778. : object (0)
  14779. {
  14780. }
  14781. const ValueTree ValueTree::invalid;
  14782. ValueTree::ValueTree (const Identifier& type_)
  14783. : object (new ValueTree::SharedObject (type_))
  14784. {
  14785. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14786. }
  14787. ValueTree::ValueTree (SharedObject* const object_)
  14788. : object (object_)
  14789. {
  14790. }
  14791. ValueTree::ValueTree (const ValueTree& other)
  14792. : object (other.object)
  14793. {
  14794. }
  14795. ValueTree& ValueTree::operator= (const ValueTree& other)
  14796. {
  14797. if (listeners.size() > 0)
  14798. {
  14799. if (object != 0)
  14800. object->valueTreesWithListeners.removeValue (this);
  14801. if (other.object != 0)
  14802. other.object->valueTreesWithListeners.add (this);
  14803. }
  14804. object = other.object;
  14805. return *this;
  14806. }
  14807. ValueTree::~ValueTree()
  14808. {
  14809. if (listeners.size() > 0 && object != 0)
  14810. object->valueTreesWithListeners.removeValue (this);
  14811. }
  14812. bool ValueTree::operator== (const ValueTree& other) const throw()
  14813. {
  14814. return object == other.object;
  14815. }
  14816. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14817. {
  14818. return object != other.object;
  14819. }
  14820. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14821. {
  14822. return object == other.object
  14823. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14824. }
  14825. ValueTree ValueTree::createCopy() const
  14826. {
  14827. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14828. }
  14829. bool ValueTree::hasType (const Identifier& typeName) const
  14830. {
  14831. return object != 0 && object->type == typeName;
  14832. }
  14833. const Identifier ValueTree::getType() const
  14834. {
  14835. return object != 0 ? object->type : Identifier();
  14836. }
  14837. ValueTree ValueTree::getParent() const
  14838. {
  14839. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14840. }
  14841. ValueTree ValueTree::getSibling (const int delta) const
  14842. {
  14843. if (object == 0 || object->parent == 0)
  14844. return invalid;
  14845. const int index = object->parent->indexOf (*this) + delta;
  14846. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14847. }
  14848. const var& ValueTree::operator[] (const Identifier& name) const
  14849. {
  14850. return object == 0 ? var::null : object->getProperty (name);
  14851. }
  14852. const var& ValueTree::getProperty (const Identifier& name) const
  14853. {
  14854. return object == 0 ? var::null : object->getProperty (name);
  14855. }
  14856. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14857. {
  14858. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14859. }
  14860. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14861. {
  14862. jassert (name.toString().isNotEmpty());
  14863. if (object != 0 && name.toString().isNotEmpty())
  14864. object->setProperty (name, newValue, undoManager);
  14865. }
  14866. bool ValueTree::hasProperty (const Identifier& name) const
  14867. {
  14868. return object != 0 && object->hasProperty (name);
  14869. }
  14870. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14871. {
  14872. if (object != 0)
  14873. object->removeProperty (name, undoManager);
  14874. }
  14875. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14876. {
  14877. if (object != 0)
  14878. object->removeAllProperties (undoManager);
  14879. }
  14880. int ValueTree::getNumProperties() const
  14881. {
  14882. return object == 0 ? 0 : object->properties.size();
  14883. }
  14884. const Identifier ValueTree::getPropertyName (const int index) const
  14885. {
  14886. return object == 0 ? Identifier()
  14887. : object->properties.getName (index);
  14888. }
  14889. class ValueTreePropertyValueSource : public Value::ValueSource,
  14890. public ValueTree::Listener
  14891. {
  14892. public:
  14893. ValueTreePropertyValueSource (const ValueTree& tree_,
  14894. const Identifier& property_,
  14895. UndoManager* const undoManager_)
  14896. : tree (tree_),
  14897. property (property_),
  14898. undoManager (undoManager_)
  14899. {
  14900. tree.addListener (this);
  14901. }
  14902. ~ValueTreePropertyValueSource()
  14903. {
  14904. tree.removeListener (this);
  14905. }
  14906. const var getValue() const
  14907. {
  14908. return tree [property];
  14909. }
  14910. void setValue (const var& newValue)
  14911. {
  14912. tree.setProperty (property, newValue, undoManager);
  14913. }
  14914. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14915. {
  14916. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14917. sendChangeMessage (false);
  14918. }
  14919. void valueTreeChildrenChanged (ValueTree&) {}
  14920. void valueTreeParentChanged (ValueTree&) {}
  14921. private:
  14922. ValueTree tree;
  14923. const Identifier property;
  14924. UndoManager* const undoManager;
  14925. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14926. };
  14927. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14928. {
  14929. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14930. }
  14931. int ValueTree::getNumChildren() const
  14932. {
  14933. return object == 0 ? 0 : object->children.size();
  14934. }
  14935. ValueTree ValueTree::getChild (int index) const
  14936. {
  14937. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14938. }
  14939. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14940. {
  14941. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14942. }
  14943. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14944. {
  14945. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14946. }
  14947. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14948. {
  14949. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14950. }
  14951. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14952. {
  14953. return object != 0 && object->isAChildOf (possibleParent.object);
  14954. }
  14955. int ValueTree::indexOf (const ValueTree& child) const
  14956. {
  14957. return object != 0 ? object->indexOf (child) : -1;
  14958. }
  14959. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14960. {
  14961. if (object != 0)
  14962. object->addChild (child.object, index, undoManager);
  14963. }
  14964. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14965. {
  14966. if (object != 0)
  14967. object->removeChild (childIndex, undoManager);
  14968. }
  14969. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14970. {
  14971. if (object != 0)
  14972. object->removeChild (object->children.indexOf (child.object), undoManager);
  14973. }
  14974. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14975. {
  14976. if (object != 0)
  14977. object->removeAllChildren (undoManager);
  14978. }
  14979. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14980. {
  14981. if (object != 0)
  14982. object->moveChild (currentIndex, newIndex, undoManager);
  14983. }
  14984. void ValueTree::addListener (Listener* listener)
  14985. {
  14986. if (listener != 0)
  14987. {
  14988. if (listeners.size() == 0 && object != 0)
  14989. object->valueTreesWithListeners.add (this);
  14990. listeners.add (listener);
  14991. }
  14992. }
  14993. void ValueTree::removeListener (Listener* listener)
  14994. {
  14995. listeners.remove (listener);
  14996. if (listeners.size() == 0 && object != 0)
  14997. object->valueTreesWithListeners.removeValue (this);
  14998. }
  14999. XmlElement* ValueTree::SharedObject::createXml() const
  15000. {
  15001. XmlElement* xml = new XmlElement (type.toString());
  15002. int i;
  15003. for (i = 0; i < properties.size(); ++i)
  15004. {
  15005. Identifier name (properties.getName(i));
  15006. const var& v = properties [name];
  15007. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  15008. xml->setAttribute (name.toString(), v.toString());
  15009. }
  15010. for (i = 0; i < children.size(); ++i)
  15011. xml->addChildElement (children.getUnchecked(i)->createXml());
  15012. return xml;
  15013. }
  15014. XmlElement* ValueTree::createXml() const
  15015. {
  15016. return object != 0 ? object->createXml() : 0;
  15017. }
  15018. ValueTree ValueTree::fromXml (const XmlElement& xml)
  15019. {
  15020. ValueTree v (xml.getTagName());
  15021. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  15022. for (int i = 0; i < numAtts; ++i)
  15023. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  15024. forEachXmlChildElement (xml, e)
  15025. {
  15026. v.addChild (fromXml (*e), -1, 0);
  15027. }
  15028. return v;
  15029. }
  15030. void ValueTree::writeToStream (OutputStream& output)
  15031. {
  15032. output.writeString (getType().toString());
  15033. const int numProps = getNumProperties();
  15034. output.writeCompressedInt (numProps);
  15035. int i;
  15036. for (i = 0; i < numProps; ++i)
  15037. {
  15038. const Identifier name (getPropertyName(i));
  15039. output.writeString (name.toString());
  15040. getProperty(name).writeToStream (output);
  15041. }
  15042. const int numChildren = getNumChildren();
  15043. output.writeCompressedInt (numChildren);
  15044. for (i = 0; i < numChildren; ++i)
  15045. getChild (i).writeToStream (output);
  15046. }
  15047. ValueTree ValueTree::readFromStream (InputStream& input)
  15048. {
  15049. const String type (input.readString());
  15050. if (type.isEmpty())
  15051. return ValueTree::invalid;
  15052. ValueTree v (type);
  15053. const int numProps = input.readCompressedInt();
  15054. if (numProps < 0)
  15055. {
  15056. jassertfalse; // trying to read corrupted data!
  15057. return v;
  15058. }
  15059. int i;
  15060. for (i = 0; i < numProps; ++i)
  15061. {
  15062. const String name (input.readString());
  15063. jassert (name.isNotEmpty());
  15064. const var value (var::readFromStream (input));
  15065. v.setProperty (name, value, 0);
  15066. }
  15067. const int numChildren = input.readCompressedInt();
  15068. for (i = 0; i < numChildren; ++i)
  15069. v.addChild (readFromStream (input), -1, 0);
  15070. return v;
  15071. }
  15072. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15073. {
  15074. MemoryInputStream in (data, numBytes, false);
  15075. return readFromStream (in);
  15076. }
  15077. END_JUCE_NAMESPACE
  15078. /*** End of inlined file: juce_ValueTree.cpp ***/
  15079. /*** Start of inlined file: juce_Value.cpp ***/
  15080. BEGIN_JUCE_NAMESPACE
  15081. Value::ValueSource::ValueSource()
  15082. {
  15083. }
  15084. Value::ValueSource::~ValueSource()
  15085. {
  15086. }
  15087. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15088. {
  15089. if (synchronous)
  15090. {
  15091. for (int i = valuesWithListeners.size(); --i >= 0;)
  15092. {
  15093. Value* const v = valuesWithListeners[i];
  15094. if (v != 0)
  15095. v->callListeners();
  15096. }
  15097. }
  15098. else
  15099. {
  15100. triggerAsyncUpdate();
  15101. }
  15102. }
  15103. void Value::ValueSource::handleAsyncUpdate()
  15104. {
  15105. sendChangeMessage (true);
  15106. }
  15107. class SimpleValueSource : public Value::ValueSource
  15108. {
  15109. public:
  15110. SimpleValueSource()
  15111. {
  15112. }
  15113. SimpleValueSource (const var& initialValue)
  15114. : value (initialValue)
  15115. {
  15116. }
  15117. ~SimpleValueSource()
  15118. {
  15119. }
  15120. const var getValue() const
  15121. {
  15122. return value;
  15123. }
  15124. void setValue (const var& newValue)
  15125. {
  15126. if (newValue != value)
  15127. {
  15128. value = newValue;
  15129. sendChangeMessage (false);
  15130. }
  15131. }
  15132. private:
  15133. var value;
  15134. SimpleValueSource (const SimpleValueSource&);
  15135. SimpleValueSource& operator= (const SimpleValueSource&);
  15136. };
  15137. Value::Value()
  15138. : value (new SimpleValueSource())
  15139. {
  15140. }
  15141. Value::Value (ValueSource* const value_)
  15142. : value (value_)
  15143. {
  15144. jassert (value_ != 0);
  15145. }
  15146. Value::Value (const var& initialValue)
  15147. : value (new SimpleValueSource (initialValue))
  15148. {
  15149. }
  15150. Value::Value (const Value& other)
  15151. : value (other.value)
  15152. {
  15153. }
  15154. Value& Value::operator= (const Value& other)
  15155. {
  15156. value = other.value;
  15157. return *this;
  15158. }
  15159. Value::~Value()
  15160. {
  15161. if (listeners.size() > 0)
  15162. value->valuesWithListeners.removeValue (this);
  15163. }
  15164. const var Value::getValue() const
  15165. {
  15166. return value->getValue();
  15167. }
  15168. Value::operator const var() const
  15169. {
  15170. return getValue();
  15171. }
  15172. void Value::setValue (const var& newValue)
  15173. {
  15174. value->setValue (newValue);
  15175. }
  15176. const String Value::toString() const
  15177. {
  15178. return value->getValue().toString();
  15179. }
  15180. Value& Value::operator= (const var& newValue)
  15181. {
  15182. value->setValue (newValue);
  15183. return *this;
  15184. }
  15185. void Value::referTo (const Value& valueToReferTo)
  15186. {
  15187. if (valueToReferTo.value != value)
  15188. {
  15189. if (listeners.size() > 0)
  15190. {
  15191. value->valuesWithListeners.removeValue (this);
  15192. valueToReferTo.value->valuesWithListeners.add (this);
  15193. }
  15194. value = valueToReferTo.value;
  15195. callListeners();
  15196. }
  15197. }
  15198. bool Value::refersToSameSourceAs (const Value& other) const
  15199. {
  15200. return value == other.value;
  15201. }
  15202. bool Value::operator== (const Value& other) const
  15203. {
  15204. return value == other.value || value->getValue() == other.getValue();
  15205. }
  15206. bool Value::operator!= (const Value& other) const
  15207. {
  15208. return value != other.value && value->getValue() != other.getValue();
  15209. }
  15210. void Value::addListener (Listener* const listener)
  15211. {
  15212. if (listener != 0)
  15213. {
  15214. if (listeners.size() == 0)
  15215. value->valuesWithListeners.add (this);
  15216. listeners.add (listener);
  15217. }
  15218. }
  15219. void Value::removeListener (Listener* const listener)
  15220. {
  15221. listeners.remove (listener);
  15222. if (listeners.size() == 0)
  15223. value->valuesWithListeners.removeValue (this);
  15224. }
  15225. void Value::callListeners()
  15226. {
  15227. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15228. listeners.call (&Value::Listener::valueChanged, v);
  15229. }
  15230. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15231. {
  15232. return stream << value.toString();
  15233. }
  15234. END_JUCE_NAMESPACE
  15235. /*** End of inlined file: juce_Value.cpp ***/
  15236. /*** Start of inlined file: juce_Application.cpp ***/
  15237. BEGIN_JUCE_NAMESPACE
  15238. #if JUCE_MAC
  15239. extern void juce_initialiseMacMainMenu();
  15240. #endif
  15241. JUCEApplication::JUCEApplication()
  15242. : appReturnValue (0),
  15243. stillInitialising (true)
  15244. {
  15245. jassert (isStandaloneApp() && appInstance == 0);
  15246. appInstance = this;
  15247. }
  15248. JUCEApplication::~JUCEApplication()
  15249. {
  15250. if (appLock != 0)
  15251. {
  15252. appLock->exit();
  15253. appLock = 0;
  15254. }
  15255. jassert (appInstance == this);
  15256. appInstance = 0;
  15257. }
  15258. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15259. JUCEApplication* JUCEApplication::appInstance = 0;
  15260. bool JUCEApplication::moreThanOneInstanceAllowed()
  15261. {
  15262. return true;
  15263. }
  15264. void JUCEApplication::anotherInstanceStarted (const String&)
  15265. {
  15266. }
  15267. void JUCEApplication::systemRequestedQuit()
  15268. {
  15269. quit();
  15270. }
  15271. void JUCEApplication::quit()
  15272. {
  15273. MessageManager::getInstance()->stopDispatchLoop();
  15274. }
  15275. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15276. {
  15277. appReturnValue = newReturnValue;
  15278. }
  15279. void JUCEApplication::actionListenerCallback (const String& message)
  15280. {
  15281. if (message.startsWith (getApplicationName() + "/"))
  15282. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15283. }
  15284. void JUCEApplication::unhandledException (const std::exception*,
  15285. const String&,
  15286. const int)
  15287. {
  15288. jassertfalse;
  15289. }
  15290. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15291. const char* const sourceFile,
  15292. const int lineNumber)
  15293. {
  15294. if (appInstance != 0)
  15295. appInstance->unhandledException (e, sourceFile, lineNumber);
  15296. }
  15297. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15298. {
  15299. return 0;
  15300. }
  15301. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15302. {
  15303. commands.add (StandardApplicationCommandIDs::quit);
  15304. }
  15305. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15306. {
  15307. if (commandID == StandardApplicationCommandIDs::quit)
  15308. {
  15309. result.setInfo (TRANS("Quit"),
  15310. TRANS("Quits the application"),
  15311. "Application",
  15312. 0);
  15313. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15314. }
  15315. }
  15316. bool JUCEApplication::perform (const InvocationInfo& info)
  15317. {
  15318. if (info.commandID == StandardApplicationCommandIDs::quit)
  15319. {
  15320. systemRequestedQuit();
  15321. return true;
  15322. }
  15323. return false;
  15324. }
  15325. bool JUCEApplication::initialiseApp (const String& commandLine)
  15326. {
  15327. commandLineParameters = commandLine.trim();
  15328. #if ! JUCE_IOS
  15329. jassert (appLock == 0); // initialiseApp must only be called once!
  15330. if (! moreThanOneInstanceAllowed())
  15331. {
  15332. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15333. if (! appLock->enter(0))
  15334. {
  15335. appLock = 0;
  15336. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15337. DBG ("Another instance is running - quitting...");
  15338. return false;
  15339. }
  15340. }
  15341. #endif
  15342. // let the app do its setting-up..
  15343. initialise (commandLineParameters);
  15344. #if JUCE_MAC
  15345. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15346. #endif
  15347. // register for broadcast new app messages
  15348. MessageManager::getInstance()->registerBroadcastListener (this);
  15349. stillInitialising = false;
  15350. return true;
  15351. }
  15352. int JUCEApplication::shutdownApp()
  15353. {
  15354. jassert (appInstance == this);
  15355. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15356. JUCE_TRY
  15357. {
  15358. // give the app a chance to clean up..
  15359. shutdown();
  15360. }
  15361. JUCE_CATCH_EXCEPTION
  15362. return getApplicationReturnValue();
  15363. }
  15364. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15365. void JUCEApplication::appWillTerminateByForce()
  15366. {
  15367. {
  15368. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15369. if (app != 0)
  15370. app->shutdownApp();
  15371. }
  15372. shutdownJuce_GUI();
  15373. }
  15374. int JUCEApplication::main (const String& commandLine)
  15375. {
  15376. ScopedJuceInitialiser_GUI libraryInitialiser;
  15377. jassert (createInstance != 0);
  15378. int returnCode = 0;
  15379. {
  15380. const ScopedPointer<JUCEApplication> app (createInstance());
  15381. if (! app->initialiseApp (commandLine))
  15382. return 0;
  15383. JUCE_TRY
  15384. {
  15385. // loop until a quit message is received..
  15386. MessageManager::getInstance()->runDispatchLoop();
  15387. }
  15388. JUCE_CATCH_EXCEPTION
  15389. returnCode = app->shutdownApp();
  15390. }
  15391. return returnCode;
  15392. }
  15393. #if JUCE_IOS
  15394. extern int juce_iOSMain (int argc, const char* argv[]);
  15395. #endif
  15396. #if ! JUCE_WINDOWS
  15397. extern const char* juce_Argv0;
  15398. #endif
  15399. int JUCEApplication::main (int argc, const char* argv[])
  15400. {
  15401. JUCE_AUTORELEASEPOOL
  15402. #if ! JUCE_WINDOWS
  15403. jassert (createInstance != 0);
  15404. juce_Argv0 = argv[0];
  15405. #endif
  15406. #if JUCE_IOS
  15407. return juce_iOSMain (argc, argv);
  15408. #else
  15409. String cmd;
  15410. for (int i = 1; i < argc; ++i)
  15411. cmd << argv[i] << ' ';
  15412. return JUCEApplication::main (cmd);
  15413. #endif
  15414. }
  15415. END_JUCE_NAMESPACE
  15416. /*** End of inlined file: juce_Application.cpp ***/
  15417. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15418. BEGIN_JUCE_NAMESPACE
  15419. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15420. : commandID (commandID_),
  15421. flags (0)
  15422. {
  15423. }
  15424. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15425. const String& description_,
  15426. const String& categoryName_,
  15427. const int flags_) throw()
  15428. {
  15429. shortName = shortName_;
  15430. description = description_;
  15431. categoryName = categoryName_;
  15432. flags = flags_;
  15433. }
  15434. void ApplicationCommandInfo::setActive (const bool b) throw()
  15435. {
  15436. if (b)
  15437. flags &= ~isDisabled;
  15438. else
  15439. flags |= isDisabled;
  15440. }
  15441. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15442. {
  15443. if (b)
  15444. flags |= isTicked;
  15445. else
  15446. flags &= ~isTicked;
  15447. }
  15448. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15449. {
  15450. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15451. }
  15452. END_JUCE_NAMESPACE
  15453. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15454. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15455. BEGIN_JUCE_NAMESPACE
  15456. ApplicationCommandManager::ApplicationCommandManager()
  15457. : firstTarget (0)
  15458. {
  15459. keyMappings = new KeyPressMappingSet (this);
  15460. Desktop::getInstance().addFocusChangeListener (this);
  15461. }
  15462. ApplicationCommandManager::~ApplicationCommandManager()
  15463. {
  15464. Desktop::getInstance().removeFocusChangeListener (this);
  15465. keyMappings = 0;
  15466. }
  15467. void ApplicationCommandManager::clearCommands()
  15468. {
  15469. commands.clear();
  15470. keyMappings->clearAllKeyPresses();
  15471. triggerAsyncUpdate();
  15472. }
  15473. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15474. {
  15475. // zero isn't a valid command ID!
  15476. jassert (newCommand.commandID != 0);
  15477. // the name isn't optional!
  15478. jassert (newCommand.shortName.isNotEmpty());
  15479. if (getCommandForID (newCommand.commandID) == 0)
  15480. {
  15481. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15482. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15483. commands.add (newInfo);
  15484. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15485. triggerAsyncUpdate();
  15486. }
  15487. else
  15488. {
  15489. // trying to re-register the same command with different parameters?
  15490. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15491. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15492. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15493. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15494. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15495. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15496. }
  15497. }
  15498. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15499. {
  15500. if (target != 0)
  15501. {
  15502. Array <CommandID> commandIDs;
  15503. target->getAllCommands (commandIDs);
  15504. for (int i = 0; i < commandIDs.size(); ++i)
  15505. {
  15506. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15507. target->getCommandInfo (info.commandID, info);
  15508. registerCommand (info);
  15509. }
  15510. }
  15511. }
  15512. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15513. {
  15514. for (int i = commands.size(); --i >= 0;)
  15515. {
  15516. if (commands.getUnchecked (i)->commandID == commandID)
  15517. {
  15518. commands.remove (i);
  15519. triggerAsyncUpdate();
  15520. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15521. for (int j = keys.size(); --j >= 0;)
  15522. keyMappings->removeKeyPress (keys.getReference (j));
  15523. }
  15524. }
  15525. }
  15526. void ApplicationCommandManager::commandStatusChanged()
  15527. {
  15528. triggerAsyncUpdate();
  15529. }
  15530. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15531. {
  15532. for (int i = commands.size(); --i >= 0;)
  15533. if (commands.getUnchecked(i)->commandID == commandID)
  15534. return commands.getUnchecked(i);
  15535. return 0;
  15536. }
  15537. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15538. {
  15539. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15540. return (ci != 0) ? ci->shortName : String::empty;
  15541. }
  15542. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15543. {
  15544. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15545. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15546. : String::empty;
  15547. }
  15548. const StringArray ApplicationCommandManager::getCommandCategories() const
  15549. {
  15550. StringArray s;
  15551. for (int i = 0; i < commands.size(); ++i)
  15552. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15553. return s;
  15554. }
  15555. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15556. {
  15557. Array <CommandID> results;
  15558. for (int i = 0; i < commands.size(); ++i)
  15559. if (commands.getUnchecked(i)->categoryName == categoryName)
  15560. results.add (commands.getUnchecked(i)->commandID);
  15561. return results;
  15562. }
  15563. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15564. {
  15565. ApplicationCommandTarget::InvocationInfo info (commandID);
  15566. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15567. return invoke (info, asynchronously);
  15568. }
  15569. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15570. {
  15571. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15572. // manager first..
  15573. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15574. ApplicationCommandInfo commandInfo (0);
  15575. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15576. if (target == 0)
  15577. return false;
  15578. ApplicationCommandTarget::InvocationInfo info (info_);
  15579. info.commandFlags = commandInfo.flags;
  15580. sendListenerInvokeCallback (info);
  15581. const bool ok = target->invoke (info, asynchronously);
  15582. commandStatusChanged();
  15583. return ok;
  15584. }
  15585. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15586. {
  15587. return firstTarget != 0 ? firstTarget
  15588. : findDefaultComponentTarget();
  15589. }
  15590. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15591. {
  15592. firstTarget = newTarget;
  15593. }
  15594. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15595. ApplicationCommandInfo& upToDateInfo)
  15596. {
  15597. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15598. if (target == 0)
  15599. target = JUCEApplication::getInstance();
  15600. if (target != 0)
  15601. target = target->getTargetForCommand (commandID);
  15602. if (target != 0)
  15603. target->getCommandInfo (commandID, upToDateInfo);
  15604. return target;
  15605. }
  15606. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15607. {
  15608. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15609. if (target == 0 && c != 0)
  15610. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15611. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15612. return target;
  15613. }
  15614. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15615. {
  15616. Component* c = Component::getCurrentlyFocusedComponent();
  15617. if (c == 0)
  15618. {
  15619. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15620. if (activeWindow != 0)
  15621. {
  15622. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15623. if (c == 0)
  15624. c = activeWindow;
  15625. }
  15626. }
  15627. if (c == 0 && Process::isForegroundProcess())
  15628. {
  15629. // getting a bit desperate now - try all desktop comps..
  15630. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15631. {
  15632. ApplicationCommandTarget* const target
  15633. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15634. ->getPeer()->getLastFocusedSubcomponent());
  15635. if (target != 0)
  15636. return target;
  15637. }
  15638. }
  15639. if (c != 0)
  15640. {
  15641. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15642. // if we're focused on a ResizableWindow, chances are that it's the content
  15643. // component that really should get the event. And if not, the event will
  15644. // still be passed up to the top level window anyway, so let's send it to the
  15645. // content comp.
  15646. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15647. c = resizableWindow->getContentComponent();
  15648. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15649. if (target != 0)
  15650. return target;
  15651. }
  15652. return JUCEApplication::getInstance();
  15653. }
  15654. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15655. {
  15656. listeners.add (listener);
  15657. }
  15658. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15659. {
  15660. listeners.remove (listener);
  15661. }
  15662. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15663. {
  15664. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15665. }
  15666. void ApplicationCommandManager::handleAsyncUpdate()
  15667. {
  15668. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15669. }
  15670. void ApplicationCommandManager::globalFocusChanged (Component*)
  15671. {
  15672. commandStatusChanged();
  15673. }
  15674. END_JUCE_NAMESPACE
  15675. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15676. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15677. BEGIN_JUCE_NAMESPACE
  15678. ApplicationCommandTarget::ApplicationCommandTarget()
  15679. {
  15680. }
  15681. ApplicationCommandTarget::~ApplicationCommandTarget()
  15682. {
  15683. messageInvoker = 0;
  15684. }
  15685. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15686. {
  15687. if (isCommandActive (info.commandID))
  15688. {
  15689. if (async)
  15690. {
  15691. if (messageInvoker == 0)
  15692. messageInvoker = new CommandTargetMessageInvoker (this);
  15693. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15694. return true;
  15695. }
  15696. else
  15697. {
  15698. const bool success = perform (info);
  15699. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15700. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15701. // returns the command's info.
  15702. return success;
  15703. }
  15704. }
  15705. return false;
  15706. }
  15707. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15708. {
  15709. Component* c = dynamic_cast <Component*> (this);
  15710. if (c != 0)
  15711. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15712. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15713. return 0;
  15714. }
  15715. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15716. {
  15717. ApplicationCommandTarget* target = this;
  15718. int depth = 0;
  15719. while (target != 0)
  15720. {
  15721. Array <CommandID> commandIDs;
  15722. target->getAllCommands (commandIDs);
  15723. if (commandIDs.contains (commandID))
  15724. return target;
  15725. target = target->getNextCommandTarget();
  15726. ++depth;
  15727. jassert (depth < 100); // could be a recursive command chain??
  15728. jassert (target != this); // definitely a recursive command chain!
  15729. if (depth > 100 || target == this)
  15730. break;
  15731. }
  15732. if (target == 0)
  15733. {
  15734. target = JUCEApplication::getInstance();
  15735. if (target != 0)
  15736. {
  15737. Array <CommandID> commandIDs;
  15738. target->getAllCommands (commandIDs);
  15739. if (commandIDs.contains (commandID))
  15740. return target;
  15741. }
  15742. }
  15743. return 0;
  15744. }
  15745. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15746. {
  15747. ApplicationCommandInfo info (commandID);
  15748. info.flags = ApplicationCommandInfo::isDisabled;
  15749. getCommandInfo (commandID, info);
  15750. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15751. }
  15752. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15753. {
  15754. ApplicationCommandTarget* target = this;
  15755. int depth = 0;
  15756. while (target != 0)
  15757. {
  15758. if (target->tryToInvoke (info, async))
  15759. return true;
  15760. target = target->getNextCommandTarget();
  15761. ++depth;
  15762. jassert (depth < 100); // could be a recursive command chain??
  15763. jassert (target != this); // definitely a recursive command chain!
  15764. if (depth > 100 || target == this)
  15765. break;
  15766. }
  15767. if (target == 0)
  15768. {
  15769. target = JUCEApplication::getInstance();
  15770. if (target != 0)
  15771. return target->tryToInvoke (info, async);
  15772. }
  15773. return false;
  15774. }
  15775. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15776. {
  15777. ApplicationCommandTarget::InvocationInfo info (commandID);
  15778. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15779. return invoke (info, asynchronously);
  15780. }
  15781. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15782. : commandID (commandID_),
  15783. commandFlags (0),
  15784. invocationMethod (direct),
  15785. originatingComponent (0),
  15786. isKeyDown (false),
  15787. millisecsSinceKeyPressed (0)
  15788. {
  15789. }
  15790. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15791. : owner (owner_)
  15792. {
  15793. }
  15794. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15795. {
  15796. }
  15797. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15798. {
  15799. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15800. owner->tryToInvoke (*info, false);
  15801. }
  15802. END_JUCE_NAMESPACE
  15803. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15804. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15805. BEGIN_JUCE_NAMESPACE
  15806. juce_ImplementSingleton (ApplicationProperties)
  15807. ApplicationProperties::ApplicationProperties()
  15808. : msBeforeSaving (3000),
  15809. options (PropertiesFile::storeAsBinary),
  15810. commonSettingsAreReadOnly (0),
  15811. processLock (0)
  15812. {
  15813. }
  15814. ApplicationProperties::~ApplicationProperties()
  15815. {
  15816. closeFiles();
  15817. clearSingletonInstance();
  15818. }
  15819. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15820. const String& fileNameSuffix,
  15821. const String& folderName_,
  15822. const int millisecondsBeforeSaving,
  15823. const int propertiesFileOptions,
  15824. InterProcessLock* processLock_)
  15825. {
  15826. appName = applicationName;
  15827. fileSuffix = fileNameSuffix;
  15828. folderName = folderName_;
  15829. msBeforeSaving = millisecondsBeforeSaving;
  15830. options = propertiesFileOptions;
  15831. processLock = processLock_;
  15832. }
  15833. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15834. const bool testCommonSettings,
  15835. const bool showWarningDialogOnFailure)
  15836. {
  15837. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15838. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15839. if (! (userOk && commonOk))
  15840. {
  15841. if (showWarningDialogOnFailure)
  15842. {
  15843. String filenames;
  15844. if (userProps != 0 && ! userOk)
  15845. filenames << '\n' << userProps->getFile().getFullPathName();
  15846. if (commonProps != 0 && ! commonOk)
  15847. filenames << '\n' << commonProps->getFile().getFullPathName();
  15848. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15849. appName + TRANS(" - Unable to save settings"),
  15850. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15851. + appName + TRANS(" needs to be able to write to the following files:\n")
  15852. + filenames
  15853. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15854. }
  15855. return false;
  15856. }
  15857. return true;
  15858. }
  15859. void ApplicationProperties::openFiles()
  15860. {
  15861. // You need to call setStorageParameters() before trying to get hold of the
  15862. // properties!
  15863. jassert (appName.isNotEmpty());
  15864. if (appName.isNotEmpty())
  15865. {
  15866. if (userProps == 0)
  15867. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15868. false, msBeforeSaving, options, processLock);
  15869. if (commonProps == 0)
  15870. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15871. true, msBeforeSaving, options, processLock);
  15872. userProps->setFallbackPropertySet (commonProps);
  15873. }
  15874. }
  15875. PropertiesFile* ApplicationProperties::getUserSettings()
  15876. {
  15877. if (userProps == 0)
  15878. openFiles();
  15879. return userProps;
  15880. }
  15881. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15882. {
  15883. if (commonProps == 0)
  15884. openFiles();
  15885. if (returnUserPropsIfReadOnly)
  15886. {
  15887. if (commonSettingsAreReadOnly == 0)
  15888. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15889. if (commonSettingsAreReadOnly > 0)
  15890. return userProps;
  15891. }
  15892. return commonProps;
  15893. }
  15894. bool ApplicationProperties::saveIfNeeded()
  15895. {
  15896. return (userProps == 0 || userProps->saveIfNeeded())
  15897. && (commonProps == 0 || commonProps->saveIfNeeded());
  15898. }
  15899. void ApplicationProperties::closeFiles()
  15900. {
  15901. userProps = 0;
  15902. commonProps = 0;
  15903. }
  15904. END_JUCE_NAMESPACE
  15905. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15906. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15907. BEGIN_JUCE_NAMESPACE
  15908. namespace PropertyFileConstants
  15909. {
  15910. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15911. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15912. static const char* const fileTag = "PROPERTIES";
  15913. static const char* const valueTag = "VALUE";
  15914. static const char* const nameAttribute = "name";
  15915. static const char* const valueAttribute = "val";
  15916. }
  15917. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15918. const int options_, InterProcessLock* const processLock_)
  15919. : PropertySet (ignoreCaseOfKeyNames),
  15920. file (f),
  15921. timerInterval (millisecondsBeforeSaving),
  15922. options (options_),
  15923. loadedOk (false),
  15924. needsWriting (false),
  15925. processLock (processLock_)
  15926. {
  15927. // You need to correctly specify just one storage format for the file
  15928. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15929. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15930. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15931. ProcessScopedLock pl (createProcessLock());
  15932. if (pl != 0 && ! pl->isLocked())
  15933. return; // locking failure..
  15934. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15935. if (fileStream != 0)
  15936. {
  15937. int magicNumber = fileStream->readInt();
  15938. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15939. {
  15940. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15941. magicNumber = PropertyFileConstants::magicNumber;
  15942. }
  15943. if (magicNumber == PropertyFileConstants::magicNumber)
  15944. {
  15945. loadedOk = true;
  15946. BufferedInputStream in (fileStream.release(), 2048, true);
  15947. int numValues = in.readInt();
  15948. while (--numValues >= 0 && ! in.isExhausted())
  15949. {
  15950. const String key (in.readString());
  15951. const String value (in.readString());
  15952. jassert (key.isNotEmpty());
  15953. if (key.isNotEmpty())
  15954. getAllProperties().set (key, value);
  15955. }
  15956. }
  15957. else
  15958. {
  15959. // Not a binary props file - let's see if it's XML..
  15960. fileStream = 0;
  15961. XmlDocument parser (f);
  15962. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15963. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15964. {
  15965. doc = parser.getDocumentElement();
  15966. if (doc != 0)
  15967. {
  15968. loadedOk = true;
  15969. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15970. {
  15971. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15972. if (name.isNotEmpty())
  15973. {
  15974. getAllProperties().set (name,
  15975. e->getFirstChildElement() != 0
  15976. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15977. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15978. }
  15979. }
  15980. }
  15981. else
  15982. {
  15983. // must be a pretty broken XML file we're trying to parse here,
  15984. // or a sign that this object needs an InterProcessLock,
  15985. // or just a failure reading the file. This last reason is why
  15986. // we don't jassertfalse here.
  15987. }
  15988. }
  15989. }
  15990. }
  15991. else
  15992. {
  15993. loadedOk = ! f.exists();
  15994. }
  15995. }
  15996. PropertiesFile::~PropertiesFile()
  15997. {
  15998. if (! saveIfNeeded())
  15999. jassertfalse;
  16000. }
  16001. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  16002. {
  16003. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  16004. }
  16005. bool PropertiesFile::saveIfNeeded()
  16006. {
  16007. const ScopedLock sl (getLock());
  16008. return (! needsWriting) || save();
  16009. }
  16010. bool PropertiesFile::needsToBeSaved() const
  16011. {
  16012. const ScopedLock sl (getLock());
  16013. return needsWriting;
  16014. }
  16015. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  16016. {
  16017. const ScopedLock sl (getLock());
  16018. needsWriting = needsToBeSaved_;
  16019. }
  16020. bool PropertiesFile::save()
  16021. {
  16022. const ScopedLock sl (getLock());
  16023. stopTimer();
  16024. if (file == File::nonexistent
  16025. || file.isDirectory()
  16026. || ! file.getParentDirectory().createDirectory())
  16027. return false;
  16028. if ((options & storeAsXML) != 0)
  16029. {
  16030. XmlElement doc (PropertyFileConstants::fileTag);
  16031. for (int i = 0; i < getAllProperties().size(); ++i)
  16032. {
  16033. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16034. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16035. // if the value seems to contain xml, store it as such..
  16036. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  16037. XmlElement* const childElement = xmlContent.getDocumentElement();
  16038. if (childElement != 0)
  16039. e->addChildElement (childElement);
  16040. else
  16041. e->setAttribute (PropertyFileConstants::valueAttribute,
  16042. getAllProperties().getAllValues() [i]);
  16043. }
  16044. ProcessScopedLock pl (createProcessLock());
  16045. if (pl != 0 && ! pl->isLocked())
  16046. return false; // locking failure..
  16047. if (doc.writeToFile (file, String::empty))
  16048. {
  16049. needsWriting = false;
  16050. return true;
  16051. }
  16052. }
  16053. else
  16054. {
  16055. ProcessScopedLock pl (createProcessLock());
  16056. if (pl != 0 && ! pl->isLocked())
  16057. return false; // locking failure..
  16058. TemporaryFile tempFile (file);
  16059. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16060. if (out != 0)
  16061. {
  16062. if ((options & storeAsCompressedBinary) != 0)
  16063. {
  16064. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16065. out->flush();
  16066. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16067. }
  16068. else
  16069. {
  16070. // have you set up the storage option flags correctly?
  16071. jassert ((options & storeAsBinary) != 0);
  16072. out->writeInt (PropertyFileConstants::magicNumber);
  16073. }
  16074. const int numProperties = getAllProperties().size();
  16075. out->writeInt (numProperties);
  16076. for (int i = 0; i < numProperties; ++i)
  16077. {
  16078. out->writeString (getAllProperties().getAllKeys() [i]);
  16079. out->writeString (getAllProperties().getAllValues() [i]);
  16080. }
  16081. out = 0;
  16082. if (tempFile.overwriteTargetFileWithTemporary())
  16083. {
  16084. needsWriting = false;
  16085. return true;
  16086. }
  16087. }
  16088. }
  16089. return false;
  16090. }
  16091. void PropertiesFile::timerCallback()
  16092. {
  16093. saveIfNeeded();
  16094. }
  16095. void PropertiesFile::propertyChanged()
  16096. {
  16097. sendChangeMessage (this);
  16098. needsWriting = true;
  16099. if (timerInterval > 0)
  16100. startTimer (timerInterval);
  16101. else if (timerInterval == 0)
  16102. saveIfNeeded();
  16103. }
  16104. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16105. const String& fileNameSuffix,
  16106. const String& folderName,
  16107. const bool commonToAllUsers)
  16108. {
  16109. // mustn't have illegal characters in this name..
  16110. jassert (applicationName == File::createLegalFileName (applicationName));
  16111. #if JUCE_MAC || JUCE_IOS
  16112. File dir (commonToAllUsers ? "/Library/Preferences"
  16113. : "~/Library/Preferences");
  16114. if (folderName.isNotEmpty())
  16115. dir = dir.getChildFile (folderName);
  16116. #endif
  16117. #ifdef JUCE_LINUX
  16118. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16119. + (folderName.isNotEmpty() ? folderName
  16120. : ("." + applicationName)));
  16121. #endif
  16122. #if JUCE_WINDOWS
  16123. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16124. : File::userApplicationDataDirectory));
  16125. if (dir == File::nonexistent)
  16126. return File::nonexistent;
  16127. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16128. : applicationName);
  16129. #endif
  16130. return dir.getChildFile (applicationName)
  16131. .withFileExtension (fileNameSuffix);
  16132. }
  16133. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16134. const String& fileNameSuffix,
  16135. const String& folderName,
  16136. const bool commonToAllUsers,
  16137. const int millisecondsBeforeSaving,
  16138. const int propertiesFileOptions,
  16139. InterProcessLock* processLock_)
  16140. {
  16141. const File file (getDefaultAppSettingsFile (applicationName,
  16142. fileNameSuffix,
  16143. folderName,
  16144. commonToAllUsers));
  16145. jassert (file != File::nonexistent);
  16146. if (file == File::nonexistent)
  16147. return 0;
  16148. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16149. }
  16150. END_JUCE_NAMESPACE
  16151. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16152. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16153. BEGIN_JUCE_NAMESPACE
  16154. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16155. const String& fileWildcard_,
  16156. const String& openFileDialogTitle_,
  16157. const String& saveFileDialogTitle_)
  16158. : changedSinceSave (false),
  16159. fileExtension (fileExtension_),
  16160. fileWildcard (fileWildcard_),
  16161. openFileDialogTitle (openFileDialogTitle_),
  16162. saveFileDialogTitle (saveFileDialogTitle_)
  16163. {
  16164. }
  16165. FileBasedDocument::~FileBasedDocument()
  16166. {
  16167. }
  16168. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16169. {
  16170. if (changedSinceSave != hasChanged)
  16171. {
  16172. changedSinceSave = hasChanged;
  16173. sendChangeMessage (this);
  16174. }
  16175. }
  16176. void FileBasedDocument::changed()
  16177. {
  16178. changedSinceSave = true;
  16179. sendChangeMessage (this);
  16180. }
  16181. void FileBasedDocument::setFile (const File& newFile)
  16182. {
  16183. if (documentFile != newFile)
  16184. {
  16185. documentFile = newFile;
  16186. changed();
  16187. }
  16188. }
  16189. bool FileBasedDocument::loadFrom (const File& newFile,
  16190. const bool showMessageOnFailure)
  16191. {
  16192. MouseCursor::showWaitCursor();
  16193. const File oldFile (documentFile);
  16194. documentFile = newFile;
  16195. String error;
  16196. if (newFile.existsAsFile())
  16197. {
  16198. error = loadDocument (newFile);
  16199. if (error.isEmpty())
  16200. {
  16201. setChangedFlag (false);
  16202. MouseCursor::hideWaitCursor();
  16203. setLastDocumentOpened (newFile);
  16204. return true;
  16205. }
  16206. }
  16207. else
  16208. {
  16209. error = "The file doesn't exist";
  16210. }
  16211. documentFile = oldFile;
  16212. MouseCursor::hideWaitCursor();
  16213. if (showMessageOnFailure)
  16214. {
  16215. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16216. TRANS("Failed to open file..."),
  16217. TRANS("There was an error while trying to load the file:\n\n")
  16218. + newFile.getFullPathName()
  16219. + "\n\n"
  16220. + error);
  16221. }
  16222. return false;
  16223. }
  16224. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16225. {
  16226. FileChooser fc (openFileDialogTitle,
  16227. getLastDocumentOpened(),
  16228. fileWildcard);
  16229. if (fc.browseForFileToOpen())
  16230. return loadFrom (fc.getResult(), showMessageOnFailure);
  16231. return false;
  16232. }
  16233. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16234. const bool showMessageOnFailure)
  16235. {
  16236. return saveAs (documentFile,
  16237. false,
  16238. askUserForFileIfNotSpecified,
  16239. showMessageOnFailure);
  16240. }
  16241. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16242. const bool warnAboutOverwritingExistingFiles,
  16243. const bool askUserForFileIfNotSpecified,
  16244. const bool showMessageOnFailure)
  16245. {
  16246. if (newFile == File::nonexistent)
  16247. {
  16248. if (askUserForFileIfNotSpecified)
  16249. {
  16250. return saveAsInteractive (true);
  16251. }
  16252. else
  16253. {
  16254. // can't save to an unspecified file
  16255. jassertfalse;
  16256. return failedToWriteToFile;
  16257. }
  16258. }
  16259. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16260. {
  16261. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16262. TRANS("File already exists"),
  16263. TRANS("There's already a file called:\n\n")
  16264. + newFile.getFullPathName()
  16265. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16266. TRANS("overwrite"),
  16267. TRANS("cancel")))
  16268. {
  16269. return userCancelledSave;
  16270. }
  16271. }
  16272. MouseCursor::showWaitCursor();
  16273. const File oldFile (documentFile);
  16274. documentFile = newFile;
  16275. String error (saveDocument (newFile));
  16276. if (error.isEmpty())
  16277. {
  16278. setChangedFlag (false);
  16279. MouseCursor::hideWaitCursor();
  16280. return savedOk;
  16281. }
  16282. documentFile = oldFile;
  16283. MouseCursor::hideWaitCursor();
  16284. if (showMessageOnFailure)
  16285. {
  16286. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16287. TRANS("Error writing to file..."),
  16288. TRANS("An error occurred while trying to save \"")
  16289. + getDocumentTitle()
  16290. + TRANS("\" to the file:\n\n")
  16291. + newFile.getFullPathName()
  16292. + "\n\n"
  16293. + error);
  16294. }
  16295. return failedToWriteToFile;
  16296. }
  16297. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16298. {
  16299. if (! hasChangedSinceSaved())
  16300. return savedOk;
  16301. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16302. TRANS("Closing document..."),
  16303. TRANS("Do you want to save the changes to \"")
  16304. + getDocumentTitle() + "\"?",
  16305. TRANS("save"),
  16306. TRANS("discard changes"),
  16307. TRANS("cancel"));
  16308. if (r == 1)
  16309. {
  16310. // save changes
  16311. return save (true, true);
  16312. }
  16313. else if (r == 2)
  16314. {
  16315. // discard changes
  16316. return savedOk;
  16317. }
  16318. return userCancelledSave;
  16319. }
  16320. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16321. {
  16322. File f;
  16323. if (documentFile.existsAsFile())
  16324. f = documentFile;
  16325. else
  16326. f = getLastDocumentOpened();
  16327. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16328. if (legalFilename.isEmpty())
  16329. legalFilename = "unnamed";
  16330. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16331. f = f.getSiblingFile (legalFilename);
  16332. else
  16333. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16334. f = f.withFileExtension (fileExtension)
  16335. .getNonexistentSibling (true);
  16336. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16337. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16338. {
  16339. File chosen (fc.getResult());
  16340. if (chosen.getFileExtension().isEmpty())
  16341. {
  16342. chosen = chosen.withFileExtension (fileExtension);
  16343. if (chosen.exists())
  16344. {
  16345. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16346. TRANS("File already exists"),
  16347. TRANS("There's already a file called:")
  16348. + "\n\n" + chosen.getFullPathName()
  16349. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16350. TRANS("overwrite"),
  16351. TRANS("cancel")))
  16352. {
  16353. return userCancelledSave;
  16354. }
  16355. }
  16356. }
  16357. setLastDocumentOpened (chosen);
  16358. return saveAs (chosen, false, false, true);
  16359. }
  16360. return userCancelledSave;
  16361. }
  16362. END_JUCE_NAMESPACE
  16363. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16364. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16365. BEGIN_JUCE_NAMESPACE
  16366. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16367. : maxNumberOfItems (10)
  16368. {
  16369. }
  16370. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16371. {
  16372. }
  16373. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16374. {
  16375. maxNumberOfItems = jmax (1, newMaxNumber);
  16376. while (getNumFiles() > maxNumberOfItems)
  16377. files.remove (getNumFiles() - 1);
  16378. }
  16379. int RecentlyOpenedFilesList::getNumFiles() const
  16380. {
  16381. return files.size();
  16382. }
  16383. const File RecentlyOpenedFilesList::getFile (const int index) const
  16384. {
  16385. return File (files [index]);
  16386. }
  16387. void RecentlyOpenedFilesList::clear()
  16388. {
  16389. files.clear();
  16390. }
  16391. void RecentlyOpenedFilesList::addFile (const File& file)
  16392. {
  16393. const String path (file.getFullPathName());
  16394. files.removeString (path, true);
  16395. files.insert (0, path);
  16396. setMaxNumberOfItems (maxNumberOfItems);
  16397. }
  16398. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16399. {
  16400. for (int i = getNumFiles(); --i >= 0;)
  16401. if (! getFile(i).exists())
  16402. files.remove (i);
  16403. }
  16404. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16405. const int baseItemId,
  16406. const bool showFullPaths,
  16407. const bool dontAddNonExistentFiles,
  16408. const File** filesToAvoid)
  16409. {
  16410. int num = 0;
  16411. for (int i = 0; i < getNumFiles(); ++i)
  16412. {
  16413. const File f (getFile(i));
  16414. if ((! dontAddNonExistentFiles) || f.exists())
  16415. {
  16416. bool needsAvoiding = false;
  16417. if (filesToAvoid != 0)
  16418. {
  16419. const File** avoid = filesToAvoid;
  16420. while (*avoid != 0)
  16421. {
  16422. if (f == **avoid)
  16423. {
  16424. needsAvoiding = true;
  16425. break;
  16426. }
  16427. ++avoid;
  16428. }
  16429. }
  16430. if (! needsAvoiding)
  16431. {
  16432. menuToAddTo.addItem (baseItemId + i,
  16433. showFullPaths ? f.getFullPathName()
  16434. : f.getFileName());
  16435. ++num;
  16436. }
  16437. }
  16438. }
  16439. return num;
  16440. }
  16441. const String RecentlyOpenedFilesList::toString() const
  16442. {
  16443. return files.joinIntoString ("\n");
  16444. }
  16445. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16446. {
  16447. clear();
  16448. files.addLines (stringifiedVersion);
  16449. setMaxNumberOfItems (maxNumberOfItems);
  16450. }
  16451. END_JUCE_NAMESPACE
  16452. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16453. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16454. BEGIN_JUCE_NAMESPACE
  16455. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16456. const int minimumTransactions)
  16457. : totalUnitsStored (0),
  16458. nextIndex (0),
  16459. newTransaction (true),
  16460. reentrancyCheck (false)
  16461. {
  16462. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16463. minimumTransactions);
  16464. }
  16465. UndoManager::~UndoManager()
  16466. {
  16467. clearUndoHistory();
  16468. }
  16469. void UndoManager::clearUndoHistory()
  16470. {
  16471. transactions.clear();
  16472. transactionNames.clear();
  16473. totalUnitsStored = 0;
  16474. nextIndex = 0;
  16475. sendChangeMessage (this);
  16476. }
  16477. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16478. {
  16479. return totalUnitsStored;
  16480. }
  16481. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16482. const int minimumTransactions)
  16483. {
  16484. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16485. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16486. }
  16487. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16488. {
  16489. if (command_ != 0)
  16490. {
  16491. ScopedPointer<UndoableAction> command (command_);
  16492. if (actionName.isNotEmpty())
  16493. currentTransactionName = actionName;
  16494. if (reentrancyCheck)
  16495. {
  16496. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16497. // undo() methods, or else these actions won't actually get done.
  16498. return false;
  16499. }
  16500. else if (command->perform())
  16501. {
  16502. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16503. if (commandSet != 0 && ! newTransaction)
  16504. {
  16505. UndoableAction* lastAction = commandSet->getLast();
  16506. if (lastAction != 0)
  16507. {
  16508. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16509. if (coalescedAction != 0)
  16510. {
  16511. command = coalescedAction;
  16512. totalUnitsStored -= lastAction->getSizeInUnits();
  16513. commandSet->removeLast();
  16514. }
  16515. }
  16516. }
  16517. else
  16518. {
  16519. commandSet = new OwnedArray<UndoableAction>();
  16520. transactions.insert (nextIndex, commandSet);
  16521. transactionNames.insert (nextIndex, currentTransactionName);
  16522. ++nextIndex;
  16523. }
  16524. totalUnitsStored += command->getSizeInUnits();
  16525. commandSet->add (command.release());
  16526. newTransaction = false;
  16527. while (nextIndex < transactions.size())
  16528. {
  16529. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16530. for (int i = lastSet->size(); --i >= 0;)
  16531. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16532. transactions.removeLast();
  16533. transactionNames.remove (transactionNames.size() - 1);
  16534. }
  16535. while (nextIndex > 0
  16536. && totalUnitsStored > maxNumUnitsToKeep
  16537. && transactions.size() > minimumTransactionsToKeep)
  16538. {
  16539. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16540. for (int i = firstSet->size(); --i >= 0;)
  16541. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16542. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16543. transactions.remove (0);
  16544. transactionNames.remove (0);
  16545. --nextIndex;
  16546. }
  16547. sendChangeMessage (this);
  16548. return true;
  16549. }
  16550. }
  16551. return false;
  16552. }
  16553. void UndoManager::beginNewTransaction (const String& actionName)
  16554. {
  16555. newTransaction = true;
  16556. currentTransactionName = actionName;
  16557. }
  16558. void UndoManager::setCurrentTransactionName (const String& newName)
  16559. {
  16560. currentTransactionName = newName;
  16561. }
  16562. bool UndoManager::canUndo() const
  16563. {
  16564. return nextIndex > 0;
  16565. }
  16566. bool UndoManager::canRedo() const
  16567. {
  16568. return nextIndex < transactions.size();
  16569. }
  16570. const String UndoManager::getUndoDescription() const
  16571. {
  16572. return transactionNames [nextIndex - 1];
  16573. }
  16574. const String UndoManager::getRedoDescription() const
  16575. {
  16576. return transactionNames [nextIndex];
  16577. }
  16578. bool UndoManager::undo()
  16579. {
  16580. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16581. if (commandSet == 0)
  16582. return false;
  16583. reentrancyCheck = true;
  16584. bool failed = false;
  16585. for (int i = commandSet->size(); --i >= 0;)
  16586. {
  16587. if (! commandSet->getUnchecked(i)->undo())
  16588. {
  16589. jassertfalse;
  16590. failed = true;
  16591. break;
  16592. }
  16593. }
  16594. reentrancyCheck = false;
  16595. if (failed)
  16596. clearUndoHistory();
  16597. else
  16598. --nextIndex;
  16599. beginNewTransaction();
  16600. sendChangeMessage (this);
  16601. return true;
  16602. }
  16603. bool UndoManager::redo()
  16604. {
  16605. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16606. if (commandSet == 0)
  16607. return false;
  16608. reentrancyCheck = true;
  16609. bool failed = false;
  16610. for (int i = 0; i < commandSet->size(); ++i)
  16611. {
  16612. if (! commandSet->getUnchecked(i)->perform())
  16613. {
  16614. jassertfalse;
  16615. failed = true;
  16616. break;
  16617. }
  16618. }
  16619. reentrancyCheck = false;
  16620. if (failed)
  16621. clearUndoHistory();
  16622. else
  16623. ++nextIndex;
  16624. beginNewTransaction();
  16625. sendChangeMessage (this);
  16626. return true;
  16627. }
  16628. bool UndoManager::undoCurrentTransactionOnly()
  16629. {
  16630. return newTransaction ? false : undo();
  16631. }
  16632. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16633. {
  16634. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16635. if (commandSet != 0 && ! newTransaction)
  16636. {
  16637. for (int i = 0; i < commandSet->size(); ++i)
  16638. actionsFound.add (commandSet->getUnchecked(i));
  16639. }
  16640. }
  16641. int UndoManager::getNumActionsInCurrentTransaction() const
  16642. {
  16643. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16644. if (commandSet != 0 && ! newTransaction)
  16645. return commandSet->size();
  16646. return 0;
  16647. }
  16648. END_JUCE_NAMESPACE
  16649. /*** End of inlined file: juce_UndoManager.cpp ***/
  16650. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16651. BEGIN_JUCE_NAMESPACE
  16652. static const char* const aiffFormatName = "AIFF file";
  16653. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16654. class AiffAudioFormatReader : public AudioFormatReader
  16655. {
  16656. public:
  16657. int bytesPerFrame;
  16658. int64 dataChunkStart;
  16659. bool littleEndian;
  16660. AiffAudioFormatReader (InputStream* in)
  16661. : AudioFormatReader (in, TRANS (aiffFormatName))
  16662. {
  16663. if (input->readInt() == chunkName ("FORM"))
  16664. {
  16665. const int len = input->readIntBigEndian();
  16666. const int64 end = input->getPosition() + len;
  16667. const int nextType = input->readInt();
  16668. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16669. {
  16670. bool hasGotVer = false;
  16671. bool hasGotData = false;
  16672. bool hasGotType = false;
  16673. while (input->getPosition() < end)
  16674. {
  16675. const int type = input->readInt();
  16676. const uint32 length = (uint32) input->readIntBigEndian();
  16677. const int64 chunkEnd = input->getPosition() + length;
  16678. if (type == chunkName ("FVER"))
  16679. {
  16680. hasGotVer = true;
  16681. const int ver = input->readIntBigEndian();
  16682. if (ver != 0 && ver != (int) 0xa2805140)
  16683. break;
  16684. }
  16685. else if (type == chunkName ("COMM"))
  16686. {
  16687. hasGotType = true;
  16688. numChannels = (unsigned int) input->readShortBigEndian();
  16689. lengthInSamples = input->readIntBigEndian();
  16690. bitsPerSample = input->readShortBigEndian();
  16691. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16692. unsigned char sampleRateBytes[10];
  16693. input->read (sampleRateBytes, 10);
  16694. const int byte0 = sampleRateBytes[0];
  16695. if ((byte0 & 0x80) != 0
  16696. || byte0 <= 0x3F || byte0 > 0x40
  16697. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16698. break;
  16699. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16700. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16701. sampleRate = (int) sampRate;
  16702. if (length <= 18)
  16703. {
  16704. // some types don't have a chunk large enough to include a compression
  16705. // type, so assume it's just big-endian pcm
  16706. littleEndian = false;
  16707. }
  16708. else
  16709. {
  16710. const int compType = input->readInt();
  16711. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16712. {
  16713. littleEndian = false;
  16714. }
  16715. else if (compType == chunkName ("sowt"))
  16716. {
  16717. littleEndian = true;
  16718. }
  16719. else
  16720. {
  16721. sampleRate = 0;
  16722. break;
  16723. }
  16724. }
  16725. }
  16726. else if (type == chunkName ("SSND"))
  16727. {
  16728. hasGotData = true;
  16729. const int offset = input->readIntBigEndian();
  16730. dataChunkStart = input->getPosition() + 4 + offset;
  16731. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16732. }
  16733. else if ((hasGotVer && hasGotData && hasGotType)
  16734. || chunkEnd < input->getPosition()
  16735. || input->isExhausted())
  16736. {
  16737. break;
  16738. }
  16739. input->setPosition (chunkEnd);
  16740. }
  16741. }
  16742. }
  16743. }
  16744. ~AiffAudioFormatReader()
  16745. {
  16746. }
  16747. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16748. int64 startSampleInFile, int numSamples)
  16749. {
  16750. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16751. if (samplesAvailable < numSamples)
  16752. {
  16753. for (int i = numDestChannels; --i >= 0;)
  16754. if (destSamples[i] != 0)
  16755. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16756. numSamples = (int) samplesAvailable;
  16757. }
  16758. if (numSamples <= 0)
  16759. return true;
  16760. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16761. while (numSamples > 0)
  16762. {
  16763. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16764. char tempBuffer [tempBufSize];
  16765. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16766. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16767. if (bytesRead < numThisTime * bytesPerFrame)
  16768. {
  16769. jassert (bytesRead >= 0);
  16770. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16771. }
  16772. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16773. if (littleEndian)
  16774. {
  16775. switch (bitsPerSample)
  16776. {
  16777. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16778. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16779. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16780. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16781. default: jassertfalse; break;
  16782. }
  16783. }
  16784. else
  16785. {
  16786. switch (bitsPerSample)
  16787. {
  16788. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16789. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16790. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16791. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16792. default: jassertfalse; break;
  16793. }
  16794. }
  16795. startOffsetInDestBuffer += numThisTime;
  16796. numSamples -= numThisTime;
  16797. }
  16798. return true;
  16799. }
  16800. juce_UseDebuggingNewOperator
  16801. private:
  16802. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16803. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16804. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16805. };
  16806. class AiffAudioFormatWriter : public AudioFormatWriter
  16807. {
  16808. public:
  16809. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16810. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16811. lengthInSamples (0),
  16812. bytesWritten (0),
  16813. writeFailed (false)
  16814. {
  16815. headerPosition = out->getPosition();
  16816. writeHeader();
  16817. }
  16818. ~AiffAudioFormatWriter()
  16819. {
  16820. if ((bytesWritten & 1) != 0)
  16821. output->writeByte (0);
  16822. writeHeader();
  16823. }
  16824. bool write (const int** data, int numSamples)
  16825. {
  16826. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16827. if (writeFailed)
  16828. return false;
  16829. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16830. tempBlock.ensureSize (bytes, false);
  16831. switch (bitsPerSample)
  16832. {
  16833. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16834. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16835. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16836. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16837. default: jassertfalse; break;
  16838. }
  16839. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16840. || ! output->write (tempBlock.getData(), bytes))
  16841. {
  16842. // failed to write to disk, so let's try writing the header.
  16843. // If it's just run out of disk space, then if it does manage
  16844. // to write the header, we'll still have a useable file..
  16845. writeHeader();
  16846. writeFailed = true;
  16847. return false;
  16848. }
  16849. else
  16850. {
  16851. bytesWritten += bytes;
  16852. lengthInSamples += numSamples;
  16853. return true;
  16854. }
  16855. }
  16856. juce_UseDebuggingNewOperator
  16857. private:
  16858. MemoryBlock tempBlock;
  16859. uint32 lengthInSamples, bytesWritten;
  16860. int64 headerPosition;
  16861. bool writeFailed;
  16862. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16863. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16864. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16865. void writeHeader()
  16866. {
  16867. const bool couldSeekOk = output->setPosition (headerPosition);
  16868. (void) couldSeekOk;
  16869. // if this fails, you've given it an output stream that can't seek! It needs
  16870. // to be able to seek back to write the header
  16871. jassert (couldSeekOk);
  16872. const int headerLen = 54;
  16873. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16874. audioBytes += (audioBytes & 1);
  16875. output->writeInt (chunkName ("FORM"));
  16876. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16877. output->writeInt (chunkName ("AIFF"));
  16878. output->writeInt (chunkName ("COMM"));
  16879. output->writeIntBigEndian (18);
  16880. output->writeShortBigEndian ((short) numChannels);
  16881. output->writeIntBigEndian (lengthInSamples);
  16882. output->writeShortBigEndian ((short) bitsPerSample);
  16883. uint8 sampleRateBytes[10];
  16884. zeromem (sampleRateBytes, 10);
  16885. if (sampleRate <= 1)
  16886. {
  16887. sampleRateBytes[0] = 0x3f;
  16888. sampleRateBytes[1] = 0xff;
  16889. sampleRateBytes[2] = 0x80;
  16890. }
  16891. else
  16892. {
  16893. int mask = 0x40000000;
  16894. sampleRateBytes[0] = 0x40;
  16895. if (sampleRate >= mask)
  16896. {
  16897. jassertfalse;
  16898. sampleRateBytes[1] = 0x1d;
  16899. }
  16900. else
  16901. {
  16902. int n = (int) sampleRate;
  16903. int i;
  16904. for (i = 0; i <= 32 ; ++i)
  16905. {
  16906. if ((n & mask) != 0)
  16907. break;
  16908. mask >>= 1;
  16909. }
  16910. n = n << (i + 1);
  16911. sampleRateBytes[1] = (uint8) (29 - i);
  16912. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16913. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16914. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16915. sampleRateBytes[5] = (uint8) (n & 0xff);
  16916. }
  16917. }
  16918. output->write (sampleRateBytes, 10);
  16919. output->writeInt (chunkName ("SSND"));
  16920. output->writeIntBigEndian (audioBytes + 8);
  16921. output->writeInt (0);
  16922. output->writeInt (0);
  16923. jassert (output->getPosition() == headerLen);
  16924. }
  16925. };
  16926. AiffAudioFormat::AiffAudioFormat()
  16927. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16928. {
  16929. }
  16930. AiffAudioFormat::~AiffAudioFormat()
  16931. {
  16932. }
  16933. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16934. {
  16935. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16936. return Array <int> (rates);
  16937. }
  16938. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16939. {
  16940. const int depths[] = { 8, 16, 24, 0 };
  16941. return Array <int> (depths);
  16942. }
  16943. bool AiffAudioFormat::canDoStereo() { return true; }
  16944. bool AiffAudioFormat::canDoMono() { return true; }
  16945. #if JUCE_MAC
  16946. bool AiffAudioFormat::canHandleFile (const File& f)
  16947. {
  16948. if (AudioFormat::canHandleFile (f))
  16949. return true;
  16950. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16951. return type == 'AIFF' || type == 'AIFC'
  16952. || type == 'aiff' || type == 'aifc';
  16953. }
  16954. #endif
  16955. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16956. {
  16957. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16958. if (w->sampleRate != 0)
  16959. return w.release();
  16960. if (! deleteStreamIfOpeningFails)
  16961. w->input = 0;
  16962. return 0;
  16963. }
  16964. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16965. double sampleRate,
  16966. unsigned int numberOfChannels,
  16967. int bitsPerSample,
  16968. const StringPairArray& /*metadataValues*/,
  16969. int /*qualityOptionIndex*/)
  16970. {
  16971. if (getPossibleBitDepths().contains (bitsPerSample))
  16972. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16973. return 0;
  16974. }
  16975. END_JUCE_NAMESPACE
  16976. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16977. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16978. BEGIN_JUCE_NAMESPACE
  16979. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16980. : formatName (name),
  16981. fileExtensions (extensions)
  16982. {
  16983. }
  16984. AudioFormat::~AudioFormat()
  16985. {
  16986. }
  16987. bool AudioFormat::canHandleFile (const File& f)
  16988. {
  16989. for (int i = 0; i < fileExtensions.size(); ++i)
  16990. if (f.hasFileExtension (fileExtensions[i]))
  16991. return true;
  16992. return false;
  16993. }
  16994. const String& AudioFormat::getFormatName() const { return formatName; }
  16995. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16996. bool AudioFormat::isCompressed() { return false; }
  16997. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16998. END_JUCE_NAMESPACE
  16999. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17000. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  17001. BEGIN_JUCE_NAMESPACE
  17002. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17003. const String& formatName_)
  17004. : sampleRate (0),
  17005. bitsPerSample (0),
  17006. lengthInSamples (0),
  17007. numChannels (0),
  17008. usesFloatingPointData (false),
  17009. input (in),
  17010. formatName (formatName_)
  17011. {
  17012. }
  17013. AudioFormatReader::~AudioFormatReader()
  17014. {
  17015. delete input;
  17016. }
  17017. bool AudioFormatReader::read (int* const* destSamples,
  17018. int numDestChannels,
  17019. int64 startSampleInSource,
  17020. int numSamplesToRead,
  17021. const bool fillLeftoverChannelsWithCopies)
  17022. {
  17023. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17024. int startOffsetInDestBuffer = 0;
  17025. if (startSampleInSource < 0)
  17026. {
  17027. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17028. for (int i = numDestChannels; --i >= 0;)
  17029. if (destSamples[i] != 0)
  17030. zeromem (destSamples[i], sizeof (int) * silence);
  17031. startOffsetInDestBuffer += silence;
  17032. numSamplesToRead -= silence;
  17033. startSampleInSource = 0;
  17034. }
  17035. if (numSamplesToRead <= 0)
  17036. return true;
  17037. if (! readSamples (const_cast<int**> (destSamples),
  17038. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17039. startSampleInSource, numSamplesToRead))
  17040. return false;
  17041. if (numDestChannels > (int) numChannels)
  17042. {
  17043. if (fillLeftoverChannelsWithCopies)
  17044. {
  17045. int* lastFullChannel = destSamples[0];
  17046. for (int i = (int) numChannels; --i > 0;)
  17047. {
  17048. if (destSamples[i] != 0)
  17049. {
  17050. lastFullChannel = destSamples[i];
  17051. break;
  17052. }
  17053. }
  17054. if (lastFullChannel != 0)
  17055. for (int i = numChannels; i < numDestChannels; ++i)
  17056. if (destSamples[i] != 0)
  17057. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17058. }
  17059. else
  17060. {
  17061. for (int i = numChannels; i < numDestChannels; ++i)
  17062. if (destSamples[i] != 0)
  17063. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17064. }
  17065. }
  17066. return true;
  17067. }
  17068. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17069. {
  17070. float mn = buffer[0];
  17071. float mx = mn;
  17072. for (int i = 1; i < num; ++i)
  17073. {
  17074. const float s = buffer[i];
  17075. if (s > mx) mx = s;
  17076. if (s < mn) mn = s;
  17077. }
  17078. maxVal = mx;
  17079. minVal = mn;
  17080. }
  17081. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17082. int64 numSamples,
  17083. float& lowestLeft, float& highestLeft,
  17084. float& lowestRight, float& highestRight)
  17085. {
  17086. if (numSamples <= 0)
  17087. {
  17088. lowestLeft = 0;
  17089. lowestRight = 0;
  17090. highestLeft = 0;
  17091. highestRight = 0;
  17092. return;
  17093. }
  17094. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17095. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17096. int* tempBuffer[3];
  17097. tempBuffer[0] = tempSpace.getData();
  17098. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17099. tempBuffer[2] = 0;
  17100. if (usesFloatingPointData)
  17101. {
  17102. float lmin = 1.0e6f;
  17103. float lmax = -lmin;
  17104. float rmin = lmin;
  17105. float rmax = lmax;
  17106. while (numSamples > 0)
  17107. {
  17108. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17109. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17110. numSamples -= numToDo;
  17111. startSampleInFile += numToDo;
  17112. float bufmin, bufmax;
  17113. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17114. lmin = jmin (lmin, bufmin);
  17115. lmax = jmax (lmax, bufmax);
  17116. if (numChannels > 1)
  17117. {
  17118. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17119. rmin = jmin (rmin, bufmin);
  17120. rmax = jmax (rmax, bufmax);
  17121. }
  17122. }
  17123. if (numChannels <= 1)
  17124. {
  17125. rmax = lmax;
  17126. rmin = lmin;
  17127. }
  17128. lowestLeft = lmin;
  17129. highestLeft = lmax;
  17130. lowestRight = rmin;
  17131. highestRight = rmax;
  17132. }
  17133. else
  17134. {
  17135. int lmax = std::numeric_limits<int>::min();
  17136. int lmin = std::numeric_limits<int>::max();
  17137. int rmax = std::numeric_limits<int>::min();
  17138. int rmin = std::numeric_limits<int>::max();
  17139. while (numSamples > 0)
  17140. {
  17141. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17142. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17143. numSamples -= numToDo;
  17144. startSampleInFile += numToDo;
  17145. for (int j = numChannels; --j >= 0;)
  17146. {
  17147. int bufMax = std::numeric_limits<int>::min();
  17148. int bufMin = std::numeric_limits<int>::max();
  17149. const int* const b = tempBuffer[j];
  17150. for (int i = 0; i < numToDo; ++i)
  17151. {
  17152. const int samp = b[i];
  17153. if (samp < bufMin)
  17154. bufMin = samp;
  17155. if (samp > bufMax)
  17156. bufMax = samp;
  17157. }
  17158. if (j == 0)
  17159. {
  17160. lmax = jmax (lmax, bufMax);
  17161. lmin = jmin (lmin, bufMin);
  17162. }
  17163. else
  17164. {
  17165. rmax = jmax (rmax, bufMax);
  17166. rmin = jmin (rmin, bufMin);
  17167. }
  17168. }
  17169. }
  17170. if (numChannels <= 1)
  17171. {
  17172. rmax = lmax;
  17173. rmin = lmin;
  17174. }
  17175. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17176. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17177. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17178. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17179. }
  17180. }
  17181. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17182. int64 numSamplesToSearch,
  17183. const double magnitudeRangeMinimum,
  17184. const double magnitudeRangeMaximum,
  17185. const int minimumConsecutiveSamples)
  17186. {
  17187. if (numSamplesToSearch == 0)
  17188. return -1;
  17189. const int bufferSize = 4096;
  17190. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17191. int* tempBuffer[3];
  17192. tempBuffer[0] = tempSpace.getData();
  17193. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17194. tempBuffer[2] = 0;
  17195. int consecutive = 0;
  17196. int64 firstMatchPos = -1;
  17197. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17198. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17199. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17200. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17201. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17202. while (numSamplesToSearch != 0)
  17203. {
  17204. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17205. int64 bufferStart = startSample;
  17206. if (numSamplesToSearch < 0)
  17207. bufferStart -= numThisTime;
  17208. if (bufferStart >= (int) lengthInSamples)
  17209. break;
  17210. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17211. int num = numThisTime;
  17212. while (--num >= 0)
  17213. {
  17214. if (numSamplesToSearch < 0)
  17215. --startSample;
  17216. bool matches = false;
  17217. const int index = (int) (startSample - bufferStart);
  17218. if (usesFloatingPointData)
  17219. {
  17220. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17221. if (sample1 >= magnitudeRangeMinimum
  17222. && sample1 <= magnitudeRangeMaximum)
  17223. {
  17224. matches = true;
  17225. }
  17226. else if (numChannels > 1)
  17227. {
  17228. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17229. matches = (sample2 >= magnitudeRangeMinimum
  17230. && sample2 <= magnitudeRangeMaximum);
  17231. }
  17232. }
  17233. else
  17234. {
  17235. const int sample1 = abs (tempBuffer[0] [index]);
  17236. if (sample1 >= intMagnitudeRangeMinimum
  17237. && sample1 <= intMagnitudeRangeMaximum)
  17238. {
  17239. matches = true;
  17240. }
  17241. else if (numChannels > 1)
  17242. {
  17243. const int sample2 = abs (tempBuffer[1][index]);
  17244. matches = (sample2 >= intMagnitudeRangeMinimum
  17245. && sample2 <= intMagnitudeRangeMaximum);
  17246. }
  17247. }
  17248. if (matches)
  17249. {
  17250. if (firstMatchPos < 0)
  17251. firstMatchPos = startSample;
  17252. if (++consecutive >= minimumConsecutiveSamples)
  17253. {
  17254. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17255. return -1;
  17256. return firstMatchPos;
  17257. }
  17258. }
  17259. else
  17260. {
  17261. consecutive = 0;
  17262. firstMatchPos = -1;
  17263. }
  17264. if (numSamplesToSearch > 0)
  17265. ++startSample;
  17266. }
  17267. if (numSamplesToSearch > 0)
  17268. numSamplesToSearch -= numThisTime;
  17269. else
  17270. numSamplesToSearch += numThisTime;
  17271. }
  17272. return -1;
  17273. }
  17274. END_JUCE_NAMESPACE
  17275. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17276. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17277. BEGIN_JUCE_NAMESPACE
  17278. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17279. const String& formatName_,
  17280. const double rate,
  17281. const unsigned int numChannels_,
  17282. const unsigned int bitsPerSample_)
  17283. : sampleRate (rate),
  17284. numChannels (numChannels_),
  17285. bitsPerSample (bitsPerSample_),
  17286. usesFloatingPointData (false),
  17287. output (out),
  17288. formatName (formatName_)
  17289. {
  17290. }
  17291. AudioFormatWriter::~AudioFormatWriter()
  17292. {
  17293. delete output;
  17294. }
  17295. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17296. int64 startSample,
  17297. int64 numSamplesToRead)
  17298. {
  17299. const int bufferSize = 16384;
  17300. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17301. int* buffers [128];
  17302. zerostruct (buffers);
  17303. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17304. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17305. if (numSamplesToRead < 0)
  17306. numSamplesToRead = reader.lengthInSamples;
  17307. while (numSamplesToRead > 0)
  17308. {
  17309. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17310. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17311. return false;
  17312. if (reader.usesFloatingPointData != isFloatingPoint())
  17313. {
  17314. int** bufferChan = buffers;
  17315. while (*bufferChan != 0)
  17316. {
  17317. int* b = *bufferChan++;
  17318. if (isFloatingPoint())
  17319. {
  17320. // int -> float
  17321. const double factor = 1.0 / std::numeric_limits<int>::max();
  17322. for (int i = 0; i < numToDo; ++i)
  17323. ((float*) b)[i] = (float) (factor * b[i]);
  17324. }
  17325. else
  17326. {
  17327. // float -> int
  17328. for (int i = 0; i < numToDo; ++i)
  17329. {
  17330. const double samp = *(const float*) b;
  17331. if (samp <= -1.0)
  17332. *b++ = std::numeric_limits<int>::min();
  17333. else if (samp >= 1.0)
  17334. *b++ = std::numeric_limits<int>::max();
  17335. else
  17336. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17337. }
  17338. }
  17339. }
  17340. }
  17341. if (! write (const_cast<const int**> (buffers), numToDo))
  17342. return false;
  17343. numSamplesToRead -= numToDo;
  17344. startSample += numToDo;
  17345. }
  17346. return true;
  17347. }
  17348. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17349. {
  17350. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17351. while (numSamplesToRead > 0)
  17352. {
  17353. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17354. AudioSourceChannelInfo info;
  17355. info.buffer = &tempBuffer;
  17356. info.startSample = 0;
  17357. info.numSamples = numToDo;
  17358. info.clearActiveBufferRegion();
  17359. source.getNextAudioBlock (info);
  17360. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17361. return false;
  17362. numSamplesToRead -= numToDo;
  17363. }
  17364. return true;
  17365. }
  17366. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17367. {
  17368. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17369. if (numSamples <= 0)
  17370. return true;
  17371. HeapBlock<int> tempBuffer;
  17372. HeapBlock<int*> chans (numChannels + 1);
  17373. chans [numChannels] = 0;
  17374. if (isFloatingPoint())
  17375. {
  17376. for (int i = numChannels; --i >= 0;)
  17377. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17378. }
  17379. else
  17380. {
  17381. tempBuffer.malloc (numSamples * numChannels);
  17382. for (unsigned int i = 0; i < numChannels; ++i)
  17383. {
  17384. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17385. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17386. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17387. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17388. destData.convertSamples (sourceData, numSamples);
  17389. }
  17390. }
  17391. return write ((const int**) chans.getData(), numSamples);
  17392. }
  17393. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17394. public AbstractFifo
  17395. {
  17396. public:
  17397. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17398. : AbstractFifo (bufferSize),
  17399. buffer (numChannels, bufferSize),
  17400. timeSliceThread (timeSliceThread_),
  17401. writer (writer_), isRunning (true)
  17402. {
  17403. timeSliceThread.addTimeSliceClient (this);
  17404. }
  17405. ~Buffer()
  17406. {
  17407. isRunning = false;
  17408. timeSliceThread.removeTimeSliceClient (this);
  17409. while (useTimeSlice())
  17410. {}
  17411. }
  17412. bool write (const float** data, int numSamples)
  17413. {
  17414. if (numSamples <= 0 || ! isRunning)
  17415. return true;
  17416. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17417. int start1, size1, start2, size2;
  17418. prepareToWrite (numSamples, start1, size1, start2, size2);
  17419. if (size1 + size2 < numSamples)
  17420. return false;
  17421. for (int i = buffer.getNumChannels(); --i >= 0;)
  17422. {
  17423. buffer.copyFrom (i, start1, data[i], size1);
  17424. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17425. }
  17426. finishedWrite (size1 + size2);
  17427. timeSliceThread.notify();
  17428. return true;
  17429. }
  17430. bool useTimeSlice()
  17431. {
  17432. const int numToDo = getTotalSize() / 4;
  17433. int start1, size1, start2, size2;
  17434. prepareToRead (numToDo, start1, size1, start2, size2);
  17435. if (size1 <= 0)
  17436. return false;
  17437. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17438. if (size2 > 0)
  17439. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17440. finishedRead (size1 + size2);
  17441. return true;
  17442. }
  17443. private:
  17444. AudioSampleBuffer buffer;
  17445. TimeSliceThread& timeSliceThread;
  17446. ScopedPointer<AudioFormatWriter> writer;
  17447. volatile bool isRunning;
  17448. Buffer (const Buffer&);
  17449. Buffer& operator= (const Buffer&);
  17450. };
  17451. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17452. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17453. {
  17454. }
  17455. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17456. {
  17457. }
  17458. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17459. {
  17460. return buffer->write (data, numSamples);
  17461. }
  17462. END_JUCE_NAMESPACE
  17463. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17464. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17465. BEGIN_JUCE_NAMESPACE
  17466. AudioFormatManager::AudioFormatManager()
  17467. : defaultFormatIndex (0)
  17468. {
  17469. }
  17470. AudioFormatManager::~AudioFormatManager()
  17471. {
  17472. clearFormats();
  17473. clearSingletonInstance();
  17474. }
  17475. juce_ImplementSingleton (AudioFormatManager);
  17476. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17477. const bool makeThisTheDefaultFormat)
  17478. {
  17479. jassert (newFormat != 0);
  17480. if (newFormat != 0)
  17481. {
  17482. #if JUCE_DEBUG
  17483. for (int i = getNumKnownFormats(); --i >= 0;)
  17484. {
  17485. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17486. {
  17487. jassertfalse; // trying to add the same format twice!
  17488. }
  17489. }
  17490. #endif
  17491. if (makeThisTheDefaultFormat)
  17492. defaultFormatIndex = getNumKnownFormats();
  17493. knownFormats.add (newFormat);
  17494. }
  17495. }
  17496. void AudioFormatManager::registerBasicFormats()
  17497. {
  17498. #if JUCE_MAC
  17499. registerFormat (new AiffAudioFormat(), true);
  17500. registerFormat (new WavAudioFormat(), false);
  17501. #else
  17502. registerFormat (new WavAudioFormat(), true);
  17503. registerFormat (new AiffAudioFormat(), false);
  17504. #endif
  17505. #if JUCE_USE_FLAC
  17506. registerFormat (new FlacAudioFormat(), false);
  17507. #endif
  17508. #if JUCE_USE_OGGVORBIS
  17509. registerFormat (new OggVorbisAudioFormat(), false);
  17510. #endif
  17511. }
  17512. void AudioFormatManager::clearFormats()
  17513. {
  17514. knownFormats.clear();
  17515. defaultFormatIndex = 0;
  17516. }
  17517. int AudioFormatManager::getNumKnownFormats() const
  17518. {
  17519. return knownFormats.size();
  17520. }
  17521. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17522. {
  17523. return knownFormats [index];
  17524. }
  17525. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17526. {
  17527. return getKnownFormat (defaultFormatIndex);
  17528. }
  17529. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17530. {
  17531. String e (fileExtension);
  17532. if (! e.startsWithChar ('.'))
  17533. e = "." + e;
  17534. for (int i = 0; i < getNumKnownFormats(); ++i)
  17535. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17536. return getKnownFormat(i);
  17537. return 0;
  17538. }
  17539. const String AudioFormatManager::getWildcardForAllFormats() const
  17540. {
  17541. StringArray allExtensions;
  17542. int i;
  17543. for (i = 0; i < getNumKnownFormats(); ++i)
  17544. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17545. allExtensions.trim();
  17546. allExtensions.removeEmptyStrings();
  17547. String s;
  17548. for (i = 0; i < allExtensions.size(); ++i)
  17549. {
  17550. s << '*';
  17551. if (! allExtensions[i].startsWithChar ('.'))
  17552. s << '.';
  17553. s << allExtensions[i];
  17554. if (i < allExtensions.size() - 1)
  17555. s << ';';
  17556. }
  17557. return s;
  17558. }
  17559. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17560. {
  17561. // you need to actually register some formats before the manager can
  17562. // use them to open a file!
  17563. jassert (getNumKnownFormats() > 0);
  17564. for (int i = 0; i < getNumKnownFormats(); ++i)
  17565. {
  17566. AudioFormat* const af = getKnownFormat(i);
  17567. if (af->canHandleFile (file))
  17568. {
  17569. InputStream* const in = file.createInputStream();
  17570. if (in != 0)
  17571. {
  17572. AudioFormatReader* const r = af->createReaderFor (in, true);
  17573. if (r != 0)
  17574. return r;
  17575. }
  17576. }
  17577. }
  17578. return 0;
  17579. }
  17580. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17581. {
  17582. // you need to actually register some formats before the manager can
  17583. // use them to open a file!
  17584. jassert (getNumKnownFormats() > 0);
  17585. ScopedPointer <InputStream> in (audioFileStream);
  17586. if (in != 0)
  17587. {
  17588. const int64 originalStreamPos = in->getPosition();
  17589. for (int i = 0; i < getNumKnownFormats(); ++i)
  17590. {
  17591. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17592. if (r != 0)
  17593. {
  17594. in.release();
  17595. return r;
  17596. }
  17597. in->setPosition (originalStreamPos);
  17598. // the stream that is passed-in must be capable of being repositioned so
  17599. // that all the formats can have a go at opening it.
  17600. jassert (in->getPosition() == originalStreamPos);
  17601. }
  17602. }
  17603. return 0;
  17604. }
  17605. END_JUCE_NAMESPACE
  17606. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17607. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17608. BEGIN_JUCE_NAMESPACE
  17609. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17610. const int64 startSample_,
  17611. const int64 length_,
  17612. const bool deleteSourceWhenDeleted_)
  17613. : AudioFormatReader (0, source_->getFormatName()),
  17614. source (source_),
  17615. startSample (startSample_),
  17616. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17617. {
  17618. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17619. sampleRate = source->sampleRate;
  17620. bitsPerSample = source->bitsPerSample;
  17621. lengthInSamples = length;
  17622. numChannels = source->numChannels;
  17623. usesFloatingPointData = source->usesFloatingPointData;
  17624. }
  17625. AudioSubsectionReader::~AudioSubsectionReader()
  17626. {
  17627. if (deleteSourceWhenDeleted)
  17628. delete source;
  17629. }
  17630. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17631. int64 startSampleInFile, int numSamples)
  17632. {
  17633. if (startSampleInFile + numSamples > length)
  17634. {
  17635. for (int i = numDestChannels; --i >= 0;)
  17636. if (destSamples[i] != 0)
  17637. zeromem (destSamples[i], sizeof (int) * numSamples);
  17638. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17639. if (numSamples <= 0)
  17640. return true;
  17641. }
  17642. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17643. startSampleInFile + startSample, numSamples);
  17644. }
  17645. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17646. int64 numSamples,
  17647. float& lowestLeft,
  17648. float& highestLeft,
  17649. float& lowestRight,
  17650. float& highestRight)
  17651. {
  17652. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17653. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17654. source->readMaxLevels (startSampleInFile + startSample,
  17655. numSamples,
  17656. lowestLeft,
  17657. highestLeft,
  17658. lowestRight,
  17659. highestRight);
  17660. }
  17661. END_JUCE_NAMESPACE
  17662. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17663. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17664. BEGIN_JUCE_NAMESPACE
  17665. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17666. AudioFormatManager& formatManagerToUse_,
  17667. AudioThumbnailCache& cacheToUse)
  17668. : formatManagerToUse (formatManagerToUse_),
  17669. cache (cacheToUse),
  17670. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17671. timeBeforeDeletingReader (2000)
  17672. {
  17673. clear();
  17674. }
  17675. AudioThumbnail::~AudioThumbnail()
  17676. {
  17677. cache.removeThumbnail (this);
  17678. const ScopedLock sl (readerLock);
  17679. reader = 0;
  17680. }
  17681. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17682. {
  17683. jassert (data.getData() != 0);
  17684. return static_cast <DataFormat*> (data.getData());
  17685. }
  17686. void AudioThumbnail::setSource (InputSource* const newSource)
  17687. {
  17688. cache.removeThumbnail (this);
  17689. timerCallback(); // stops the timer and deletes the reader
  17690. source = newSource;
  17691. clear();
  17692. if (newSource != 0
  17693. && ! (cache.loadThumb (*this, newSource->hashCode())
  17694. && isFullyLoaded()))
  17695. {
  17696. {
  17697. const ScopedLock sl (readerLock);
  17698. reader = createReader();
  17699. }
  17700. if (reader != 0)
  17701. {
  17702. initialiseFromAudioFile (*reader);
  17703. cache.addThumbnail (this);
  17704. }
  17705. }
  17706. sendChangeMessage (this);
  17707. }
  17708. bool AudioThumbnail::useTimeSlice()
  17709. {
  17710. const ScopedLock sl (readerLock);
  17711. if (isFullyLoaded())
  17712. {
  17713. if (reader != 0)
  17714. startTimer (timeBeforeDeletingReader);
  17715. cache.removeThumbnail (this);
  17716. return false;
  17717. }
  17718. if (reader == 0)
  17719. reader = createReader();
  17720. if (reader != 0)
  17721. {
  17722. readNextBlockFromAudioFile (*reader);
  17723. stopTimer();
  17724. sendChangeMessage (this);
  17725. const bool justFinished = isFullyLoaded();
  17726. if (justFinished)
  17727. cache.storeThumb (*this, source->hashCode());
  17728. return ! justFinished;
  17729. }
  17730. return false;
  17731. }
  17732. AudioFormatReader* AudioThumbnail::createReader() const
  17733. {
  17734. if (source != 0)
  17735. {
  17736. InputStream* const audioFileStream = source->createInputStream();
  17737. if (audioFileStream != 0)
  17738. return formatManagerToUse.createReaderFor (audioFileStream);
  17739. }
  17740. return 0;
  17741. }
  17742. void AudioThumbnail::timerCallback()
  17743. {
  17744. stopTimer();
  17745. const ScopedLock sl (readerLock);
  17746. reader = 0;
  17747. }
  17748. void AudioThumbnail::clear()
  17749. {
  17750. data.setSize (sizeof (DataFormat) + 3);
  17751. DataFormat* const d = getData();
  17752. d->thumbnailMagic[0] = 'j';
  17753. d->thumbnailMagic[1] = 'a';
  17754. d->thumbnailMagic[2] = 't';
  17755. d->thumbnailMagic[3] = 'm';
  17756. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17757. d->totalSamples = 0;
  17758. d->numFinishedSamples = 0;
  17759. d->numThumbnailSamples = 0;
  17760. d->numChannels = 0;
  17761. d->sampleRate = 0;
  17762. numSamplesCached = 0;
  17763. cacheNeedsRefilling = true;
  17764. }
  17765. void AudioThumbnail::loadFrom (InputStream& input)
  17766. {
  17767. const ScopedLock sl (readerLock);
  17768. data.setSize (0);
  17769. input.readIntoMemoryBlock (data);
  17770. DataFormat* const d = getData();
  17771. d->flipEndiannessIfBigEndian();
  17772. if (! (d->thumbnailMagic[0] == 'j'
  17773. && d->thumbnailMagic[1] == 'a'
  17774. && d->thumbnailMagic[2] == 't'
  17775. && d->thumbnailMagic[3] == 'm'))
  17776. {
  17777. clear();
  17778. }
  17779. numSamplesCached = 0;
  17780. cacheNeedsRefilling = true;
  17781. }
  17782. void AudioThumbnail::saveTo (OutputStream& output) const
  17783. {
  17784. const ScopedLock sl (readerLock);
  17785. DataFormat* const d = getData();
  17786. d->flipEndiannessIfBigEndian();
  17787. output.write (d, (int) data.getSize());
  17788. d->flipEndiannessIfBigEndian();
  17789. }
  17790. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17791. {
  17792. DataFormat* d = getData();
  17793. d->totalSamples = fileReader.lengthInSamples;
  17794. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17795. d->numFinishedSamples = 0;
  17796. d->sampleRate = roundToInt (fileReader.sampleRate);
  17797. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17798. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17799. d = getData();
  17800. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17801. return d->totalSamples > 0;
  17802. }
  17803. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17804. {
  17805. DataFormat* const d = getData();
  17806. if (d->numFinishedSamples < d->totalSamples)
  17807. {
  17808. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17809. generateSection (fileReader,
  17810. d->numFinishedSamples,
  17811. numToDo);
  17812. d->numFinishedSamples += numToDo;
  17813. }
  17814. cacheNeedsRefilling = true;
  17815. return d->numFinishedSamples < d->totalSamples;
  17816. }
  17817. int AudioThumbnail::getNumChannels() const throw()
  17818. {
  17819. return getData()->numChannels;
  17820. }
  17821. double AudioThumbnail::getTotalLength() const throw()
  17822. {
  17823. const DataFormat* const d = getData();
  17824. if (d->sampleRate > 0)
  17825. return d->totalSamples / (double) d->sampleRate;
  17826. else
  17827. return 0.0;
  17828. }
  17829. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17830. int64 startSample,
  17831. int numSamples)
  17832. {
  17833. DataFormat* const d = getData();
  17834. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17835. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17836. char* const l = getChannelData (0);
  17837. char* const r = getChannelData (1);
  17838. for (int i = firstDataPos; i < lastDataPos; ++i)
  17839. {
  17840. const int sourceStart = i * d->samplesPerThumbSample;
  17841. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17842. float lowestLeft, highestLeft, lowestRight, highestRight;
  17843. fileReader.readMaxLevels (sourceStart,
  17844. sourceEnd - sourceStart,
  17845. lowestLeft,
  17846. highestLeft,
  17847. lowestRight,
  17848. highestRight);
  17849. int n = i * 2;
  17850. if (r != 0)
  17851. {
  17852. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17853. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17854. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17855. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17856. }
  17857. else
  17858. {
  17859. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17860. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17861. }
  17862. }
  17863. }
  17864. char* AudioThumbnail::getChannelData (int channel) const
  17865. {
  17866. DataFormat* const d = getData();
  17867. if (channel >= 0 && channel < d->numChannels)
  17868. return d->data + (channel * 2 * d->numThumbnailSamples);
  17869. return 0;
  17870. }
  17871. bool AudioThumbnail::isFullyLoaded() const throw()
  17872. {
  17873. const DataFormat* const d = getData();
  17874. return d->numFinishedSamples >= d->totalSamples;
  17875. }
  17876. void AudioThumbnail::refillCache (const int numSamples,
  17877. double startTime,
  17878. const double timePerPixel)
  17879. {
  17880. const DataFormat* const d = getData();
  17881. if (numSamples <= 0
  17882. || timePerPixel <= 0.0
  17883. || d->sampleRate <= 0)
  17884. {
  17885. numSamplesCached = 0;
  17886. cacheNeedsRefilling = true;
  17887. return;
  17888. }
  17889. if (numSamples == numSamplesCached
  17890. && numChannelsCached == d->numChannels
  17891. && startTime == cachedStart
  17892. && timePerPixel == cachedTimePerPixel
  17893. && ! cacheNeedsRefilling)
  17894. {
  17895. return;
  17896. }
  17897. numSamplesCached = numSamples;
  17898. numChannelsCached = d->numChannels;
  17899. cachedStart = startTime;
  17900. cachedTimePerPixel = timePerPixel;
  17901. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17902. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17903. const ScopedLock sl (readerLock);
  17904. cacheNeedsRefilling = false;
  17905. if (needExtraDetail && reader == 0)
  17906. reader = createReader();
  17907. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17908. {
  17909. startTimer (timeBeforeDeletingReader);
  17910. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17911. int sample = roundToInt (startTime * d->sampleRate);
  17912. for (int i = numSamples; --i >= 0;)
  17913. {
  17914. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17915. if (sample >= 0)
  17916. {
  17917. if (sample >= reader->lengthInSamples)
  17918. break;
  17919. float lmin, lmax, rmin, rmax;
  17920. reader->readMaxLevels (sample,
  17921. jmax (1, nextSample - sample),
  17922. lmin, lmax, rmin, rmax);
  17923. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17924. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17925. if (numChannelsCached > 1)
  17926. {
  17927. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17928. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17929. }
  17930. cacheData += 2 * numChannelsCached;
  17931. }
  17932. startTime += timePerPixel;
  17933. sample = nextSample;
  17934. }
  17935. }
  17936. else
  17937. {
  17938. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17939. {
  17940. char* const channelData = getChannelData (channelNum);
  17941. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17942. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17943. startTime = cachedStart;
  17944. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17945. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17946. for (int i = numSamples; --i >= 0;)
  17947. {
  17948. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17949. if (sample >= 0 && channelData != 0)
  17950. {
  17951. char mx = -128;
  17952. char mn = 127;
  17953. while (sample <= nextSample)
  17954. {
  17955. if (sample >= numFinished)
  17956. break;
  17957. const int n = sample << 1;
  17958. const char sampMin = channelData [n];
  17959. const char sampMax = channelData [n + 1];
  17960. if (sampMin < mn)
  17961. mn = sampMin;
  17962. if (sampMax > mx)
  17963. mx = sampMax;
  17964. ++sample;
  17965. }
  17966. if (mn <= mx)
  17967. {
  17968. cacheData[0] = mn;
  17969. cacheData[1] = mx;
  17970. }
  17971. else
  17972. {
  17973. cacheData[0] = 1;
  17974. cacheData[1] = 0;
  17975. }
  17976. }
  17977. else
  17978. {
  17979. cacheData[0] = 1;
  17980. cacheData[1] = 0;
  17981. }
  17982. cacheData += numChannelsCached * 2;
  17983. startTime += timePerPixel;
  17984. sample = nextSample;
  17985. }
  17986. }
  17987. }
  17988. }
  17989. void AudioThumbnail::drawChannel (Graphics& g,
  17990. int x, int y, int w, int h,
  17991. double startTime,
  17992. double endTime,
  17993. int channelNum,
  17994. const float verticalZoomFactor)
  17995. {
  17996. refillCache (w, startTime, (endTime - startTime) / w);
  17997. if (numSamplesCached >= w
  17998. && channelNum >= 0
  17999. && channelNum < numChannelsCached)
  18000. {
  18001. const float topY = (float) y;
  18002. const float bottomY = topY + h;
  18003. const float midY = topY + h * 0.5f;
  18004. const float vscale = verticalZoomFactor * h / 256.0f;
  18005. const Rectangle<int> clip (g.getClipBounds());
  18006. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18007. w -= skipLeft;
  18008. x += skipLeft;
  18009. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18010. + (channelNum << 1)
  18011. + skipLeft * (numChannelsCached << 1);
  18012. while (--w >= 0)
  18013. {
  18014. const char mn = cacheData[0];
  18015. const char mx = cacheData[1];
  18016. cacheData += numChannelsCached << 1;
  18017. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18018. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18019. jmin (midY - mn * vscale + 0.3f, bottomY));
  18020. if (++x >= clip.getRight())
  18021. break;
  18022. }
  18023. }
  18024. }
  18025. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18026. {
  18027. #if JUCE_BIG_ENDIAN
  18028. struct Flipper
  18029. {
  18030. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18031. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18032. };
  18033. Flipper::flip (samplesPerThumbSample);
  18034. Flipper::flip (totalSamples);
  18035. Flipper::flip (numFinishedSamples);
  18036. Flipper::flip (numThumbnailSamples);
  18037. Flipper::flip (numChannels);
  18038. Flipper::flip (sampleRate);
  18039. #endif
  18040. }
  18041. END_JUCE_NAMESPACE
  18042. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18043. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18044. BEGIN_JUCE_NAMESPACE
  18045. struct ThumbnailCacheEntry
  18046. {
  18047. int64 hash;
  18048. uint32 lastUsed;
  18049. MemoryBlock data;
  18050. juce_UseDebuggingNewOperator
  18051. };
  18052. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18053. : TimeSliceThread ("thumb cache"),
  18054. maxNumThumbsToStore (maxNumThumbsToStore_)
  18055. {
  18056. startThread (2);
  18057. }
  18058. AudioThumbnailCache::~AudioThumbnailCache()
  18059. {
  18060. }
  18061. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18062. {
  18063. for (int i = thumbs.size(); --i >= 0;)
  18064. {
  18065. if (thumbs[i]->hash == hashCode)
  18066. {
  18067. MemoryInputStream in (thumbs[i]->data, false);
  18068. thumb.loadFrom (in);
  18069. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18070. return true;
  18071. }
  18072. }
  18073. return false;
  18074. }
  18075. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18076. const int64 hashCode)
  18077. {
  18078. MemoryOutputStream out;
  18079. thumb.saveTo (out);
  18080. ThumbnailCacheEntry* te = 0;
  18081. for (int i = thumbs.size(); --i >= 0;)
  18082. {
  18083. if (thumbs[i]->hash == hashCode)
  18084. {
  18085. te = thumbs[i];
  18086. break;
  18087. }
  18088. }
  18089. if (te == 0)
  18090. {
  18091. te = new ThumbnailCacheEntry();
  18092. te->hash = hashCode;
  18093. if (thumbs.size() < maxNumThumbsToStore)
  18094. {
  18095. thumbs.add (te);
  18096. }
  18097. else
  18098. {
  18099. int oldest = 0;
  18100. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18101. int i;
  18102. for (i = thumbs.size(); --i >= 0;)
  18103. if (thumbs[i]->lastUsed < oldestTime)
  18104. oldest = i;
  18105. thumbs.set (i, te);
  18106. }
  18107. }
  18108. te->lastUsed = Time::getMillisecondCounter();
  18109. te->data.setSize (0);
  18110. te->data.append (out.getData(), out.getDataSize());
  18111. }
  18112. void AudioThumbnailCache::clear()
  18113. {
  18114. thumbs.clear();
  18115. }
  18116. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18117. {
  18118. addTimeSliceClient (thumb);
  18119. }
  18120. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18121. {
  18122. removeTimeSliceClient (thumb);
  18123. }
  18124. END_JUCE_NAMESPACE
  18125. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18126. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18127. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18128. #if ! JUCE_WINDOWS
  18129. #include <QuickTime/Movies.h>
  18130. #include <QuickTime/QTML.h>
  18131. #include <QuickTime/QuickTimeComponents.h>
  18132. #include <QuickTime/MediaHandlers.h>
  18133. #include <QuickTime/ImageCodec.h>
  18134. #else
  18135. #if JUCE_MSVC
  18136. #pragma warning (push)
  18137. #pragma warning (disable : 4100)
  18138. #endif
  18139. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18140. add its header directory to your include path.
  18141. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18142. flag in juce_Config.h
  18143. */
  18144. #include <Movies.h>
  18145. #include <QTML.h>
  18146. #include <QuickTimeComponents.h>
  18147. #include <MediaHandlers.h>
  18148. #include <ImageCodec.h>
  18149. #if JUCE_MSVC
  18150. #pragma warning (pop)
  18151. #endif
  18152. #endif
  18153. BEGIN_JUCE_NAMESPACE
  18154. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18155. static const char* const quickTimeFormatName = "QuickTime file";
  18156. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18157. class QTAudioReader : public AudioFormatReader
  18158. {
  18159. public:
  18160. QTAudioReader (InputStream* const input_, const int trackNum_)
  18161. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18162. ok (false),
  18163. movie (0),
  18164. trackNum (trackNum_),
  18165. lastSampleRead (0),
  18166. lastThreadId (0),
  18167. extractor (0),
  18168. dataHandle (0)
  18169. {
  18170. JUCE_AUTORELEASEPOOL
  18171. bufferList.calloc (256, 1);
  18172. #if JUCE_WINDOWS
  18173. if (InitializeQTML (0) != noErr)
  18174. return;
  18175. #endif
  18176. if (EnterMovies() != noErr)
  18177. return;
  18178. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18179. if (! opened)
  18180. return;
  18181. {
  18182. const int numTracks = GetMovieTrackCount (movie);
  18183. int trackCount = 0;
  18184. for (int i = 1; i <= numTracks; ++i)
  18185. {
  18186. track = GetMovieIndTrack (movie, i);
  18187. media = GetTrackMedia (track);
  18188. OSType mediaType;
  18189. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18190. if (mediaType == SoundMediaType
  18191. && trackCount++ == trackNum_)
  18192. {
  18193. ok = true;
  18194. break;
  18195. }
  18196. }
  18197. }
  18198. if (! ok)
  18199. return;
  18200. ok = false;
  18201. lengthInSamples = GetMediaDecodeDuration (media);
  18202. usesFloatingPointData = false;
  18203. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18204. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18205. / GetMediaTimeScale (media);
  18206. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18207. unsigned long output_layout_size;
  18208. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18209. kQTPropertyClass_MovieAudioExtraction_Audio,
  18210. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18211. 0, &output_layout_size, 0);
  18212. if (err != noErr)
  18213. return;
  18214. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18215. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18216. err = MovieAudioExtractionGetProperty (extractor,
  18217. kQTPropertyClass_MovieAudioExtraction_Audio,
  18218. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18219. output_layout_size, qt_audio_channel_layout, 0);
  18220. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18221. err = MovieAudioExtractionSetProperty (extractor,
  18222. kQTPropertyClass_MovieAudioExtraction_Audio,
  18223. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18224. output_layout_size,
  18225. qt_audio_channel_layout);
  18226. err = MovieAudioExtractionGetProperty (extractor,
  18227. kQTPropertyClass_MovieAudioExtraction_Audio,
  18228. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18229. sizeof (inputStreamDesc),
  18230. &inputStreamDesc, 0);
  18231. if (err != noErr)
  18232. return;
  18233. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18234. | kAudioFormatFlagIsPacked
  18235. | kAudioFormatFlagsNativeEndian;
  18236. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18237. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18238. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18239. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18240. err = MovieAudioExtractionSetProperty (extractor,
  18241. kQTPropertyClass_MovieAudioExtraction_Audio,
  18242. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18243. sizeof (inputStreamDesc),
  18244. &inputStreamDesc);
  18245. if (err != noErr)
  18246. return;
  18247. Boolean allChannelsDiscrete = false;
  18248. err = MovieAudioExtractionSetProperty (extractor,
  18249. kQTPropertyClass_MovieAudioExtraction_Movie,
  18250. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18251. sizeof (allChannelsDiscrete),
  18252. &allChannelsDiscrete);
  18253. if (err != noErr)
  18254. return;
  18255. bufferList->mNumberBuffers = 1;
  18256. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18257. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18258. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18259. bufferList->mBuffers[0].mData = dataBuffer;
  18260. sampleRate = inputStreamDesc.mSampleRate;
  18261. bitsPerSample = 16;
  18262. numChannels = inputStreamDesc.mChannelsPerFrame;
  18263. detachThread();
  18264. ok = true;
  18265. }
  18266. ~QTAudioReader()
  18267. {
  18268. JUCE_AUTORELEASEPOOL
  18269. checkThreadIsAttached();
  18270. if (dataHandle != 0)
  18271. DisposeHandle (dataHandle);
  18272. if (extractor != 0)
  18273. {
  18274. MovieAudioExtractionEnd (extractor);
  18275. extractor = 0;
  18276. }
  18277. DisposeMovie (movie);
  18278. #if JUCE_MAC
  18279. ExitMoviesOnThread ();
  18280. #endif
  18281. }
  18282. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18283. int64 startSampleInFile, int numSamples)
  18284. {
  18285. JUCE_AUTORELEASEPOOL
  18286. checkThreadIsAttached();
  18287. bool ok = true;
  18288. while (numSamples > 0)
  18289. {
  18290. if (lastSampleRead != startSampleInFile)
  18291. {
  18292. TimeRecord time;
  18293. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18294. time.base = 0;
  18295. time.value.hi = 0;
  18296. time.value.lo = (UInt32) startSampleInFile;
  18297. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18298. kQTPropertyClass_MovieAudioExtraction_Movie,
  18299. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18300. sizeof (time), &time);
  18301. if (err != noErr)
  18302. {
  18303. ok = false;
  18304. break;
  18305. }
  18306. }
  18307. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18308. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18309. UInt32 outFlags = 0;
  18310. UInt32 actualNumFrames = framesToDo;
  18311. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18312. if (err != noErr)
  18313. {
  18314. ok = false;
  18315. break;
  18316. }
  18317. lastSampleRead = startSampleInFile + actualNumFrames;
  18318. const int samplesReceived = actualNumFrames;
  18319. for (int j = numDestChannels; --j >= 0;)
  18320. {
  18321. if (destSamples[j] != 0)
  18322. {
  18323. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18324. for (int i = 0; i < samplesReceived; ++i)
  18325. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18326. }
  18327. }
  18328. startOffsetInDestBuffer += samplesReceived;
  18329. startSampleInFile += samplesReceived;
  18330. numSamples -= samplesReceived;
  18331. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18332. {
  18333. for (int j = numDestChannels; --j >= 0;)
  18334. if (destSamples[j] != 0)
  18335. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18336. break;
  18337. }
  18338. }
  18339. detachThread();
  18340. return ok;
  18341. }
  18342. juce_UseDebuggingNewOperator
  18343. bool ok;
  18344. private:
  18345. Movie movie;
  18346. Media media;
  18347. Track track;
  18348. const int trackNum;
  18349. double trackUnitsPerFrame;
  18350. int samplesPerFrame;
  18351. int64 lastSampleRead;
  18352. Thread::ThreadID lastThreadId;
  18353. MovieAudioExtractionRef extractor;
  18354. AudioStreamBasicDescription inputStreamDesc;
  18355. HeapBlock <AudioBufferList> bufferList;
  18356. HeapBlock <char> dataBuffer;
  18357. Handle dataHandle;
  18358. void checkThreadIsAttached()
  18359. {
  18360. #if JUCE_MAC
  18361. if (Thread::getCurrentThreadId() != lastThreadId)
  18362. EnterMoviesOnThread (0);
  18363. AttachMovieToCurrentThread (movie);
  18364. #endif
  18365. }
  18366. void detachThread()
  18367. {
  18368. #if JUCE_MAC
  18369. DetachMovieFromCurrentThread (movie);
  18370. #endif
  18371. }
  18372. QTAudioReader (const QTAudioReader&);
  18373. QTAudioReader& operator= (const QTAudioReader&);
  18374. };
  18375. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18376. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18377. {
  18378. }
  18379. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18380. {
  18381. }
  18382. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18383. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18384. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18385. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18386. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18387. const bool deleteStreamIfOpeningFails)
  18388. {
  18389. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18390. if (r->ok)
  18391. return r.release();
  18392. if (! deleteStreamIfOpeningFails)
  18393. r->input = 0;
  18394. return 0;
  18395. }
  18396. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18397. double /*sampleRateToUse*/,
  18398. unsigned int /*numberOfChannels*/,
  18399. int /*bitsPerSample*/,
  18400. const StringPairArray& /*metadataValues*/,
  18401. int /*qualityOptionIndex*/)
  18402. {
  18403. jassertfalse; // not yet implemented!
  18404. return 0;
  18405. }
  18406. END_JUCE_NAMESPACE
  18407. #endif
  18408. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18409. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18410. BEGIN_JUCE_NAMESPACE
  18411. static const char* const wavFormatName = "WAV file";
  18412. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18413. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18414. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18415. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18416. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18417. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18418. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18419. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18420. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18421. const String& originator,
  18422. const String& originatorRef,
  18423. const Time& date,
  18424. const int64 timeReferenceSamples,
  18425. const String& codingHistory)
  18426. {
  18427. StringPairArray m;
  18428. m.set (bwavDescription, description);
  18429. m.set (bwavOriginator, originator);
  18430. m.set (bwavOriginatorRef, originatorRef);
  18431. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18432. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18433. m.set (bwavTimeReference, String (timeReferenceSamples));
  18434. m.set (bwavCodingHistory, codingHistory);
  18435. return m;
  18436. }
  18437. #if JUCE_MSVC
  18438. #pragma pack (push, 1)
  18439. #define PACKED
  18440. #elif JUCE_GCC
  18441. #define PACKED __attribute__((packed))
  18442. #else
  18443. #define PACKED
  18444. #endif
  18445. struct BWAVChunk
  18446. {
  18447. char description [256];
  18448. char originator [32];
  18449. char originatorRef [32];
  18450. char originationDate [10];
  18451. char originationTime [8];
  18452. uint32 timeRefLow;
  18453. uint32 timeRefHigh;
  18454. uint16 version;
  18455. uint8 umid[64];
  18456. uint8 reserved[190];
  18457. char codingHistory[1];
  18458. void copyTo (StringPairArray& values) const
  18459. {
  18460. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18461. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18462. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18463. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18464. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18465. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18466. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18467. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18468. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18469. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18470. }
  18471. static MemoryBlock createFrom (const StringPairArray& values)
  18472. {
  18473. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18474. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18475. data.fillWith (0);
  18476. BWAVChunk* b = (BWAVChunk*) data.getData();
  18477. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18478. // as they get called in the right order..
  18479. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18480. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18481. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18482. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18483. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18484. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18485. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18486. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18487. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18488. if (b->description[0] != 0
  18489. || b->originator[0] != 0
  18490. || b->originationDate[0] != 0
  18491. || b->originationTime[0] != 0
  18492. || b->codingHistory[0] != 0
  18493. || time != 0)
  18494. {
  18495. return data;
  18496. }
  18497. return MemoryBlock();
  18498. }
  18499. } PACKED;
  18500. struct SMPLChunk
  18501. {
  18502. struct SampleLoop
  18503. {
  18504. uint32 identifier;
  18505. uint32 type;
  18506. uint32 start;
  18507. uint32 end;
  18508. uint32 fraction;
  18509. uint32 playCount;
  18510. } PACKED;
  18511. uint32 manufacturer;
  18512. uint32 product;
  18513. uint32 samplePeriod;
  18514. uint32 midiUnityNote;
  18515. uint32 midiPitchFraction;
  18516. uint32 smpteFormat;
  18517. uint32 smpteOffset;
  18518. uint32 numSampleLoops;
  18519. uint32 samplerData;
  18520. SampleLoop loops[1];
  18521. void copyTo (StringPairArray& values, const int totalSize) const
  18522. {
  18523. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18524. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18525. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18526. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18527. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18528. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18529. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18530. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18531. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18532. for (uint32 i = 0; i < numSampleLoops; ++i)
  18533. {
  18534. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18535. break;
  18536. const String prefix ("Loop" + String(i));
  18537. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18538. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18539. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18540. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18541. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18542. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18543. }
  18544. }
  18545. static MemoryBlock createFrom (const StringPairArray& values)
  18546. {
  18547. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18548. if (numLoops <= 0)
  18549. return MemoryBlock();
  18550. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18551. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18552. data.fillWith (0);
  18553. SMPLChunk* s = (SMPLChunk*) data.getData();
  18554. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18555. // as they get called in the right order..
  18556. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18557. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18558. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18559. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18560. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18561. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18562. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18563. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18564. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18565. for (int i = 0; i < numLoops; ++i)
  18566. {
  18567. const String prefix ("Loop" + String(i));
  18568. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18569. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18570. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18571. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18572. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18573. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18574. }
  18575. return data;
  18576. }
  18577. } PACKED;
  18578. struct ExtensibleWavSubFormat
  18579. {
  18580. uint32 data1;
  18581. uint16 data2;
  18582. uint16 data3;
  18583. uint8 data4[8];
  18584. } PACKED;
  18585. #if JUCE_MSVC
  18586. #pragma pack (pop)
  18587. #endif
  18588. #undef PACKED
  18589. class WavAudioFormatReader : public AudioFormatReader
  18590. {
  18591. public:
  18592. WavAudioFormatReader (InputStream* const in)
  18593. : AudioFormatReader (in, TRANS (wavFormatName)),
  18594. bwavChunkStart (0),
  18595. bwavSize (0),
  18596. dataLength (0)
  18597. {
  18598. if (input->readInt() == chunkName ("RIFF"))
  18599. {
  18600. const uint32 len = (uint32) input->readInt();
  18601. const int64 end = input->getPosition() + len;
  18602. bool hasGotType = false;
  18603. bool hasGotData = false;
  18604. if (input->readInt() == chunkName ("WAVE"))
  18605. {
  18606. while (input->getPosition() < end
  18607. && ! input->isExhausted())
  18608. {
  18609. const int chunkType = input->readInt();
  18610. uint32 length = (uint32) input->readInt();
  18611. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18612. if (chunkType == chunkName ("fmt "))
  18613. {
  18614. // read the format chunk
  18615. const unsigned short format = input->readShort();
  18616. const short numChans = input->readShort();
  18617. sampleRate = input->readInt();
  18618. const int bytesPerSec = input->readInt();
  18619. numChannels = numChans;
  18620. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18621. bitsPerSample = 8 * bytesPerFrame / numChans;
  18622. if (format == 3)
  18623. {
  18624. usesFloatingPointData = true;
  18625. }
  18626. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18627. {
  18628. if (length < 40) // too short
  18629. {
  18630. bytesPerFrame = 0;
  18631. }
  18632. else
  18633. {
  18634. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18635. ExtensibleWavSubFormat subFormat;
  18636. subFormat.data1 = input->readInt();
  18637. subFormat.data2 = input->readShort();
  18638. subFormat.data3 = input->readShort();
  18639. input->read (subFormat.data4, sizeof (subFormat.data4));
  18640. const ExtensibleWavSubFormat pcmFormat
  18641. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18642. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18643. {
  18644. const ExtensibleWavSubFormat ambisonicFormat
  18645. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18646. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18647. bytesPerFrame = 0;
  18648. }
  18649. }
  18650. }
  18651. else if (format != 1)
  18652. {
  18653. bytesPerFrame = 0;
  18654. }
  18655. hasGotType = true;
  18656. }
  18657. else if (chunkType == chunkName ("data"))
  18658. {
  18659. // get the data chunk's position
  18660. dataLength = length;
  18661. dataChunkStart = input->getPosition();
  18662. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18663. hasGotData = true;
  18664. }
  18665. else if (chunkType == chunkName ("bext"))
  18666. {
  18667. bwavChunkStart = input->getPosition();
  18668. bwavSize = length;
  18669. // Broadcast-wav extension chunk..
  18670. HeapBlock <BWAVChunk> bwav;
  18671. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18672. input->read (bwav, length);
  18673. bwav->copyTo (metadataValues);
  18674. }
  18675. else if (chunkType == chunkName ("smpl"))
  18676. {
  18677. HeapBlock <SMPLChunk> smpl;
  18678. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18679. input->read (smpl, length);
  18680. smpl->copyTo (metadataValues, length);
  18681. }
  18682. else if (chunkEnd <= input->getPosition())
  18683. {
  18684. break;
  18685. }
  18686. input->setPosition (chunkEnd);
  18687. }
  18688. }
  18689. }
  18690. }
  18691. ~WavAudioFormatReader()
  18692. {
  18693. }
  18694. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18695. int64 startSampleInFile, int numSamples)
  18696. {
  18697. jassert (destSamples != 0);
  18698. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18699. if (samplesAvailable < numSamples)
  18700. {
  18701. for (int i = numDestChannels; --i >= 0;)
  18702. if (destSamples[i] != 0)
  18703. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18704. numSamples = (int) samplesAvailable;
  18705. }
  18706. if (numSamples <= 0)
  18707. return true;
  18708. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18709. while (numSamples > 0)
  18710. {
  18711. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18712. char tempBuffer [tempBufSize];
  18713. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18714. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18715. if (bytesRead < numThisTime * bytesPerFrame)
  18716. {
  18717. jassert (bytesRead >= 0);
  18718. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18719. }
  18720. switch (bitsPerSample)
  18721. {
  18722. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18723. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18724. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18725. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18726. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18727. default: jassertfalse; break;
  18728. }
  18729. startOffsetInDestBuffer += numThisTime;
  18730. numSamples -= numThisTime;
  18731. }
  18732. return true;
  18733. }
  18734. int64 bwavChunkStart, bwavSize;
  18735. juce_UseDebuggingNewOperator
  18736. private:
  18737. ScopedPointer<AudioData::Converter> converter;
  18738. int bytesPerFrame;
  18739. int64 dataChunkStart, dataLength;
  18740. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18741. WavAudioFormatReader (const WavAudioFormatReader&);
  18742. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18743. };
  18744. class WavAudioFormatWriter : public AudioFormatWriter
  18745. {
  18746. public:
  18747. WavAudioFormatWriter (OutputStream* const out,
  18748. const double sampleRate_,
  18749. const unsigned int numChannels_,
  18750. const int bits,
  18751. const StringPairArray& metadataValues)
  18752. : AudioFormatWriter (out,
  18753. TRANS (wavFormatName),
  18754. sampleRate_,
  18755. numChannels_,
  18756. bits),
  18757. lengthInSamples (0),
  18758. bytesWritten (0),
  18759. writeFailed (false)
  18760. {
  18761. if (metadataValues.size() > 0)
  18762. {
  18763. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18764. smplChunk = SMPLChunk::createFrom (metadataValues);
  18765. }
  18766. headerPosition = out->getPosition();
  18767. writeHeader();
  18768. }
  18769. ~WavAudioFormatWriter()
  18770. {
  18771. writeHeader();
  18772. }
  18773. bool write (const int** data, int numSamples)
  18774. {
  18775. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18776. if (writeFailed)
  18777. return false;
  18778. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18779. tempBlock.ensureSize (bytes, false);
  18780. switch (bitsPerSample)
  18781. {
  18782. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18783. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18784. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18785. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18786. default: jassertfalse; break;
  18787. }
  18788. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18789. || ! output->write (tempBlock.getData(), bytes))
  18790. {
  18791. // failed to write to disk, so let's try writing the header.
  18792. // If it's just run out of disk space, then if it does manage
  18793. // to write the header, we'll still have a useable file..
  18794. writeHeader();
  18795. writeFailed = true;
  18796. return false;
  18797. }
  18798. else
  18799. {
  18800. bytesWritten += bytes;
  18801. lengthInSamples += numSamples;
  18802. return true;
  18803. }
  18804. }
  18805. juce_UseDebuggingNewOperator
  18806. private:
  18807. ScopedPointer<AudioData::Converter> converter;
  18808. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18809. uint32 lengthInSamples, bytesWritten;
  18810. int64 headerPosition;
  18811. bool writeFailed;
  18812. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18813. void writeHeader()
  18814. {
  18815. const bool seekedOk = output->setPosition (headerPosition);
  18816. (void) seekedOk;
  18817. // if this fails, you've given it an output stream that can't seek! It needs
  18818. // to be able to seek back to write the header
  18819. jassert (seekedOk);
  18820. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18821. output->writeInt (chunkName ("RIFF"));
  18822. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18823. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18824. output->writeInt (chunkName ("WAVE"));
  18825. output->writeInt (chunkName ("fmt "));
  18826. output->writeInt (16);
  18827. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18828. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18829. output->writeShort ((short) numChannels);
  18830. output->writeInt ((int) sampleRate);
  18831. output->writeInt (bytesPerFrame * (int) sampleRate);
  18832. output->writeShort ((short) bytesPerFrame);
  18833. output->writeShort ((short) bitsPerSample);
  18834. if (bwavChunk.getSize() > 0)
  18835. {
  18836. output->writeInt (chunkName ("bext"));
  18837. output->writeInt ((int) bwavChunk.getSize());
  18838. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18839. }
  18840. if (smplChunk.getSize() > 0)
  18841. {
  18842. output->writeInt (chunkName ("smpl"));
  18843. output->writeInt ((int) smplChunk.getSize());
  18844. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18845. }
  18846. output->writeInt (chunkName ("data"));
  18847. output->writeInt (lengthInSamples * bytesPerFrame);
  18848. usesFloatingPointData = (bitsPerSample == 32);
  18849. }
  18850. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18851. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18852. };
  18853. WavAudioFormat::WavAudioFormat()
  18854. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18855. {
  18856. }
  18857. WavAudioFormat::~WavAudioFormat()
  18858. {
  18859. }
  18860. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18861. {
  18862. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18863. return Array <int> (rates);
  18864. }
  18865. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18866. {
  18867. const int depths[] = { 8, 16, 24, 32, 0 };
  18868. return Array <int> (depths);
  18869. }
  18870. bool WavAudioFormat::canDoStereo() { return true; }
  18871. bool WavAudioFormat::canDoMono() { return true; }
  18872. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18873. const bool deleteStreamIfOpeningFails)
  18874. {
  18875. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18876. if (r->sampleRate != 0)
  18877. return r.release();
  18878. if (! deleteStreamIfOpeningFails)
  18879. r->input = 0;
  18880. return 0;
  18881. }
  18882. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18883. double sampleRate,
  18884. unsigned int numChannels,
  18885. int bitsPerSample,
  18886. const StringPairArray& metadataValues,
  18887. int /*qualityOptionIndex*/)
  18888. {
  18889. if (getPossibleBitDepths().contains (bitsPerSample))
  18890. {
  18891. return new WavAudioFormatWriter (out,
  18892. sampleRate,
  18893. numChannels,
  18894. bitsPerSample,
  18895. metadataValues);
  18896. }
  18897. return 0;
  18898. }
  18899. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18900. {
  18901. TemporaryFile tempFile (file);
  18902. WavAudioFormat wav;
  18903. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18904. if (reader != 0)
  18905. {
  18906. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18907. if (outStream != 0)
  18908. {
  18909. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18910. reader->numChannels, reader->bitsPerSample,
  18911. metadata, 0));
  18912. if (writer != 0)
  18913. {
  18914. outStream.release();
  18915. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18916. writer = 0;
  18917. reader = 0;
  18918. return ok && tempFile.overwriteTargetFileWithTemporary();
  18919. }
  18920. }
  18921. }
  18922. return false;
  18923. }
  18924. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18925. {
  18926. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18927. if (reader != 0)
  18928. {
  18929. const int64 bwavPos = reader->bwavChunkStart;
  18930. const int64 bwavSize = reader->bwavSize;
  18931. reader = 0;
  18932. if (bwavSize > 0)
  18933. {
  18934. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18935. if (chunk.getSize() <= (size_t) bwavSize)
  18936. {
  18937. // the new one will fit in the space available, so write it directly..
  18938. const int64 oldSize = wavFile.getSize();
  18939. {
  18940. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18941. out->setPosition (bwavPos);
  18942. out->write (chunk.getData(), (int) chunk.getSize());
  18943. out->setPosition (oldSize);
  18944. }
  18945. jassert (wavFile.getSize() == oldSize);
  18946. return true;
  18947. }
  18948. }
  18949. }
  18950. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18951. }
  18952. END_JUCE_NAMESPACE
  18953. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18954. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18955. #if JUCE_USE_CDREADER
  18956. BEGIN_JUCE_NAMESPACE
  18957. int AudioCDReader::getNumTracks() const
  18958. {
  18959. return trackStartSamples.size() - 1;
  18960. }
  18961. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18962. {
  18963. return trackStartSamples [trackNum];
  18964. }
  18965. const Array<int>& AudioCDReader::getTrackOffsets() const
  18966. {
  18967. return trackStartSamples;
  18968. }
  18969. int AudioCDReader::getCDDBId()
  18970. {
  18971. int checksum = 0;
  18972. const int numTracks = getNumTracks();
  18973. for (int i = 0; i < numTracks; ++i)
  18974. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18975. checksum += offset % 10;
  18976. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18977. // CCLLLLTT: checksum, length, tracks
  18978. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18979. }
  18980. END_JUCE_NAMESPACE
  18981. #endif
  18982. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18983. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18984. BEGIN_JUCE_NAMESPACE
  18985. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18986. const bool deleteReaderWhenThisIsDeleted)
  18987. : reader (reader_),
  18988. deleteReader (deleteReaderWhenThisIsDeleted),
  18989. nextPlayPos (0),
  18990. looping (false)
  18991. {
  18992. jassert (reader != 0);
  18993. }
  18994. AudioFormatReaderSource::~AudioFormatReaderSource()
  18995. {
  18996. releaseResources();
  18997. if (deleteReader)
  18998. delete reader;
  18999. }
  19000. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19001. {
  19002. nextPlayPos = newPosition;
  19003. }
  19004. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19005. {
  19006. looping = shouldLoop;
  19007. }
  19008. int AudioFormatReaderSource::getNextReadPosition() const
  19009. {
  19010. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19011. : nextPlayPos;
  19012. }
  19013. int AudioFormatReaderSource::getTotalLength() const
  19014. {
  19015. return (int) reader->lengthInSamples;
  19016. }
  19017. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19018. double /*sampleRate*/)
  19019. {
  19020. }
  19021. void AudioFormatReaderSource::releaseResources()
  19022. {
  19023. }
  19024. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19025. {
  19026. if (info.numSamples > 0)
  19027. {
  19028. const int start = nextPlayPos;
  19029. if (looping)
  19030. {
  19031. const int newStart = start % (int) reader->lengthInSamples;
  19032. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19033. if (newEnd > newStart)
  19034. {
  19035. info.buffer->readFromAudioReader (reader,
  19036. info.startSample,
  19037. newEnd - newStart,
  19038. newStart,
  19039. true, true);
  19040. }
  19041. else
  19042. {
  19043. const int endSamps = (int) reader->lengthInSamples - newStart;
  19044. info.buffer->readFromAudioReader (reader,
  19045. info.startSample,
  19046. endSamps,
  19047. newStart,
  19048. true, true);
  19049. info.buffer->readFromAudioReader (reader,
  19050. info.startSample + endSamps,
  19051. newEnd,
  19052. 0,
  19053. true, true);
  19054. }
  19055. nextPlayPos = newEnd;
  19056. }
  19057. else
  19058. {
  19059. info.buffer->readFromAudioReader (reader,
  19060. info.startSample,
  19061. info.numSamples,
  19062. start,
  19063. true, true);
  19064. nextPlayPos += info.numSamples;
  19065. }
  19066. }
  19067. }
  19068. END_JUCE_NAMESPACE
  19069. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19070. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19071. BEGIN_JUCE_NAMESPACE
  19072. AudioSourcePlayer::AudioSourcePlayer()
  19073. : source (0),
  19074. sampleRate (0),
  19075. bufferSize (0),
  19076. tempBuffer (2, 8),
  19077. lastGain (1.0f),
  19078. gain (1.0f)
  19079. {
  19080. }
  19081. AudioSourcePlayer::~AudioSourcePlayer()
  19082. {
  19083. setSource (0);
  19084. }
  19085. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19086. {
  19087. if (source != newSource)
  19088. {
  19089. AudioSource* const oldSource = source;
  19090. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19091. newSource->prepareToPlay (bufferSize, sampleRate);
  19092. {
  19093. const ScopedLock sl (readLock);
  19094. source = newSource;
  19095. }
  19096. if (oldSource != 0)
  19097. oldSource->releaseResources();
  19098. }
  19099. }
  19100. void AudioSourcePlayer::setGain (const float newGain) throw()
  19101. {
  19102. gain = newGain;
  19103. }
  19104. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19105. int totalNumInputChannels,
  19106. float** outputChannelData,
  19107. int totalNumOutputChannels,
  19108. int numSamples)
  19109. {
  19110. // these should have been prepared by audioDeviceAboutToStart()...
  19111. jassert (sampleRate > 0 && bufferSize > 0);
  19112. const ScopedLock sl (readLock);
  19113. if (source != 0)
  19114. {
  19115. AudioSourceChannelInfo info;
  19116. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19117. // messy stuff needed to compact the channels down into an array
  19118. // of non-zero pointers..
  19119. for (i = 0; i < totalNumInputChannels; ++i)
  19120. {
  19121. if (inputChannelData[i] != 0)
  19122. {
  19123. inputChans [numInputs++] = inputChannelData[i];
  19124. if (numInputs >= numElementsInArray (inputChans))
  19125. break;
  19126. }
  19127. }
  19128. for (i = 0; i < totalNumOutputChannels; ++i)
  19129. {
  19130. if (outputChannelData[i] != 0)
  19131. {
  19132. outputChans [numOutputs++] = outputChannelData[i];
  19133. if (numOutputs >= numElementsInArray (outputChans))
  19134. break;
  19135. }
  19136. }
  19137. if (numInputs > numOutputs)
  19138. {
  19139. // if there aren't enough output channels for the number of
  19140. // inputs, we need to create some temporary extra ones (can't
  19141. // use the input data in case it gets written to)
  19142. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19143. false, false, true);
  19144. for (i = 0; i < numOutputs; ++i)
  19145. {
  19146. channels[numActiveChans] = outputChans[i];
  19147. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19148. ++numActiveChans;
  19149. }
  19150. for (i = numOutputs; i < numInputs; ++i)
  19151. {
  19152. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19153. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19154. ++numActiveChans;
  19155. }
  19156. }
  19157. else
  19158. {
  19159. for (i = 0; i < numInputs; ++i)
  19160. {
  19161. channels[numActiveChans] = outputChans[i];
  19162. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19163. ++numActiveChans;
  19164. }
  19165. for (i = numInputs; i < numOutputs; ++i)
  19166. {
  19167. channels[numActiveChans] = outputChans[i];
  19168. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19169. ++numActiveChans;
  19170. }
  19171. }
  19172. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19173. info.buffer = &buffer;
  19174. info.startSample = 0;
  19175. info.numSamples = numSamples;
  19176. source->getNextAudioBlock (info);
  19177. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19178. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19179. lastGain = gain;
  19180. }
  19181. else
  19182. {
  19183. for (int i = 0; i < totalNumOutputChannels; ++i)
  19184. if (outputChannelData[i] != 0)
  19185. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19186. }
  19187. }
  19188. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19189. {
  19190. sampleRate = device->getCurrentSampleRate();
  19191. bufferSize = device->getCurrentBufferSizeSamples();
  19192. zeromem (channels, sizeof (channels));
  19193. if (source != 0)
  19194. source->prepareToPlay (bufferSize, sampleRate);
  19195. }
  19196. void AudioSourcePlayer::audioDeviceStopped()
  19197. {
  19198. if (source != 0)
  19199. source->releaseResources();
  19200. sampleRate = 0.0;
  19201. bufferSize = 0;
  19202. tempBuffer.setSize (2, 8);
  19203. }
  19204. END_JUCE_NAMESPACE
  19205. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19206. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19207. BEGIN_JUCE_NAMESPACE
  19208. AudioTransportSource::AudioTransportSource()
  19209. : source (0),
  19210. resamplerSource (0),
  19211. bufferingSource (0),
  19212. positionableSource (0),
  19213. masterSource (0),
  19214. gain (1.0f),
  19215. lastGain (1.0f),
  19216. playing (false),
  19217. stopped (true),
  19218. sampleRate (44100.0),
  19219. sourceSampleRate (0.0),
  19220. blockSize (128),
  19221. readAheadBufferSize (0),
  19222. isPrepared (false),
  19223. inputStreamEOF (false)
  19224. {
  19225. }
  19226. AudioTransportSource::~AudioTransportSource()
  19227. {
  19228. setSource (0);
  19229. releaseResources();
  19230. }
  19231. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19232. int readAheadBufferSize_,
  19233. double sourceSampleRateToCorrectFor)
  19234. {
  19235. if (source == newSource)
  19236. {
  19237. if (source == 0)
  19238. return;
  19239. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19240. }
  19241. readAheadBufferSize = readAheadBufferSize_;
  19242. sourceSampleRate = sourceSampleRateToCorrectFor;
  19243. ResamplingAudioSource* newResamplerSource = 0;
  19244. BufferingAudioSource* newBufferingSource = 0;
  19245. PositionableAudioSource* newPositionableSource = 0;
  19246. AudioSource* newMasterSource = 0;
  19247. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19248. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19249. AudioSource* oldMasterSource = masterSource;
  19250. if (newSource != 0)
  19251. {
  19252. newPositionableSource = newSource;
  19253. if (readAheadBufferSize_ > 0)
  19254. newPositionableSource = newBufferingSource
  19255. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19256. newPositionableSource->setNextReadPosition (0);
  19257. if (sourceSampleRateToCorrectFor != 0)
  19258. newMasterSource = newResamplerSource
  19259. = new ResamplingAudioSource (newPositionableSource, false);
  19260. else
  19261. newMasterSource = newPositionableSource;
  19262. if (isPrepared)
  19263. {
  19264. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19265. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19266. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19267. }
  19268. }
  19269. {
  19270. const ScopedLock sl (callbackLock);
  19271. source = newSource;
  19272. resamplerSource = newResamplerSource;
  19273. bufferingSource = newBufferingSource;
  19274. masterSource = newMasterSource;
  19275. positionableSource = newPositionableSource;
  19276. playing = false;
  19277. }
  19278. if (oldMasterSource != 0)
  19279. oldMasterSource->releaseResources();
  19280. }
  19281. void AudioTransportSource::start()
  19282. {
  19283. if ((! playing) && masterSource != 0)
  19284. {
  19285. {
  19286. const ScopedLock sl (callbackLock);
  19287. playing = true;
  19288. stopped = false;
  19289. inputStreamEOF = false;
  19290. }
  19291. sendChangeMessage (this);
  19292. }
  19293. }
  19294. void AudioTransportSource::stop()
  19295. {
  19296. if (playing)
  19297. {
  19298. {
  19299. const ScopedLock sl (callbackLock);
  19300. playing = false;
  19301. }
  19302. int n = 500;
  19303. while (--n >= 0 && ! stopped)
  19304. Thread::sleep (2);
  19305. sendChangeMessage (this);
  19306. }
  19307. }
  19308. void AudioTransportSource::setPosition (double newPosition)
  19309. {
  19310. if (sampleRate > 0.0)
  19311. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19312. }
  19313. double AudioTransportSource::getCurrentPosition() const
  19314. {
  19315. if (sampleRate > 0.0)
  19316. return getNextReadPosition() / sampleRate;
  19317. else
  19318. return 0.0;
  19319. }
  19320. void AudioTransportSource::setNextReadPosition (int newPosition)
  19321. {
  19322. if (positionableSource != 0)
  19323. {
  19324. if (sampleRate > 0 && sourceSampleRate > 0)
  19325. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19326. positionableSource->setNextReadPosition (newPosition);
  19327. }
  19328. }
  19329. int AudioTransportSource::getNextReadPosition() const
  19330. {
  19331. if (positionableSource != 0)
  19332. {
  19333. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19334. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19335. }
  19336. return 0;
  19337. }
  19338. int AudioTransportSource::getTotalLength() const
  19339. {
  19340. const ScopedLock sl (callbackLock);
  19341. if (positionableSource != 0)
  19342. {
  19343. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19344. return roundToInt (positionableSource->getTotalLength() * ratio);
  19345. }
  19346. return 0;
  19347. }
  19348. bool AudioTransportSource::isLooping() const
  19349. {
  19350. const ScopedLock sl (callbackLock);
  19351. return positionableSource != 0
  19352. && positionableSource->isLooping();
  19353. }
  19354. void AudioTransportSource::setGain (const float newGain) throw()
  19355. {
  19356. gain = newGain;
  19357. }
  19358. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19359. double sampleRate_)
  19360. {
  19361. const ScopedLock sl (callbackLock);
  19362. sampleRate = sampleRate_;
  19363. blockSize = samplesPerBlockExpected;
  19364. if (masterSource != 0)
  19365. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19366. if (resamplerSource != 0 && sourceSampleRate != 0)
  19367. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19368. isPrepared = true;
  19369. }
  19370. void AudioTransportSource::releaseResources()
  19371. {
  19372. const ScopedLock sl (callbackLock);
  19373. if (masterSource != 0)
  19374. masterSource->releaseResources();
  19375. isPrepared = false;
  19376. }
  19377. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19378. {
  19379. const ScopedLock sl (callbackLock);
  19380. inputStreamEOF = false;
  19381. if (masterSource != 0 && ! stopped)
  19382. {
  19383. masterSource->getNextAudioBlock (info);
  19384. if (! playing)
  19385. {
  19386. // just stopped playing, so fade out the last block..
  19387. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19388. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19389. if (info.numSamples > 256)
  19390. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19391. }
  19392. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19393. && ! positionableSource->isLooping())
  19394. {
  19395. playing = false;
  19396. inputStreamEOF = true;
  19397. sendChangeMessage (this);
  19398. }
  19399. stopped = ! playing;
  19400. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19401. {
  19402. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19403. lastGain, gain);
  19404. }
  19405. }
  19406. else
  19407. {
  19408. info.clearActiveBufferRegion();
  19409. stopped = true;
  19410. }
  19411. lastGain = gain;
  19412. }
  19413. END_JUCE_NAMESPACE
  19414. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19415. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19416. BEGIN_JUCE_NAMESPACE
  19417. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19418. public Thread,
  19419. private Timer
  19420. {
  19421. public:
  19422. SharedBufferingAudioSourceThread()
  19423. : Thread ("Audio Buffer")
  19424. {
  19425. }
  19426. ~SharedBufferingAudioSourceThread()
  19427. {
  19428. stopThread (10000);
  19429. clearSingletonInstance();
  19430. }
  19431. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19432. void addSource (BufferingAudioSource* source)
  19433. {
  19434. const ScopedLock sl (lock);
  19435. if (! sources.contains (source))
  19436. {
  19437. sources.add (source);
  19438. startThread();
  19439. stopTimer();
  19440. }
  19441. notify();
  19442. }
  19443. void removeSource (BufferingAudioSource* source)
  19444. {
  19445. const ScopedLock sl (lock);
  19446. sources.removeValue (source);
  19447. if (sources.size() == 0)
  19448. startTimer (5000);
  19449. }
  19450. private:
  19451. Array <BufferingAudioSource*> sources;
  19452. CriticalSection lock;
  19453. void run()
  19454. {
  19455. while (! threadShouldExit())
  19456. {
  19457. bool busy = false;
  19458. for (int i = sources.size(); --i >= 0;)
  19459. {
  19460. if (threadShouldExit())
  19461. return;
  19462. const ScopedLock sl (lock);
  19463. BufferingAudioSource* const b = sources[i];
  19464. if (b != 0 && b->readNextBufferChunk())
  19465. busy = true;
  19466. }
  19467. if (! busy)
  19468. wait (500);
  19469. }
  19470. }
  19471. void timerCallback()
  19472. {
  19473. stopTimer();
  19474. if (sources.size() == 0)
  19475. deleteInstance();
  19476. }
  19477. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19478. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19479. };
  19480. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19481. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19482. const bool deleteSourceWhenDeleted_,
  19483. int numberOfSamplesToBuffer_)
  19484. : source (source_),
  19485. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19486. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19487. buffer (2, 0),
  19488. bufferValidStart (0),
  19489. bufferValidEnd (0),
  19490. nextPlayPos (0),
  19491. wasSourceLooping (false)
  19492. {
  19493. jassert (source_ != 0);
  19494. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19495. // not using a larger buffer..
  19496. }
  19497. BufferingAudioSource::~BufferingAudioSource()
  19498. {
  19499. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19500. if (thread != 0)
  19501. thread->removeSource (this);
  19502. if (deleteSourceWhenDeleted)
  19503. delete source;
  19504. }
  19505. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19506. {
  19507. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19508. sampleRate = sampleRate_;
  19509. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19510. buffer.clear();
  19511. bufferValidStart = 0;
  19512. bufferValidEnd = 0;
  19513. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19514. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19515. buffer.getNumSamples() / 2))
  19516. {
  19517. SharedBufferingAudioSourceThread::getInstance()->notify();
  19518. Thread::sleep (5);
  19519. }
  19520. }
  19521. void BufferingAudioSource::releaseResources()
  19522. {
  19523. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19524. if (thread != 0)
  19525. thread->removeSource (this);
  19526. buffer.setSize (2, 0);
  19527. source->releaseResources();
  19528. }
  19529. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19530. {
  19531. const ScopedLock sl (bufferStartPosLock);
  19532. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19533. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19534. if (validStart == validEnd)
  19535. {
  19536. // total cache miss
  19537. info.clearActiveBufferRegion();
  19538. }
  19539. else
  19540. {
  19541. if (validStart > 0)
  19542. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19543. if (validEnd < info.numSamples)
  19544. info.buffer->clear (info.startSample + validEnd,
  19545. info.numSamples - validEnd); // partial cache miss at end
  19546. if (validStart < validEnd)
  19547. {
  19548. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19549. {
  19550. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19551. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19552. if (startBufferIndex < endBufferIndex)
  19553. {
  19554. info.buffer->copyFrom (chan, info.startSample + validStart,
  19555. buffer,
  19556. chan, startBufferIndex,
  19557. validEnd - validStart);
  19558. }
  19559. else
  19560. {
  19561. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19562. info.buffer->copyFrom (chan, info.startSample + validStart,
  19563. buffer,
  19564. chan, startBufferIndex,
  19565. initialSize);
  19566. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19567. buffer,
  19568. chan, 0,
  19569. (validEnd - validStart) - initialSize);
  19570. }
  19571. }
  19572. }
  19573. nextPlayPos += info.numSamples;
  19574. if (source->isLooping() && nextPlayPos > 0)
  19575. nextPlayPos %= source->getTotalLength();
  19576. }
  19577. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19578. if (thread != 0)
  19579. thread->notify();
  19580. }
  19581. int BufferingAudioSource::getNextReadPosition() const
  19582. {
  19583. return (source->isLooping() && nextPlayPos > 0)
  19584. ? nextPlayPos % source->getTotalLength()
  19585. : nextPlayPos;
  19586. }
  19587. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19588. {
  19589. const ScopedLock sl (bufferStartPosLock);
  19590. nextPlayPos = newPosition;
  19591. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19592. if (thread != 0)
  19593. thread->notify();
  19594. }
  19595. bool BufferingAudioSource::readNextBufferChunk()
  19596. {
  19597. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19598. {
  19599. const ScopedLock sl (bufferStartPosLock);
  19600. if (wasSourceLooping != isLooping())
  19601. {
  19602. wasSourceLooping = isLooping();
  19603. bufferValidStart = 0;
  19604. bufferValidEnd = 0;
  19605. }
  19606. newBVS = jmax (0, nextPlayPos);
  19607. newBVE = newBVS + buffer.getNumSamples() - 4;
  19608. sectionToReadStart = 0;
  19609. sectionToReadEnd = 0;
  19610. const int maxChunkSize = 2048;
  19611. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19612. {
  19613. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19614. sectionToReadStart = newBVS;
  19615. sectionToReadEnd = newBVE;
  19616. bufferValidStart = 0;
  19617. bufferValidEnd = 0;
  19618. }
  19619. else if (abs (newBVS - bufferValidStart) > 512
  19620. || abs (newBVE - bufferValidEnd) > 512)
  19621. {
  19622. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19623. sectionToReadStart = bufferValidEnd;
  19624. sectionToReadEnd = newBVE;
  19625. bufferValidStart = newBVS;
  19626. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19627. }
  19628. }
  19629. if (sectionToReadStart != sectionToReadEnd)
  19630. {
  19631. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19632. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19633. if (bufferIndexStart < bufferIndexEnd)
  19634. {
  19635. readBufferSection (sectionToReadStart,
  19636. sectionToReadEnd - sectionToReadStart,
  19637. bufferIndexStart);
  19638. }
  19639. else
  19640. {
  19641. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19642. readBufferSection (sectionToReadStart,
  19643. initialSize,
  19644. bufferIndexStart);
  19645. readBufferSection (sectionToReadStart + initialSize,
  19646. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19647. 0);
  19648. }
  19649. const ScopedLock sl2 (bufferStartPosLock);
  19650. bufferValidStart = newBVS;
  19651. bufferValidEnd = newBVE;
  19652. return true;
  19653. }
  19654. else
  19655. {
  19656. return false;
  19657. }
  19658. }
  19659. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19660. {
  19661. if (source->getNextReadPosition() != start)
  19662. source->setNextReadPosition (start);
  19663. AudioSourceChannelInfo info;
  19664. info.buffer = &buffer;
  19665. info.startSample = bufferOffset;
  19666. info.numSamples = length;
  19667. source->getNextAudioBlock (info);
  19668. }
  19669. END_JUCE_NAMESPACE
  19670. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19671. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19672. BEGIN_JUCE_NAMESPACE
  19673. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19674. const bool deleteSourceWhenDeleted_)
  19675. : requiredNumberOfChannels (2),
  19676. source (source_),
  19677. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19678. buffer (2, 16)
  19679. {
  19680. remappedInfo.buffer = &buffer;
  19681. remappedInfo.startSample = 0;
  19682. }
  19683. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19684. {
  19685. if (deleteSourceWhenDeleted)
  19686. delete source;
  19687. }
  19688. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19689. {
  19690. const ScopedLock sl (lock);
  19691. requiredNumberOfChannels = requiredNumberOfChannels_;
  19692. }
  19693. void ChannelRemappingAudioSource::clearAllMappings()
  19694. {
  19695. const ScopedLock sl (lock);
  19696. remappedInputs.clear();
  19697. remappedOutputs.clear();
  19698. }
  19699. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19700. {
  19701. const ScopedLock sl (lock);
  19702. while (remappedInputs.size() < destIndex)
  19703. remappedInputs.add (-1);
  19704. remappedInputs.set (destIndex, sourceIndex);
  19705. }
  19706. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19707. {
  19708. const ScopedLock sl (lock);
  19709. while (remappedOutputs.size() < sourceIndex)
  19710. remappedOutputs.add (-1);
  19711. remappedOutputs.set (sourceIndex, destIndex);
  19712. }
  19713. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19714. {
  19715. const ScopedLock sl (lock);
  19716. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19717. return remappedInputs.getUnchecked (inputChannelIndex);
  19718. return -1;
  19719. }
  19720. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19721. {
  19722. const ScopedLock sl (lock);
  19723. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19724. return remappedOutputs .getUnchecked (outputChannelIndex);
  19725. return -1;
  19726. }
  19727. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19728. {
  19729. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19730. }
  19731. void ChannelRemappingAudioSource::releaseResources()
  19732. {
  19733. source->releaseResources();
  19734. }
  19735. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19736. {
  19737. const ScopedLock sl (lock);
  19738. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19739. const int numChans = bufferToFill.buffer->getNumChannels();
  19740. int i;
  19741. for (i = 0; i < buffer.getNumChannels(); ++i)
  19742. {
  19743. const int remappedChan = getRemappedInputChannel (i);
  19744. if (remappedChan >= 0 && remappedChan < numChans)
  19745. {
  19746. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19747. remappedChan,
  19748. bufferToFill.startSample,
  19749. bufferToFill.numSamples);
  19750. }
  19751. else
  19752. {
  19753. buffer.clear (i, 0, bufferToFill.numSamples);
  19754. }
  19755. }
  19756. remappedInfo.numSamples = bufferToFill.numSamples;
  19757. source->getNextAudioBlock (remappedInfo);
  19758. bufferToFill.clearActiveBufferRegion();
  19759. for (i = 0; i < requiredNumberOfChannels; ++i)
  19760. {
  19761. const int remappedChan = getRemappedOutputChannel (i);
  19762. if (remappedChan >= 0 && remappedChan < numChans)
  19763. {
  19764. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19765. buffer, i, 0, bufferToFill.numSamples);
  19766. }
  19767. }
  19768. }
  19769. XmlElement* ChannelRemappingAudioSource::createXml() const
  19770. {
  19771. XmlElement* e = new XmlElement ("MAPPINGS");
  19772. String ins, outs;
  19773. int i;
  19774. const ScopedLock sl (lock);
  19775. for (i = 0; i < remappedInputs.size(); ++i)
  19776. ins << remappedInputs.getUnchecked(i) << ' ';
  19777. for (i = 0; i < remappedOutputs.size(); ++i)
  19778. outs << remappedOutputs.getUnchecked(i) << ' ';
  19779. e->setAttribute ("inputs", ins.trimEnd());
  19780. e->setAttribute ("outputs", outs.trimEnd());
  19781. return e;
  19782. }
  19783. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19784. {
  19785. if (e.hasTagName ("MAPPINGS"))
  19786. {
  19787. const ScopedLock sl (lock);
  19788. clearAllMappings();
  19789. StringArray ins, outs;
  19790. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19791. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19792. int i;
  19793. for (i = 0; i < ins.size(); ++i)
  19794. remappedInputs.add (ins[i].getIntValue());
  19795. for (i = 0; i < outs.size(); ++i)
  19796. remappedOutputs.add (outs[i].getIntValue());
  19797. }
  19798. }
  19799. END_JUCE_NAMESPACE
  19800. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19801. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19802. BEGIN_JUCE_NAMESPACE
  19803. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19804. const bool deleteInputWhenDeleted_)
  19805. : input (inputSource),
  19806. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19807. {
  19808. jassert (inputSource != 0);
  19809. for (int i = 2; --i >= 0;)
  19810. iirFilters.add (new IIRFilter());
  19811. }
  19812. IIRFilterAudioSource::~IIRFilterAudioSource()
  19813. {
  19814. if (deleteInputWhenDeleted)
  19815. delete input;
  19816. }
  19817. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19818. {
  19819. for (int i = iirFilters.size(); --i >= 0;)
  19820. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19821. }
  19822. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19823. {
  19824. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19825. for (int i = iirFilters.size(); --i >= 0;)
  19826. iirFilters.getUnchecked(i)->reset();
  19827. }
  19828. void IIRFilterAudioSource::releaseResources()
  19829. {
  19830. input->releaseResources();
  19831. }
  19832. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19833. {
  19834. input->getNextAudioBlock (bufferToFill);
  19835. const int numChannels = bufferToFill.buffer->getNumChannels();
  19836. while (numChannels > iirFilters.size())
  19837. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19838. for (int i = 0; i < numChannels; ++i)
  19839. iirFilters.getUnchecked(i)
  19840. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19841. bufferToFill.numSamples);
  19842. }
  19843. END_JUCE_NAMESPACE
  19844. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19845. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19846. BEGIN_JUCE_NAMESPACE
  19847. MixerAudioSource::MixerAudioSource()
  19848. : tempBuffer (2, 0),
  19849. currentSampleRate (0.0),
  19850. bufferSizeExpected (0)
  19851. {
  19852. }
  19853. MixerAudioSource::~MixerAudioSource()
  19854. {
  19855. removeAllInputs();
  19856. }
  19857. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19858. {
  19859. if (input != 0 && ! inputs.contains (input))
  19860. {
  19861. double localRate;
  19862. int localBufferSize;
  19863. {
  19864. const ScopedLock sl (lock);
  19865. localRate = currentSampleRate;
  19866. localBufferSize = bufferSizeExpected;
  19867. }
  19868. if (localRate != 0.0)
  19869. input->prepareToPlay (localBufferSize, localRate);
  19870. const ScopedLock sl (lock);
  19871. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19872. inputs.add (input);
  19873. }
  19874. }
  19875. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19876. {
  19877. if (input != 0)
  19878. {
  19879. int index;
  19880. {
  19881. const ScopedLock sl (lock);
  19882. index = inputs.indexOf (input);
  19883. if (index >= 0)
  19884. {
  19885. inputsToDelete.shiftBits (index, 1);
  19886. inputs.remove (index);
  19887. }
  19888. }
  19889. if (index >= 0)
  19890. {
  19891. input->releaseResources();
  19892. if (deleteInput)
  19893. delete input;
  19894. }
  19895. }
  19896. }
  19897. void MixerAudioSource::removeAllInputs()
  19898. {
  19899. OwnedArray<AudioSource> toDelete;
  19900. {
  19901. const ScopedLock sl (lock);
  19902. for (int i = inputs.size(); --i >= 0;)
  19903. if (inputsToDelete[i])
  19904. toDelete.add (inputs.getUnchecked(i));
  19905. }
  19906. }
  19907. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19908. {
  19909. tempBuffer.setSize (2, samplesPerBlockExpected);
  19910. const ScopedLock sl (lock);
  19911. currentSampleRate = sampleRate;
  19912. bufferSizeExpected = samplesPerBlockExpected;
  19913. for (int i = inputs.size(); --i >= 0;)
  19914. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19915. }
  19916. void MixerAudioSource::releaseResources()
  19917. {
  19918. const ScopedLock sl (lock);
  19919. for (int i = inputs.size(); --i >= 0;)
  19920. inputs.getUnchecked(i)->releaseResources();
  19921. tempBuffer.setSize (2, 0);
  19922. currentSampleRate = 0;
  19923. bufferSizeExpected = 0;
  19924. }
  19925. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19926. {
  19927. const ScopedLock sl (lock);
  19928. if (inputs.size() > 0)
  19929. {
  19930. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19931. if (inputs.size() > 1)
  19932. {
  19933. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19934. info.buffer->getNumSamples());
  19935. AudioSourceChannelInfo info2;
  19936. info2.buffer = &tempBuffer;
  19937. info2.numSamples = info.numSamples;
  19938. info2.startSample = 0;
  19939. for (int i = 1; i < inputs.size(); ++i)
  19940. {
  19941. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19942. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19943. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19944. }
  19945. }
  19946. }
  19947. else
  19948. {
  19949. info.clearActiveBufferRegion();
  19950. }
  19951. }
  19952. END_JUCE_NAMESPACE
  19953. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19954. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19955. BEGIN_JUCE_NAMESPACE
  19956. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19957. const bool deleteInputWhenDeleted_,
  19958. const int numChannels_)
  19959. : input (inputSource),
  19960. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19961. ratio (1.0),
  19962. lastRatio (1.0),
  19963. buffer (numChannels_, 0),
  19964. sampsInBuffer (0),
  19965. numChannels (numChannels_)
  19966. {
  19967. jassert (input != 0);
  19968. }
  19969. ResamplingAudioSource::~ResamplingAudioSource()
  19970. {
  19971. if (deleteInputWhenDeleted)
  19972. delete input;
  19973. }
  19974. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19975. {
  19976. jassert (samplesInPerOutputSample > 0);
  19977. const ScopedLock sl (ratioLock);
  19978. ratio = jmax (0.0, samplesInPerOutputSample);
  19979. }
  19980. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19981. double sampleRate)
  19982. {
  19983. const ScopedLock sl (ratioLock);
  19984. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19985. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19986. buffer.clear();
  19987. sampsInBuffer = 0;
  19988. bufferPos = 0;
  19989. subSampleOffset = 0.0;
  19990. filterStates.calloc (numChannels);
  19991. srcBuffers.calloc (numChannels);
  19992. destBuffers.calloc (numChannels);
  19993. createLowPass (ratio);
  19994. resetFilters();
  19995. }
  19996. void ResamplingAudioSource::releaseResources()
  19997. {
  19998. input->releaseResources();
  19999. buffer.setSize (numChannels, 0);
  20000. }
  20001. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20002. {
  20003. const ScopedLock sl (ratioLock);
  20004. if (lastRatio != ratio)
  20005. {
  20006. createLowPass (ratio);
  20007. lastRatio = ratio;
  20008. }
  20009. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20010. int bufferSize = buffer.getNumSamples();
  20011. if (bufferSize < sampsNeeded + 8)
  20012. {
  20013. bufferPos %= bufferSize;
  20014. bufferSize = sampsNeeded + 32;
  20015. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20016. }
  20017. bufferPos %= bufferSize;
  20018. int endOfBufferPos = bufferPos + sampsInBuffer;
  20019. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20020. while (sampsNeeded > sampsInBuffer)
  20021. {
  20022. endOfBufferPos %= bufferSize;
  20023. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20024. bufferSize - endOfBufferPos);
  20025. AudioSourceChannelInfo readInfo;
  20026. readInfo.buffer = &buffer;
  20027. readInfo.numSamples = numToDo;
  20028. readInfo.startSample = endOfBufferPos;
  20029. input->getNextAudioBlock (readInfo);
  20030. if (ratio > 1.0001)
  20031. {
  20032. // for down-sampling, pre-apply the filter..
  20033. for (int i = channelsToProcess; --i >= 0;)
  20034. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20035. }
  20036. sampsInBuffer += numToDo;
  20037. endOfBufferPos += numToDo;
  20038. }
  20039. for (int channel = 0; channel < channelsToProcess; ++channel)
  20040. {
  20041. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20042. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20043. }
  20044. int nextPos = (bufferPos + 1) % bufferSize;
  20045. for (int m = info.numSamples; --m >= 0;)
  20046. {
  20047. const float alpha = (float) subSampleOffset;
  20048. const float invAlpha = 1.0f - alpha;
  20049. for (int channel = 0; channel < channelsToProcess; ++channel)
  20050. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20051. subSampleOffset += ratio;
  20052. jassert (sampsInBuffer > 0);
  20053. while (subSampleOffset >= 1.0)
  20054. {
  20055. if (++bufferPos >= bufferSize)
  20056. bufferPos = 0;
  20057. --sampsInBuffer;
  20058. nextPos = (bufferPos + 1) % bufferSize;
  20059. subSampleOffset -= 1.0;
  20060. }
  20061. }
  20062. if (ratio < 0.9999)
  20063. {
  20064. // for up-sampling, apply the filter after transposing..
  20065. for (int i = channelsToProcess; --i >= 0;)
  20066. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20067. }
  20068. else if (ratio <= 1.0001)
  20069. {
  20070. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20071. for (int i = channelsToProcess; --i >= 0;)
  20072. {
  20073. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20074. FilterState& fs = filterStates[i];
  20075. if (info.numSamples > 1)
  20076. {
  20077. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20078. }
  20079. else
  20080. {
  20081. fs.y2 = fs.y1;
  20082. fs.x2 = fs.x1;
  20083. }
  20084. fs.y1 = fs.x1 = *endOfBuffer;
  20085. }
  20086. }
  20087. jassert (sampsInBuffer >= 0);
  20088. }
  20089. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20090. {
  20091. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20092. : 0.5 * frequencyRatio;
  20093. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20094. const double nSquared = n * n;
  20095. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20096. setFilterCoefficients (c1,
  20097. c1 * 2.0f,
  20098. c1,
  20099. 1.0,
  20100. c1 * 2.0 * (1.0 - nSquared),
  20101. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20102. }
  20103. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20104. {
  20105. const double a = 1.0 / c4;
  20106. c1 *= a;
  20107. c2 *= a;
  20108. c3 *= a;
  20109. c5 *= a;
  20110. c6 *= a;
  20111. coefficients[0] = c1;
  20112. coefficients[1] = c2;
  20113. coefficients[2] = c3;
  20114. coefficients[3] = c4;
  20115. coefficients[4] = c5;
  20116. coefficients[5] = c6;
  20117. }
  20118. void ResamplingAudioSource::resetFilters()
  20119. {
  20120. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20121. }
  20122. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20123. {
  20124. while (--num >= 0)
  20125. {
  20126. const double in = *samples;
  20127. double out = coefficients[0] * in
  20128. + coefficients[1] * fs.x1
  20129. + coefficients[2] * fs.x2
  20130. - coefficients[4] * fs.y1
  20131. - coefficients[5] * fs.y2;
  20132. #if JUCE_INTEL
  20133. if (! (out < -1.0e-8 || out > 1.0e-8))
  20134. out = 0;
  20135. #endif
  20136. fs.x2 = fs.x1;
  20137. fs.x1 = in;
  20138. fs.y2 = fs.y1;
  20139. fs.y1 = out;
  20140. *samples++ = (float) out;
  20141. }
  20142. }
  20143. END_JUCE_NAMESPACE
  20144. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20145. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20146. BEGIN_JUCE_NAMESPACE
  20147. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20148. : frequency (1000.0),
  20149. sampleRate (44100.0),
  20150. currentPhase (0.0),
  20151. phasePerSample (0.0),
  20152. amplitude (0.5f)
  20153. {
  20154. }
  20155. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20156. {
  20157. }
  20158. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20159. {
  20160. amplitude = newAmplitude;
  20161. }
  20162. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20163. {
  20164. frequency = newFrequencyHz;
  20165. phasePerSample = 0.0;
  20166. }
  20167. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20168. double sampleRate_)
  20169. {
  20170. currentPhase = 0.0;
  20171. phasePerSample = 0.0;
  20172. sampleRate = sampleRate_;
  20173. }
  20174. void ToneGeneratorAudioSource::releaseResources()
  20175. {
  20176. }
  20177. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20178. {
  20179. if (phasePerSample == 0.0)
  20180. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20181. for (int i = 0; i < info.numSamples; ++i)
  20182. {
  20183. const float sample = amplitude * (float) std::sin (currentPhase);
  20184. currentPhase += phasePerSample;
  20185. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20186. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20187. }
  20188. }
  20189. END_JUCE_NAMESPACE
  20190. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20191. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20192. BEGIN_JUCE_NAMESPACE
  20193. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20194. : sampleRate (0),
  20195. bufferSize (0),
  20196. useDefaultInputChannels (true),
  20197. useDefaultOutputChannels (true)
  20198. {
  20199. }
  20200. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20201. {
  20202. return outputDeviceName == other.outputDeviceName
  20203. && inputDeviceName == other.inputDeviceName
  20204. && sampleRate == other.sampleRate
  20205. && bufferSize == other.bufferSize
  20206. && inputChannels == other.inputChannels
  20207. && useDefaultInputChannels == other.useDefaultInputChannels
  20208. && outputChannels == other.outputChannels
  20209. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20210. }
  20211. AudioDeviceManager::AudioDeviceManager()
  20212. : currentAudioDevice (0),
  20213. numInputChansNeeded (0),
  20214. numOutputChansNeeded (2),
  20215. listNeedsScanning (true),
  20216. useInputNames (false),
  20217. inputLevelMeasurementEnabledCount (0),
  20218. inputLevel (0),
  20219. tempBuffer (2, 2),
  20220. defaultMidiOutput (0),
  20221. cpuUsageMs (0),
  20222. timeToCpuScale (0)
  20223. {
  20224. callbackHandler.owner = this;
  20225. }
  20226. AudioDeviceManager::~AudioDeviceManager()
  20227. {
  20228. currentAudioDevice = 0;
  20229. defaultMidiOutput = 0;
  20230. }
  20231. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20232. {
  20233. if (availableDeviceTypes.size() == 0)
  20234. {
  20235. createAudioDeviceTypes (availableDeviceTypes);
  20236. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20237. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20238. if (availableDeviceTypes.size() > 0)
  20239. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20240. }
  20241. }
  20242. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20243. {
  20244. scanDevicesIfNeeded();
  20245. return availableDeviceTypes;
  20246. }
  20247. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20248. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20249. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20250. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20251. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20252. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20253. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20254. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20255. {
  20256. (void) list; // (to avoid 'unused param' warnings)
  20257. #if JUCE_WINDOWS
  20258. #if JUCE_WASAPI
  20259. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20260. list.add (juce_createAudioIODeviceType_WASAPI());
  20261. #endif
  20262. #if JUCE_DIRECTSOUND
  20263. list.add (juce_createAudioIODeviceType_DirectSound());
  20264. #endif
  20265. #if JUCE_ASIO
  20266. list.add (juce_createAudioIODeviceType_ASIO());
  20267. #endif
  20268. #endif
  20269. #if JUCE_MAC
  20270. list.add (juce_createAudioIODeviceType_CoreAudio());
  20271. #endif
  20272. #if JUCE_IOS
  20273. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20274. #endif
  20275. #if JUCE_LINUX && JUCE_ALSA
  20276. list.add (juce_createAudioIODeviceType_ALSA());
  20277. #endif
  20278. #if JUCE_LINUX && JUCE_JACK
  20279. list.add (juce_createAudioIODeviceType_JACK());
  20280. #endif
  20281. }
  20282. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20283. const int numOutputChannelsNeeded,
  20284. const XmlElement* const e,
  20285. const bool selectDefaultDeviceOnFailure,
  20286. const String& preferredDefaultDeviceName,
  20287. const AudioDeviceSetup* preferredSetupOptions)
  20288. {
  20289. scanDevicesIfNeeded();
  20290. numInputChansNeeded = numInputChannelsNeeded;
  20291. numOutputChansNeeded = numOutputChannelsNeeded;
  20292. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20293. {
  20294. lastExplicitSettings = new XmlElement (*e);
  20295. String error;
  20296. AudioDeviceSetup setup;
  20297. if (preferredSetupOptions != 0)
  20298. setup = *preferredSetupOptions;
  20299. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20300. {
  20301. setup.inputDeviceName = setup.outputDeviceName
  20302. = e->getStringAttribute ("audioDeviceName");
  20303. }
  20304. else
  20305. {
  20306. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20307. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20308. }
  20309. currentDeviceType = e->getStringAttribute ("deviceType");
  20310. if (currentDeviceType.isEmpty())
  20311. {
  20312. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20313. if (type != 0)
  20314. currentDeviceType = type->getTypeName();
  20315. else if (availableDeviceTypes.size() > 0)
  20316. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20317. }
  20318. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20319. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20320. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20321. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20322. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20323. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20324. error = setAudioDeviceSetup (setup, true);
  20325. midiInsFromXml.clear();
  20326. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20327. midiInsFromXml.add (c->getStringAttribute ("name"));
  20328. const StringArray allMidiIns (MidiInput::getDevices());
  20329. for (int i = allMidiIns.size(); --i >= 0;)
  20330. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20331. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20332. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20333. false, preferredDefaultDeviceName);
  20334. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20335. return error;
  20336. }
  20337. else
  20338. {
  20339. AudioDeviceSetup setup;
  20340. if (preferredSetupOptions != 0)
  20341. {
  20342. setup = *preferredSetupOptions;
  20343. }
  20344. else if (preferredDefaultDeviceName.isNotEmpty())
  20345. {
  20346. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20347. {
  20348. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20349. StringArray outs (type->getDeviceNames (false));
  20350. int i;
  20351. for (i = 0; i < outs.size(); ++i)
  20352. {
  20353. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20354. {
  20355. setup.outputDeviceName = outs[i];
  20356. break;
  20357. }
  20358. }
  20359. StringArray ins (type->getDeviceNames (true));
  20360. for (i = 0; i < ins.size(); ++i)
  20361. {
  20362. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20363. {
  20364. setup.inputDeviceName = ins[i];
  20365. break;
  20366. }
  20367. }
  20368. }
  20369. }
  20370. insertDefaultDeviceNames (setup);
  20371. return setAudioDeviceSetup (setup, false);
  20372. }
  20373. }
  20374. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20375. {
  20376. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20377. if (type != 0)
  20378. {
  20379. if (setup.outputDeviceName.isEmpty())
  20380. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20381. if (setup.inputDeviceName.isEmpty())
  20382. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20383. }
  20384. }
  20385. XmlElement* AudioDeviceManager::createStateXml() const
  20386. {
  20387. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20388. }
  20389. void AudioDeviceManager::scanDevicesIfNeeded()
  20390. {
  20391. if (listNeedsScanning)
  20392. {
  20393. listNeedsScanning = false;
  20394. createDeviceTypesIfNeeded();
  20395. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20396. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20397. }
  20398. }
  20399. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20400. {
  20401. scanDevicesIfNeeded();
  20402. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20403. {
  20404. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20405. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20406. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20407. {
  20408. return type;
  20409. }
  20410. }
  20411. return 0;
  20412. }
  20413. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20414. {
  20415. setup = currentSetup;
  20416. }
  20417. void AudioDeviceManager::deleteCurrentDevice()
  20418. {
  20419. currentAudioDevice = 0;
  20420. currentSetup.inputDeviceName = String::empty;
  20421. currentSetup.outputDeviceName = String::empty;
  20422. }
  20423. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20424. const bool treatAsChosenDevice)
  20425. {
  20426. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20427. {
  20428. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20429. && currentDeviceType != type)
  20430. {
  20431. currentDeviceType = type;
  20432. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20433. insertDefaultDeviceNames (s);
  20434. setAudioDeviceSetup (s, treatAsChosenDevice);
  20435. sendChangeMessage (this);
  20436. break;
  20437. }
  20438. }
  20439. }
  20440. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20441. {
  20442. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20443. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20444. return availableDeviceTypes[i];
  20445. return availableDeviceTypes[0];
  20446. }
  20447. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20448. const bool treatAsChosenDevice)
  20449. {
  20450. jassert (&newSetup != &currentSetup); // this will have no effect
  20451. if (newSetup == currentSetup && currentAudioDevice != 0)
  20452. return String::empty;
  20453. if (! (newSetup == currentSetup))
  20454. sendChangeMessage (this);
  20455. stopDevice();
  20456. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20457. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20458. String error;
  20459. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20460. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20461. {
  20462. deleteCurrentDevice();
  20463. if (treatAsChosenDevice)
  20464. updateXml();
  20465. return String::empty;
  20466. }
  20467. if (currentSetup.inputDeviceName != newInputDeviceName
  20468. || currentSetup.outputDeviceName != newOutputDeviceName
  20469. || currentAudioDevice == 0)
  20470. {
  20471. deleteCurrentDevice();
  20472. scanDevicesIfNeeded();
  20473. if (newOutputDeviceName.isNotEmpty()
  20474. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20475. {
  20476. return "No such device: " + newOutputDeviceName;
  20477. }
  20478. if (newInputDeviceName.isNotEmpty()
  20479. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20480. {
  20481. return "No such device: " + newInputDeviceName;
  20482. }
  20483. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20484. if (currentAudioDevice == 0)
  20485. 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!";
  20486. else
  20487. error = currentAudioDevice->getLastError();
  20488. if (error.isNotEmpty())
  20489. {
  20490. deleteCurrentDevice();
  20491. return error;
  20492. }
  20493. if (newSetup.useDefaultInputChannels)
  20494. {
  20495. inputChannels.clear();
  20496. inputChannels.setRange (0, numInputChansNeeded, true);
  20497. }
  20498. if (newSetup.useDefaultOutputChannels)
  20499. {
  20500. outputChannels.clear();
  20501. outputChannels.setRange (0, numOutputChansNeeded, true);
  20502. }
  20503. if (newInputDeviceName.isEmpty())
  20504. inputChannels.clear();
  20505. if (newOutputDeviceName.isEmpty())
  20506. outputChannels.clear();
  20507. }
  20508. if (! newSetup.useDefaultInputChannels)
  20509. inputChannels = newSetup.inputChannels;
  20510. if (! newSetup.useDefaultOutputChannels)
  20511. outputChannels = newSetup.outputChannels;
  20512. currentSetup = newSetup;
  20513. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20514. error = currentAudioDevice->open (inputChannels,
  20515. outputChannels,
  20516. currentSetup.sampleRate,
  20517. currentSetup.bufferSize);
  20518. if (error.isEmpty())
  20519. {
  20520. currentDeviceType = currentAudioDevice->getTypeName();
  20521. currentAudioDevice->start (&callbackHandler);
  20522. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20523. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20524. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20525. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20526. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20527. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20528. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20529. if (treatAsChosenDevice)
  20530. updateXml();
  20531. }
  20532. else
  20533. {
  20534. deleteCurrentDevice();
  20535. }
  20536. return error;
  20537. }
  20538. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20539. {
  20540. jassert (currentAudioDevice != 0);
  20541. if (rate > 0)
  20542. {
  20543. bool ok = false;
  20544. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20545. {
  20546. const double sr = currentAudioDevice->getSampleRate (i);
  20547. if (sr == rate)
  20548. ok = true;
  20549. }
  20550. if (! ok)
  20551. rate = 0;
  20552. }
  20553. if (rate == 0)
  20554. {
  20555. double lowestAbove44 = 0.0;
  20556. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20557. {
  20558. const double sr = currentAudioDevice->getSampleRate (i);
  20559. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20560. lowestAbove44 = sr;
  20561. }
  20562. if (lowestAbove44 == 0.0)
  20563. rate = currentAudioDevice->getSampleRate (0);
  20564. else
  20565. rate = lowestAbove44;
  20566. }
  20567. return rate;
  20568. }
  20569. void AudioDeviceManager::stopDevice()
  20570. {
  20571. if (currentAudioDevice != 0)
  20572. currentAudioDevice->stop();
  20573. testSound = 0;
  20574. }
  20575. void AudioDeviceManager::closeAudioDevice()
  20576. {
  20577. stopDevice();
  20578. currentAudioDevice = 0;
  20579. }
  20580. void AudioDeviceManager::restartLastAudioDevice()
  20581. {
  20582. if (currentAudioDevice == 0)
  20583. {
  20584. if (currentSetup.inputDeviceName.isEmpty()
  20585. && currentSetup.outputDeviceName.isEmpty())
  20586. {
  20587. // This method will only reload the last device that was running
  20588. // before closeAudioDevice() was called - you need to actually open
  20589. // one first, with setAudioDevice().
  20590. jassertfalse;
  20591. return;
  20592. }
  20593. AudioDeviceSetup s (currentSetup);
  20594. setAudioDeviceSetup (s, false);
  20595. }
  20596. }
  20597. void AudioDeviceManager::updateXml()
  20598. {
  20599. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20600. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20601. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20602. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20603. if (currentAudioDevice != 0)
  20604. {
  20605. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20606. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20607. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20608. if (! currentSetup.useDefaultInputChannels)
  20609. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20610. if (! currentSetup.useDefaultOutputChannels)
  20611. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20612. }
  20613. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20614. {
  20615. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20616. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20617. }
  20618. if (midiInsFromXml.size() > 0)
  20619. {
  20620. // Add any midi devices that have been enabled before, but which aren't currently
  20621. // open because the device has been disconnected.
  20622. const StringArray availableMidiDevices (MidiInput::getDevices());
  20623. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20624. {
  20625. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20626. {
  20627. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20628. m->setAttribute ("name", midiInsFromXml[i]);
  20629. }
  20630. }
  20631. }
  20632. if (defaultMidiOutputName.isNotEmpty())
  20633. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20634. }
  20635. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20636. {
  20637. {
  20638. const ScopedLock sl (audioCallbackLock);
  20639. if (callbacks.contains (newCallback))
  20640. return;
  20641. }
  20642. if (currentAudioDevice != 0 && newCallback != 0)
  20643. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20644. const ScopedLock sl (audioCallbackLock);
  20645. callbacks.add (newCallback);
  20646. }
  20647. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20648. {
  20649. if (callback != 0)
  20650. {
  20651. bool needsDeinitialising = currentAudioDevice != 0;
  20652. {
  20653. const ScopedLock sl (audioCallbackLock);
  20654. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20655. callbacks.removeValue (callback);
  20656. }
  20657. if (needsDeinitialising)
  20658. callback->audioDeviceStopped();
  20659. }
  20660. }
  20661. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20662. int numInputChannels,
  20663. float** outputChannelData,
  20664. int numOutputChannels,
  20665. int numSamples)
  20666. {
  20667. const ScopedLock sl (audioCallbackLock);
  20668. if (inputLevelMeasurementEnabledCount > 0)
  20669. {
  20670. for (int j = 0; j < numSamples; ++j)
  20671. {
  20672. float s = 0;
  20673. for (int i = 0; i < numInputChannels; ++i)
  20674. s += std::abs (inputChannelData[i][j]);
  20675. s /= numInputChannels;
  20676. const double decayFactor = 0.99992;
  20677. if (s > inputLevel)
  20678. inputLevel = s;
  20679. else if (inputLevel > 0.001f)
  20680. inputLevel *= decayFactor;
  20681. else
  20682. inputLevel = 0;
  20683. }
  20684. }
  20685. if (callbacks.size() > 0)
  20686. {
  20687. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20688. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20689. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20690. outputChannelData, numOutputChannels, numSamples);
  20691. float** const tempChans = tempBuffer.getArrayOfChannels();
  20692. for (int i = callbacks.size(); --i > 0;)
  20693. {
  20694. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20695. tempChans, numOutputChannels, numSamples);
  20696. for (int chan = 0; chan < numOutputChannels; ++chan)
  20697. {
  20698. const float* const src = tempChans [chan];
  20699. float* const dst = outputChannelData [chan];
  20700. if (src != 0 && dst != 0)
  20701. for (int j = 0; j < numSamples; ++j)
  20702. dst[j] += src[j];
  20703. }
  20704. }
  20705. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20706. const double filterAmount = 0.2;
  20707. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20708. }
  20709. else
  20710. {
  20711. for (int i = 0; i < numOutputChannels; ++i)
  20712. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20713. }
  20714. if (testSound != 0)
  20715. {
  20716. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20717. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20718. for (int i = 0; i < numOutputChannels; ++i)
  20719. for (int j = 0; j < numSamps; ++j)
  20720. outputChannelData [i][j] += src[j];
  20721. testSoundPosition += numSamps;
  20722. if (testSoundPosition >= testSound->getNumSamples())
  20723. testSound = 0;
  20724. }
  20725. }
  20726. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20727. {
  20728. cpuUsageMs = 0;
  20729. const double sampleRate = device->getCurrentSampleRate();
  20730. const int blockSize = device->getCurrentBufferSizeSamples();
  20731. if (sampleRate > 0.0 && blockSize > 0)
  20732. {
  20733. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20734. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20735. }
  20736. {
  20737. const ScopedLock sl (audioCallbackLock);
  20738. for (int i = callbacks.size(); --i >= 0;)
  20739. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20740. }
  20741. sendChangeMessage (this);
  20742. }
  20743. void AudioDeviceManager::audioDeviceStoppedInt()
  20744. {
  20745. cpuUsageMs = 0;
  20746. timeToCpuScale = 0;
  20747. sendChangeMessage (this);
  20748. const ScopedLock sl (audioCallbackLock);
  20749. for (int i = callbacks.size(); --i >= 0;)
  20750. callbacks.getUnchecked(i)->audioDeviceStopped();
  20751. }
  20752. double AudioDeviceManager::getCpuUsage() const
  20753. {
  20754. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20755. }
  20756. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20757. const bool enabled)
  20758. {
  20759. if (enabled != isMidiInputEnabled (name))
  20760. {
  20761. if (enabled)
  20762. {
  20763. const int index = MidiInput::getDevices().indexOf (name);
  20764. if (index >= 0)
  20765. {
  20766. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20767. if (min != 0)
  20768. {
  20769. enabledMidiInputs.add (min);
  20770. min->start();
  20771. }
  20772. }
  20773. }
  20774. else
  20775. {
  20776. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20777. if (enabledMidiInputs[i]->getName() == name)
  20778. enabledMidiInputs.remove (i);
  20779. }
  20780. updateXml();
  20781. sendChangeMessage (this);
  20782. }
  20783. }
  20784. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20785. {
  20786. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20787. if (enabledMidiInputs[i]->getName() == name)
  20788. return true;
  20789. return false;
  20790. }
  20791. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20792. MidiInputCallback* callback)
  20793. {
  20794. removeMidiInputCallback (name, callback);
  20795. if (name.isEmpty())
  20796. {
  20797. midiCallbacks.add (callback);
  20798. midiCallbackDevices.add (0);
  20799. }
  20800. else
  20801. {
  20802. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20803. {
  20804. if (enabledMidiInputs[i]->getName() == name)
  20805. {
  20806. const ScopedLock sl (midiCallbackLock);
  20807. midiCallbacks.add (callback);
  20808. midiCallbackDevices.add (enabledMidiInputs[i]);
  20809. break;
  20810. }
  20811. }
  20812. }
  20813. }
  20814. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20815. MidiInputCallback* /*callback*/)
  20816. {
  20817. const ScopedLock sl (midiCallbackLock);
  20818. for (int i = midiCallbacks.size(); --i >= 0;)
  20819. {
  20820. String devName;
  20821. if (midiCallbackDevices.getUnchecked(i) != 0)
  20822. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20823. if (devName == name)
  20824. {
  20825. midiCallbacks.remove (i);
  20826. midiCallbackDevices.remove (i);
  20827. }
  20828. }
  20829. }
  20830. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20831. const MidiMessage& message)
  20832. {
  20833. if (! message.isActiveSense())
  20834. {
  20835. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20836. const ScopedLock sl (midiCallbackLock);
  20837. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20838. {
  20839. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20840. if (md == source || (md == 0 && isDefaultSource))
  20841. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20842. }
  20843. }
  20844. }
  20845. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20846. {
  20847. if (defaultMidiOutputName != deviceName)
  20848. {
  20849. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20850. {
  20851. const ScopedLock sl (audioCallbackLock);
  20852. oldCallbacks = callbacks;
  20853. callbacks.clear();
  20854. }
  20855. if (currentAudioDevice != 0)
  20856. for (int i = oldCallbacks.size(); --i >= 0;)
  20857. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20858. defaultMidiOutput = 0;
  20859. defaultMidiOutputName = deviceName;
  20860. if (deviceName.isNotEmpty())
  20861. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20862. if (currentAudioDevice != 0)
  20863. for (int i = oldCallbacks.size(); --i >= 0;)
  20864. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20865. {
  20866. const ScopedLock sl (audioCallbackLock);
  20867. callbacks = oldCallbacks;
  20868. }
  20869. updateXml();
  20870. sendChangeMessage (this);
  20871. }
  20872. }
  20873. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20874. int numInputChannels,
  20875. float** outputChannelData,
  20876. int numOutputChannels,
  20877. int numSamples)
  20878. {
  20879. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20880. }
  20881. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20882. {
  20883. owner->audioDeviceAboutToStartInt (device);
  20884. }
  20885. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20886. {
  20887. owner->audioDeviceStoppedInt();
  20888. }
  20889. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20890. {
  20891. owner->handleIncomingMidiMessageInt (source, message);
  20892. }
  20893. void AudioDeviceManager::playTestSound()
  20894. {
  20895. { // cunningly nested to swap, unlock and delete in that order.
  20896. ScopedPointer <AudioSampleBuffer> oldSound;
  20897. {
  20898. const ScopedLock sl (audioCallbackLock);
  20899. oldSound = testSound;
  20900. }
  20901. }
  20902. testSoundPosition = 0;
  20903. if (currentAudioDevice != 0)
  20904. {
  20905. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20906. const int soundLength = (int) sampleRate;
  20907. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20908. float* samples = newSound->getSampleData (0);
  20909. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20910. const float amplitude = 0.5f;
  20911. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20912. for (int i = 0; i < soundLength; ++i)
  20913. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20914. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20915. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20916. const ScopedLock sl (audioCallbackLock);
  20917. testSound = newSound;
  20918. }
  20919. }
  20920. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20921. {
  20922. const ScopedLock sl (audioCallbackLock);
  20923. if (enableMeasurement)
  20924. ++inputLevelMeasurementEnabledCount;
  20925. else
  20926. --inputLevelMeasurementEnabledCount;
  20927. inputLevel = 0;
  20928. }
  20929. double AudioDeviceManager::getCurrentInputLevel() const
  20930. {
  20931. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20932. return inputLevel;
  20933. }
  20934. END_JUCE_NAMESPACE
  20935. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20936. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20937. BEGIN_JUCE_NAMESPACE
  20938. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20939. : name (deviceName),
  20940. typeName (typeName_)
  20941. {
  20942. }
  20943. AudioIODevice::~AudioIODevice()
  20944. {
  20945. }
  20946. bool AudioIODevice::hasControlPanel() const
  20947. {
  20948. return false;
  20949. }
  20950. bool AudioIODevice::showControlPanel()
  20951. {
  20952. jassertfalse; // this should only be called for devices which return true from
  20953. // their hasControlPanel() method.
  20954. return false;
  20955. }
  20956. END_JUCE_NAMESPACE
  20957. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20958. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20959. BEGIN_JUCE_NAMESPACE
  20960. AudioIODeviceType::AudioIODeviceType (const String& name)
  20961. : typeName (name)
  20962. {
  20963. }
  20964. AudioIODeviceType::~AudioIODeviceType()
  20965. {
  20966. }
  20967. END_JUCE_NAMESPACE
  20968. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20969. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20970. BEGIN_JUCE_NAMESPACE
  20971. MidiOutput::MidiOutput()
  20972. : Thread ("midi out"),
  20973. internal (0),
  20974. firstMessage (0)
  20975. {
  20976. }
  20977. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20978. const double sampleNumber)
  20979. : message (data, len, sampleNumber)
  20980. {
  20981. }
  20982. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20983. const double millisecondCounterToStartAt,
  20984. double samplesPerSecondForBuffer)
  20985. {
  20986. // You've got to call startBackgroundThread() for this to actually work..
  20987. jassert (isThreadRunning());
  20988. // this needs to be a value in the future - RTFM for this method!
  20989. jassert (millisecondCounterToStartAt > 0);
  20990. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20991. MidiBuffer::Iterator i (buffer);
  20992. const uint8* data;
  20993. int len, time;
  20994. while (i.getNextEvent (data, len, time))
  20995. {
  20996. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20997. PendingMessage* const m
  20998. = new PendingMessage (data, len, eventTime);
  20999. const ScopedLock sl (lock);
  21000. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21001. {
  21002. m->next = firstMessage;
  21003. firstMessage = m;
  21004. }
  21005. else
  21006. {
  21007. PendingMessage* mm = firstMessage;
  21008. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21009. mm = mm->next;
  21010. m->next = mm->next;
  21011. mm->next = m;
  21012. }
  21013. }
  21014. notify();
  21015. }
  21016. void MidiOutput::clearAllPendingMessages()
  21017. {
  21018. const ScopedLock sl (lock);
  21019. while (firstMessage != 0)
  21020. {
  21021. PendingMessage* const m = firstMessage;
  21022. firstMessage = firstMessage->next;
  21023. delete m;
  21024. }
  21025. }
  21026. void MidiOutput::startBackgroundThread()
  21027. {
  21028. startThread (9);
  21029. }
  21030. void MidiOutput::stopBackgroundThread()
  21031. {
  21032. stopThread (5000);
  21033. }
  21034. void MidiOutput::run()
  21035. {
  21036. while (! threadShouldExit())
  21037. {
  21038. uint32 now = Time::getMillisecondCounter();
  21039. uint32 eventTime = 0;
  21040. uint32 timeToWait = 500;
  21041. PendingMessage* message;
  21042. {
  21043. const ScopedLock sl (lock);
  21044. message = firstMessage;
  21045. if (message != 0)
  21046. {
  21047. eventTime = roundToInt (message->message.getTimeStamp());
  21048. if (eventTime > now + 20)
  21049. {
  21050. timeToWait = eventTime - (now + 20);
  21051. message = 0;
  21052. }
  21053. else
  21054. {
  21055. firstMessage = message->next;
  21056. }
  21057. }
  21058. }
  21059. if (message != 0)
  21060. {
  21061. if (eventTime > now)
  21062. {
  21063. Time::waitForMillisecondCounter (eventTime);
  21064. if (threadShouldExit())
  21065. break;
  21066. }
  21067. if (eventTime > now - 200)
  21068. sendMessageNow (message->message);
  21069. delete message;
  21070. }
  21071. else
  21072. {
  21073. jassert (timeToWait < 1000 * 30);
  21074. wait (timeToWait);
  21075. }
  21076. }
  21077. clearAllPendingMessages();
  21078. }
  21079. END_JUCE_NAMESPACE
  21080. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21081. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21082. BEGIN_JUCE_NAMESPACE
  21083. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21084. {
  21085. const double maxVal = (double) 0x7fff;
  21086. char* intData = static_cast <char*> (dest);
  21087. if (dest != (void*) source || destBytesPerSample <= 4)
  21088. {
  21089. for (int i = 0; i < numSamples; ++i)
  21090. {
  21091. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21092. intData += destBytesPerSample;
  21093. }
  21094. }
  21095. else
  21096. {
  21097. intData += destBytesPerSample * numSamples;
  21098. for (int i = numSamples; --i >= 0;)
  21099. {
  21100. intData -= destBytesPerSample;
  21101. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21102. }
  21103. }
  21104. }
  21105. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21106. {
  21107. const double maxVal = (double) 0x7fff;
  21108. char* intData = static_cast <char*> (dest);
  21109. if (dest != (void*) source || destBytesPerSample <= 4)
  21110. {
  21111. for (int i = 0; i < numSamples; ++i)
  21112. {
  21113. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21114. intData += destBytesPerSample;
  21115. }
  21116. }
  21117. else
  21118. {
  21119. intData += destBytesPerSample * numSamples;
  21120. for (int i = numSamples; --i >= 0;)
  21121. {
  21122. intData -= destBytesPerSample;
  21123. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21124. }
  21125. }
  21126. }
  21127. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21128. {
  21129. const double maxVal = (double) 0x7fffff;
  21130. char* intData = static_cast <char*> (dest);
  21131. if (dest != (void*) source || destBytesPerSample <= 4)
  21132. {
  21133. for (int i = 0; i < numSamples; ++i)
  21134. {
  21135. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21136. intData += destBytesPerSample;
  21137. }
  21138. }
  21139. else
  21140. {
  21141. intData += destBytesPerSample * numSamples;
  21142. for (int i = numSamples; --i >= 0;)
  21143. {
  21144. intData -= destBytesPerSample;
  21145. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21146. }
  21147. }
  21148. }
  21149. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21150. {
  21151. const double maxVal = (double) 0x7fffff;
  21152. char* intData = static_cast <char*> (dest);
  21153. if (dest != (void*) source || destBytesPerSample <= 4)
  21154. {
  21155. for (int i = 0; i < numSamples; ++i)
  21156. {
  21157. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21158. intData += destBytesPerSample;
  21159. }
  21160. }
  21161. else
  21162. {
  21163. intData += destBytesPerSample * numSamples;
  21164. for (int i = numSamples; --i >= 0;)
  21165. {
  21166. intData -= destBytesPerSample;
  21167. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21168. }
  21169. }
  21170. }
  21171. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21172. {
  21173. const double maxVal = (double) 0x7fffffff;
  21174. char* intData = static_cast <char*> (dest);
  21175. if (dest != (void*) source || destBytesPerSample <= 4)
  21176. {
  21177. for (int i = 0; i < numSamples; ++i)
  21178. {
  21179. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21180. intData += destBytesPerSample;
  21181. }
  21182. }
  21183. else
  21184. {
  21185. intData += destBytesPerSample * numSamples;
  21186. for (int i = numSamples; --i >= 0;)
  21187. {
  21188. intData -= destBytesPerSample;
  21189. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21190. }
  21191. }
  21192. }
  21193. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21194. {
  21195. const double maxVal = (double) 0x7fffffff;
  21196. char* intData = static_cast <char*> (dest);
  21197. if (dest != (void*) source || destBytesPerSample <= 4)
  21198. {
  21199. for (int i = 0; i < numSamples; ++i)
  21200. {
  21201. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21202. intData += destBytesPerSample;
  21203. }
  21204. }
  21205. else
  21206. {
  21207. intData += destBytesPerSample * numSamples;
  21208. for (int i = numSamples; --i >= 0;)
  21209. {
  21210. intData -= destBytesPerSample;
  21211. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21212. }
  21213. }
  21214. }
  21215. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21216. {
  21217. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21218. char* d = static_cast <char*> (dest);
  21219. for (int i = 0; i < numSamples; ++i)
  21220. {
  21221. *(float*) d = source[i];
  21222. #if JUCE_BIG_ENDIAN
  21223. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21224. #endif
  21225. d += destBytesPerSample;
  21226. }
  21227. }
  21228. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21229. {
  21230. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21231. char* d = static_cast <char*> (dest);
  21232. for (int i = 0; i < numSamples; ++i)
  21233. {
  21234. *(float*) d = source[i];
  21235. #if JUCE_LITTLE_ENDIAN
  21236. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21237. #endif
  21238. d += destBytesPerSample;
  21239. }
  21240. }
  21241. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21242. {
  21243. const float scale = 1.0f / 0x7fff;
  21244. const char* intData = static_cast <const char*> (source);
  21245. if (source != (void*) dest || srcBytesPerSample >= 4)
  21246. {
  21247. for (int i = 0; i < numSamples; ++i)
  21248. {
  21249. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21250. intData += srcBytesPerSample;
  21251. }
  21252. }
  21253. else
  21254. {
  21255. intData += srcBytesPerSample * numSamples;
  21256. for (int i = numSamples; --i >= 0;)
  21257. {
  21258. intData -= srcBytesPerSample;
  21259. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21260. }
  21261. }
  21262. }
  21263. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21264. {
  21265. const float scale = 1.0f / 0x7fff;
  21266. const char* intData = static_cast <const char*> (source);
  21267. if (source != (void*) dest || srcBytesPerSample >= 4)
  21268. {
  21269. for (int i = 0; i < numSamples; ++i)
  21270. {
  21271. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21272. intData += srcBytesPerSample;
  21273. }
  21274. }
  21275. else
  21276. {
  21277. intData += srcBytesPerSample * numSamples;
  21278. for (int i = numSamples; --i >= 0;)
  21279. {
  21280. intData -= srcBytesPerSample;
  21281. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21282. }
  21283. }
  21284. }
  21285. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21286. {
  21287. const float scale = 1.0f / 0x7fffff;
  21288. const char* intData = static_cast <const char*> (source);
  21289. if (source != (void*) dest || srcBytesPerSample >= 4)
  21290. {
  21291. for (int i = 0; i < numSamples; ++i)
  21292. {
  21293. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21294. intData += srcBytesPerSample;
  21295. }
  21296. }
  21297. else
  21298. {
  21299. intData += srcBytesPerSample * numSamples;
  21300. for (int i = numSamples; --i >= 0;)
  21301. {
  21302. intData -= srcBytesPerSample;
  21303. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21304. }
  21305. }
  21306. }
  21307. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21308. {
  21309. const float scale = 1.0f / 0x7fffff;
  21310. const char* intData = static_cast <const char*> (source);
  21311. if (source != (void*) dest || srcBytesPerSample >= 4)
  21312. {
  21313. for (int i = 0; i < numSamples; ++i)
  21314. {
  21315. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21316. intData += srcBytesPerSample;
  21317. }
  21318. }
  21319. else
  21320. {
  21321. intData += srcBytesPerSample * numSamples;
  21322. for (int i = numSamples; --i >= 0;)
  21323. {
  21324. intData -= srcBytesPerSample;
  21325. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21326. }
  21327. }
  21328. }
  21329. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21330. {
  21331. const float scale = 1.0f / 0x7fffffff;
  21332. const char* intData = static_cast <const char*> (source);
  21333. if (source != (void*) dest || srcBytesPerSample >= 4)
  21334. {
  21335. for (int i = 0; i < numSamples; ++i)
  21336. {
  21337. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21338. intData += srcBytesPerSample;
  21339. }
  21340. }
  21341. else
  21342. {
  21343. intData += srcBytesPerSample * numSamples;
  21344. for (int i = numSamples; --i >= 0;)
  21345. {
  21346. intData -= srcBytesPerSample;
  21347. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21348. }
  21349. }
  21350. }
  21351. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21352. {
  21353. const float scale = 1.0f / 0x7fffffff;
  21354. const char* intData = static_cast <const char*> (source);
  21355. if (source != (void*) dest || srcBytesPerSample >= 4)
  21356. {
  21357. for (int i = 0; i < numSamples; ++i)
  21358. {
  21359. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21360. intData += srcBytesPerSample;
  21361. }
  21362. }
  21363. else
  21364. {
  21365. intData += srcBytesPerSample * numSamples;
  21366. for (int i = numSamples; --i >= 0;)
  21367. {
  21368. intData -= srcBytesPerSample;
  21369. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21370. }
  21371. }
  21372. }
  21373. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21374. {
  21375. const char* s = static_cast <const char*> (source);
  21376. for (int i = 0; i < numSamples; ++i)
  21377. {
  21378. dest[i] = *(float*)s;
  21379. #if JUCE_BIG_ENDIAN
  21380. uint32* const d = (uint32*) (dest + i);
  21381. *d = ByteOrder::swap (*d);
  21382. #endif
  21383. s += srcBytesPerSample;
  21384. }
  21385. }
  21386. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21387. {
  21388. const char* s = static_cast <const char*> (source);
  21389. for (int i = 0; i < numSamples; ++i)
  21390. {
  21391. dest[i] = *(float*)s;
  21392. #if JUCE_LITTLE_ENDIAN
  21393. uint32* const d = (uint32*) (dest + i);
  21394. *d = ByteOrder::swap (*d);
  21395. #endif
  21396. s += srcBytesPerSample;
  21397. }
  21398. }
  21399. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21400. const float* const source,
  21401. void* const dest,
  21402. const int numSamples)
  21403. {
  21404. switch (destFormat)
  21405. {
  21406. case int16LE:
  21407. convertFloatToInt16LE (source, dest, numSamples);
  21408. break;
  21409. case int16BE:
  21410. convertFloatToInt16BE (source, dest, numSamples);
  21411. break;
  21412. case int24LE:
  21413. convertFloatToInt24LE (source, dest, numSamples);
  21414. break;
  21415. case int24BE:
  21416. convertFloatToInt24BE (source, dest, numSamples);
  21417. break;
  21418. case int32LE:
  21419. convertFloatToInt32LE (source, dest, numSamples);
  21420. break;
  21421. case int32BE:
  21422. convertFloatToInt32BE (source, dest, numSamples);
  21423. break;
  21424. case float32LE:
  21425. convertFloatToFloat32LE (source, dest, numSamples);
  21426. break;
  21427. case float32BE:
  21428. convertFloatToFloat32BE (source, dest, numSamples);
  21429. break;
  21430. default:
  21431. jassertfalse;
  21432. break;
  21433. }
  21434. }
  21435. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21436. const void* const source,
  21437. float* const dest,
  21438. const int numSamples)
  21439. {
  21440. switch (sourceFormat)
  21441. {
  21442. case int16LE:
  21443. convertInt16LEToFloat (source, dest, numSamples);
  21444. break;
  21445. case int16BE:
  21446. convertInt16BEToFloat (source, dest, numSamples);
  21447. break;
  21448. case int24LE:
  21449. convertInt24LEToFloat (source, dest, numSamples);
  21450. break;
  21451. case int24BE:
  21452. convertInt24BEToFloat (source, dest, numSamples);
  21453. break;
  21454. case int32LE:
  21455. convertInt32LEToFloat (source, dest, numSamples);
  21456. break;
  21457. case int32BE:
  21458. convertInt32BEToFloat (source, dest, numSamples);
  21459. break;
  21460. case float32LE:
  21461. convertFloat32LEToFloat (source, dest, numSamples);
  21462. break;
  21463. case float32BE:
  21464. convertFloat32BEToFloat (source, dest, numSamples);
  21465. break;
  21466. default:
  21467. jassertfalse;
  21468. break;
  21469. }
  21470. }
  21471. void AudioDataConverters::interleaveSamples (const float** const source,
  21472. float* const dest,
  21473. const int numSamples,
  21474. const int numChannels)
  21475. {
  21476. for (int chan = 0; chan < numChannels; ++chan)
  21477. {
  21478. int i = chan;
  21479. const float* src = source [chan];
  21480. for (int j = 0; j < numSamples; ++j)
  21481. {
  21482. dest [i] = src [j];
  21483. i += numChannels;
  21484. }
  21485. }
  21486. }
  21487. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21488. float** const dest,
  21489. const int numSamples,
  21490. const int numChannels)
  21491. {
  21492. for (int chan = 0; chan < numChannels; ++chan)
  21493. {
  21494. int i = chan;
  21495. float* dst = dest [chan];
  21496. for (int j = 0; j < numSamples; ++j)
  21497. {
  21498. dst [j] = source [i];
  21499. i += numChannels;
  21500. }
  21501. }
  21502. }
  21503. #if JUCE_UNIT_TESTS
  21504. class AudioConversionTests : public UnitTest
  21505. {
  21506. public:
  21507. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21508. template <class F1, class E1, class F2, class E2>
  21509. struct Test5
  21510. {
  21511. static void test (UnitTest& unitTest)
  21512. {
  21513. test (unitTest, false);
  21514. test (unitTest, true);
  21515. }
  21516. static void test (UnitTest& unitTest, bool inPlace)
  21517. {
  21518. const int numSamples = 2048;
  21519. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21520. {
  21521. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21522. bool clippingFailed = false;
  21523. for (int i = 0; i < numSamples / 2; ++i)
  21524. {
  21525. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21526. if (! d.isFloatingPoint())
  21527. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21528. ++d;
  21529. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21530. ++d;
  21531. }
  21532. unitTest.expect (! clippingFailed);
  21533. }
  21534. // convert data from the source to dest format..
  21535. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21536. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21537. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21538. // ..and back again..
  21539. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21540. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21541. if (! inPlace)
  21542. zerostruct (reversed);
  21543. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21544. {
  21545. int biggestDiff = 0;
  21546. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21547. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21548. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21549. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21550. for (int i = 0; i < numSamples; ++i)
  21551. {
  21552. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21553. ++d1;
  21554. ++d2;
  21555. }
  21556. unitTest.expect (biggestDiff <= errorMargin);
  21557. }
  21558. }
  21559. };
  21560. template <class F1, class E1, class FormatType>
  21561. struct Test3
  21562. {
  21563. static void test (UnitTest& unitTest)
  21564. {
  21565. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21566. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21567. }
  21568. };
  21569. template <class FormatType, class Endianness>
  21570. struct Test2
  21571. {
  21572. static void test (UnitTest& unitTest)
  21573. {
  21574. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21575. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21576. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21577. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21578. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21579. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21580. }
  21581. };
  21582. template <class FormatType>
  21583. struct Test1
  21584. {
  21585. static void test (UnitTest& unitTest)
  21586. {
  21587. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21588. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21589. }
  21590. };
  21591. void runTest()
  21592. {
  21593. beginTest ("Round-trip conversion");
  21594. Test1 <AudioData::Int8>::test (*this);
  21595. Test1 <AudioData::Int16>::test (*this);
  21596. Test1 <AudioData::Int24>::test (*this);
  21597. Test1 <AudioData::Int32>::test (*this);
  21598. Test1 <AudioData::Float32>::test (*this);
  21599. }
  21600. };
  21601. static AudioConversionTests audioConversionUnitTests;
  21602. #endif
  21603. END_JUCE_NAMESPACE
  21604. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21605. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21606. BEGIN_JUCE_NAMESPACE
  21607. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21608. const int numSamples) throw()
  21609. : numChannels (numChannels_),
  21610. size (numSamples)
  21611. {
  21612. jassert (numSamples >= 0);
  21613. jassert (numChannels_ > 0);
  21614. allocateData();
  21615. }
  21616. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21617. : numChannels (other.numChannels),
  21618. size (other.size)
  21619. {
  21620. allocateData();
  21621. const size_t numBytes = size * sizeof (float);
  21622. for (int i = 0; i < numChannels; ++i)
  21623. memcpy (channels[i], other.channels[i], numBytes);
  21624. }
  21625. void AudioSampleBuffer::allocateData()
  21626. {
  21627. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21628. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21629. allocatedData.malloc (allocatedBytes);
  21630. channels = reinterpret_cast <float**> (allocatedData.getData());
  21631. float* chan = (float*) (allocatedData + channelListSize);
  21632. for (int i = 0; i < numChannels; ++i)
  21633. {
  21634. channels[i] = chan;
  21635. chan += size;
  21636. }
  21637. channels [numChannels] = 0;
  21638. }
  21639. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21640. const int numChannels_,
  21641. const int numSamples) throw()
  21642. : numChannels (numChannels_),
  21643. size (numSamples),
  21644. allocatedBytes (0)
  21645. {
  21646. jassert (numChannels_ > 0);
  21647. allocateChannels (dataToReferTo);
  21648. }
  21649. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21650. const int newNumChannels,
  21651. const int newNumSamples) throw()
  21652. {
  21653. jassert (newNumChannels > 0);
  21654. allocatedBytes = 0;
  21655. allocatedData.free();
  21656. numChannels = newNumChannels;
  21657. size = newNumSamples;
  21658. allocateChannels (dataToReferTo);
  21659. }
  21660. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21661. {
  21662. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21663. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21664. {
  21665. channels = static_cast <float**> (preallocatedChannelSpace);
  21666. }
  21667. else
  21668. {
  21669. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21670. channels = reinterpret_cast <float**> (allocatedData.getData());
  21671. }
  21672. for (int i = 0; i < numChannels; ++i)
  21673. {
  21674. // you have to pass in the same number of valid pointers as numChannels
  21675. jassert (dataToReferTo[i] != 0);
  21676. channels[i] = dataToReferTo[i];
  21677. }
  21678. channels [numChannels] = 0;
  21679. }
  21680. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21681. {
  21682. if (this != &other)
  21683. {
  21684. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21685. const size_t numBytes = size * sizeof (float);
  21686. for (int i = 0; i < numChannels; ++i)
  21687. memcpy (channels[i], other.channels[i], numBytes);
  21688. }
  21689. return *this;
  21690. }
  21691. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21692. {
  21693. }
  21694. void AudioSampleBuffer::setSize (const int newNumChannels,
  21695. const int newNumSamples,
  21696. const bool keepExistingContent,
  21697. const bool clearExtraSpace,
  21698. const bool avoidReallocating) throw()
  21699. {
  21700. jassert (newNumChannels > 0);
  21701. if (newNumSamples != size || newNumChannels != numChannels)
  21702. {
  21703. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21704. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21705. if (keepExistingContent)
  21706. {
  21707. HeapBlock <char> newData;
  21708. newData.allocate (newTotalBytes, clearExtraSpace);
  21709. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21710. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21711. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21712. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21713. for (int i = 0; i < numChansToCopy; ++i)
  21714. {
  21715. memcpy (newChan, channels[i], numBytesToCopy);
  21716. newChannels[i] = newChan;
  21717. newChan += newNumSamples;
  21718. }
  21719. allocatedData.swapWith (newData);
  21720. allocatedBytes = (int) newTotalBytes;
  21721. channels = newChannels;
  21722. }
  21723. else
  21724. {
  21725. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21726. {
  21727. if (clearExtraSpace)
  21728. zeromem (allocatedData, newTotalBytes);
  21729. }
  21730. else
  21731. {
  21732. allocatedBytes = newTotalBytes;
  21733. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21734. channels = reinterpret_cast <float**> (allocatedData.getData());
  21735. }
  21736. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21737. for (int i = 0; i < newNumChannels; ++i)
  21738. {
  21739. channels[i] = chan;
  21740. chan += newNumSamples;
  21741. }
  21742. }
  21743. channels [newNumChannels] = 0;
  21744. size = newNumSamples;
  21745. numChannels = newNumChannels;
  21746. }
  21747. }
  21748. void AudioSampleBuffer::clear() throw()
  21749. {
  21750. for (int i = 0; i < numChannels; ++i)
  21751. zeromem (channels[i], size * sizeof (float));
  21752. }
  21753. void AudioSampleBuffer::clear (const int startSample,
  21754. const int numSamples) throw()
  21755. {
  21756. jassert (startSample >= 0 && startSample + numSamples <= size);
  21757. for (int i = 0; i < numChannels; ++i)
  21758. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21759. }
  21760. void AudioSampleBuffer::clear (const int channel,
  21761. const int startSample,
  21762. const int numSamples) throw()
  21763. {
  21764. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21765. jassert (startSample >= 0 && startSample + numSamples <= size);
  21766. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21767. }
  21768. void AudioSampleBuffer::applyGain (const int channel,
  21769. const int startSample,
  21770. int numSamples,
  21771. const float gain) throw()
  21772. {
  21773. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21774. jassert (startSample >= 0 && startSample + numSamples <= size);
  21775. if (gain != 1.0f)
  21776. {
  21777. float* d = channels [channel] + startSample;
  21778. if (gain == 0.0f)
  21779. {
  21780. zeromem (d, sizeof (float) * numSamples);
  21781. }
  21782. else
  21783. {
  21784. while (--numSamples >= 0)
  21785. *d++ *= gain;
  21786. }
  21787. }
  21788. }
  21789. void AudioSampleBuffer::applyGainRamp (const int channel,
  21790. const int startSample,
  21791. int numSamples,
  21792. float startGain,
  21793. float endGain) throw()
  21794. {
  21795. if (startGain == endGain)
  21796. {
  21797. applyGain (channel, startSample, numSamples, startGain);
  21798. }
  21799. else
  21800. {
  21801. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21802. jassert (startSample >= 0 && startSample + numSamples <= size);
  21803. const float increment = (endGain - startGain) / numSamples;
  21804. float* d = channels [channel] + startSample;
  21805. while (--numSamples >= 0)
  21806. {
  21807. *d++ *= startGain;
  21808. startGain += increment;
  21809. }
  21810. }
  21811. }
  21812. void AudioSampleBuffer::applyGain (const int startSample,
  21813. const int numSamples,
  21814. const float gain) throw()
  21815. {
  21816. for (int i = 0; i < numChannels; ++i)
  21817. applyGain (i, startSample, numSamples, gain);
  21818. }
  21819. void AudioSampleBuffer::addFrom (const int destChannel,
  21820. const int destStartSample,
  21821. const AudioSampleBuffer& source,
  21822. const int sourceChannel,
  21823. const int sourceStartSample,
  21824. int numSamples,
  21825. const float gain) throw()
  21826. {
  21827. jassert (&source != this || sourceChannel != destChannel);
  21828. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21829. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21830. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21831. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21832. if (gain != 0.0f && numSamples > 0)
  21833. {
  21834. float* d = channels [destChannel] + destStartSample;
  21835. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21836. if (gain != 1.0f)
  21837. {
  21838. while (--numSamples >= 0)
  21839. *d++ += gain * *s++;
  21840. }
  21841. else
  21842. {
  21843. while (--numSamples >= 0)
  21844. *d++ += *s++;
  21845. }
  21846. }
  21847. }
  21848. void AudioSampleBuffer::addFrom (const int destChannel,
  21849. const int destStartSample,
  21850. const float* source,
  21851. int numSamples,
  21852. const float gain) throw()
  21853. {
  21854. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21855. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21856. jassert (source != 0);
  21857. if (gain != 0.0f && numSamples > 0)
  21858. {
  21859. float* d = channels [destChannel] + destStartSample;
  21860. if (gain != 1.0f)
  21861. {
  21862. while (--numSamples >= 0)
  21863. *d++ += gain * *source++;
  21864. }
  21865. else
  21866. {
  21867. while (--numSamples >= 0)
  21868. *d++ += *source++;
  21869. }
  21870. }
  21871. }
  21872. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21873. const int destStartSample,
  21874. const float* source,
  21875. int numSamples,
  21876. float startGain,
  21877. const float endGain) throw()
  21878. {
  21879. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21880. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21881. jassert (source != 0);
  21882. if (startGain == endGain)
  21883. {
  21884. addFrom (destChannel,
  21885. destStartSample,
  21886. source,
  21887. numSamples,
  21888. startGain);
  21889. }
  21890. else
  21891. {
  21892. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21893. {
  21894. const float increment = (endGain - startGain) / numSamples;
  21895. float* d = channels [destChannel] + destStartSample;
  21896. while (--numSamples >= 0)
  21897. {
  21898. *d++ += startGain * *source++;
  21899. startGain += increment;
  21900. }
  21901. }
  21902. }
  21903. }
  21904. void AudioSampleBuffer::copyFrom (const int destChannel,
  21905. const int destStartSample,
  21906. const AudioSampleBuffer& source,
  21907. const int sourceChannel,
  21908. const int sourceStartSample,
  21909. int numSamples) throw()
  21910. {
  21911. jassert (&source != this || sourceChannel != destChannel);
  21912. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21913. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21914. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21915. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21916. if (numSamples > 0)
  21917. {
  21918. memcpy (channels [destChannel] + destStartSample,
  21919. source.channels [sourceChannel] + sourceStartSample,
  21920. sizeof (float) * numSamples);
  21921. }
  21922. }
  21923. void AudioSampleBuffer::copyFrom (const int destChannel,
  21924. const int destStartSample,
  21925. const float* source,
  21926. int numSamples) throw()
  21927. {
  21928. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21929. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21930. jassert (source != 0);
  21931. if (numSamples > 0)
  21932. {
  21933. memcpy (channels [destChannel] + destStartSample,
  21934. source,
  21935. sizeof (float) * numSamples);
  21936. }
  21937. }
  21938. void AudioSampleBuffer::copyFrom (const int destChannel,
  21939. const int destStartSample,
  21940. const float* source,
  21941. int numSamples,
  21942. const float gain) throw()
  21943. {
  21944. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21945. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21946. jassert (source != 0);
  21947. if (numSamples > 0)
  21948. {
  21949. float* d = channels [destChannel] + destStartSample;
  21950. if (gain != 1.0f)
  21951. {
  21952. if (gain == 0)
  21953. {
  21954. zeromem (d, sizeof (float) * numSamples);
  21955. }
  21956. else
  21957. {
  21958. while (--numSamples >= 0)
  21959. *d++ = gain * *source++;
  21960. }
  21961. }
  21962. else
  21963. {
  21964. memcpy (d, source, sizeof (float) * numSamples);
  21965. }
  21966. }
  21967. }
  21968. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21969. const int destStartSample,
  21970. const float* source,
  21971. int numSamples,
  21972. float startGain,
  21973. float endGain) throw()
  21974. {
  21975. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21976. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21977. jassert (source != 0);
  21978. if (startGain == endGain)
  21979. {
  21980. copyFrom (destChannel,
  21981. destStartSample,
  21982. source,
  21983. numSamples,
  21984. startGain);
  21985. }
  21986. else
  21987. {
  21988. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21989. {
  21990. const float increment = (endGain - startGain) / numSamples;
  21991. float* d = channels [destChannel] + destStartSample;
  21992. while (--numSamples >= 0)
  21993. {
  21994. *d++ = startGain * *source++;
  21995. startGain += increment;
  21996. }
  21997. }
  21998. }
  21999. }
  22000. void AudioSampleBuffer::findMinMax (const int channel,
  22001. const int startSample,
  22002. int numSamples,
  22003. float& minVal,
  22004. float& maxVal) const throw()
  22005. {
  22006. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22007. jassert (startSample >= 0 && startSample + numSamples <= size);
  22008. if (numSamples <= 0)
  22009. {
  22010. minVal = 0.0f;
  22011. maxVal = 0.0f;
  22012. }
  22013. else
  22014. {
  22015. const float* d = channels [channel] + startSample;
  22016. float mn = *d++;
  22017. float mx = mn;
  22018. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22019. {
  22020. const float samp = *d++;
  22021. if (samp > mx)
  22022. mx = samp;
  22023. if (samp < mn)
  22024. mn = samp;
  22025. }
  22026. maxVal = mx;
  22027. minVal = mn;
  22028. }
  22029. }
  22030. float AudioSampleBuffer::getMagnitude (const int channel,
  22031. const int startSample,
  22032. const int numSamples) const throw()
  22033. {
  22034. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22035. jassert (startSample >= 0 && startSample + numSamples <= size);
  22036. float mn, mx;
  22037. findMinMax (channel, startSample, numSamples, mn, mx);
  22038. return jmax (mn, -mn, mx, -mx);
  22039. }
  22040. float AudioSampleBuffer::getMagnitude (const int startSample,
  22041. const int numSamples) const throw()
  22042. {
  22043. float mag = 0.0f;
  22044. for (int i = 0; i < numChannels; ++i)
  22045. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22046. return mag;
  22047. }
  22048. float AudioSampleBuffer::getRMSLevel (const int channel,
  22049. const int startSample,
  22050. const int numSamples) const throw()
  22051. {
  22052. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22053. jassert (startSample >= 0 && startSample + numSamples <= size);
  22054. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22055. return 0.0f;
  22056. const float* const data = channels [channel] + startSample;
  22057. double sum = 0.0;
  22058. for (int i = 0; i < numSamples; ++i)
  22059. {
  22060. const float sample = data [i];
  22061. sum += sample * sample;
  22062. }
  22063. return (float) std::sqrt (sum / numSamples);
  22064. }
  22065. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22066. const int startSample,
  22067. const int numSamples,
  22068. const int readerStartSample,
  22069. const bool useLeftChan,
  22070. const bool useRightChan)
  22071. {
  22072. jassert (reader != 0);
  22073. jassert (startSample >= 0 && startSample + numSamples <= size);
  22074. if (numSamples > 0)
  22075. {
  22076. int* chans[3];
  22077. if (useLeftChan == useRightChan)
  22078. {
  22079. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22080. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22081. }
  22082. else if (useLeftChan || (reader->numChannels == 1))
  22083. {
  22084. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22085. chans[1] = 0;
  22086. }
  22087. else if (useRightChan)
  22088. {
  22089. chans[0] = 0;
  22090. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22091. }
  22092. chans[2] = 0;
  22093. reader->read (chans, 2, readerStartSample, numSamples, true);
  22094. if (! reader->usesFloatingPointData)
  22095. {
  22096. for (int j = 0; j < 2; ++j)
  22097. {
  22098. float* const d = reinterpret_cast <float*> (chans[j]);
  22099. if (d != 0)
  22100. {
  22101. const float multiplier = 1.0f / 0x7fffffff;
  22102. for (int i = 0; i < numSamples; ++i)
  22103. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22104. }
  22105. }
  22106. }
  22107. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22108. {
  22109. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22110. memcpy (getSampleData (1, startSample),
  22111. getSampleData (0, startSample),
  22112. sizeof (float) * numSamples);
  22113. }
  22114. }
  22115. }
  22116. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22117. const int startSample,
  22118. const int numSamples) const
  22119. {
  22120. jassert (writer != 0);
  22121. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22122. }
  22123. END_JUCE_NAMESPACE
  22124. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22125. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22126. BEGIN_JUCE_NAMESPACE
  22127. IIRFilter::IIRFilter()
  22128. : active (false)
  22129. {
  22130. reset();
  22131. }
  22132. IIRFilter::IIRFilter (const IIRFilter& other)
  22133. : active (other.active)
  22134. {
  22135. const ScopedLock sl (other.processLock);
  22136. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22137. reset();
  22138. }
  22139. IIRFilter::~IIRFilter()
  22140. {
  22141. }
  22142. void IIRFilter::reset() throw()
  22143. {
  22144. const ScopedLock sl (processLock);
  22145. x1 = 0;
  22146. x2 = 0;
  22147. y1 = 0;
  22148. y2 = 0;
  22149. }
  22150. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22151. {
  22152. float out = coefficients[0] * in
  22153. + coefficients[1] * x1
  22154. + coefficients[2] * x2
  22155. - coefficients[4] * y1
  22156. - coefficients[5] * y2;
  22157. #if JUCE_INTEL
  22158. if (! (out < -1.0e-8 || out > 1.0e-8))
  22159. out = 0;
  22160. #endif
  22161. x2 = x1;
  22162. x1 = in;
  22163. y2 = y1;
  22164. y1 = out;
  22165. return out;
  22166. }
  22167. void IIRFilter::processSamples (float* const samples,
  22168. const int numSamples) throw()
  22169. {
  22170. const ScopedLock sl (processLock);
  22171. if (active)
  22172. {
  22173. for (int i = 0; i < numSamples; ++i)
  22174. {
  22175. const float in = samples[i];
  22176. float out = coefficients[0] * in
  22177. + coefficients[1] * x1
  22178. + coefficients[2] * x2
  22179. - coefficients[4] * y1
  22180. - coefficients[5] * y2;
  22181. #if JUCE_INTEL
  22182. if (! (out < -1.0e-8 || out > 1.0e-8))
  22183. out = 0;
  22184. #endif
  22185. x2 = x1;
  22186. x1 = in;
  22187. y2 = y1;
  22188. y1 = out;
  22189. samples[i] = out;
  22190. }
  22191. }
  22192. }
  22193. void IIRFilter::makeLowPass (const double sampleRate,
  22194. const double frequency) throw()
  22195. {
  22196. jassert (sampleRate > 0);
  22197. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22198. const double nSquared = n * n;
  22199. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22200. setCoefficients (c1,
  22201. c1 * 2.0f,
  22202. c1,
  22203. 1.0,
  22204. c1 * 2.0 * (1.0 - nSquared),
  22205. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22206. }
  22207. void IIRFilter::makeHighPass (const double sampleRate,
  22208. const double frequency) throw()
  22209. {
  22210. const double n = tan (double_Pi * frequency / sampleRate);
  22211. const double nSquared = n * n;
  22212. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22213. setCoefficients (c1,
  22214. c1 * -2.0f,
  22215. c1,
  22216. 1.0,
  22217. c1 * 2.0 * (nSquared - 1.0),
  22218. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22219. }
  22220. void IIRFilter::makeLowShelf (const double sampleRate,
  22221. const double cutOffFrequency,
  22222. const double Q,
  22223. const float gainFactor) throw()
  22224. {
  22225. jassert (sampleRate > 0);
  22226. jassert (Q > 0);
  22227. const double A = jmax (0.0f, gainFactor);
  22228. const double aminus1 = A - 1.0;
  22229. const double aplus1 = A + 1.0;
  22230. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22231. const double coso = std::cos (omega);
  22232. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22233. const double aminus1TimesCoso = aminus1 * coso;
  22234. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22235. A * 2.0 * (aminus1 - aplus1 * coso),
  22236. A * (aplus1 - aminus1TimesCoso - beta),
  22237. aplus1 + aminus1TimesCoso + beta,
  22238. -2.0 * (aminus1 + aplus1 * coso),
  22239. aplus1 + aminus1TimesCoso - beta);
  22240. }
  22241. void IIRFilter::makeHighShelf (const double sampleRate,
  22242. const double cutOffFrequency,
  22243. const double Q,
  22244. const float gainFactor) throw()
  22245. {
  22246. jassert (sampleRate > 0);
  22247. jassert (Q > 0);
  22248. const double A = jmax (0.0f, gainFactor);
  22249. const double aminus1 = A - 1.0;
  22250. const double aplus1 = A + 1.0;
  22251. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22252. const double coso = std::cos (omega);
  22253. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22254. const double aminus1TimesCoso = aminus1 * coso;
  22255. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22256. A * -2.0 * (aminus1 + aplus1 * coso),
  22257. A * (aplus1 + aminus1TimesCoso - beta),
  22258. aplus1 - aminus1TimesCoso + beta,
  22259. 2.0 * (aminus1 - aplus1 * coso),
  22260. aplus1 - aminus1TimesCoso - beta);
  22261. }
  22262. void IIRFilter::makeBandPass (const double sampleRate,
  22263. const double centreFrequency,
  22264. const double Q,
  22265. const float gainFactor) throw()
  22266. {
  22267. jassert (sampleRate > 0);
  22268. jassert (Q > 0);
  22269. const double A = jmax (0.0f, gainFactor);
  22270. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22271. const double alpha = 0.5 * std::sin (omega) / Q;
  22272. const double c2 = -2.0 * std::cos (omega);
  22273. const double alphaTimesA = alpha * A;
  22274. const double alphaOverA = alpha / A;
  22275. setCoefficients (1.0 + alphaTimesA,
  22276. c2,
  22277. 1.0 - alphaTimesA,
  22278. 1.0 + alphaOverA,
  22279. c2,
  22280. 1.0 - alphaOverA);
  22281. }
  22282. void IIRFilter::makeInactive() throw()
  22283. {
  22284. const ScopedLock sl (processLock);
  22285. active = false;
  22286. }
  22287. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22288. {
  22289. const ScopedLock sl (processLock);
  22290. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22291. active = other.active;
  22292. }
  22293. void IIRFilter::setCoefficients (double c1,
  22294. double c2,
  22295. double c3,
  22296. double c4,
  22297. double c5,
  22298. double c6) throw()
  22299. {
  22300. const double a = 1.0 / c4;
  22301. c1 *= a;
  22302. c2 *= a;
  22303. c3 *= a;
  22304. c5 *= a;
  22305. c6 *= a;
  22306. const ScopedLock sl (processLock);
  22307. coefficients[0] = (float) c1;
  22308. coefficients[1] = (float) c2;
  22309. coefficients[2] = (float) c3;
  22310. coefficients[3] = (float) c4;
  22311. coefficients[4] = (float) c5;
  22312. coefficients[5] = (float) c6;
  22313. active = true;
  22314. }
  22315. END_JUCE_NAMESPACE
  22316. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22317. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22318. BEGIN_JUCE_NAMESPACE
  22319. MidiBuffer::MidiBuffer() throw()
  22320. : bytesUsed (0)
  22321. {
  22322. }
  22323. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22324. : bytesUsed (0)
  22325. {
  22326. addEvent (message, 0);
  22327. }
  22328. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22329. : data (other.data),
  22330. bytesUsed (other.bytesUsed)
  22331. {
  22332. }
  22333. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22334. {
  22335. bytesUsed = other.bytesUsed;
  22336. data = other.data;
  22337. return *this;
  22338. }
  22339. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22340. {
  22341. data.swapWith (other.data);
  22342. swapVariables <int> (bytesUsed, other.bytesUsed);
  22343. }
  22344. MidiBuffer::~MidiBuffer()
  22345. {
  22346. }
  22347. inline uint8* MidiBuffer::getData() const throw()
  22348. {
  22349. return static_cast <uint8*> (data.getData());
  22350. }
  22351. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22352. {
  22353. return *static_cast <const int*> (d);
  22354. }
  22355. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22356. {
  22357. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22358. }
  22359. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22360. {
  22361. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22362. }
  22363. void MidiBuffer::clear() throw()
  22364. {
  22365. bytesUsed = 0;
  22366. }
  22367. void MidiBuffer::clear (const int startSample, const int numSamples)
  22368. {
  22369. uint8* const start = findEventAfter (getData(), startSample - 1);
  22370. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22371. if (end > start)
  22372. {
  22373. const int bytesToMove = bytesUsed - (int) (end - getData());
  22374. if (bytesToMove > 0)
  22375. memmove (start, end, bytesToMove);
  22376. bytesUsed -= (int) (end - start);
  22377. }
  22378. }
  22379. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22380. {
  22381. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22382. }
  22383. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22384. {
  22385. unsigned int byte = (unsigned int) *data;
  22386. int size = 0;
  22387. if (byte == 0xf0 || byte == 0xf7)
  22388. {
  22389. const uint8* d = data + 1;
  22390. while (d < data + maxBytes)
  22391. if (*d++ == 0xf7)
  22392. break;
  22393. size = (int) (d - data);
  22394. }
  22395. else if (byte == 0xff)
  22396. {
  22397. int n;
  22398. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22399. size = jmin (maxBytes, n + 2 + bytesLeft);
  22400. }
  22401. else if (byte >= 0x80)
  22402. {
  22403. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22404. }
  22405. return size;
  22406. }
  22407. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22408. {
  22409. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22410. if (numBytes > 0)
  22411. {
  22412. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22413. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22414. uint8* d = findEventAfter (getData(), sampleNumber);
  22415. const int bytesToMove = bytesUsed - (int) (d - getData());
  22416. if (bytesToMove > 0)
  22417. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22418. *reinterpret_cast <int*> (d) = sampleNumber;
  22419. d += sizeof (int);
  22420. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22421. d += sizeof (uint16);
  22422. memcpy (d, newData, numBytes);
  22423. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22424. }
  22425. }
  22426. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22427. const int startSample,
  22428. const int numSamples,
  22429. const int sampleDeltaToAdd)
  22430. {
  22431. Iterator i (otherBuffer);
  22432. i.setNextSamplePosition (startSample);
  22433. const uint8* eventData;
  22434. int eventSize, position;
  22435. while (i.getNextEvent (eventData, eventSize, position)
  22436. && (position < startSample + numSamples || numSamples < 0))
  22437. {
  22438. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22439. }
  22440. }
  22441. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22442. {
  22443. data.ensureSize (minimumNumBytes);
  22444. }
  22445. bool MidiBuffer::isEmpty() const throw()
  22446. {
  22447. return bytesUsed == 0;
  22448. }
  22449. int MidiBuffer::getNumEvents() const throw()
  22450. {
  22451. int n = 0;
  22452. const uint8* d = getData();
  22453. const uint8* const end = d + bytesUsed;
  22454. while (d < end)
  22455. {
  22456. d += getEventTotalSize (d);
  22457. ++n;
  22458. }
  22459. return n;
  22460. }
  22461. int MidiBuffer::getFirstEventTime() const throw()
  22462. {
  22463. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22464. }
  22465. int MidiBuffer::getLastEventTime() const throw()
  22466. {
  22467. if (bytesUsed == 0)
  22468. return 0;
  22469. const uint8* d = getData();
  22470. const uint8* const endData = d + bytesUsed;
  22471. for (;;)
  22472. {
  22473. const uint8* const nextOne = d + getEventTotalSize (d);
  22474. if (nextOne >= endData)
  22475. return getEventTime (d);
  22476. d = nextOne;
  22477. }
  22478. }
  22479. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22480. {
  22481. const uint8* const endData = getData() + bytesUsed;
  22482. while (d < endData && getEventTime (d) <= samplePosition)
  22483. d += getEventTotalSize (d);
  22484. return d;
  22485. }
  22486. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22487. : buffer (buffer_),
  22488. data (buffer_.getData())
  22489. {
  22490. }
  22491. MidiBuffer::Iterator::~Iterator() throw()
  22492. {
  22493. }
  22494. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22495. {
  22496. data = buffer.getData();
  22497. const uint8* dataEnd = data + buffer.bytesUsed;
  22498. while (data < dataEnd && getEventTime (data) < samplePosition)
  22499. data += getEventTotalSize (data);
  22500. }
  22501. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22502. {
  22503. if (data >= buffer.getData() + buffer.bytesUsed)
  22504. return false;
  22505. samplePosition = getEventTime (data);
  22506. numBytes = getEventDataSize (data);
  22507. data += sizeof (int) + sizeof (uint16);
  22508. midiData = data;
  22509. data += numBytes;
  22510. return true;
  22511. }
  22512. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22513. {
  22514. if (data >= buffer.getData() + buffer.bytesUsed)
  22515. return false;
  22516. samplePosition = getEventTime (data);
  22517. const int numBytes = getEventDataSize (data);
  22518. data += sizeof (int) + sizeof (uint16);
  22519. result = MidiMessage (data, numBytes, samplePosition);
  22520. data += numBytes;
  22521. return true;
  22522. }
  22523. END_JUCE_NAMESPACE
  22524. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22525. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22526. BEGIN_JUCE_NAMESPACE
  22527. namespace MidiFileHelpers
  22528. {
  22529. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22530. {
  22531. unsigned int buffer = v & 0x7F;
  22532. while ((v >>= 7) != 0)
  22533. {
  22534. buffer <<= 8;
  22535. buffer |= ((v & 0x7F) | 0x80);
  22536. }
  22537. for (;;)
  22538. {
  22539. out.writeByte ((char) buffer);
  22540. if (buffer & 0x80)
  22541. buffer >>= 8;
  22542. else
  22543. break;
  22544. }
  22545. }
  22546. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22547. {
  22548. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22549. data += 4;
  22550. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22551. {
  22552. bool ok = false;
  22553. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22554. {
  22555. for (int i = 0; i < 8; ++i)
  22556. {
  22557. ch = ByteOrder::bigEndianInt (data);
  22558. data += 4;
  22559. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22560. {
  22561. ok = true;
  22562. break;
  22563. }
  22564. }
  22565. }
  22566. if (! ok)
  22567. return false;
  22568. }
  22569. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22570. data += 4;
  22571. fileType = (short) ByteOrder::bigEndianShort (data);
  22572. data += 2;
  22573. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22574. data += 2;
  22575. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22576. data += 2;
  22577. bytesRemaining -= 6;
  22578. data += bytesRemaining;
  22579. return true;
  22580. }
  22581. static double convertTicksToSeconds (const double time,
  22582. const MidiMessageSequence& tempoEvents,
  22583. const int timeFormat)
  22584. {
  22585. if (timeFormat > 0)
  22586. {
  22587. int numer = 4, denom = 4;
  22588. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22589. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22590. double secsPerTick = 0.5 * tickLen;
  22591. const int numEvents = tempoEvents.getNumEvents();
  22592. for (int i = 0; i < numEvents; ++i)
  22593. {
  22594. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22595. if (time <= m.getTimeStamp())
  22596. break;
  22597. if (timeFormat > 0)
  22598. {
  22599. correctedTempoTime = correctedTempoTime
  22600. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22601. }
  22602. else
  22603. {
  22604. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22605. }
  22606. tempoTime = m.getTimeStamp();
  22607. if (m.isTempoMetaEvent())
  22608. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22609. else if (m.isTimeSignatureMetaEvent())
  22610. m.getTimeSignatureInfo (numer, denom);
  22611. while (i + 1 < numEvents)
  22612. {
  22613. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22614. if (m2.getTimeStamp() == tempoTime)
  22615. {
  22616. ++i;
  22617. if (m2.isTempoMetaEvent())
  22618. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22619. else if (m2.isTimeSignatureMetaEvent())
  22620. m2.getTimeSignatureInfo (numer, denom);
  22621. }
  22622. else
  22623. {
  22624. break;
  22625. }
  22626. }
  22627. }
  22628. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22629. }
  22630. else
  22631. {
  22632. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22633. }
  22634. }
  22635. // a comparator that puts all the note-offs before note-ons that have the same time
  22636. struct Sorter
  22637. {
  22638. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22639. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22640. {
  22641. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22642. if (diff == 0)
  22643. {
  22644. if (first->message.isNoteOff() && second->message.isNoteOn())
  22645. return -1;
  22646. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22647. return 1;
  22648. else
  22649. return 0;
  22650. }
  22651. else
  22652. {
  22653. return (diff > 0) ? 1 : -1;
  22654. }
  22655. }
  22656. };
  22657. }
  22658. MidiFile::MidiFile()
  22659. : timeFormat ((short) (unsigned short) 0xe728)
  22660. {
  22661. }
  22662. MidiFile::~MidiFile()
  22663. {
  22664. clear();
  22665. }
  22666. void MidiFile::clear()
  22667. {
  22668. tracks.clear();
  22669. }
  22670. int MidiFile::getNumTracks() const throw()
  22671. {
  22672. return tracks.size();
  22673. }
  22674. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22675. {
  22676. return tracks [index];
  22677. }
  22678. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22679. {
  22680. tracks.add (new MidiMessageSequence (trackSequence));
  22681. }
  22682. short MidiFile::getTimeFormat() const throw()
  22683. {
  22684. return timeFormat;
  22685. }
  22686. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22687. {
  22688. timeFormat = (short) ticks;
  22689. }
  22690. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22691. const int subframeResolution) throw()
  22692. {
  22693. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22694. }
  22695. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22696. {
  22697. for (int i = tracks.size(); --i >= 0;)
  22698. {
  22699. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22700. for (int j = 0; j < numEvents; ++j)
  22701. {
  22702. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22703. if (m.isTempoMetaEvent())
  22704. tempoChangeEvents.addEvent (m);
  22705. }
  22706. }
  22707. }
  22708. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22709. {
  22710. for (int i = tracks.size(); --i >= 0;)
  22711. {
  22712. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22713. for (int j = 0; j < numEvents; ++j)
  22714. {
  22715. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22716. if (m.isTimeSignatureMetaEvent())
  22717. timeSigEvents.addEvent (m);
  22718. }
  22719. }
  22720. }
  22721. double MidiFile::getLastTimestamp() const
  22722. {
  22723. double t = 0.0;
  22724. for (int i = tracks.size(); --i >= 0;)
  22725. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22726. return t;
  22727. }
  22728. bool MidiFile::readFrom (InputStream& sourceStream)
  22729. {
  22730. clear();
  22731. MemoryBlock data;
  22732. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22733. // (put a sanity-check on the file size, as midi files are generally small)
  22734. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22735. {
  22736. size_t size = data.getSize();
  22737. const uint8* d = static_cast <const uint8*> (data.getData());
  22738. short fileType, expectedTracks;
  22739. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22740. {
  22741. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22742. int track = 0;
  22743. while (size > 0 && track < expectedTracks)
  22744. {
  22745. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22746. d += 4;
  22747. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22748. d += 4;
  22749. if (chunkSize <= 0)
  22750. break;
  22751. if (size < 0)
  22752. return false;
  22753. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22754. {
  22755. readNextTrack (d, chunkSize);
  22756. }
  22757. size -= chunkSize + 8;
  22758. d += chunkSize;
  22759. ++track;
  22760. }
  22761. return true;
  22762. }
  22763. }
  22764. return false;
  22765. }
  22766. void MidiFile::readNextTrack (const uint8* data, int size)
  22767. {
  22768. double time = 0;
  22769. char lastStatusByte = 0;
  22770. MidiMessageSequence result;
  22771. while (size > 0)
  22772. {
  22773. int bytesUsed;
  22774. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22775. data += bytesUsed;
  22776. size -= bytesUsed;
  22777. time += delay;
  22778. int messSize = 0;
  22779. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22780. if (messSize <= 0)
  22781. break;
  22782. size -= messSize;
  22783. data += messSize;
  22784. result.addEvent (mm);
  22785. const char firstByte = *(mm.getRawData());
  22786. if ((firstByte & 0xf0) != 0xf0)
  22787. lastStatusByte = firstByte;
  22788. }
  22789. // use a sort that puts all the note-offs before note-ons that have the same time
  22790. MidiFileHelpers::Sorter sorter;
  22791. result.list.sort (sorter, true);
  22792. result.updateMatchedPairs();
  22793. addTrack (result);
  22794. }
  22795. void MidiFile::convertTimestampTicksToSeconds()
  22796. {
  22797. MidiMessageSequence tempoEvents;
  22798. findAllTempoEvents (tempoEvents);
  22799. findAllTimeSigEvents (tempoEvents);
  22800. for (int i = 0; i < tracks.size(); ++i)
  22801. {
  22802. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22803. for (int j = ms.getNumEvents(); --j >= 0;)
  22804. {
  22805. MidiMessage& m = ms.getEventPointer(j)->message;
  22806. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22807. tempoEvents,
  22808. timeFormat));
  22809. }
  22810. }
  22811. }
  22812. bool MidiFile::writeTo (OutputStream& out)
  22813. {
  22814. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22815. out.writeIntBigEndian (6);
  22816. out.writeShortBigEndian (1); // type
  22817. out.writeShortBigEndian ((short) tracks.size());
  22818. out.writeShortBigEndian (timeFormat);
  22819. for (int i = 0; i < tracks.size(); ++i)
  22820. writeTrack (out, i);
  22821. out.flush();
  22822. return true;
  22823. }
  22824. void MidiFile::writeTrack (OutputStream& mainOut,
  22825. const int trackNum)
  22826. {
  22827. MemoryOutputStream out;
  22828. const MidiMessageSequence& ms = *tracks[trackNum];
  22829. int lastTick = 0;
  22830. char lastStatusByte = 0;
  22831. for (int i = 0; i < ms.getNumEvents(); ++i)
  22832. {
  22833. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22834. const int tick = roundToInt (mm.getTimeStamp());
  22835. const int delta = jmax (0, tick - lastTick);
  22836. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22837. lastTick = tick;
  22838. const char statusByte = *(mm.getRawData());
  22839. if ((statusByte == lastStatusByte)
  22840. && ((statusByte & 0xf0) != 0xf0)
  22841. && i > 0
  22842. && mm.getRawDataSize() > 1)
  22843. {
  22844. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22845. }
  22846. else
  22847. {
  22848. out.write (mm.getRawData(), mm.getRawDataSize());
  22849. }
  22850. lastStatusByte = statusByte;
  22851. }
  22852. out.writeByte (0);
  22853. const MidiMessage m (MidiMessage::endOfTrack());
  22854. out.write (m.getRawData(),
  22855. m.getRawDataSize());
  22856. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22857. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22858. mainOut.write (out.getData(), (int) out.getDataSize());
  22859. }
  22860. END_JUCE_NAMESPACE
  22861. /*** End of inlined file: juce_MidiFile.cpp ***/
  22862. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22863. BEGIN_JUCE_NAMESPACE
  22864. MidiKeyboardState::MidiKeyboardState()
  22865. {
  22866. zerostruct (noteStates);
  22867. }
  22868. MidiKeyboardState::~MidiKeyboardState()
  22869. {
  22870. }
  22871. void MidiKeyboardState::reset()
  22872. {
  22873. const ScopedLock sl (lock);
  22874. zerostruct (noteStates);
  22875. eventsToAdd.clear();
  22876. }
  22877. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22878. {
  22879. jassert (midiChannel >= 0 && midiChannel <= 16);
  22880. return ((unsigned int) n) < 128
  22881. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22882. }
  22883. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22884. {
  22885. return ((unsigned int) n) < 128
  22886. && (noteStates[n] & midiChannelMask) != 0;
  22887. }
  22888. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22889. {
  22890. jassert (midiChannel >= 0 && midiChannel <= 16);
  22891. jassert (((unsigned int) midiNoteNumber) < 128);
  22892. const ScopedLock sl (lock);
  22893. if (((unsigned int) midiNoteNumber) < 128)
  22894. {
  22895. const int timeNow = (int) Time::getMillisecondCounter();
  22896. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22897. eventsToAdd.clear (0, timeNow - 500);
  22898. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22899. }
  22900. }
  22901. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22902. {
  22903. if (((unsigned int) midiNoteNumber) < 128)
  22904. {
  22905. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22906. for (int i = listeners.size(); --i >= 0;)
  22907. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22908. }
  22909. }
  22910. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22911. {
  22912. const ScopedLock sl (lock);
  22913. if (isNoteOn (midiChannel, midiNoteNumber))
  22914. {
  22915. const int timeNow = (int) Time::getMillisecondCounter();
  22916. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22917. eventsToAdd.clear (0, timeNow - 500);
  22918. noteOffInternal (midiChannel, midiNoteNumber);
  22919. }
  22920. }
  22921. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22922. {
  22923. if (isNoteOn (midiChannel, midiNoteNumber))
  22924. {
  22925. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22926. for (int i = listeners.size(); --i >= 0;)
  22927. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22928. }
  22929. }
  22930. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22931. {
  22932. const ScopedLock sl (lock);
  22933. if (midiChannel <= 0)
  22934. {
  22935. for (int i = 1; i <= 16; ++i)
  22936. allNotesOff (i);
  22937. }
  22938. else
  22939. {
  22940. for (int i = 0; i < 128; ++i)
  22941. noteOff (midiChannel, i);
  22942. }
  22943. }
  22944. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22945. {
  22946. if (message.isNoteOn())
  22947. {
  22948. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22949. }
  22950. else if (message.isNoteOff())
  22951. {
  22952. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22953. }
  22954. else if (message.isAllNotesOff())
  22955. {
  22956. for (int i = 0; i < 128; ++i)
  22957. noteOffInternal (message.getChannel(), i);
  22958. }
  22959. }
  22960. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22961. const int startSample,
  22962. const int numSamples,
  22963. const bool injectIndirectEvents)
  22964. {
  22965. MidiBuffer::Iterator i (buffer);
  22966. MidiMessage message (0xf4, 0.0);
  22967. int time;
  22968. const ScopedLock sl (lock);
  22969. while (i.getNextEvent (message, time))
  22970. processNextMidiEvent (message);
  22971. if (injectIndirectEvents)
  22972. {
  22973. MidiBuffer::Iterator i2 (eventsToAdd);
  22974. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22975. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22976. while (i2.getNextEvent (message, time))
  22977. {
  22978. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22979. buffer.addEvent (message, startSample + pos);
  22980. }
  22981. }
  22982. eventsToAdd.clear();
  22983. }
  22984. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22985. {
  22986. const ScopedLock sl (lock);
  22987. listeners.addIfNotAlreadyThere (listener);
  22988. }
  22989. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22990. {
  22991. const ScopedLock sl (lock);
  22992. listeners.removeValue (listener);
  22993. }
  22994. END_JUCE_NAMESPACE
  22995. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22996. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22997. BEGIN_JUCE_NAMESPACE
  22998. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22999. {
  23000. numBytesUsed = 0;
  23001. int v = 0;
  23002. int i;
  23003. do
  23004. {
  23005. i = (int) *data++;
  23006. if (++numBytesUsed > 6)
  23007. break;
  23008. v = (v << 7) + (i & 0x7f);
  23009. } while (i & 0x80);
  23010. return v;
  23011. }
  23012. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23013. {
  23014. // this method only works for valid starting bytes of a short midi message
  23015. jassert (firstByte >= 0x80
  23016. && firstByte != 0xf0
  23017. && firstByte != 0xf7);
  23018. static const char messageLengths[] =
  23019. {
  23020. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23021. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23022. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23023. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23024. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23025. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23026. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23027. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23028. };
  23029. return messageLengths [firstByte & 0x7f];
  23030. }
  23031. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23032. : timeStamp (t),
  23033. size (dataSize)
  23034. {
  23035. jassert (dataSize > 0);
  23036. if (dataSize <= 4)
  23037. data = static_cast<uint8*> (preallocatedData.asBytes);
  23038. else
  23039. data = new uint8 [dataSize];
  23040. memcpy (data, d, dataSize);
  23041. // check that the length matches the data..
  23042. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23043. }
  23044. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23045. : timeStamp (t),
  23046. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23047. size (1)
  23048. {
  23049. data[0] = (uint8) byte1;
  23050. // check that the length matches the data..
  23051. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23052. }
  23053. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23054. : timeStamp (t),
  23055. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23056. size (2)
  23057. {
  23058. data[0] = (uint8) byte1;
  23059. data[1] = (uint8) byte2;
  23060. // check that the length matches the data..
  23061. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23062. }
  23063. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23064. : timeStamp (t),
  23065. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23066. size (3)
  23067. {
  23068. data[0] = (uint8) byte1;
  23069. data[1] = (uint8) byte2;
  23070. data[2] = (uint8) byte3;
  23071. // check that the length matches the data..
  23072. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23073. }
  23074. MidiMessage::MidiMessage (const MidiMessage& other)
  23075. : timeStamp (other.timeStamp),
  23076. size (other.size)
  23077. {
  23078. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23079. {
  23080. data = new uint8 [size];
  23081. memcpy (data, other.data, size);
  23082. }
  23083. else
  23084. {
  23085. data = static_cast<uint8*> (preallocatedData.asBytes);
  23086. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23087. }
  23088. }
  23089. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23090. : timeStamp (newTimeStamp),
  23091. size (other.size)
  23092. {
  23093. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23094. {
  23095. data = new uint8 [size];
  23096. memcpy (data, other.data, size);
  23097. }
  23098. else
  23099. {
  23100. data = static_cast<uint8*> (preallocatedData.asBytes);
  23101. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23102. }
  23103. }
  23104. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23105. : timeStamp (t),
  23106. data (static_cast<uint8*> (preallocatedData.asBytes))
  23107. {
  23108. const uint8* src = static_cast <const uint8*> (src_);
  23109. unsigned int byte = (unsigned int) *src;
  23110. if (byte < 0x80)
  23111. {
  23112. byte = (unsigned int) (uint8) lastStatusByte;
  23113. numBytesUsed = -1;
  23114. }
  23115. else
  23116. {
  23117. numBytesUsed = 0;
  23118. --sz;
  23119. ++src;
  23120. }
  23121. if (byte >= 0x80)
  23122. {
  23123. if (byte == 0xf0)
  23124. {
  23125. const uint8* d = src;
  23126. while (d < src + sz)
  23127. {
  23128. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23129. {
  23130. if (*d == 0xf7) // include an 0xf7 if we hit one
  23131. ++d;
  23132. break;
  23133. }
  23134. ++d;
  23135. }
  23136. size = 1 + (int) (d - src);
  23137. data = new uint8 [size];
  23138. *data = (uint8) byte;
  23139. memcpy (data + 1, src, size - 1);
  23140. }
  23141. else if (byte == 0xff)
  23142. {
  23143. int n;
  23144. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23145. size = jmin (sz + 1, n + 2 + bytesLeft);
  23146. data = new uint8 [size];
  23147. *data = (uint8) byte;
  23148. memcpy (data + 1, src, size - 1);
  23149. }
  23150. else
  23151. {
  23152. preallocatedData.asInt32 = 0;
  23153. size = getMessageLengthFromFirstByte ((uint8) byte);
  23154. data[0] = (uint8) byte;
  23155. if (size > 1)
  23156. {
  23157. data[1] = src[0];
  23158. if (size > 2)
  23159. data[2] = src[1];
  23160. }
  23161. }
  23162. numBytesUsed += size;
  23163. }
  23164. else
  23165. {
  23166. preallocatedData.asInt32 = 0;
  23167. size = 0;
  23168. }
  23169. }
  23170. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23171. {
  23172. if (this != &other)
  23173. {
  23174. timeStamp = other.timeStamp;
  23175. size = other.size;
  23176. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23177. delete[] data;
  23178. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23179. {
  23180. data = new uint8 [size];
  23181. memcpy (data, other.data, size);
  23182. }
  23183. else
  23184. {
  23185. data = static_cast<uint8*> (preallocatedData.asBytes);
  23186. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23187. }
  23188. }
  23189. return *this;
  23190. }
  23191. MidiMessage::~MidiMessage()
  23192. {
  23193. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23194. delete[] data;
  23195. }
  23196. int MidiMessage::getChannel() const throw()
  23197. {
  23198. if ((data[0] & 0xf0) != 0xf0)
  23199. return (data[0] & 0xf) + 1;
  23200. else
  23201. return 0;
  23202. }
  23203. bool MidiMessage::isForChannel (const int channel) const throw()
  23204. {
  23205. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23206. return ((data[0] & 0xf) == channel - 1)
  23207. && ((data[0] & 0xf0) != 0xf0);
  23208. }
  23209. void MidiMessage::setChannel (const int channel) throw()
  23210. {
  23211. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23212. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23213. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23214. | (uint8)(channel - 1));
  23215. }
  23216. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23217. {
  23218. return ((data[0] & 0xf0) == 0x90)
  23219. && (returnTrueForVelocity0 || data[2] != 0);
  23220. }
  23221. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23222. {
  23223. return ((data[0] & 0xf0) == 0x80)
  23224. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23225. }
  23226. bool MidiMessage::isNoteOnOrOff() const throw()
  23227. {
  23228. const int d = data[0] & 0xf0;
  23229. return (d == 0x90) || (d == 0x80);
  23230. }
  23231. int MidiMessage::getNoteNumber() const throw()
  23232. {
  23233. return data[1];
  23234. }
  23235. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23236. {
  23237. if (isNoteOnOrOff())
  23238. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23239. }
  23240. uint8 MidiMessage::getVelocity() const throw()
  23241. {
  23242. if (isNoteOnOrOff())
  23243. return data[2];
  23244. else
  23245. return 0;
  23246. }
  23247. float MidiMessage::getFloatVelocity() const throw()
  23248. {
  23249. return getVelocity() * (1.0f / 127.0f);
  23250. }
  23251. void MidiMessage::setVelocity (const float newVelocity) throw()
  23252. {
  23253. if (isNoteOnOrOff())
  23254. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23255. }
  23256. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23257. {
  23258. if (isNoteOnOrOff())
  23259. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23260. }
  23261. bool MidiMessage::isAftertouch() const throw()
  23262. {
  23263. return (data[0] & 0xf0) == 0xa0;
  23264. }
  23265. int MidiMessage::getAfterTouchValue() const throw()
  23266. {
  23267. return data[2];
  23268. }
  23269. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23270. const int noteNum,
  23271. const int aftertouchValue) throw()
  23272. {
  23273. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23274. jassert (((unsigned int) noteNum) <= 127);
  23275. jassert (((unsigned int) aftertouchValue) <= 127);
  23276. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23277. noteNum & 0x7f,
  23278. aftertouchValue & 0x7f);
  23279. }
  23280. bool MidiMessage::isChannelPressure() const throw()
  23281. {
  23282. return (data[0] & 0xf0) == 0xd0;
  23283. }
  23284. int MidiMessage::getChannelPressureValue() const throw()
  23285. {
  23286. jassert (isChannelPressure());
  23287. return data[1];
  23288. }
  23289. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23290. const int pressure) throw()
  23291. {
  23292. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23293. jassert (((unsigned int) pressure) <= 127);
  23294. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23295. pressure & 0x7f);
  23296. }
  23297. bool MidiMessage::isProgramChange() const throw()
  23298. {
  23299. return (data[0] & 0xf0) == 0xc0;
  23300. }
  23301. int MidiMessage::getProgramChangeNumber() const throw()
  23302. {
  23303. return data[1];
  23304. }
  23305. const MidiMessage MidiMessage::programChange (const int channel,
  23306. const int programNumber) throw()
  23307. {
  23308. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23309. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23310. programNumber & 0x7f);
  23311. }
  23312. bool MidiMessage::isPitchWheel() const throw()
  23313. {
  23314. return (data[0] & 0xf0) == 0xe0;
  23315. }
  23316. int MidiMessage::getPitchWheelValue() const throw()
  23317. {
  23318. return data[1] | (data[2] << 7);
  23319. }
  23320. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23321. const int position) throw()
  23322. {
  23323. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23324. jassert (((unsigned int) position) <= 0x3fff);
  23325. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23326. position & 127,
  23327. (position >> 7) & 127);
  23328. }
  23329. bool MidiMessage::isController() const throw()
  23330. {
  23331. return (data[0] & 0xf0) == 0xb0;
  23332. }
  23333. int MidiMessage::getControllerNumber() const throw()
  23334. {
  23335. jassert (isController());
  23336. return data[1];
  23337. }
  23338. int MidiMessage::getControllerValue() const throw()
  23339. {
  23340. jassert (isController());
  23341. return data[2];
  23342. }
  23343. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23344. const int controllerType,
  23345. const int value) throw()
  23346. {
  23347. // the channel must be between 1 and 16 inclusive
  23348. jassert (channel > 0 && channel <= 16);
  23349. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23350. controllerType & 127,
  23351. value & 127);
  23352. }
  23353. const MidiMessage MidiMessage::noteOn (const int channel,
  23354. const int noteNumber,
  23355. const float velocity) throw()
  23356. {
  23357. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23358. }
  23359. const MidiMessage MidiMessage::noteOn (const int channel,
  23360. const int noteNumber,
  23361. const uint8 velocity) throw()
  23362. {
  23363. jassert (channel > 0 && channel <= 16);
  23364. jassert (((unsigned int) noteNumber) <= 127);
  23365. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23366. noteNumber & 127,
  23367. jlimit (0, 127, roundToInt (velocity)));
  23368. }
  23369. const MidiMessage MidiMessage::noteOff (const int channel,
  23370. const int noteNumber) throw()
  23371. {
  23372. jassert (channel > 0 && channel <= 16);
  23373. jassert (((unsigned int) noteNumber) <= 127);
  23374. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23375. }
  23376. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23377. {
  23378. return controllerEvent (channel, 123, 0);
  23379. }
  23380. bool MidiMessage::isAllNotesOff() const throw()
  23381. {
  23382. return (data[0] & 0xf0) == 0xb0
  23383. && data[1] == 123;
  23384. }
  23385. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23386. {
  23387. return controllerEvent (channel, 120, 0);
  23388. }
  23389. bool MidiMessage::isAllSoundOff() const throw()
  23390. {
  23391. return (data[0] & 0xf0) == 0xb0
  23392. && data[1] == 120;
  23393. }
  23394. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23395. {
  23396. return controllerEvent (channel, 121, 0);
  23397. }
  23398. const MidiMessage MidiMessage::masterVolume (const float volume)
  23399. {
  23400. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23401. uint8 buf[8];
  23402. buf[0] = 0xf0;
  23403. buf[1] = 0x7f;
  23404. buf[2] = 0x7f;
  23405. buf[3] = 0x04;
  23406. buf[4] = 0x01;
  23407. buf[5] = (uint8) (vol & 0x7f);
  23408. buf[6] = (uint8) (vol >> 7);
  23409. buf[7] = 0xf7;
  23410. return MidiMessage (buf, 8);
  23411. }
  23412. bool MidiMessage::isSysEx() const throw()
  23413. {
  23414. return *data == 0xf0;
  23415. }
  23416. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23417. {
  23418. MemoryBlock mm (dataSize + 2);
  23419. uint8* const m = static_cast <uint8*> (mm.getData());
  23420. m[0] = 0xf0;
  23421. memcpy (m + 1, sysexData, dataSize);
  23422. m[dataSize + 1] = 0xf7;
  23423. return MidiMessage (m, dataSize + 2);
  23424. }
  23425. const uint8* MidiMessage::getSysExData() const throw()
  23426. {
  23427. return (isSysEx()) ? getRawData() + 1 : 0;
  23428. }
  23429. int MidiMessage::getSysExDataSize() const throw()
  23430. {
  23431. return (isSysEx()) ? size - 2 : 0;
  23432. }
  23433. bool MidiMessage::isMetaEvent() const throw()
  23434. {
  23435. return *data == 0xff;
  23436. }
  23437. bool MidiMessage::isActiveSense() const throw()
  23438. {
  23439. return *data == 0xfe;
  23440. }
  23441. int MidiMessage::getMetaEventType() const throw()
  23442. {
  23443. if (*data != 0xff)
  23444. return -1;
  23445. else
  23446. return data[1];
  23447. }
  23448. int MidiMessage::getMetaEventLength() const throw()
  23449. {
  23450. if (*data == 0xff)
  23451. {
  23452. int n;
  23453. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23454. }
  23455. return 0;
  23456. }
  23457. const uint8* MidiMessage::getMetaEventData() const throw()
  23458. {
  23459. int n;
  23460. const uint8* d = data + 2;
  23461. readVariableLengthVal (d, n);
  23462. return d + n;
  23463. }
  23464. bool MidiMessage::isTrackMetaEvent() const throw()
  23465. {
  23466. return getMetaEventType() == 0;
  23467. }
  23468. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23469. {
  23470. return getMetaEventType() == 47;
  23471. }
  23472. bool MidiMessage::isTextMetaEvent() const throw()
  23473. {
  23474. const int t = getMetaEventType();
  23475. return t > 0 && t < 16;
  23476. }
  23477. const String MidiMessage::getTextFromTextMetaEvent() const
  23478. {
  23479. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23480. }
  23481. bool MidiMessage::isTrackNameEvent() const throw()
  23482. {
  23483. return (data[1] == 3)
  23484. && (*data == 0xff);
  23485. }
  23486. bool MidiMessage::isTempoMetaEvent() const throw()
  23487. {
  23488. return (data[1] == 81)
  23489. && (*data == 0xff);
  23490. }
  23491. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23492. {
  23493. return (data[1] == 0x20)
  23494. && (*data == 0xff)
  23495. && (data[2] == 1);
  23496. }
  23497. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23498. {
  23499. return data[3] + 1;
  23500. }
  23501. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23502. {
  23503. if (! isTempoMetaEvent())
  23504. return 0.0;
  23505. const uint8* const d = getMetaEventData();
  23506. return (((unsigned int) d[0] << 16)
  23507. | ((unsigned int) d[1] << 8)
  23508. | d[2])
  23509. / 1000000.0;
  23510. }
  23511. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23512. {
  23513. if (timeFormat > 0)
  23514. {
  23515. if (! isTempoMetaEvent())
  23516. return 0.5 / timeFormat;
  23517. return getTempoSecondsPerQuarterNote() / timeFormat;
  23518. }
  23519. else
  23520. {
  23521. const int frameCode = (-timeFormat) >> 8;
  23522. double framesPerSecond;
  23523. switch (frameCode)
  23524. {
  23525. case 24: framesPerSecond = 24.0; break;
  23526. case 25: framesPerSecond = 25.0; break;
  23527. case 29: framesPerSecond = 29.97; break;
  23528. case 30: framesPerSecond = 30.0; break;
  23529. default: framesPerSecond = 30.0; break;
  23530. }
  23531. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23532. }
  23533. }
  23534. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23535. {
  23536. uint8 d[8];
  23537. d[0] = 0xff;
  23538. d[1] = 81;
  23539. d[2] = 3;
  23540. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23541. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23542. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23543. return MidiMessage (d, 6, 0.0);
  23544. }
  23545. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23546. {
  23547. return (data[1] == 0x58)
  23548. && (*data == (uint8) 0xff);
  23549. }
  23550. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23551. {
  23552. if (isTimeSignatureMetaEvent())
  23553. {
  23554. const uint8* const d = getMetaEventData();
  23555. numerator = d[0];
  23556. denominator = 1 << d[1];
  23557. }
  23558. else
  23559. {
  23560. numerator = 4;
  23561. denominator = 4;
  23562. }
  23563. }
  23564. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23565. {
  23566. uint8 d[8];
  23567. d[0] = 0xff;
  23568. d[1] = 0x58;
  23569. d[2] = 0x04;
  23570. d[3] = (uint8) numerator;
  23571. int n = 1;
  23572. int powerOfTwo = 0;
  23573. while (n < denominator)
  23574. {
  23575. n <<= 1;
  23576. ++powerOfTwo;
  23577. }
  23578. d[4] = (uint8) powerOfTwo;
  23579. d[5] = 0x01;
  23580. d[6] = 96;
  23581. return MidiMessage (d, 7, 0.0);
  23582. }
  23583. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23584. {
  23585. uint8 d[8];
  23586. d[0] = 0xff;
  23587. d[1] = 0x20;
  23588. d[2] = 0x01;
  23589. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23590. return MidiMessage (d, 4, 0.0);
  23591. }
  23592. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23593. {
  23594. return getMetaEventType() == 89;
  23595. }
  23596. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23597. {
  23598. return (int) *getMetaEventData();
  23599. }
  23600. const MidiMessage MidiMessage::endOfTrack() throw()
  23601. {
  23602. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23603. }
  23604. bool MidiMessage::isSongPositionPointer() const throw()
  23605. {
  23606. return *data == 0xf2;
  23607. }
  23608. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23609. {
  23610. return data[1] | (data[2] << 7);
  23611. }
  23612. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23613. {
  23614. return MidiMessage (0xf2,
  23615. positionInMidiBeats & 127,
  23616. (positionInMidiBeats >> 7) & 127);
  23617. }
  23618. bool MidiMessage::isMidiStart() const throw()
  23619. {
  23620. return *data == 0xfa;
  23621. }
  23622. const MidiMessage MidiMessage::midiStart() throw()
  23623. {
  23624. return MidiMessage (0xfa);
  23625. }
  23626. bool MidiMessage::isMidiContinue() const throw()
  23627. {
  23628. return *data == 0xfb;
  23629. }
  23630. const MidiMessage MidiMessage::midiContinue() throw()
  23631. {
  23632. return MidiMessage (0xfb);
  23633. }
  23634. bool MidiMessage::isMidiStop() const throw()
  23635. {
  23636. return *data == 0xfc;
  23637. }
  23638. const MidiMessage MidiMessage::midiStop() throw()
  23639. {
  23640. return MidiMessage (0xfc);
  23641. }
  23642. bool MidiMessage::isMidiClock() const throw()
  23643. {
  23644. return *data == 0xf8;
  23645. }
  23646. const MidiMessage MidiMessage::midiClock() throw()
  23647. {
  23648. return MidiMessage (0xf8);
  23649. }
  23650. bool MidiMessage::isQuarterFrame() const throw()
  23651. {
  23652. return *data == 0xf1;
  23653. }
  23654. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23655. {
  23656. return ((int) data[1]) >> 4;
  23657. }
  23658. int MidiMessage::getQuarterFrameValue() const throw()
  23659. {
  23660. return ((int) data[1]) & 0x0f;
  23661. }
  23662. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23663. const int value) throw()
  23664. {
  23665. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23666. }
  23667. bool MidiMessage::isFullFrame() const throw()
  23668. {
  23669. return data[0] == 0xf0
  23670. && data[1] == 0x7f
  23671. && size >= 10
  23672. && data[3] == 0x01
  23673. && data[4] == 0x01;
  23674. }
  23675. void MidiMessage::getFullFrameParameters (int& hours,
  23676. int& minutes,
  23677. int& seconds,
  23678. int& frames,
  23679. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23680. {
  23681. jassert (isFullFrame());
  23682. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23683. hours = data[5] & 0x1f;
  23684. minutes = data[6];
  23685. seconds = data[7];
  23686. frames = data[8];
  23687. }
  23688. const MidiMessage MidiMessage::fullFrame (const int hours,
  23689. const int minutes,
  23690. const int seconds,
  23691. const int frames,
  23692. MidiMessage::SmpteTimecodeType timecodeType)
  23693. {
  23694. uint8 d[10];
  23695. d[0] = 0xf0;
  23696. d[1] = 0x7f;
  23697. d[2] = 0x7f;
  23698. d[3] = 0x01;
  23699. d[4] = 0x01;
  23700. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23701. d[6] = (uint8) minutes;
  23702. d[7] = (uint8) seconds;
  23703. d[8] = (uint8) frames;
  23704. d[9] = 0xf7;
  23705. return MidiMessage (d, 10, 0.0);
  23706. }
  23707. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23708. {
  23709. return data[0] == 0xf0
  23710. && data[1] == 0x7f
  23711. && data[3] == 0x06
  23712. && size > 5;
  23713. }
  23714. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23715. {
  23716. jassert (isMidiMachineControlMessage());
  23717. return (MidiMachineControlCommand) data[4];
  23718. }
  23719. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23720. {
  23721. uint8 d[6];
  23722. d[0] = 0xf0;
  23723. d[1] = 0x7f;
  23724. d[2] = 0x00;
  23725. d[3] = 0x06;
  23726. d[4] = (uint8) command;
  23727. d[5] = 0xf7;
  23728. return MidiMessage (d, 6, 0.0);
  23729. }
  23730. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23731. int& minutes,
  23732. int& seconds,
  23733. int& frames) const throw()
  23734. {
  23735. if (size >= 12
  23736. && data[0] == 0xf0
  23737. && data[1] == 0x7f
  23738. && data[3] == 0x06
  23739. && data[4] == 0x44
  23740. && data[5] == 0x06
  23741. && data[6] == 0x01)
  23742. {
  23743. hours = data[7] % 24; // (that some machines send out hours > 24)
  23744. minutes = data[8];
  23745. seconds = data[9];
  23746. frames = data[10];
  23747. return true;
  23748. }
  23749. return false;
  23750. }
  23751. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23752. int minutes,
  23753. int seconds,
  23754. int frames)
  23755. {
  23756. uint8 d[12];
  23757. d[0] = 0xf0;
  23758. d[1] = 0x7f;
  23759. d[2] = 0x00;
  23760. d[3] = 0x06;
  23761. d[4] = 0x44;
  23762. d[5] = 0x06;
  23763. d[6] = 0x01;
  23764. d[7] = (uint8) hours;
  23765. d[8] = (uint8) minutes;
  23766. d[9] = (uint8) seconds;
  23767. d[10] = (uint8) frames;
  23768. d[11] = 0xf7;
  23769. return MidiMessage (d, 12, 0.0);
  23770. }
  23771. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23772. {
  23773. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23774. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23775. if (((unsigned int) note) < 128)
  23776. {
  23777. String s (useSharps ? sharpNoteNames [note % 12]
  23778. : flatNoteNames [note % 12]);
  23779. if (includeOctaveNumber)
  23780. s << (note / 12 + (octaveNumForMiddleC - 5));
  23781. return s;
  23782. }
  23783. return String::empty;
  23784. }
  23785. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23786. {
  23787. noteNumber -= 12 * 6 + 9; // now 0 = A
  23788. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23789. }
  23790. const String MidiMessage::getGMInstrumentName (const int n)
  23791. {
  23792. const char* names[] =
  23793. {
  23794. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23795. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23796. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23797. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23798. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23799. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23800. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23801. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23802. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23803. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23804. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23805. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23806. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23807. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23808. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23809. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23810. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23811. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23812. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23813. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23814. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23815. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23816. "Applause", "Gunshot"
  23817. };
  23818. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23819. }
  23820. const String MidiMessage::getGMInstrumentBankName (const int n)
  23821. {
  23822. const char* names[] =
  23823. {
  23824. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23825. "Bass", "Strings", "Ensemble", "Brass",
  23826. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23827. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23828. };
  23829. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23830. }
  23831. const String MidiMessage::getRhythmInstrumentName (const int n)
  23832. {
  23833. const char* names[] =
  23834. {
  23835. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23836. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23837. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23838. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23839. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23840. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23841. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23842. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23843. "Mute Triangle", "Open Triangle"
  23844. };
  23845. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23846. }
  23847. const String MidiMessage::getControllerName (const int n)
  23848. {
  23849. const char* names[] =
  23850. {
  23851. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23852. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23853. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23854. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23855. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23856. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23857. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23858. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23859. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23860. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23861. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23862. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23863. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23864. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23865. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23866. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23867. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23868. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23869. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23871. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23872. "Poly Operation"
  23873. };
  23874. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23875. }
  23876. END_JUCE_NAMESPACE
  23877. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23878. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23879. BEGIN_JUCE_NAMESPACE
  23880. MidiMessageCollector::MidiMessageCollector()
  23881. : lastCallbackTime (0),
  23882. sampleRate (44100.0001)
  23883. {
  23884. }
  23885. MidiMessageCollector::~MidiMessageCollector()
  23886. {
  23887. }
  23888. void MidiMessageCollector::reset (const double sampleRate_)
  23889. {
  23890. jassert (sampleRate_ > 0);
  23891. const ScopedLock sl (midiCallbackLock);
  23892. sampleRate = sampleRate_;
  23893. incomingMessages.clear();
  23894. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23895. }
  23896. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23897. {
  23898. // you need to call reset() to set the correct sample rate before using this object
  23899. jassert (sampleRate != 44100.0001);
  23900. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23901. // for details of what the number should be.
  23902. jassert (message.getTimeStamp() != 0);
  23903. const ScopedLock sl (midiCallbackLock);
  23904. const int sampleNumber
  23905. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23906. incomingMessages.addEvent (message, sampleNumber);
  23907. // if the messages don't get used for over a second, we'd better
  23908. // get rid of any old ones to avoid the queue getting too big
  23909. if (sampleNumber > sampleRate)
  23910. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23911. }
  23912. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23913. const int numSamples)
  23914. {
  23915. // you need to call reset() to set the correct sample rate before using this object
  23916. jassert (sampleRate != 44100.0001);
  23917. const double timeNow = Time::getMillisecondCounterHiRes();
  23918. const double msElapsed = timeNow - lastCallbackTime;
  23919. const ScopedLock sl (midiCallbackLock);
  23920. lastCallbackTime = timeNow;
  23921. if (! incomingMessages.isEmpty())
  23922. {
  23923. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23924. int startSample = 0;
  23925. int scale = 1 << 16;
  23926. const uint8* midiData;
  23927. int numBytes, samplePosition;
  23928. MidiBuffer::Iterator iter (incomingMessages);
  23929. if (numSourceSamples > numSamples)
  23930. {
  23931. // if our list of events is longer than the buffer we're being
  23932. // asked for, scale them down to squeeze them all in..
  23933. const int maxBlockLengthToUse = numSamples << 5;
  23934. if (numSourceSamples > maxBlockLengthToUse)
  23935. {
  23936. startSample = numSourceSamples - maxBlockLengthToUse;
  23937. numSourceSamples = maxBlockLengthToUse;
  23938. iter.setNextSamplePosition (startSample);
  23939. }
  23940. scale = (numSamples << 10) / numSourceSamples;
  23941. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23942. {
  23943. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23944. destBuffer.addEvent (midiData, numBytes,
  23945. jlimit (0, numSamples - 1, samplePosition));
  23946. }
  23947. }
  23948. else
  23949. {
  23950. // if our event list is shorter than the number we need, put them
  23951. // towards the end of the buffer
  23952. startSample = numSamples - numSourceSamples;
  23953. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23954. {
  23955. destBuffer.addEvent (midiData, numBytes,
  23956. jlimit (0, numSamples - 1, samplePosition + startSample));
  23957. }
  23958. }
  23959. incomingMessages.clear();
  23960. }
  23961. }
  23962. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23963. {
  23964. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23965. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23966. addMessageToQueue (m);
  23967. }
  23968. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23969. {
  23970. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23971. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23972. addMessageToQueue (m);
  23973. }
  23974. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23975. {
  23976. addMessageToQueue (message);
  23977. }
  23978. END_JUCE_NAMESPACE
  23979. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23980. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23981. BEGIN_JUCE_NAMESPACE
  23982. MidiMessageSequence::MidiMessageSequence()
  23983. {
  23984. }
  23985. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23986. {
  23987. list.ensureStorageAllocated (other.list.size());
  23988. for (int i = 0; i < other.list.size(); ++i)
  23989. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23990. }
  23991. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23992. {
  23993. MidiMessageSequence otherCopy (other);
  23994. swapWith (otherCopy);
  23995. return *this;
  23996. }
  23997. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23998. {
  23999. list.swapWithArray (other.list);
  24000. }
  24001. MidiMessageSequence::~MidiMessageSequence()
  24002. {
  24003. }
  24004. void MidiMessageSequence::clear()
  24005. {
  24006. list.clear();
  24007. }
  24008. int MidiMessageSequence::getNumEvents() const
  24009. {
  24010. return list.size();
  24011. }
  24012. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24013. {
  24014. return list [index];
  24015. }
  24016. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24017. {
  24018. const MidiEventHolder* const meh = list [index];
  24019. if (meh != 0 && meh->noteOffObject != 0)
  24020. return meh->noteOffObject->message.getTimeStamp();
  24021. else
  24022. return 0.0;
  24023. }
  24024. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24025. {
  24026. const MidiEventHolder* const meh = list [index];
  24027. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24028. }
  24029. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24030. {
  24031. return list.indexOf (event);
  24032. }
  24033. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24034. {
  24035. const int numEvents = list.size();
  24036. int i;
  24037. for (i = 0; i < numEvents; ++i)
  24038. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24039. break;
  24040. return i;
  24041. }
  24042. double MidiMessageSequence::getStartTime() const
  24043. {
  24044. if (list.size() > 0)
  24045. return list.getUnchecked(0)->message.getTimeStamp();
  24046. else
  24047. return 0;
  24048. }
  24049. double MidiMessageSequence::getEndTime() const
  24050. {
  24051. if (list.size() > 0)
  24052. return list.getLast()->message.getTimeStamp();
  24053. else
  24054. return 0;
  24055. }
  24056. double MidiMessageSequence::getEventTime (const int index) const
  24057. {
  24058. if (((unsigned int) index) < (unsigned int) list.size())
  24059. return list.getUnchecked (index)->message.getTimeStamp();
  24060. return 0.0;
  24061. }
  24062. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24063. double timeAdjustment)
  24064. {
  24065. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24066. timeAdjustment += newMessage.getTimeStamp();
  24067. newOne->message.setTimeStamp (timeAdjustment);
  24068. int i;
  24069. for (i = list.size(); --i >= 0;)
  24070. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24071. break;
  24072. list.insert (i + 1, newOne);
  24073. }
  24074. void MidiMessageSequence::deleteEvent (const int index,
  24075. const bool deleteMatchingNoteUp)
  24076. {
  24077. if (((unsigned int) index) < (unsigned int) list.size())
  24078. {
  24079. if (deleteMatchingNoteUp)
  24080. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24081. list.remove (index);
  24082. }
  24083. }
  24084. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24085. double timeAdjustment,
  24086. double firstAllowableTime,
  24087. double endOfAllowableDestTimes)
  24088. {
  24089. firstAllowableTime -= timeAdjustment;
  24090. endOfAllowableDestTimes -= timeAdjustment;
  24091. for (int i = 0; i < other.list.size(); ++i)
  24092. {
  24093. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24094. const double t = m.getTimeStamp();
  24095. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24096. {
  24097. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24098. newOne->message.setTimeStamp (timeAdjustment + t);
  24099. list.add (newOne);
  24100. }
  24101. }
  24102. sort();
  24103. }
  24104. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24105. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24106. {
  24107. const double diff = first->message.getTimeStamp()
  24108. - second->message.getTimeStamp();
  24109. return (diff > 0) - (diff < 0);
  24110. }
  24111. void MidiMessageSequence::sort()
  24112. {
  24113. list.sort (*this, true);
  24114. }
  24115. void MidiMessageSequence::updateMatchedPairs()
  24116. {
  24117. for (int i = 0; i < list.size(); ++i)
  24118. {
  24119. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24120. if (m1.isNoteOn())
  24121. {
  24122. list.getUnchecked(i)->noteOffObject = 0;
  24123. const int note = m1.getNoteNumber();
  24124. const int chan = m1.getChannel();
  24125. const int len = list.size();
  24126. for (int j = i + 1; j < len; ++j)
  24127. {
  24128. const MidiMessage& m = list.getUnchecked(j)->message;
  24129. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24130. {
  24131. if (m.isNoteOff())
  24132. {
  24133. list.getUnchecked(i)->noteOffObject = list[j];
  24134. break;
  24135. }
  24136. else if (m.isNoteOn())
  24137. {
  24138. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24139. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24140. list.getUnchecked(i)->noteOffObject = list[j];
  24141. break;
  24142. }
  24143. }
  24144. }
  24145. }
  24146. }
  24147. }
  24148. void MidiMessageSequence::addTimeToMessages (const double delta)
  24149. {
  24150. for (int i = list.size(); --i >= 0;)
  24151. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24152. + delta);
  24153. }
  24154. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24155. MidiMessageSequence& destSequence,
  24156. const bool alsoIncludeMetaEvents) const
  24157. {
  24158. for (int i = 0; i < list.size(); ++i)
  24159. {
  24160. const MidiMessage& mm = list.getUnchecked(i)->message;
  24161. if (mm.isForChannel (channelNumberToExtract)
  24162. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24163. {
  24164. destSequence.addEvent (mm);
  24165. }
  24166. }
  24167. }
  24168. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24169. {
  24170. for (int i = 0; i < list.size(); ++i)
  24171. {
  24172. const MidiMessage& mm = list.getUnchecked(i)->message;
  24173. if (mm.isSysEx())
  24174. destSequence.addEvent (mm);
  24175. }
  24176. }
  24177. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24178. {
  24179. for (int i = list.size(); --i >= 0;)
  24180. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24181. list.remove(i);
  24182. }
  24183. void MidiMessageSequence::deleteSysExMessages()
  24184. {
  24185. for (int i = list.size(); --i >= 0;)
  24186. if (list.getUnchecked(i)->message.isSysEx())
  24187. list.remove(i);
  24188. }
  24189. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24190. const double time,
  24191. OwnedArray<MidiMessage>& dest)
  24192. {
  24193. bool doneProg = false;
  24194. bool donePitchWheel = false;
  24195. Array <int> doneControllers;
  24196. doneControllers.ensureStorageAllocated (32);
  24197. for (int i = list.size(); --i >= 0;)
  24198. {
  24199. const MidiMessage& mm = list.getUnchecked(i)->message;
  24200. if (mm.isForChannel (channelNumber)
  24201. && mm.getTimeStamp() <= time)
  24202. {
  24203. if (mm.isProgramChange())
  24204. {
  24205. if (! doneProg)
  24206. {
  24207. dest.add (new MidiMessage (mm, 0.0));
  24208. doneProg = true;
  24209. }
  24210. }
  24211. else if (mm.isController())
  24212. {
  24213. if (! doneControllers.contains (mm.getControllerNumber()))
  24214. {
  24215. dest.add (new MidiMessage (mm, 0.0));
  24216. doneControllers.add (mm.getControllerNumber());
  24217. }
  24218. }
  24219. else if (mm.isPitchWheel())
  24220. {
  24221. if (! donePitchWheel)
  24222. {
  24223. dest.add (new MidiMessage (mm, 0.0));
  24224. donePitchWheel = true;
  24225. }
  24226. }
  24227. }
  24228. }
  24229. }
  24230. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24231. : message (message_),
  24232. noteOffObject (0)
  24233. {
  24234. }
  24235. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24236. {
  24237. }
  24238. END_JUCE_NAMESPACE
  24239. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24240. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24241. BEGIN_JUCE_NAMESPACE
  24242. AudioPluginFormat::AudioPluginFormat() throw()
  24243. {
  24244. }
  24245. AudioPluginFormat::~AudioPluginFormat()
  24246. {
  24247. }
  24248. END_JUCE_NAMESPACE
  24249. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24250. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24251. BEGIN_JUCE_NAMESPACE
  24252. AudioPluginFormatManager::AudioPluginFormatManager()
  24253. {
  24254. }
  24255. AudioPluginFormatManager::~AudioPluginFormatManager()
  24256. {
  24257. clearSingletonInstance();
  24258. }
  24259. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24260. void AudioPluginFormatManager::addDefaultFormats()
  24261. {
  24262. #if JUCE_DEBUG
  24263. // you should only call this method once!
  24264. for (int i = formats.size(); --i >= 0;)
  24265. {
  24266. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24267. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24268. #endif
  24269. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24270. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24271. #endif
  24272. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24273. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24274. #endif
  24275. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24276. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24277. #endif
  24278. }
  24279. #endif
  24280. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24281. formats.add (new AudioUnitPluginFormat());
  24282. #endif
  24283. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24284. formats.add (new VSTPluginFormat());
  24285. #endif
  24286. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24287. formats.add (new DirectXPluginFormat());
  24288. #endif
  24289. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24290. formats.add (new LADSPAPluginFormat());
  24291. #endif
  24292. }
  24293. int AudioPluginFormatManager::getNumFormats()
  24294. {
  24295. return formats.size();
  24296. }
  24297. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24298. {
  24299. return formats [index];
  24300. }
  24301. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24302. {
  24303. formats.add (format);
  24304. }
  24305. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24306. String& errorMessage) const
  24307. {
  24308. AudioPluginInstance* result = 0;
  24309. for (int i = 0; i < formats.size(); ++i)
  24310. {
  24311. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24312. if (result != 0)
  24313. break;
  24314. }
  24315. if (result == 0)
  24316. {
  24317. if (! doesPluginStillExist (description))
  24318. errorMessage = TRANS ("This plug-in file no longer exists");
  24319. else
  24320. errorMessage = TRANS ("This plug-in failed to load correctly");
  24321. }
  24322. return result;
  24323. }
  24324. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24325. {
  24326. for (int i = 0; i < formats.size(); ++i)
  24327. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24328. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24329. return false;
  24330. }
  24331. END_JUCE_NAMESPACE
  24332. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24333. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24334. #define JUCE_PLUGIN_HOST 1
  24335. BEGIN_JUCE_NAMESPACE
  24336. AudioPluginInstance::AudioPluginInstance()
  24337. {
  24338. }
  24339. AudioPluginInstance::~AudioPluginInstance()
  24340. {
  24341. }
  24342. END_JUCE_NAMESPACE
  24343. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24344. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24345. BEGIN_JUCE_NAMESPACE
  24346. KnownPluginList::KnownPluginList()
  24347. {
  24348. }
  24349. KnownPluginList::~KnownPluginList()
  24350. {
  24351. }
  24352. void KnownPluginList::clear()
  24353. {
  24354. if (types.size() > 0)
  24355. {
  24356. types.clear();
  24357. sendChangeMessage (this);
  24358. }
  24359. }
  24360. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24361. {
  24362. for (int i = 0; i < types.size(); ++i)
  24363. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24364. return types.getUnchecked(i);
  24365. return 0;
  24366. }
  24367. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24368. {
  24369. for (int i = 0; i < types.size(); ++i)
  24370. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24371. return types.getUnchecked(i);
  24372. return 0;
  24373. }
  24374. bool KnownPluginList::addType (const PluginDescription& type)
  24375. {
  24376. for (int i = types.size(); --i >= 0;)
  24377. {
  24378. if (types.getUnchecked(i)->isDuplicateOf (type))
  24379. {
  24380. // strange - found a duplicate plugin with different info..
  24381. jassert (types.getUnchecked(i)->name == type.name);
  24382. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24383. *types.getUnchecked(i) = type;
  24384. return false;
  24385. }
  24386. }
  24387. types.add (new PluginDescription (type));
  24388. sendChangeMessage (this);
  24389. return true;
  24390. }
  24391. void KnownPluginList::removeType (const int index)
  24392. {
  24393. types.remove (index);
  24394. sendChangeMessage (this);
  24395. }
  24396. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24397. {
  24398. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24399. return File (fileOrIdentifier).getLastModificationTime();
  24400. return Time (0);
  24401. }
  24402. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24403. {
  24404. return t1 != t2 || t1 == Time (0);
  24405. }
  24406. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24407. {
  24408. if (getTypeForFile (fileOrIdentifier) == 0)
  24409. return false;
  24410. for (int i = types.size(); --i >= 0;)
  24411. {
  24412. const PluginDescription* const d = types.getUnchecked(i);
  24413. if (d->fileOrIdentifier == fileOrIdentifier
  24414. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24415. {
  24416. return false;
  24417. }
  24418. }
  24419. return true;
  24420. }
  24421. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24422. const bool dontRescanIfAlreadyInList,
  24423. OwnedArray <PluginDescription>& typesFound,
  24424. AudioPluginFormat& format)
  24425. {
  24426. bool addedOne = false;
  24427. if (dontRescanIfAlreadyInList
  24428. && getTypeForFile (fileOrIdentifier) != 0)
  24429. {
  24430. bool needsRescanning = false;
  24431. for (int i = types.size(); --i >= 0;)
  24432. {
  24433. const PluginDescription* const d = types.getUnchecked(i);
  24434. if (d->fileOrIdentifier == fileOrIdentifier)
  24435. {
  24436. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24437. needsRescanning = true;
  24438. else
  24439. typesFound.add (new PluginDescription (*d));
  24440. }
  24441. }
  24442. if (! needsRescanning)
  24443. return false;
  24444. }
  24445. OwnedArray <PluginDescription> found;
  24446. format.findAllTypesForFile (found, fileOrIdentifier);
  24447. for (int i = 0; i < found.size(); ++i)
  24448. {
  24449. PluginDescription* const desc = found.getUnchecked(i);
  24450. jassert (desc != 0);
  24451. if (addType (*desc))
  24452. addedOne = true;
  24453. typesFound.add (new PluginDescription (*desc));
  24454. }
  24455. return addedOne;
  24456. }
  24457. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24458. OwnedArray <PluginDescription>& typesFound)
  24459. {
  24460. for (int i = 0; i < files.size(); ++i)
  24461. {
  24462. bool loaded = false;
  24463. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24464. {
  24465. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24466. if (scanAndAddFile (files[i], true, typesFound, *format))
  24467. loaded = true;
  24468. }
  24469. if (! loaded)
  24470. {
  24471. const File f (files[i]);
  24472. if (f.isDirectory())
  24473. {
  24474. StringArray s;
  24475. {
  24476. Array<File> subFiles;
  24477. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24478. for (int j = 0; j < subFiles.size(); ++j)
  24479. s.add (subFiles.getReference(j).getFullPathName());
  24480. }
  24481. scanAndAddDragAndDroppedFiles (s, typesFound);
  24482. }
  24483. }
  24484. }
  24485. }
  24486. class PluginSorter
  24487. {
  24488. public:
  24489. KnownPluginList::SortMethod method;
  24490. PluginSorter() throw() {}
  24491. int compareElements (const PluginDescription* const first,
  24492. const PluginDescription* const second) const
  24493. {
  24494. int diff = 0;
  24495. if (method == KnownPluginList::sortByCategory)
  24496. diff = first->category.compareLexicographically (second->category);
  24497. else if (method == KnownPluginList::sortByManufacturer)
  24498. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24499. else if (method == KnownPluginList::sortByFileSystemLocation)
  24500. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24501. .upToLastOccurrenceOf ("/", false, false)
  24502. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24503. .upToLastOccurrenceOf ("/", false, false));
  24504. if (diff == 0)
  24505. diff = first->name.compareLexicographically (second->name);
  24506. return diff;
  24507. }
  24508. };
  24509. void KnownPluginList::sort (const SortMethod method)
  24510. {
  24511. if (method != defaultOrder)
  24512. {
  24513. PluginSorter sorter;
  24514. sorter.method = method;
  24515. types.sort (sorter, true);
  24516. sendChangeMessage (this);
  24517. }
  24518. }
  24519. XmlElement* KnownPluginList::createXml() const
  24520. {
  24521. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24522. for (int i = 0; i < types.size(); ++i)
  24523. e->addChildElement (types.getUnchecked(i)->createXml());
  24524. return e;
  24525. }
  24526. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24527. {
  24528. clear();
  24529. if (xml.hasTagName ("KNOWNPLUGINS"))
  24530. {
  24531. forEachXmlChildElement (xml, e)
  24532. {
  24533. PluginDescription info;
  24534. if (info.loadFromXml (*e))
  24535. addType (info);
  24536. }
  24537. }
  24538. }
  24539. const int menuIdBase = 0x324503f4;
  24540. // This is used to turn a bunch of paths into a nested menu structure.
  24541. struct PluginFilesystemTree
  24542. {
  24543. private:
  24544. String folder;
  24545. OwnedArray <PluginFilesystemTree> subFolders;
  24546. Array <PluginDescription*> plugins;
  24547. void addPlugin (PluginDescription* const pd, const String& path)
  24548. {
  24549. if (path.isEmpty())
  24550. {
  24551. plugins.add (pd);
  24552. }
  24553. else
  24554. {
  24555. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24556. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24557. for (int i = subFolders.size(); --i >= 0;)
  24558. {
  24559. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24560. {
  24561. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24562. return;
  24563. }
  24564. }
  24565. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24566. newFolder->folder = firstSubFolder;
  24567. subFolders.add (newFolder);
  24568. newFolder->addPlugin (pd, remainingPath);
  24569. }
  24570. }
  24571. // removes any deeply nested folders that don't contain any actual plugins
  24572. void optimise()
  24573. {
  24574. for (int i = subFolders.size(); --i >= 0;)
  24575. {
  24576. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24577. sub->optimise();
  24578. if (sub->plugins.size() == 0)
  24579. {
  24580. for (int j = 0; j < sub->subFolders.size(); ++j)
  24581. subFolders.add (sub->subFolders.getUnchecked(j));
  24582. sub->subFolders.clear (false);
  24583. subFolders.remove (i);
  24584. }
  24585. }
  24586. }
  24587. public:
  24588. void buildTree (const Array <PluginDescription*>& allPlugins)
  24589. {
  24590. for (int i = 0; i < allPlugins.size(); ++i)
  24591. {
  24592. String path (allPlugins.getUnchecked(i)
  24593. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24594. .upToLastOccurrenceOf ("/", false, false));
  24595. if (path.substring (1, 2) == ":")
  24596. path = path.substring (2);
  24597. addPlugin (allPlugins.getUnchecked(i), path);
  24598. }
  24599. optimise();
  24600. }
  24601. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24602. {
  24603. int i;
  24604. for (i = 0; i < subFolders.size(); ++i)
  24605. {
  24606. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24607. PopupMenu subMenu;
  24608. sub->addToMenu (subMenu, allPlugins);
  24609. #if JUCE_MAC
  24610. // avoid the special AU formatting nonsense on Mac..
  24611. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24612. #else
  24613. m.addSubMenu (sub->folder, subMenu);
  24614. #endif
  24615. }
  24616. for (i = 0; i < plugins.size(); ++i)
  24617. {
  24618. PluginDescription* const plugin = plugins.getUnchecked(i);
  24619. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24620. plugin->name, true, false);
  24621. }
  24622. }
  24623. };
  24624. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24625. {
  24626. Array <PluginDescription*> sorted;
  24627. {
  24628. PluginSorter sorter;
  24629. sorter.method = sortMethod;
  24630. for (int i = 0; i < types.size(); ++i)
  24631. sorted.addSorted (sorter, types.getUnchecked(i));
  24632. }
  24633. if (sortMethod == sortByCategory
  24634. || sortMethod == sortByManufacturer)
  24635. {
  24636. String lastSubMenuName;
  24637. PopupMenu sub;
  24638. for (int i = 0; i < sorted.size(); ++i)
  24639. {
  24640. const PluginDescription* const pd = sorted.getUnchecked(i);
  24641. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24642. : pd->manufacturerName);
  24643. if (! thisSubMenuName.containsNonWhitespaceChars())
  24644. thisSubMenuName = "Other";
  24645. if (thisSubMenuName != lastSubMenuName)
  24646. {
  24647. if (sub.getNumItems() > 0)
  24648. {
  24649. menu.addSubMenu (lastSubMenuName, sub);
  24650. sub.clear();
  24651. }
  24652. lastSubMenuName = thisSubMenuName;
  24653. }
  24654. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24655. }
  24656. if (sub.getNumItems() > 0)
  24657. menu.addSubMenu (lastSubMenuName, sub);
  24658. }
  24659. else if (sortMethod == sortByFileSystemLocation)
  24660. {
  24661. PluginFilesystemTree root;
  24662. root.buildTree (sorted);
  24663. root.addToMenu (menu, types);
  24664. }
  24665. else
  24666. {
  24667. for (int i = 0; i < sorted.size(); ++i)
  24668. {
  24669. const PluginDescription* const pd = sorted.getUnchecked(i);
  24670. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24671. }
  24672. }
  24673. }
  24674. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24675. {
  24676. const int i = menuResultCode - menuIdBase;
  24677. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24678. }
  24679. END_JUCE_NAMESPACE
  24680. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24681. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24682. BEGIN_JUCE_NAMESPACE
  24683. PluginDescription::PluginDescription()
  24684. : uid (0),
  24685. isInstrument (false),
  24686. numInputChannels (0),
  24687. numOutputChannels (0)
  24688. {
  24689. }
  24690. PluginDescription::~PluginDescription()
  24691. {
  24692. }
  24693. PluginDescription::PluginDescription (const PluginDescription& other)
  24694. : name (other.name),
  24695. pluginFormatName (other.pluginFormatName),
  24696. category (other.category),
  24697. manufacturerName (other.manufacturerName),
  24698. version (other.version),
  24699. fileOrIdentifier (other.fileOrIdentifier),
  24700. lastFileModTime (other.lastFileModTime),
  24701. uid (other.uid),
  24702. isInstrument (other.isInstrument),
  24703. numInputChannels (other.numInputChannels),
  24704. numOutputChannels (other.numOutputChannels)
  24705. {
  24706. }
  24707. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24708. {
  24709. name = other.name;
  24710. pluginFormatName = other.pluginFormatName;
  24711. category = other.category;
  24712. manufacturerName = other.manufacturerName;
  24713. version = other.version;
  24714. fileOrIdentifier = other.fileOrIdentifier;
  24715. uid = other.uid;
  24716. isInstrument = other.isInstrument;
  24717. lastFileModTime = other.lastFileModTime;
  24718. numInputChannels = other.numInputChannels;
  24719. numOutputChannels = other.numOutputChannels;
  24720. return *this;
  24721. }
  24722. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24723. {
  24724. return fileOrIdentifier == other.fileOrIdentifier
  24725. && uid == other.uid;
  24726. }
  24727. const String PluginDescription::createIdentifierString() const
  24728. {
  24729. return pluginFormatName
  24730. + "-" + name
  24731. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24732. + "-" + String::toHexString (uid);
  24733. }
  24734. XmlElement* PluginDescription::createXml() const
  24735. {
  24736. XmlElement* const e = new XmlElement ("PLUGIN");
  24737. e->setAttribute ("name", name);
  24738. e->setAttribute ("format", pluginFormatName);
  24739. e->setAttribute ("category", category);
  24740. e->setAttribute ("manufacturer", manufacturerName);
  24741. e->setAttribute ("version", version);
  24742. e->setAttribute ("file", fileOrIdentifier);
  24743. e->setAttribute ("uid", String::toHexString (uid));
  24744. e->setAttribute ("isInstrument", isInstrument);
  24745. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24746. e->setAttribute ("numInputs", numInputChannels);
  24747. e->setAttribute ("numOutputs", numOutputChannels);
  24748. return e;
  24749. }
  24750. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24751. {
  24752. if (xml.hasTagName ("PLUGIN"))
  24753. {
  24754. name = xml.getStringAttribute ("name");
  24755. pluginFormatName = xml.getStringAttribute ("format");
  24756. category = xml.getStringAttribute ("category");
  24757. manufacturerName = xml.getStringAttribute ("manufacturer");
  24758. version = xml.getStringAttribute ("version");
  24759. fileOrIdentifier = xml.getStringAttribute ("file");
  24760. uid = xml.getStringAttribute ("uid").getHexValue32();
  24761. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24762. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24763. numInputChannels = xml.getIntAttribute ("numInputs");
  24764. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24765. return true;
  24766. }
  24767. return false;
  24768. }
  24769. END_JUCE_NAMESPACE
  24770. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24771. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24772. BEGIN_JUCE_NAMESPACE
  24773. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24774. AudioPluginFormat& formatToLookFor,
  24775. FileSearchPath directoriesToSearch,
  24776. const bool recursive,
  24777. const File& deadMansPedalFile_)
  24778. : list (listToAddTo),
  24779. format (formatToLookFor),
  24780. deadMansPedalFile (deadMansPedalFile_),
  24781. nextIndex (0),
  24782. progress (0)
  24783. {
  24784. directoriesToSearch.removeRedundantPaths();
  24785. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24786. // If any plugins have crashed recently when being loaded, move them to the
  24787. // end of the list to give the others a chance to load correctly..
  24788. const StringArray crashedPlugins (getDeadMansPedalFile());
  24789. for (int i = 0; i < crashedPlugins.size(); ++i)
  24790. {
  24791. const String f = crashedPlugins[i];
  24792. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24793. if (f == filesOrIdentifiersToScan[j])
  24794. filesOrIdentifiersToScan.move (j, -1);
  24795. }
  24796. }
  24797. PluginDirectoryScanner::~PluginDirectoryScanner()
  24798. {
  24799. }
  24800. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24801. {
  24802. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24803. }
  24804. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24805. {
  24806. String file (filesOrIdentifiersToScan [nextIndex]);
  24807. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24808. {
  24809. OwnedArray <PluginDescription> typesFound;
  24810. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24811. StringArray crashedPlugins (getDeadMansPedalFile());
  24812. crashedPlugins.removeString (file);
  24813. crashedPlugins.add (file);
  24814. setDeadMansPedalFile (crashedPlugins);
  24815. list.scanAndAddFile (file,
  24816. dontRescanIfAlreadyInList,
  24817. typesFound,
  24818. format);
  24819. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24820. crashedPlugins.removeString (file);
  24821. setDeadMansPedalFile (crashedPlugins);
  24822. if (typesFound.size() == 0)
  24823. failedFiles.add (file);
  24824. }
  24825. return skipNextFile();
  24826. }
  24827. bool PluginDirectoryScanner::skipNextFile()
  24828. {
  24829. if (nextIndex >= filesOrIdentifiersToScan.size())
  24830. return false;
  24831. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24832. return nextIndex < filesOrIdentifiersToScan.size();
  24833. }
  24834. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24835. {
  24836. StringArray lines;
  24837. if (deadMansPedalFile != File::nonexistent)
  24838. {
  24839. lines.addLines (deadMansPedalFile.loadFileAsString());
  24840. lines.removeEmptyStrings();
  24841. }
  24842. return lines;
  24843. }
  24844. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24845. {
  24846. if (deadMansPedalFile != File::nonexistent)
  24847. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24848. }
  24849. END_JUCE_NAMESPACE
  24850. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24851. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24852. BEGIN_JUCE_NAMESPACE
  24853. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24854. const File& deadMansPedalFile_,
  24855. PropertiesFile* const propertiesToUse_)
  24856. : list (listToEdit),
  24857. deadMansPedalFile (deadMansPedalFile_),
  24858. propertiesToUse (propertiesToUse_)
  24859. {
  24860. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  24861. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  24862. optionsButton->addButtonListener (this);
  24863. optionsButton->setTriggeredOnMouseDown (true);
  24864. setSize (400, 600);
  24865. list.addChangeListener (this);
  24866. changeListenerCallback (0);
  24867. }
  24868. PluginListComponent::~PluginListComponent()
  24869. {
  24870. list.removeChangeListener (this);
  24871. deleteAllChildren();
  24872. }
  24873. void PluginListComponent::resized()
  24874. {
  24875. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  24876. optionsButton->changeWidthToFitText (24);
  24877. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  24878. }
  24879. void PluginListComponent::changeListenerCallback (void*)
  24880. {
  24881. listBox->updateContent();
  24882. listBox->repaint();
  24883. }
  24884. int PluginListComponent::getNumRows()
  24885. {
  24886. return list.getNumTypes();
  24887. }
  24888. void PluginListComponent::paintListBoxItem (int row,
  24889. Graphics& g,
  24890. int width, int height,
  24891. bool rowIsSelected)
  24892. {
  24893. if (rowIsSelected)
  24894. g.fillAll (findColour (TextEditor::highlightColourId));
  24895. const PluginDescription* const pd = list.getType (row);
  24896. if (pd != 0)
  24897. {
  24898. GlyphArrangement ga;
  24899. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24900. g.setColour (Colours::black);
  24901. ga.draw (g);
  24902. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24903. String desc;
  24904. desc << pd->pluginFormatName
  24905. << (pd->isInstrument ? " instrument" : " effect")
  24906. << " - "
  24907. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24908. << " / "
  24909. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24910. if (pd->manufacturerName.isNotEmpty())
  24911. desc << " - " << pd->manufacturerName;
  24912. if (pd->version.isNotEmpty())
  24913. desc << " - " << pd->version;
  24914. if (pd->category.isNotEmpty())
  24915. desc << " - category: '" << pd->category << '\'';
  24916. g.setColour (Colours::grey);
  24917. ga.clear();
  24918. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24919. ga.draw (g);
  24920. }
  24921. }
  24922. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24923. {
  24924. list.removeType (lastRowSelected);
  24925. }
  24926. void PluginListComponent::buttonClicked (Button* b)
  24927. {
  24928. if (optionsButton == b)
  24929. {
  24930. PopupMenu menu;
  24931. menu.addItem (1, TRANS("Clear list"));
  24932. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24933. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24934. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24935. menu.addSeparator();
  24936. menu.addItem (2, TRANS("Sort alphabetically"));
  24937. menu.addItem (3, TRANS("Sort by category"));
  24938. menu.addItem (4, TRANS("Sort by manufacturer"));
  24939. menu.addSeparator();
  24940. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24941. {
  24942. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24943. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24944. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24945. }
  24946. const int r = menu.showAt (optionsButton);
  24947. if (r == 1)
  24948. {
  24949. list.clear();
  24950. }
  24951. else if (r == 2)
  24952. {
  24953. list.sort (KnownPluginList::sortAlphabetically);
  24954. }
  24955. else if (r == 3)
  24956. {
  24957. list.sort (KnownPluginList::sortByCategory);
  24958. }
  24959. else if (r == 4)
  24960. {
  24961. list.sort (KnownPluginList::sortByManufacturer);
  24962. }
  24963. else if (r == 5)
  24964. {
  24965. const SparseSet <int> selected (listBox->getSelectedRows());
  24966. for (int i = list.getNumTypes(); --i >= 0;)
  24967. if (selected.contains (i))
  24968. list.removeType (i);
  24969. }
  24970. else if (r == 6)
  24971. {
  24972. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24973. if (desc != 0)
  24974. {
  24975. if (File (desc->fileOrIdentifier).existsAsFile())
  24976. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24977. }
  24978. }
  24979. else if (r == 7)
  24980. {
  24981. for (int i = list.getNumTypes(); --i >= 0;)
  24982. {
  24983. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24984. {
  24985. list.removeType (i);
  24986. }
  24987. }
  24988. }
  24989. else if (r != 0)
  24990. {
  24991. typeToScan = r - 10;
  24992. startTimer (1);
  24993. }
  24994. }
  24995. }
  24996. void PluginListComponent::timerCallback()
  24997. {
  24998. stopTimer();
  24999. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25000. }
  25001. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25002. {
  25003. return true;
  25004. }
  25005. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25006. {
  25007. OwnedArray <PluginDescription> typesFound;
  25008. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25009. }
  25010. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25011. {
  25012. if (format == 0)
  25013. return;
  25014. FileSearchPath path (format->getDefaultLocationsToSearch());
  25015. if (propertiesToUse != 0)
  25016. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25017. {
  25018. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25019. FileSearchPathListComponent pathList;
  25020. pathList.setSize (500, 300);
  25021. pathList.setPath (path);
  25022. aw.addCustomComponent (&pathList);
  25023. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25024. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25025. if (aw.runModalLoop() == 0)
  25026. return;
  25027. path = pathList.getPath();
  25028. }
  25029. if (propertiesToUse != 0)
  25030. {
  25031. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25032. propertiesToUse->saveIfNeeded();
  25033. }
  25034. double progress = 0.0;
  25035. AlertWindow aw (TRANS("Scanning for plugins..."),
  25036. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25037. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25038. aw.addProgressBarComponent (progress);
  25039. aw.enterModalState();
  25040. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25041. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25042. for (;;)
  25043. {
  25044. aw.setMessage (TRANS("Testing:\n\n")
  25045. + scanner.getNextPluginFileThatWillBeScanned());
  25046. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25047. if (! scanner.scanNextFile (true))
  25048. break;
  25049. if (! aw.isCurrentlyModal())
  25050. break;
  25051. progress = scanner.getProgress();
  25052. }
  25053. if (scanner.getFailedFiles().size() > 0)
  25054. {
  25055. StringArray shortNames;
  25056. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25057. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25058. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25059. TRANS("Scan complete"),
  25060. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25061. + shortNames.joinIntoString (", "));
  25062. }
  25063. }
  25064. END_JUCE_NAMESPACE
  25065. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25066. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25067. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25068. #include <AudioUnit/AudioUnit.h>
  25069. #include <AudioUnit/AUCocoaUIView.h>
  25070. #include <CoreAudioKit/AUGenericView.h>
  25071. #if JUCE_SUPPORT_CARBON
  25072. #include <AudioToolbox/AudioUnitUtilities.h>
  25073. #include <AudioUnit/AudioUnitCarbonView.h>
  25074. #endif
  25075. BEGIN_JUCE_NAMESPACE
  25076. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25077. #endif
  25078. #if JUCE_MAC
  25079. // Change this to disable logging of various activities
  25080. #ifndef AU_LOGGING
  25081. #define AU_LOGGING 1
  25082. #endif
  25083. #if AU_LOGGING
  25084. #define log(a) Logger::writeToLog(a);
  25085. #else
  25086. #define log(a)
  25087. #endif
  25088. namespace AudioUnitFormatHelpers
  25089. {
  25090. static int insideCallback = 0;
  25091. static const String osTypeToString (OSType type)
  25092. {
  25093. char s[4];
  25094. s[0] = (char) (((uint32) type) >> 24);
  25095. s[1] = (char) (((uint32) type) >> 16);
  25096. s[2] = (char) (((uint32) type) >> 8);
  25097. s[3] = (char) ((uint32) type);
  25098. return String (s, 4);
  25099. }
  25100. static OSType stringToOSType (const String& s1)
  25101. {
  25102. const String s (s1 + " ");
  25103. return (((OSType) (unsigned char) s[0]) << 24)
  25104. | (((OSType) (unsigned char) s[1]) << 16)
  25105. | (((OSType) (unsigned char) s[2]) << 8)
  25106. | ((OSType) (unsigned char) s[3]);
  25107. }
  25108. static const char* auIdentifierPrefix = "AudioUnit:";
  25109. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25110. {
  25111. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25112. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25113. String s (auIdentifierPrefix);
  25114. if (desc.componentType == kAudioUnitType_MusicDevice)
  25115. s << "Synths/";
  25116. else if (desc.componentType == kAudioUnitType_MusicEffect
  25117. || desc.componentType == kAudioUnitType_Effect)
  25118. s << "Effects/";
  25119. else if (desc.componentType == kAudioUnitType_Generator)
  25120. s << "Generators/";
  25121. else if (desc.componentType == kAudioUnitType_Panner)
  25122. s << "Panners/";
  25123. s << osTypeToString (desc.componentType) << ","
  25124. << osTypeToString (desc.componentSubType) << ","
  25125. << osTypeToString (desc.componentManufacturer);
  25126. return s;
  25127. }
  25128. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25129. {
  25130. Handle componentNameHandle = NewHandle (sizeof (void*));
  25131. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25132. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25133. {
  25134. ComponentDescription desc;
  25135. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25136. {
  25137. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25138. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25139. if (nameString != 0 && nameString[0] != 0)
  25140. {
  25141. const String all ((const char*) nameString + 1, nameString[0]);
  25142. DBG ("name: "+ all);
  25143. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25144. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25145. }
  25146. if (infoString != 0 && infoString[0] != 0)
  25147. {
  25148. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25149. }
  25150. if (name.isEmpty())
  25151. name = "<Unknown>";
  25152. }
  25153. DisposeHandle (componentNameHandle);
  25154. DisposeHandle (componentInfoHandle);
  25155. }
  25156. }
  25157. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25158. String& name, String& version, String& manufacturer)
  25159. {
  25160. zerostruct (desc);
  25161. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25162. {
  25163. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25164. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25165. StringArray tokens;
  25166. tokens.addTokens (s, ",", String::empty);
  25167. tokens.trim();
  25168. tokens.removeEmptyStrings();
  25169. if (tokens.size() == 3)
  25170. {
  25171. desc.componentType = stringToOSType (tokens[0]);
  25172. desc.componentSubType = stringToOSType (tokens[1]);
  25173. desc.componentManufacturer = stringToOSType (tokens[2]);
  25174. ComponentRecord* comp = FindNextComponent (0, &desc);
  25175. if (comp != 0)
  25176. {
  25177. getAUDetails (comp, name, manufacturer);
  25178. return true;
  25179. }
  25180. }
  25181. }
  25182. return false;
  25183. }
  25184. }
  25185. class AudioUnitPluginWindowCarbon;
  25186. class AudioUnitPluginWindowCocoa;
  25187. class AudioUnitPluginInstance : public AudioPluginInstance
  25188. {
  25189. public:
  25190. ~AudioUnitPluginInstance();
  25191. void initialise();
  25192. // AudioPluginInstance methods:
  25193. void fillInPluginDescription (PluginDescription& desc) const
  25194. {
  25195. desc.name = pluginName;
  25196. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25197. desc.uid = ((int) componentDesc.componentType)
  25198. ^ ((int) componentDesc.componentSubType)
  25199. ^ ((int) componentDesc.componentManufacturer);
  25200. desc.lastFileModTime = 0;
  25201. desc.pluginFormatName = "AudioUnit";
  25202. desc.category = getCategory();
  25203. desc.manufacturerName = manufacturer;
  25204. desc.version = version;
  25205. desc.numInputChannels = getNumInputChannels();
  25206. desc.numOutputChannels = getNumOutputChannels();
  25207. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25208. }
  25209. const String getName() const { return pluginName; }
  25210. bool acceptsMidi() const { return wantsMidiMessages; }
  25211. bool producesMidi() const { return false; }
  25212. // AudioProcessor methods:
  25213. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25214. void releaseResources();
  25215. void processBlock (AudioSampleBuffer& buffer,
  25216. MidiBuffer& midiMessages);
  25217. bool hasEditor() const;
  25218. AudioProcessorEditor* createEditor();
  25219. const String getInputChannelName (int index) const;
  25220. bool isInputChannelStereoPair (int index) const;
  25221. const String getOutputChannelName (int index) const;
  25222. bool isOutputChannelStereoPair (int index) const;
  25223. int getNumParameters();
  25224. float getParameter (int index);
  25225. void setParameter (int index, float newValue);
  25226. const String getParameterName (int index);
  25227. const String getParameterText (int index);
  25228. bool isParameterAutomatable (int index) const;
  25229. int getNumPrograms();
  25230. int getCurrentProgram();
  25231. void setCurrentProgram (int index);
  25232. const String getProgramName (int index);
  25233. void changeProgramName (int index, const String& newName);
  25234. void getStateInformation (MemoryBlock& destData);
  25235. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25236. void setStateInformation (const void* data, int sizeInBytes);
  25237. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25238. juce_UseDebuggingNewOperator
  25239. private:
  25240. friend class AudioUnitPluginWindowCarbon;
  25241. friend class AudioUnitPluginWindowCocoa;
  25242. friend class AudioUnitPluginFormat;
  25243. ComponentDescription componentDesc;
  25244. String pluginName, manufacturer, version;
  25245. String fileOrIdentifier;
  25246. CriticalSection lock;
  25247. bool wantsMidiMessages, wasPlaying, prepared;
  25248. HeapBlock <AudioBufferList> outputBufferList;
  25249. AudioTimeStamp timeStamp;
  25250. AudioSampleBuffer* currentBuffer;
  25251. AudioUnit audioUnit;
  25252. Array <int> parameterIds;
  25253. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25254. void setPluginCallbacks();
  25255. void getParameterListFromPlugin();
  25256. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25257. const AudioTimeStamp* inTimeStamp,
  25258. UInt32 inBusNumber,
  25259. UInt32 inNumberFrames,
  25260. AudioBufferList* ioData) const;
  25261. static OSStatus renderGetInputCallback (void* inRefCon,
  25262. AudioUnitRenderActionFlags* ioActionFlags,
  25263. const AudioTimeStamp* inTimeStamp,
  25264. UInt32 inBusNumber,
  25265. UInt32 inNumberFrames,
  25266. AudioBufferList* ioData)
  25267. {
  25268. return ((AudioUnitPluginInstance*) inRefCon)
  25269. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25270. }
  25271. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25272. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25273. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25274. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25275. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25276. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25277. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25278. {
  25279. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25280. }
  25281. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25282. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25283. Float64* outCurrentMeasureDownBeat)
  25284. {
  25285. return ((AudioUnitPluginInstance*) inHostUserData)
  25286. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25287. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25288. }
  25289. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25290. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25291. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25292. {
  25293. return ((AudioUnitPluginInstance*) inHostUserData)
  25294. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25295. outCurrentSampleInTimeLine, outIsCycling,
  25296. outCycleStartBeat, outCycleEndBeat);
  25297. }
  25298. void getNumChannels (int& numIns, int& numOuts)
  25299. {
  25300. numIns = 0;
  25301. numOuts = 0;
  25302. AUChannelInfo supportedChannels [128];
  25303. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25304. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25305. 0, supportedChannels, &supportedChannelsSize) == noErr
  25306. && supportedChannelsSize > 0)
  25307. {
  25308. int explicitNumIns = 0;
  25309. int explicitNumOuts = 0;
  25310. int maximumNumIns = 0;
  25311. int maximumNumOuts = 0;
  25312. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25313. {
  25314. const int inChannels = (int) supportedChannels[i].inChannels;
  25315. const int outChannels = (int) supportedChannels[i].outChannels;
  25316. if (inChannels < 0)
  25317. maximumNumIns = jmin (maximumNumIns, inChannels);
  25318. else
  25319. explicitNumIns = jmax (explicitNumIns, inChannels);
  25320. if (outChannels < 0)
  25321. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25322. else
  25323. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25324. }
  25325. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25326. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25327. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25328. {
  25329. numIns = numOuts = 2;
  25330. }
  25331. else
  25332. {
  25333. numIns = explicitNumIns;
  25334. numOuts = explicitNumOuts;
  25335. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25336. numIns = 2;
  25337. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25338. numOuts = 2;
  25339. }
  25340. }
  25341. else
  25342. {
  25343. // (this really means the plugin will take any number of ins/outs as long
  25344. // as they are the same)
  25345. numIns = numOuts = 2;
  25346. }
  25347. }
  25348. const String getCategory() const;
  25349. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25350. };
  25351. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25352. : fileOrIdentifier (fileOrIdentifier),
  25353. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25354. audioUnit (0),
  25355. currentBuffer (0)
  25356. {
  25357. using namespace AudioUnitFormatHelpers;
  25358. try
  25359. {
  25360. ++insideCallback;
  25361. log ("Opening AU: " + fileOrIdentifier);
  25362. if (getComponentDescFromFile (fileOrIdentifier))
  25363. {
  25364. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25365. if (comp != 0)
  25366. {
  25367. audioUnit = (AudioUnit) OpenComponent (comp);
  25368. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25369. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25370. }
  25371. }
  25372. --insideCallback;
  25373. }
  25374. catch (...)
  25375. {
  25376. --insideCallback;
  25377. }
  25378. }
  25379. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25380. {
  25381. const ScopedLock sl (lock);
  25382. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25383. if (audioUnit != 0)
  25384. {
  25385. AudioUnitUninitialize (audioUnit);
  25386. CloseComponent (audioUnit);
  25387. audioUnit = 0;
  25388. }
  25389. }
  25390. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25391. {
  25392. zerostruct (componentDesc);
  25393. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25394. return true;
  25395. const File file (fileOrIdentifier);
  25396. if (! file.hasFileExtension (".component"))
  25397. return false;
  25398. const char* const utf8 = fileOrIdentifier.toUTF8();
  25399. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25400. strlen (utf8), file.isDirectory());
  25401. if (url != 0)
  25402. {
  25403. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25404. CFRelease (url);
  25405. if (bundleRef != 0)
  25406. {
  25407. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25408. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25409. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25410. if (pluginName.isEmpty())
  25411. pluginName = file.getFileNameWithoutExtension();
  25412. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25413. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25414. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25415. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25416. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25417. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25418. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25419. UseResFile (resFileId);
  25420. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25421. {
  25422. Handle h = Get1IndResource ('thng', i);
  25423. if (h != 0)
  25424. {
  25425. HLock (h);
  25426. const uint32* const types = (const uint32*) *h;
  25427. if (types[0] == kAudioUnitType_MusicDevice
  25428. || types[0] == kAudioUnitType_MusicEffect
  25429. || types[0] == kAudioUnitType_Effect
  25430. || types[0] == kAudioUnitType_Generator
  25431. || types[0] == kAudioUnitType_Panner)
  25432. {
  25433. componentDesc.componentType = types[0];
  25434. componentDesc.componentSubType = types[1];
  25435. componentDesc.componentManufacturer = types[2];
  25436. break;
  25437. }
  25438. HUnlock (h);
  25439. ReleaseResource (h);
  25440. }
  25441. }
  25442. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25443. CFRelease (bundleRef);
  25444. }
  25445. }
  25446. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25447. }
  25448. void AudioUnitPluginInstance::initialise()
  25449. {
  25450. getParameterListFromPlugin();
  25451. setPluginCallbacks();
  25452. int numIns, numOuts;
  25453. getNumChannels (numIns, numOuts);
  25454. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25455. setLatencySamples (0);
  25456. }
  25457. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25458. {
  25459. parameterIds.clear();
  25460. if (audioUnit != 0)
  25461. {
  25462. UInt32 paramListSize = 0;
  25463. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25464. 0, 0, &paramListSize);
  25465. if (paramListSize > 0)
  25466. {
  25467. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25468. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25469. 0, &parameterIds.getReference(0), &paramListSize);
  25470. }
  25471. }
  25472. }
  25473. void AudioUnitPluginInstance::setPluginCallbacks()
  25474. {
  25475. if (audioUnit != 0)
  25476. {
  25477. {
  25478. AURenderCallbackStruct info;
  25479. zerostruct (info);
  25480. info.inputProcRefCon = this;
  25481. info.inputProc = renderGetInputCallback;
  25482. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25483. 0, &info, sizeof (info));
  25484. }
  25485. {
  25486. HostCallbackInfo info;
  25487. zerostruct (info);
  25488. info.hostUserData = this;
  25489. info.beatAndTempoProc = getBeatAndTempoCallback;
  25490. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25491. info.transportStateProc = getTransportStateCallback;
  25492. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25493. 0, &info, sizeof (info));
  25494. }
  25495. }
  25496. }
  25497. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25498. int samplesPerBlockExpected)
  25499. {
  25500. if (audioUnit != 0)
  25501. {
  25502. releaseResources();
  25503. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25504. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25505. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25506. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25507. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25508. {
  25509. Float64 sr = sampleRate_;
  25510. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25511. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25512. }
  25513. int numIns, numOuts;
  25514. getNumChannels (numIns, numOuts);
  25515. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25516. Float64 latencySecs = 0.0;
  25517. UInt32 latencySize = sizeof (latencySecs);
  25518. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25519. 0, &latencySecs, &latencySize);
  25520. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25521. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25522. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25523. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25524. {
  25525. AudioStreamBasicDescription stream;
  25526. zerostruct (stream);
  25527. stream.mSampleRate = sampleRate_;
  25528. stream.mFormatID = kAudioFormatLinearPCM;
  25529. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25530. stream.mFramesPerPacket = 1;
  25531. stream.mBytesPerPacket = 4;
  25532. stream.mBytesPerFrame = 4;
  25533. stream.mBitsPerChannel = 32;
  25534. stream.mChannelsPerFrame = numIns;
  25535. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25536. 0, &stream, sizeof (stream));
  25537. stream.mChannelsPerFrame = numOuts;
  25538. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25539. 0, &stream, sizeof (stream));
  25540. }
  25541. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25542. outputBufferList->mNumberBuffers = numOuts;
  25543. for (int i = numOuts; --i >= 0;)
  25544. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25545. zerostruct (timeStamp);
  25546. timeStamp.mSampleTime = 0;
  25547. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25548. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25549. currentBuffer = 0;
  25550. wasPlaying = false;
  25551. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25552. }
  25553. }
  25554. void AudioUnitPluginInstance::releaseResources()
  25555. {
  25556. if (prepared)
  25557. {
  25558. AudioUnitUninitialize (audioUnit);
  25559. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25560. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25561. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25562. outputBufferList.free();
  25563. currentBuffer = 0;
  25564. prepared = false;
  25565. }
  25566. }
  25567. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25568. const AudioTimeStamp* inTimeStamp,
  25569. UInt32 inBusNumber,
  25570. UInt32 inNumberFrames,
  25571. AudioBufferList* ioData) const
  25572. {
  25573. if (inBusNumber == 0
  25574. && currentBuffer != 0)
  25575. {
  25576. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25577. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25578. {
  25579. if (i < currentBuffer->getNumChannels())
  25580. {
  25581. memcpy (ioData->mBuffers[i].mData,
  25582. currentBuffer->getSampleData (i, 0),
  25583. sizeof (float) * inNumberFrames);
  25584. }
  25585. else
  25586. {
  25587. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25588. }
  25589. }
  25590. }
  25591. return noErr;
  25592. }
  25593. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25594. MidiBuffer& midiMessages)
  25595. {
  25596. const int numSamples = buffer.getNumSamples();
  25597. if (prepared)
  25598. {
  25599. AudioUnitRenderActionFlags flags = 0;
  25600. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25601. for (int i = getNumOutputChannels(); --i >= 0;)
  25602. {
  25603. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25604. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25605. }
  25606. currentBuffer = &buffer;
  25607. if (wantsMidiMessages)
  25608. {
  25609. const uint8* midiEventData;
  25610. int midiEventSize, midiEventPosition;
  25611. MidiBuffer::Iterator i (midiMessages);
  25612. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25613. {
  25614. if (midiEventSize <= 3)
  25615. MusicDeviceMIDIEvent (audioUnit,
  25616. midiEventData[0], midiEventData[1], midiEventData[2],
  25617. midiEventPosition);
  25618. else
  25619. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25620. }
  25621. midiMessages.clear();
  25622. }
  25623. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25624. 0, numSamples, outputBufferList);
  25625. timeStamp.mSampleTime += numSamples;
  25626. }
  25627. else
  25628. {
  25629. // Plugin not working correctly, so just bypass..
  25630. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25631. buffer.clear (i, 0, buffer.getNumSamples());
  25632. }
  25633. }
  25634. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25635. {
  25636. AudioPlayHead* const ph = getPlayHead();
  25637. AudioPlayHead::CurrentPositionInfo result;
  25638. if (ph != 0 && ph->getCurrentPosition (result))
  25639. {
  25640. if (outCurrentBeat != 0)
  25641. *outCurrentBeat = result.ppqPosition;
  25642. if (outCurrentTempo != 0)
  25643. *outCurrentTempo = result.bpm;
  25644. }
  25645. else
  25646. {
  25647. if (outCurrentBeat != 0)
  25648. *outCurrentBeat = 0;
  25649. if (outCurrentTempo != 0)
  25650. *outCurrentTempo = 120.0;
  25651. }
  25652. return noErr;
  25653. }
  25654. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25655. Float32* outTimeSig_Numerator,
  25656. UInt32* outTimeSig_Denominator,
  25657. Float64* outCurrentMeasureDownBeat) const
  25658. {
  25659. AudioPlayHead* const ph = getPlayHead();
  25660. AudioPlayHead::CurrentPositionInfo result;
  25661. if (ph != 0 && ph->getCurrentPosition (result))
  25662. {
  25663. if (outTimeSig_Numerator != 0)
  25664. *outTimeSig_Numerator = result.timeSigNumerator;
  25665. if (outTimeSig_Denominator != 0)
  25666. *outTimeSig_Denominator = result.timeSigDenominator;
  25667. if (outDeltaSampleOffsetToNextBeat != 0)
  25668. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25669. if (outCurrentMeasureDownBeat != 0)
  25670. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25671. }
  25672. else
  25673. {
  25674. if (outDeltaSampleOffsetToNextBeat != 0)
  25675. *outDeltaSampleOffsetToNextBeat = 0;
  25676. if (outTimeSig_Numerator != 0)
  25677. *outTimeSig_Numerator = 4;
  25678. if (outTimeSig_Denominator != 0)
  25679. *outTimeSig_Denominator = 4;
  25680. if (outCurrentMeasureDownBeat != 0)
  25681. *outCurrentMeasureDownBeat = 0;
  25682. }
  25683. return noErr;
  25684. }
  25685. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25686. Boolean* outTransportStateChanged,
  25687. Float64* outCurrentSampleInTimeLine,
  25688. Boolean* outIsCycling,
  25689. Float64* outCycleStartBeat,
  25690. Float64* outCycleEndBeat)
  25691. {
  25692. AudioPlayHead* const ph = getPlayHead();
  25693. AudioPlayHead::CurrentPositionInfo result;
  25694. if (ph != 0 && ph->getCurrentPosition (result))
  25695. {
  25696. if (outIsPlaying != 0)
  25697. *outIsPlaying = result.isPlaying;
  25698. if (outTransportStateChanged != 0)
  25699. {
  25700. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25701. wasPlaying = result.isPlaying;
  25702. }
  25703. if (outCurrentSampleInTimeLine != 0)
  25704. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25705. if (outIsCycling != 0)
  25706. *outIsCycling = false;
  25707. if (outCycleStartBeat != 0)
  25708. *outCycleStartBeat = 0;
  25709. if (outCycleEndBeat != 0)
  25710. *outCycleEndBeat = 0;
  25711. }
  25712. else
  25713. {
  25714. if (outIsPlaying != 0)
  25715. *outIsPlaying = false;
  25716. if (outTransportStateChanged != 0)
  25717. *outTransportStateChanged = false;
  25718. if (outCurrentSampleInTimeLine != 0)
  25719. *outCurrentSampleInTimeLine = 0;
  25720. if (outIsCycling != 0)
  25721. *outIsCycling = false;
  25722. if (outCycleStartBeat != 0)
  25723. *outCycleStartBeat = 0;
  25724. if (outCycleEndBeat != 0)
  25725. *outCycleEndBeat = 0;
  25726. }
  25727. return noErr;
  25728. }
  25729. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25730. public Timer
  25731. {
  25732. public:
  25733. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25734. : AudioProcessorEditor (&plugin_),
  25735. plugin (plugin_)
  25736. {
  25737. addAndMakeVisible (&wrapper);
  25738. setOpaque (true);
  25739. setVisible (true);
  25740. setSize (100, 100);
  25741. createView (createGenericViewIfNeeded);
  25742. }
  25743. ~AudioUnitPluginWindowCocoa()
  25744. {
  25745. const bool wasValid = isValid();
  25746. wrapper.setView (0);
  25747. if (wasValid)
  25748. plugin.editorBeingDeleted (this);
  25749. }
  25750. bool isValid() const { return wrapper.getView() != 0; }
  25751. void paint (Graphics& g)
  25752. {
  25753. g.fillAll (Colours::white);
  25754. }
  25755. void resized()
  25756. {
  25757. wrapper.setSize (getWidth(), getHeight());
  25758. }
  25759. void timerCallback()
  25760. {
  25761. wrapper.resizeToFitView();
  25762. startTimer (jmin (713, getTimerInterval() + 51));
  25763. }
  25764. void childBoundsChanged (Component* child)
  25765. {
  25766. setSize (wrapper.getWidth(), wrapper.getHeight());
  25767. startTimer (70);
  25768. }
  25769. private:
  25770. AudioUnitPluginInstance& plugin;
  25771. NSViewComponent wrapper;
  25772. bool createView (const bool createGenericViewIfNeeded)
  25773. {
  25774. NSView* pluginView = 0;
  25775. UInt32 dataSize = 0;
  25776. Boolean isWritable = false;
  25777. AudioUnitInitialize (plugin.audioUnit);
  25778. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25779. 0, &dataSize, &isWritable) == noErr
  25780. && dataSize != 0
  25781. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25782. 0, &dataSize, &isWritable) == noErr)
  25783. {
  25784. HeapBlock <AudioUnitCocoaViewInfo> info;
  25785. info.calloc (dataSize, 1);
  25786. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25787. 0, info, &dataSize) == noErr)
  25788. {
  25789. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25790. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25791. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25792. Class viewClass = [viewBundle classNamed: viewClassName];
  25793. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25794. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25795. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25796. {
  25797. id factory = [[[viewClass alloc] init] autorelease];
  25798. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25799. withSize: NSMakeSize (getWidth(), getHeight())];
  25800. }
  25801. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25802. CFRelease (info->mCocoaAUViewClass[i]);
  25803. CFRelease (info->mCocoaAUViewBundleLocation);
  25804. }
  25805. }
  25806. if (createGenericViewIfNeeded && (pluginView == 0))
  25807. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25808. wrapper.setView (pluginView);
  25809. if (pluginView != 0)
  25810. {
  25811. timerCallback();
  25812. startTimer (70);
  25813. }
  25814. return pluginView != 0;
  25815. }
  25816. };
  25817. #if JUCE_SUPPORT_CARBON
  25818. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25819. {
  25820. public:
  25821. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25822. : AudioProcessorEditor (&plugin_),
  25823. plugin (plugin_),
  25824. viewComponent (0)
  25825. {
  25826. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25827. setOpaque (true);
  25828. setVisible (true);
  25829. setSize (400, 300);
  25830. ComponentDescription viewList [16];
  25831. UInt32 viewListSize = sizeof (viewList);
  25832. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25833. 0, &viewList, &viewListSize);
  25834. componentRecord = FindNextComponent (0, &viewList[0]);
  25835. }
  25836. ~AudioUnitPluginWindowCarbon()
  25837. {
  25838. innerWrapper = 0;
  25839. if (isValid())
  25840. plugin.editorBeingDeleted (this);
  25841. }
  25842. bool isValid() const throw() { return componentRecord != 0; }
  25843. void paint (Graphics& g)
  25844. {
  25845. g.fillAll (Colours::black);
  25846. }
  25847. void resized()
  25848. {
  25849. innerWrapper->setSize (getWidth(), getHeight());
  25850. }
  25851. bool keyStateChanged (bool)
  25852. {
  25853. return false;
  25854. }
  25855. bool keyPressed (const KeyPress&)
  25856. {
  25857. return false;
  25858. }
  25859. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25860. AudioUnitCarbonView getViewComponent()
  25861. {
  25862. if (viewComponent == 0 && componentRecord != 0)
  25863. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25864. return viewComponent;
  25865. }
  25866. void closeViewComponent()
  25867. {
  25868. if (viewComponent != 0)
  25869. {
  25870. log ("Closing AU GUI: " + plugin.getName());
  25871. CloseComponent (viewComponent);
  25872. viewComponent = 0;
  25873. }
  25874. }
  25875. juce_UseDebuggingNewOperator
  25876. private:
  25877. AudioUnitPluginInstance& plugin;
  25878. ComponentRecord* componentRecord;
  25879. AudioUnitCarbonView viewComponent;
  25880. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25881. {
  25882. public:
  25883. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25884. : owner (owner_)
  25885. {
  25886. }
  25887. ~InnerWrapperComponent()
  25888. {
  25889. deleteWindow();
  25890. }
  25891. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25892. {
  25893. log ("Opening AU GUI: " + owner->plugin.getName());
  25894. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25895. if (viewComponent == 0)
  25896. return 0;
  25897. Float32Point pos = { 0, 0 };
  25898. Float32Point size = { 250, 200 };
  25899. HIViewRef pluginView = 0;
  25900. AudioUnitCarbonViewCreate (viewComponent,
  25901. owner->getAudioUnit(),
  25902. windowRef,
  25903. rootView,
  25904. &pos,
  25905. &size,
  25906. (ControlRef*) &pluginView);
  25907. return pluginView;
  25908. }
  25909. void removeView (HIViewRef)
  25910. {
  25911. owner->closeViewComponent();
  25912. }
  25913. private:
  25914. AudioUnitPluginWindowCarbon* const owner;
  25915. };
  25916. friend class InnerWrapperComponent;
  25917. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25918. };
  25919. #endif
  25920. bool AudioUnitPluginInstance::hasEditor() const
  25921. {
  25922. return true;
  25923. }
  25924. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25925. {
  25926. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25927. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25928. w = 0;
  25929. #if JUCE_SUPPORT_CARBON
  25930. if (w == 0)
  25931. {
  25932. w = new AudioUnitPluginWindowCarbon (*this);
  25933. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25934. w = 0;
  25935. }
  25936. #endif
  25937. if (w == 0)
  25938. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25939. return w.release();
  25940. }
  25941. const String AudioUnitPluginInstance::getCategory() const
  25942. {
  25943. const char* result = 0;
  25944. switch (componentDesc.componentType)
  25945. {
  25946. case kAudioUnitType_Effect:
  25947. case kAudioUnitType_MusicEffect:
  25948. result = "Effect";
  25949. break;
  25950. case kAudioUnitType_MusicDevice:
  25951. result = "Synth";
  25952. break;
  25953. case kAudioUnitType_Generator:
  25954. result = "Generator";
  25955. break;
  25956. case kAudioUnitType_Panner:
  25957. result = "Panner";
  25958. break;
  25959. default:
  25960. break;
  25961. }
  25962. return result;
  25963. }
  25964. int AudioUnitPluginInstance::getNumParameters()
  25965. {
  25966. return parameterIds.size();
  25967. }
  25968. float AudioUnitPluginInstance::getParameter (int index)
  25969. {
  25970. const ScopedLock sl (lock);
  25971. Float32 value = 0.0f;
  25972. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25973. {
  25974. AudioUnitGetParameter (audioUnit,
  25975. (UInt32) parameterIds.getUnchecked (index),
  25976. kAudioUnitScope_Global, 0,
  25977. &value);
  25978. }
  25979. return value;
  25980. }
  25981. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25982. {
  25983. const ScopedLock sl (lock);
  25984. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25985. {
  25986. AudioUnitSetParameter (audioUnit,
  25987. (UInt32) parameterIds.getUnchecked (index),
  25988. kAudioUnitScope_Global, 0,
  25989. newValue, 0);
  25990. }
  25991. }
  25992. const String AudioUnitPluginInstance::getParameterName (int index)
  25993. {
  25994. AudioUnitParameterInfo info;
  25995. zerostruct (info);
  25996. UInt32 sz = sizeof (info);
  25997. String name;
  25998. if (AudioUnitGetProperty (audioUnit,
  25999. kAudioUnitProperty_ParameterInfo,
  26000. kAudioUnitScope_Global,
  26001. parameterIds [index], &info, &sz) == noErr)
  26002. {
  26003. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26004. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26005. else
  26006. name = String (info.name, sizeof (info.name));
  26007. }
  26008. return name;
  26009. }
  26010. const String AudioUnitPluginInstance::getParameterText (int index)
  26011. {
  26012. return String (getParameter (index));
  26013. }
  26014. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26015. {
  26016. AudioUnitParameterInfo info;
  26017. UInt32 sz = sizeof (info);
  26018. if (AudioUnitGetProperty (audioUnit,
  26019. kAudioUnitProperty_ParameterInfo,
  26020. kAudioUnitScope_Global,
  26021. parameterIds [index], &info, &sz) == noErr)
  26022. {
  26023. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26024. }
  26025. return true;
  26026. }
  26027. int AudioUnitPluginInstance::getNumPrograms()
  26028. {
  26029. CFArrayRef presets;
  26030. UInt32 sz = sizeof (CFArrayRef);
  26031. int num = 0;
  26032. if (AudioUnitGetProperty (audioUnit,
  26033. kAudioUnitProperty_FactoryPresets,
  26034. kAudioUnitScope_Global,
  26035. 0, &presets, &sz) == noErr)
  26036. {
  26037. num = (int) CFArrayGetCount (presets);
  26038. CFRelease (presets);
  26039. }
  26040. return num;
  26041. }
  26042. int AudioUnitPluginInstance::getCurrentProgram()
  26043. {
  26044. AUPreset current;
  26045. current.presetNumber = 0;
  26046. UInt32 sz = sizeof (AUPreset);
  26047. AudioUnitGetProperty (audioUnit,
  26048. kAudioUnitProperty_FactoryPresets,
  26049. kAudioUnitScope_Global,
  26050. 0, &current, &sz);
  26051. return current.presetNumber;
  26052. }
  26053. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26054. {
  26055. AUPreset current;
  26056. current.presetNumber = newIndex;
  26057. current.presetName = 0;
  26058. AudioUnitSetProperty (audioUnit,
  26059. kAudioUnitProperty_FactoryPresets,
  26060. kAudioUnitScope_Global,
  26061. 0, &current, sizeof (AUPreset));
  26062. }
  26063. const String AudioUnitPluginInstance::getProgramName (int index)
  26064. {
  26065. String s;
  26066. CFArrayRef presets;
  26067. UInt32 sz = sizeof (CFArrayRef);
  26068. if (AudioUnitGetProperty (audioUnit,
  26069. kAudioUnitProperty_FactoryPresets,
  26070. kAudioUnitScope_Global,
  26071. 0, &presets, &sz) == noErr)
  26072. {
  26073. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26074. {
  26075. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26076. if (p != 0 && p->presetNumber == index)
  26077. {
  26078. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26079. break;
  26080. }
  26081. }
  26082. CFRelease (presets);
  26083. }
  26084. return s;
  26085. }
  26086. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26087. {
  26088. jassertfalse; // xxx not implemented!
  26089. }
  26090. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26091. {
  26092. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26093. return "Input " + String (index + 1);
  26094. return String::empty;
  26095. }
  26096. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26097. {
  26098. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26099. return false;
  26100. return true;
  26101. }
  26102. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26103. {
  26104. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26105. return "Output " + String (index + 1);
  26106. return String::empty;
  26107. }
  26108. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26109. {
  26110. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26111. return false;
  26112. return true;
  26113. }
  26114. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26115. {
  26116. getCurrentProgramStateInformation (destData);
  26117. }
  26118. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26119. {
  26120. CFPropertyListRef propertyList = 0;
  26121. UInt32 sz = sizeof (CFPropertyListRef);
  26122. if (AudioUnitGetProperty (audioUnit,
  26123. kAudioUnitProperty_ClassInfo,
  26124. kAudioUnitScope_Global,
  26125. 0, &propertyList, &sz) == noErr)
  26126. {
  26127. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26128. CFWriteStreamOpen (stream);
  26129. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26130. CFWriteStreamClose (stream);
  26131. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26132. destData.setSize (bytesWritten);
  26133. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26134. CFRelease (data);
  26135. CFRelease (stream);
  26136. CFRelease (propertyList);
  26137. }
  26138. }
  26139. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26140. {
  26141. setCurrentProgramStateInformation (data, sizeInBytes);
  26142. }
  26143. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26144. {
  26145. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26146. (const UInt8*) data,
  26147. sizeInBytes,
  26148. kCFAllocatorNull);
  26149. CFReadStreamOpen (stream);
  26150. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26151. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26152. stream,
  26153. 0,
  26154. kCFPropertyListImmutable,
  26155. &format,
  26156. 0);
  26157. CFRelease (stream);
  26158. if (propertyList != 0)
  26159. AudioUnitSetProperty (audioUnit,
  26160. kAudioUnitProperty_ClassInfo,
  26161. kAudioUnitScope_Global,
  26162. 0, &propertyList, sizeof (propertyList));
  26163. }
  26164. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26165. {
  26166. }
  26167. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26168. {
  26169. }
  26170. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26171. const String& fileOrIdentifier)
  26172. {
  26173. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26174. return;
  26175. PluginDescription desc;
  26176. desc.fileOrIdentifier = fileOrIdentifier;
  26177. desc.uid = 0;
  26178. try
  26179. {
  26180. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26181. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26182. if (auInstance != 0)
  26183. {
  26184. auInstance->fillInPluginDescription (desc);
  26185. results.add (new PluginDescription (desc));
  26186. }
  26187. }
  26188. catch (...)
  26189. {
  26190. // crashed while loading...
  26191. }
  26192. }
  26193. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26194. {
  26195. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26196. {
  26197. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26198. if (result->audioUnit != 0)
  26199. {
  26200. result->initialise();
  26201. return result.release();
  26202. }
  26203. }
  26204. return 0;
  26205. }
  26206. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26207. const bool /*recursive*/)
  26208. {
  26209. StringArray result;
  26210. ComponentRecord* comp = 0;
  26211. ComponentDescription desc;
  26212. zerostruct (desc);
  26213. for (;;)
  26214. {
  26215. zerostruct (desc);
  26216. comp = FindNextComponent (comp, &desc);
  26217. if (comp == 0)
  26218. break;
  26219. GetComponentInfo (comp, &desc, 0, 0, 0);
  26220. if (desc.componentType == kAudioUnitType_MusicDevice
  26221. || desc.componentType == kAudioUnitType_MusicEffect
  26222. || desc.componentType == kAudioUnitType_Effect
  26223. || desc.componentType == kAudioUnitType_Generator
  26224. || desc.componentType == kAudioUnitType_Panner)
  26225. {
  26226. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26227. DBG (s);
  26228. result.add (s);
  26229. }
  26230. }
  26231. return result;
  26232. }
  26233. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26234. {
  26235. ComponentDescription desc;
  26236. String name, version, manufacturer;
  26237. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26238. return FindNextComponent (0, &desc) != 0;
  26239. const File f (fileOrIdentifier);
  26240. return f.hasFileExtension (".component")
  26241. && f.isDirectory();
  26242. }
  26243. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26244. {
  26245. ComponentDescription desc;
  26246. String name, version, manufacturer;
  26247. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26248. if (name.isEmpty())
  26249. name = fileOrIdentifier;
  26250. return name;
  26251. }
  26252. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26253. {
  26254. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26255. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26256. else
  26257. return File (desc.fileOrIdentifier).exists();
  26258. }
  26259. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26260. {
  26261. return FileSearchPath ("/(Default AudioUnit locations)");
  26262. }
  26263. #endif
  26264. END_JUCE_NAMESPACE
  26265. #undef log
  26266. #endif
  26267. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26268. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26269. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26270. #define JUCE_MAC_VST_INCLUDED 1
  26271. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26272. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26273. #if JUCE_WINDOWS
  26274. #undef _WIN32_WINNT
  26275. #define _WIN32_WINNT 0x500
  26276. #undef STRICT
  26277. #define STRICT
  26278. #include <windows.h>
  26279. #include <float.h>
  26280. #pragma warning (disable : 4312 4355)
  26281. #elif JUCE_LINUX
  26282. #include <float.h>
  26283. #include <sys/time.h>
  26284. #include <X11/Xlib.h>
  26285. #include <X11/Xutil.h>
  26286. #include <X11/Xatom.h>
  26287. #undef Font
  26288. #undef KeyPress
  26289. #undef Drawable
  26290. #undef Time
  26291. #else
  26292. #include <Cocoa/Cocoa.h>
  26293. #include <Carbon/Carbon.h>
  26294. #endif
  26295. #if ! (JUCE_MAC && JUCE_64BIT)
  26296. BEGIN_JUCE_NAMESPACE
  26297. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26298. #endif
  26299. #undef PRAGMA_ALIGN_SUPPORTED
  26300. #define VST_FORCE_DEPRECATED 0
  26301. #if JUCE_MSVC
  26302. #pragma warning (push)
  26303. #pragma warning (disable: 4996)
  26304. #endif
  26305. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26306. your include path if you want to add VST support.
  26307. If you're not interested in VSTs, you can disable them by changing the
  26308. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26309. */
  26310. #include "pluginterfaces/vst2.x/aeffectx.h"
  26311. #if JUCE_MSVC
  26312. #pragma warning (pop)
  26313. #endif
  26314. #if JUCE_LINUX
  26315. #define Font JUCE_NAMESPACE::Font
  26316. #define KeyPress JUCE_NAMESPACE::KeyPress
  26317. #define Drawable JUCE_NAMESPACE::Drawable
  26318. #define Time JUCE_NAMESPACE::Time
  26319. #endif
  26320. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26321. #ifdef __aeffect__
  26322. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26323. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26324. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26325. events to the list.
  26326. This is used by both the VST hosting code and the plugin wrapper.
  26327. */
  26328. class VSTMidiEventList
  26329. {
  26330. public:
  26331. VSTMidiEventList()
  26332. : numEventsUsed (0), numEventsAllocated (0)
  26333. {
  26334. }
  26335. ~VSTMidiEventList()
  26336. {
  26337. freeEvents();
  26338. }
  26339. void clear()
  26340. {
  26341. numEventsUsed = 0;
  26342. if (events != 0)
  26343. events->numEvents = 0;
  26344. }
  26345. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26346. {
  26347. ensureSize (numEventsUsed + 1);
  26348. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26349. events->numEvents = ++numEventsUsed;
  26350. if (numBytes <= 4)
  26351. {
  26352. if (e->type == kVstSysExType)
  26353. {
  26354. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26355. e->type = kVstMidiType;
  26356. e->byteSize = sizeof (VstMidiEvent);
  26357. e->noteLength = 0;
  26358. e->noteOffset = 0;
  26359. e->detune = 0;
  26360. e->noteOffVelocity = 0;
  26361. }
  26362. e->deltaFrames = frameOffset;
  26363. memcpy (e->midiData, midiData, numBytes);
  26364. }
  26365. else
  26366. {
  26367. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26368. if (se->type == kVstSysExType)
  26369. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26370. else
  26371. se->sysexDump = (char*) juce_malloc (numBytes);
  26372. memcpy (se->sysexDump, midiData, numBytes);
  26373. se->type = kVstSysExType;
  26374. se->byteSize = sizeof (VstMidiSysexEvent);
  26375. se->deltaFrames = frameOffset;
  26376. se->flags = 0;
  26377. se->dumpBytes = numBytes;
  26378. se->resvd1 = 0;
  26379. se->resvd2 = 0;
  26380. }
  26381. }
  26382. // Handy method to pull the events out of an event buffer supplied by the host
  26383. // or plugin.
  26384. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26385. {
  26386. for (int i = 0; i < events->numEvents; ++i)
  26387. {
  26388. const VstEvent* const e = events->events[i];
  26389. if (e != 0)
  26390. {
  26391. if (e->type == kVstMidiType)
  26392. {
  26393. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26394. 4, e->deltaFrames);
  26395. }
  26396. else if (e->type == kVstSysExType)
  26397. {
  26398. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26399. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26400. e->deltaFrames);
  26401. }
  26402. }
  26403. }
  26404. }
  26405. void ensureSize (int numEventsNeeded)
  26406. {
  26407. if (numEventsNeeded > numEventsAllocated)
  26408. {
  26409. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26410. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26411. if (events == 0)
  26412. events.calloc (size, 1);
  26413. else
  26414. events.realloc (size, 1);
  26415. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26416. {
  26417. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26418. (int) sizeof (VstMidiSysexEvent)));
  26419. e->type = kVstMidiType;
  26420. e->byteSize = sizeof (VstMidiEvent);
  26421. events->events[i] = (VstEvent*) e;
  26422. }
  26423. numEventsAllocated = numEventsNeeded;
  26424. }
  26425. }
  26426. void freeEvents()
  26427. {
  26428. if (events != 0)
  26429. {
  26430. for (int i = numEventsAllocated; --i >= 0;)
  26431. {
  26432. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26433. if (e->type == kVstSysExType)
  26434. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26435. juce_free (e);
  26436. }
  26437. events.free();
  26438. numEventsUsed = 0;
  26439. numEventsAllocated = 0;
  26440. }
  26441. }
  26442. HeapBlock <VstEvents> events;
  26443. private:
  26444. int numEventsUsed, numEventsAllocated;
  26445. };
  26446. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26447. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26448. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26449. #if ! JUCE_WINDOWS
  26450. static void _fpreset() {}
  26451. static void _clearfp() {}
  26452. #endif
  26453. extern void juce_callAnyTimersSynchronously();
  26454. const int fxbVersionNum = 1;
  26455. struct fxProgram
  26456. {
  26457. long chunkMagic; // 'CcnK'
  26458. long byteSize; // of this chunk, excl. magic + byteSize
  26459. long fxMagic; // 'FxCk'
  26460. long version;
  26461. long fxID; // fx unique id
  26462. long fxVersion;
  26463. long numParams;
  26464. char prgName[28];
  26465. float params[1]; // variable no. of parameters
  26466. };
  26467. struct fxSet
  26468. {
  26469. long chunkMagic; // 'CcnK'
  26470. long byteSize; // of this chunk, excl. magic + byteSize
  26471. long fxMagic; // 'FxBk'
  26472. long version;
  26473. long fxID; // fx unique id
  26474. long fxVersion;
  26475. long numPrograms;
  26476. char future[128];
  26477. fxProgram programs[1]; // variable no. of programs
  26478. };
  26479. struct fxChunkSet
  26480. {
  26481. long chunkMagic; // 'CcnK'
  26482. long byteSize; // of this chunk, excl. magic + byteSize
  26483. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26484. long version;
  26485. long fxID; // fx unique id
  26486. long fxVersion;
  26487. long numPrograms;
  26488. char future[128];
  26489. long chunkSize;
  26490. char chunk[8]; // variable
  26491. };
  26492. struct fxProgramSet
  26493. {
  26494. long chunkMagic; // 'CcnK'
  26495. long byteSize; // of this chunk, excl. magic + byteSize
  26496. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26497. long version;
  26498. long fxID; // fx unique id
  26499. long fxVersion;
  26500. long numPrograms;
  26501. char name[28];
  26502. long chunkSize;
  26503. char chunk[8]; // variable
  26504. };
  26505. static long vst_swap (const long x) throw()
  26506. {
  26507. #ifdef JUCE_LITTLE_ENDIAN
  26508. return (long) ByteOrder::swap ((uint32) x);
  26509. #else
  26510. return x;
  26511. #endif
  26512. }
  26513. static float vst_swapFloat (const float x) throw()
  26514. {
  26515. #ifdef JUCE_LITTLE_ENDIAN
  26516. union { uint32 asInt; float asFloat; } n;
  26517. n.asFloat = x;
  26518. n.asInt = ByteOrder::swap (n.asInt);
  26519. return n.asFloat;
  26520. #else
  26521. return x;
  26522. #endif
  26523. }
  26524. static double getVSTHostTimeNanoseconds()
  26525. {
  26526. #if JUCE_WINDOWS
  26527. return timeGetTime() * 1000000.0;
  26528. #elif JUCE_LINUX
  26529. timeval micro;
  26530. gettimeofday (&micro, 0);
  26531. return micro.tv_usec * 1000.0;
  26532. #elif JUCE_MAC
  26533. UnsignedWide micro;
  26534. Microseconds (&micro);
  26535. return micro.lo * 1000.0;
  26536. #endif
  26537. }
  26538. typedef AEffect* (*MainCall) (audioMasterCallback);
  26539. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26540. static int shellUIDToCreate = 0;
  26541. static int insideVSTCallback = 0;
  26542. class VSTPluginWindow;
  26543. // Change this to disable logging of various VST activities
  26544. #ifndef VST_LOGGING
  26545. #define VST_LOGGING 1
  26546. #endif
  26547. #if VST_LOGGING
  26548. #define log(a) Logger::writeToLog(a);
  26549. #else
  26550. #define log(a)
  26551. #endif
  26552. #if JUCE_MAC && JUCE_PPC
  26553. static void* NewCFMFromMachO (void* const machofp) throw()
  26554. {
  26555. void* result = juce_malloc (8);
  26556. ((void**) result)[0] = machofp;
  26557. ((void**) result)[1] = result;
  26558. return result;
  26559. }
  26560. #endif
  26561. #if JUCE_LINUX
  26562. extern Display* display;
  26563. extern XContext windowHandleXContext;
  26564. typedef void (*EventProcPtr) (XEvent* ev);
  26565. static bool xErrorTriggered;
  26566. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26567. {
  26568. xErrorTriggered = true;
  26569. return 0;
  26570. }
  26571. static int getPropertyFromXWindow (Window handle, Atom atom)
  26572. {
  26573. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26574. xErrorTriggered = false;
  26575. int userSize;
  26576. unsigned long bytes, userCount;
  26577. unsigned char* data;
  26578. Atom userType;
  26579. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26580. &userType, &userSize, &userCount, &bytes, &data);
  26581. XSetErrorHandler (oldErrorHandler);
  26582. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26583. : 0;
  26584. }
  26585. static Window getChildWindow (Window windowToCheck)
  26586. {
  26587. Window rootWindow, parentWindow;
  26588. Window* childWindows;
  26589. unsigned int numChildren;
  26590. XQueryTree (display,
  26591. windowToCheck,
  26592. &rootWindow,
  26593. &parentWindow,
  26594. &childWindows,
  26595. &numChildren);
  26596. if (numChildren > 0)
  26597. return childWindows [0];
  26598. return 0;
  26599. }
  26600. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26601. {
  26602. if (e.mods.isLeftButtonDown())
  26603. {
  26604. ev.xbutton.button = Button1;
  26605. ev.xbutton.state |= Button1Mask;
  26606. }
  26607. else if (e.mods.isRightButtonDown())
  26608. {
  26609. ev.xbutton.button = Button3;
  26610. ev.xbutton.state |= Button3Mask;
  26611. }
  26612. else if (e.mods.isMiddleButtonDown())
  26613. {
  26614. ev.xbutton.button = Button2;
  26615. ev.xbutton.state |= Button2Mask;
  26616. }
  26617. }
  26618. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26619. {
  26620. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26621. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26622. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26623. }
  26624. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26625. {
  26626. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26627. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26628. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26629. }
  26630. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26631. {
  26632. if (increment < 0)
  26633. {
  26634. ev.xbutton.button = Button5;
  26635. ev.xbutton.state |= Button5Mask;
  26636. }
  26637. else if (increment > 0)
  26638. {
  26639. ev.xbutton.button = Button4;
  26640. ev.xbutton.state |= Button4Mask;
  26641. }
  26642. }
  26643. #endif
  26644. class ModuleHandle : public ReferenceCountedObject
  26645. {
  26646. public:
  26647. File file;
  26648. MainCall moduleMain;
  26649. String pluginName;
  26650. static Array <ModuleHandle*>& getActiveModules()
  26651. {
  26652. static Array <ModuleHandle*> activeModules;
  26653. return activeModules;
  26654. }
  26655. static ModuleHandle* findOrCreateModule (const File& file)
  26656. {
  26657. for (int i = getActiveModules().size(); --i >= 0;)
  26658. {
  26659. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26660. if (module->file == file)
  26661. return module;
  26662. }
  26663. _fpreset(); // (doesn't do any harm)
  26664. ++insideVSTCallback;
  26665. shellUIDToCreate = 0;
  26666. log ("Attempting to load VST: " + file.getFullPathName());
  26667. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26668. if (! m->open())
  26669. m = 0;
  26670. --insideVSTCallback;
  26671. _fpreset(); // (doesn't do any harm)
  26672. return m.release();
  26673. }
  26674. ModuleHandle (const File& file_)
  26675. : file (file_),
  26676. moduleMain (0),
  26677. #if JUCE_WINDOWS || JUCE_LINUX
  26678. hModule (0)
  26679. #elif JUCE_MAC
  26680. fragId (0),
  26681. resHandle (0),
  26682. bundleRef (0),
  26683. resFileId (0)
  26684. #endif
  26685. {
  26686. getActiveModules().add (this);
  26687. #if JUCE_WINDOWS || JUCE_LINUX
  26688. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26689. #elif JUCE_MAC
  26690. FSRef ref;
  26691. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26692. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26693. #endif
  26694. }
  26695. ~ModuleHandle()
  26696. {
  26697. getActiveModules().removeValue (this);
  26698. close();
  26699. }
  26700. juce_UseDebuggingNewOperator
  26701. #if JUCE_WINDOWS || JUCE_LINUX
  26702. void* hModule;
  26703. String fullParentDirectoryPathName;
  26704. bool open()
  26705. {
  26706. #if JUCE_WINDOWS
  26707. static bool timePeriodSet = false;
  26708. if (! timePeriodSet)
  26709. {
  26710. timePeriodSet = true;
  26711. timeBeginPeriod (2);
  26712. }
  26713. #endif
  26714. pluginName = file.getFileNameWithoutExtension();
  26715. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26716. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26717. if (moduleMain == 0)
  26718. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26719. return moduleMain != 0;
  26720. }
  26721. void close()
  26722. {
  26723. _fpreset(); // (doesn't do any harm)
  26724. PlatformUtilities::freeDynamicLibrary (hModule);
  26725. }
  26726. void closeEffect (AEffect* eff)
  26727. {
  26728. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26729. }
  26730. #else
  26731. CFragConnectionID fragId;
  26732. Handle resHandle;
  26733. CFBundleRef bundleRef;
  26734. FSSpec parentDirFSSpec;
  26735. short resFileId;
  26736. bool open()
  26737. {
  26738. bool ok = false;
  26739. const String filename (file.getFullPathName());
  26740. if (file.hasFileExtension (".vst"))
  26741. {
  26742. const char* const utf8 = filename.toUTF8();
  26743. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26744. strlen (utf8), file.isDirectory());
  26745. if (url != 0)
  26746. {
  26747. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26748. CFRelease (url);
  26749. if (bundleRef != 0)
  26750. {
  26751. if (CFBundleLoadExecutable (bundleRef))
  26752. {
  26753. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26754. if (moduleMain == 0)
  26755. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26756. if (moduleMain != 0)
  26757. {
  26758. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26759. if (name != 0)
  26760. {
  26761. if (CFGetTypeID (name) == CFStringGetTypeID())
  26762. {
  26763. char buffer[1024];
  26764. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26765. pluginName = buffer;
  26766. }
  26767. }
  26768. if (pluginName.isEmpty())
  26769. pluginName = file.getFileNameWithoutExtension();
  26770. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26771. ok = true;
  26772. }
  26773. }
  26774. if (! ok)
  26775. {
  26776. CFBundleUnloadExecutable (bundleRef);
  26777. CFRelease (bundleRef);
  26778. bundleRef = 0;
  26779. }
  26780. }
  26781. }
  26782. }
  26783. #if JUCE_PPC
  26784. else
  26785. {
  26786. FSRef fn;
  26787. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26788. {
  26789. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26790. if (resFileId != -1)
  26791. {
  26792. const int numEffs = Count1Resources ('aEff');
  26793. for (int i = 0; i < numEffs; ++i)
  26794. {
  26795. resHandle = Get1IndResource ('aEff', i + 1);
  26796. if (resHandle != 0)
  26797. {
  26798. OSType type;
  26799. Str255 name;
  26800. SInt16 id;
  26801. GetResInfo (resHandle, &id, &type, name);
  26802. pluginName = String ((const char*) name + 1, name[0]);
  26803. DetachResource (resHandle);
  26804. HLock (resHandle);
  26805. Ptr ptr;
  26806. Str255 errorText;
  26807. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26808. name, kPrivateCFragCopy,
  26809. &fragId, &ptr, errorText);
  26810. if (err == noErr)
  26811. {
  26812. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26813. ok = true;
  26814. }
  26815. else
  26816. {
  26817. HUnlock (resHandle);
  26818. }
  26819. break;
  26820. }
  26821. }
  26822. if (! ok)
  26823. CloseResFile (resFileId);
  26824. }
  26825. }
  26826. }
  26827. #endif
  26828. return ok;
  26829. }
  26830. void close()
  26831. {
  26832. #if JUCE_PPC
  26833. if (fragId != 0)
  26834. {
  26835. if (moduleMain != 0)
  26836. disposeMachOFromCFM ((void*) moduleMain);
  26837. CloseConnection (&fragId);
  26838. HUnlock (resHandle);
  26839. if (resFileId != 0)
  26840. CloseResFile (resFileId);
  26841. }
  26842. else
  26843. #endif
  26844. if (bundleRef != 0)
  26845. {
  26846. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26847. if (CFGetRetainCount (bundleRef) == 1)
  26848. CFBundleUnloadExecutable (bundleRef);
  26849. if (CFGetRetainCount (bundleRef) > 0)
  26850. CFRelease (bundleRef);
  26851. }
  26852. }
  26853. void closeEffect (AEffect* eff)
  26854. {
  26855. #if JUCE_PPC
  26856. if (fragId != 0)
  26857. {
  26858. Array<void*> thingsToDelete;
  26859. thingsToDelete.add ((void*) eff->dispatcher);
  26860. thingsToDelete.add ((void*) eff->process);
  26861. thingsToDelete.add ((void*) eff->setParameter);
  26862. thingsToDelete.add ((void*) eff->getParameter);
  26863. thingsToDelete.add ((void*) eff->processReplacing);
  26864. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26865. for (int i = thingsToDelete.size(); --i >= 0;)
  26866. disposeMachOFromCFM (thingsToDelete[i]);
  26867. }
  26868. else
  26869. #endif
  26870. {
  26871. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26872. }
  26873. }
  26874. #if JUCE_PPC
  26875. static void* newMachOFromCFM (void* cfmfp)
  26876. {
  26877. if (cfmfp == 0)
  26878. return 0;
  26879. UInt32* const mfp = new UInt32[6];
  26880. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26881. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26882. mfp[2] = 0x800c0000;
  26883. mfp[3] = 0x804c0004;
  26884. mfp[4] = 0x7c0903a6;
  26885. mfp[5] = 0x4e800420;
  26886. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26887. return mfp;
  26888. }
  26889. static void disposeMachOFromCFM (void* ptr)
  26890. {
  26891. delete[] static_cast <UInt32*> (ptr);
  26892. }
  26893. void coerceAEffectFunctionCalls (AEffect* eff)
  26894. {
  26895. if (fragId != 0)
  26896. {
  26897. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26898. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26899. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26900. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26901. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26902. }
  26903. }
  26904. #endif
  26905. #endif
  26906. };
  26907. /**
  26908. An instance of a plugin, created by a VSTPluginFormat.
  26909. */
  26910. class VSTPluginInstance : public AudioPluginInstance,
  26911. private Timer,
  26912. private AsyncUpdater
  26913. {
  26914. public:
  26915. ~VSTPluginInstance();
  26916. // AudioPluginInstance methods:
  26917. void fillInPluginDescription (PluginDescription& desc) const
  26918. {
  26919. desc.name = name;
  26920. desc.fileOrIdentifier = module->file.getFullPathName();
  26921. desc.uid = getUID();
  26922. desc.lastFileModTime = module->file.getLastModificationTime();
  26923. desc.pluginFormatName = "VST";
  26924. desc.category = getCategory();
  26925. {
  26926. char buffer [kVstMaxVendorStrLen + 8];
  26927. zerostruct (buffer);
  26928. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26929. desc.manufacturerName = buffer;
  26930. }
  26931. desc.version = getVersion();
  26932. desc.numInputChannels = getNumInputChannels();
  26933. desc.numOutputChannels = getNumOutputChannels();
  26934. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26935. }
  26936. const String getName() const { return name; }
  26937. int getUID() const;
  26938. bool acceptsMidi() const { return wantsMidiMessages; }
  26939. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26940. // AudioProcessor methods:
  26941. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26942. void releaseResources();
  26943. void processBlock (AudioSampleBuffer& buffer,
  26944. MidiBuffer& midiMessages);
  26945. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26946. AudioProcessorEditor* createEditor();
  26947. const String getInputChannelName (int index) const;
  26948. bool isInputChannelStereoPair (int index) const;
  26949. const String getOutputChannelName (int index) const;
  26950. bool isOutputChannelStereoPair (int index) const;
  26951. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26952. float getParameter (int index);
  26953. void setParameter (int index, float newValue);
  26954. const String getParameterName (int index);
  26955. const String getParameterText (int index);
  26956. bool isParameterAutomatable (int index) const;
  26957. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26958. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26959. void setCurrentProgram (int index);
  26960. const String getProgramName (int index);
  26961. void changeProgramName (int index, const String& newName);
  26962. void getStateInformation (MemoryBlock& destData);
  26963. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26964. void setStateInformation (const void* data, int sizeInBytes);
  26965. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26966. void timerCallback();
  26967. void handleAsyncUpdate();
  26968. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26969. juce_UseDebuggingNewOperator
  26970. private:
  26971. friend class VSTPluginWindow;
  26972. friend class VSTPluginFormat;
  26973. AEffect* effect;
  26974. String name;
  26975. CriticalSection lock;
  26976. bool wantsMidiMessages, initialised, isPowerOn;
  26977. mutable StringArray programNames;
  26978. AudioSampleBuffer tempBuffer;
  26979. CriticalSection midiInLock;
  26980. MidiBuffer incomingMidi;
  26981. VSTMidiEventList midiEventsToSend;
  26982. VstTimeInfo vstHostTime;
  26983. ReferenceCountedObjectPtr <ModuleHandle> module;
  26984. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26985. bool restoreProgramSettings (const fxProgram* const prog);
  26986. const String getCurrentProgramName();
  26987. void setParamsInProgramBlock (fxProgram* const prog);
  26988. void updateStoredProgramNames();
  26989. void initialise();
  26990. void handleMidiFromPlugin (const VstEvents* const events);
  26991. void createTempParameterStore (MemoryBlock& dest);
  26992. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26993. const String getParameterLabel (int index) const;
  26994. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26995. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26996. void setChunkData (const char* data, int size, bool isPreset);
  26997. bool loadFromFXBFile (const void* data, int numBytes);
  26998. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26999. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27000. const String getVersion() const;
  27001. const String getCategory() const;
  27002. void setPower (const bool on);
  27003. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27004. };
  27005. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27006. : effect (0),
  27007. wantsMidiMessages (false),
  27008. initialised (false),
  27009. isPowerOn (false),
  27010. tempBuffer (1, 1),
  27011. module (module_)
  27012. {
  27013. try
  27014. {
  27015. _fpreset();
  27016. ++insideVSTCallback;
  27017. name = module->pluginName;
  27018. log ("Creating VST instance: " + name);
  27019. #if JUCE_MAC
  27020. if (module->resFileId != 0)
  27021. UseResFile (module->resFileId);
  27022. #if JUCE_PPC
  27023. if (module->fragId != 0)
  27024. {
  27025. static void* audioMasterCoerced = 0;
  27026. if (audioMasterCoerced == 0)
  27027. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27028. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27029. }
  27030. else
  27031. #endif
  27032. #endif
  27033. {
  27034. effect = module->moduleMain (&audioMaster);
  27035. }
  27036. --insideVSTCallback;
  27037. if (effect != 0 && effect->magic == kEffectMagic)
  27038. {
  27039. #if JUCE_PPC
  27040. module->coerceAEffectFunctionCalls (effect);
  27041. #endif
  27042. jassert (effect->resvd2 == 0);
  27043. jassert (effect->object != 0);
  27044. _fpreset(); // some dodgy plugs fuck around with this
  27045. }
  27046. else
  27047. {
  27048. effect = 0;
  27049. }
  27050. }
  27051. catch (...)
  27052. {
  27053. --insideVSTCallback;
  27054. }
  27055. }
  27056. VSTPluginInstance::~VSTPluginInstance()
  27057. {
  27058. const ScopedLock sl (lock);
  27059. jassert (insideVSTCallback == 0);
  27060. if (effect != 0 && effect->magic == kEffectMagic)
  27061. {
  27062. try
  27063. {
  27064. #if JUCE_MAC
  27065. if (module->resFileId != 0)
  27066. UseResFile (module->resFileId);
  27067. #endif
  27068. // Must delete any editors before deleting the plugin instance!
  27069. jassert (getActiveEditor() == 0);
  27070. _fpreset(); // some dodgy plugs fuck around with this
  27071. module->closeEffect (effect);
  27072. }
  27073. catch (...)
  27074. {}
  27075. }
  27076. module = 0;
  27077. effect = 0;
  27078. }
  27079. void VSTPluginInstance::initialise()
  27080. {
  27081. if (initialised || effect == 0)
  27082. return;
  27083. log ("Initialising VST: " + module->pluginName);
  27084. initialised = true;
  27085. dispatch (effIdentify, 0, 0, 0, 0);
  27086. // this code would ask the plugin for its name, but so few plugins
  27087. // actually bother implementing this correctly, that it's better to
  27088. // just ignore it and use the file name instead.
  27089. /* {
  27090. char buffer [256];
  27091. zerostruct (buffer);
  27092. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27093. name = String (buffer).trim();
  27094. if (name.isEmpty())
  27095. name = module->pluginName;
  27096. }
  27097. */
  27098. if (getSampleRate() > 0)
  27099. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27100. if (getBlockSize() > 0)
  27101. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27102. dispatch (effOpen, 0, 0, 0, 0);
  27103. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27104. getSampleRate(), getBlockSize());
  27105. if (getNumPrograms() > 1)
  27106. setCurrentProgram (0);
  27107. else
  27108. dispatch (effSetProgram, 0, 0, 0, 0);
  27109. int i;
  27110. for (i = effect->numInputs; --i >= 0;)
  27111. dispatch (effConnectInput, i, 1, 0, 0);
  27112. for (i = effect->numOutputs; --i >= 0;)
  27113. dispatch (effConnectOutput, i, 1, 0, 0);
  27114. updateStoredProgramNames();
  27115. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27116. setLatencySamples (effect->initialDelay);
  27117. }
  27118. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27119. int samplesPerBlockExpected)
  27120. {
  27121. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27122. sampleRate_, samplesPerBlockExpected);
  27123. setLatencySamples (effect->initialDelay);
  27124. vstHostTime.tempo = 120.0;
  27125. vstHostTime.timeSigNumerator = 4;
  27126. vstHostTime.timeSigDenominator = 4;
  27127. vstHostTime.sampleRate = sampleRate_;
  27128. vstHostTime.samplePos = 0;
  27129. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27130. initialise();
  27131. if (initialised)
  27132. {
  27133. wantsMidiMessages = wantsMidiMessages
  27134. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27135. if (wantsMidiMessages)
  27136. midiEventsToSend.ensureSize (256);
  27137. else
  27138. midiEventsToSend.freeEvents();
  27139. incomingMidi.clear();
  27140. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27141. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27142. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27143. if (! isPowerOn)
  27144. setPower (true);
  27145. // dodgy hack to force some plugins to initialise the sample rate..
  27146. if ((! hasEditor()) && getNumParameters() > 0)
  27147. {
  27148. const float old = getParameter (0);
  27149. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27150. setParameter (0, old);
  27151. }
  27152. dispatch (effStartProcess, 0, 0, 0, 0);
  27153. }
  27154. }
  27155. void VSTPluginInstance::releaseResources()
  27156. {
  27157. if (initialised)
  27158. {
  27159. dispatch (effStopProcess, 0, 0, 0, 0);
  27160. setPower (false);
  27161. }
  27162. tempBuffer.setSize (1, 1);
  27163. incomingMidi.clear();
  27164. midiEventsToSend.freeEvents();
  27165. }
  27166. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27167. MidiBuffer& midiMessages)
  27168. {
  27169. const int numSamples = buffer.getNumSamples();
  27170. if (initialised)
  27171. {
  27172. AudioPlayHead* playHead = getPlayHead();
  27173. if (playHead != 0)
  27174. {
  27175. AudioPlayHead::CurrentPositionInfo position;
  27176. playHead->getCurrentPosition (position);
  27177. vstHostTime.tempo = position.bpm;
  27178. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27179. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27180. vstHostTime.ppqPos = position.ppqPosition;
  27181. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27182. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27183. if (position.isPlaying)
  27184. vstHostTime.flags |= kVstTransportPlaying;
  27185. else
  27186. vstHostTime.flags &= ~kVstTransportPlaying;
  27187. }
  27188. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27189. if (wantsMidiMessages)
  27190. {
  27191. midiEventsToSend.clear();
  27192. midiEventsToSend.ensureSize (1);
  27193. MidiBuffer::Iterator iter (midiMessages);
  27194. const uint8* midiData;
  27195. int numBytesOfMidiData, samplePosition;
  27196. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27197. {
  27198. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27199. jlimit (0, numSamples - 1, samplePosition));
  27200. }
  27201. try
  27202. {
  27203. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27204. }
  27205. catch (...)
  27206. {}
  27207. }
  27208. _clearfp();
  27209. if ((effect->flags & effFlagsCanReplacing) != 0)
  27210. {
  27211. try
  27212. {
  27213. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27214. }
  27215. catch (...)
  27216. {}
  27217. }
  27218. else
  27219. {
  27220. tempBuffer.setSize (effect->numOutputs, numSamples);
  27221. tempBuffer.clear();
  27222. try
  27223. {
  27224. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27225. }
  27226. catch (...)
  27227. {}
  27228. for (int i = effect->numOutputs; --i >= 0;)
  27229. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27230. }
  27231. }
  27232. else
  27233. {
  27234. // Not initialised, so just bypass..
  27235. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27236. buffer.clear (i, 0, buffer.getNumSamples());
  27237. }
  27238. {
  27239. // copy any incoming midi..
  27240. const ScopedLock sl (midiInLock);
  27241. midiMessages.swapWith (incomingMidi);
  27242. incomingMidi.clear();
  27243. }
  27244. }
  27245. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27246. {
  27247. if (events != 0)
  27248. {
  27249. const ScopedLock sl (midiInLock);
  27250. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27251. }
  27252. }
  27253. static Array <VSTPluginWindow*> activeVSTWindows;
  27254. class VSTPluginWindow : public AudioProcessorEditor,
  27255. #if ! JUCE_MAC
  27256. public ComponentMovementWatcher,
  27257. #endif
  27258. public Timer
  27259. {
  27260. public:
  27261. VSTPluginWindow (VSTPluginInstance& plugin_)
  27262. : AudioProcessorEditor (&plugin_),
  27263. #if ! JUCE_MAC
  27264. ComponentMovementWatcher (this),
  27265. #endif
  27266. plugin (plugin_),
  27267. isOpen (false),
  27268. wasShowing (false),
  27269. pluginRefusesToResize (false),
  27270. pluginWantsKeys (false),
  27271. alreadyInside (false),
  27272. recursiveResize (false)
  27273. {
  27274. #if JUCE_WINDOWS
  27275. sizeCheckCount = 0;
  27276. pluginHWND = 0;
  27277. #elif JUCE_LINUX
  27278. pluginWindow = None;
  27279. pluginProc = None;
  27280. #else
  27281. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27282. #endif
  27283. activeVSTWindows.add (this);
  27284. setSize (1, 1);
  27285. setOpaque (true);
  27286. setVisible (true);
  27287. }
  27288. ~VSTPluginWindow()
  27289. {
  27290. #if JUCE_MAC
  27291. innerWrapper = 0;
  27292. #else
  27293. closePluginWindow();
  27294. #endif
  27295. activeVSTWindows.removeValue (this);
  27296. plugin.editorBeingDeleted (this);
  27297. }
  27298. #if ! JUCE_MAC
  27299. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27300. {
  27301. if (recursiveResize)
  27302. return;
  27303. Component* const topComp = getTopLevelComponent();
  27304. if (topComp->getPeer() != 0)
  27305. {
  27306. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27307. recursiveResize = true;
  27308. #if JUCE_WINDOWS
  27309. if (pluginHWND != 0)
  27310. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27311. #elif JUCE_LINUX
  27312. if (pluginWindow != 0)
  27313. {
  27314. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27315. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27316. XMapRaised (display, pluginWindow);
  27317. }
  27318. #endif
  27319. recursiveResize = false;
  27320. }
  27321. }
  27322. void componentVisibilityChanged (Component&)
  27323. {
  27324. const bool isShowingNow = isShowing();
  27325. if (wasShowing != isShowingNow)
  27326. {
  27327. wasShowing = isShowingNow;
  27328. if (isShowingNow)
  27329. openPluginWindow();
  27330. else
  27331. closePluginWindow();
  27332. }
  27333. componentMovedOrResized (true, true);
  27334. }
  27335. void componentPeerChanged()
  27336. {
  27337. closePluginWindow();
  27338. openPluginWindow();
  27339. }
  27340. #endif
  27341. bool keyStateChanged (bool)
  27342. {
  27343. return pluginWantsKeys;
  27344. }
  27345. bool keyPressed (const KeyPress&)
  27346. {
  27347. return pluginWantsKeys;
  27348. }
  27349. #if JUCE_MAC
  27350. void paint (Graphics& g)
  27351. {
  27352. g.fillAll (Colours::black);
  27353. }
  27354. #else
  27355. void paint (Graphics& g)
  27356. {
  27357. if (isOpen)
  27358. {
  27359. ComponentPeer* const peer = getPeer();
  27360. if (peer != 0)
  27361. {
  27362. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27363. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27364. #if JUCE_LINUX
  27365. if (pluginWindow != 0)
  27366. {
  27367. const Rectangle<int> clip (g.getClipBounds());
  27368. XEvent ev;
  27369. zerostruct (ev);
  27370. ev.xexpose.type = Expose;
  27371. ev.xexpose.display = display;
  27372. ev.xexpose.window = pluginWindow;
  27373. ev.xexpose.x = clip.getX();
  27374. ev.xexpose.y = clip.getY();
  27375. ev.xexpose.width = clip.getWidth();
  27376. ev.xexpose.height = clip.getHeight();
  27377. sendEventToChild (&ev);
  27378. }
  27379. #endif
  27380. }
  27381. }
  27382. else
  27383. {
  27384. g.fillAll (Colours::black);
  27385. }
  27386. }
  27387. #endif
  27388. void timerCallback()
  27389. {
  27390. #if JUCE_WINDOWS
  27391. if (--sizeCheckCount <= 0)
  27392. {
  27393. sizeCheckCount = 10;
  27394. checkPluginWindowSize();
  27395. }
  27396. #endif
  27397. try
  27398. {
  27399. static bool reentrant = false;
  27400. if (! reentrant)
  27401. {
  27402. reentrant = true;
  27403. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27404. reentrant = false;
  27405. }
  27406. }
  27407. catch (...)
  27408. {}
  27409. }
  27410. void mouseDown (const MouseEvent& e)
  27411. {
  27412. #if JUCE_LINUX
  27413. if (pluginWindow == 0)
  27414. return;
  27415. toFront (true);
  27416. XEvent ev;
  27417. zerostruct (ev);
  27418. ev.xbutton.display = display;
  27419. ev.xbutton.type = ButtonPress;
  27420. ev.xbutton.window = pluginWindow;
  27421. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27422. ev.xbutton.time = CurrentTime;
  27423. ev.xbutton.x = e.x;
  27424. ev.xbutton.y = e.y;
  27425. ev.xbutton.x_root = e.getScreenX();
  27426. ev.xbutton.y_root = e.getScreenY();
  27427. translateJuceToXButtonModifiers (e, ev);
  27428. sendEventToChild (&ev);
  27429. #elif JUCE_WINDOWS
  27430. (void) e;
  27431. toFront (true);
  27432. #endif
  27433. }
  27434. void broughtToFront()
  27435. {
  27436. activeVSTWindows.removeValue (this);
  27437. activeVSTWindows.add (this);
  27438. #if JUCE_MAC
  27439. dispatch (effEditTop, 0, 0, 0, 0);
  27440. #endif
  27441. }
  27442. juce_UseDebuggingNewOperator
  27443. private:
  27444. VSTPluginInstance& plugin;
  27445. bool isOpen, wasShowing, recursiveResize;
  27446. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27447. #if JUCE_WINDOWS
  27448. HWND pluginHWND;
  27449. void* originalWndProc;
  27450. int sizeCheckCount;
  27451. #elif JUCE_LINUX
  27452. Window pluginWindow;
  27453. EventProcPtr pluginProc;
  27454. #endif
  27455. #if JUCE_MAC
  27456. void openPluginWindow (WindowRef parentWindow)
  27457. {
  27458. if (isOpen || parentWindow == 0)
  27459. return;
  27460. isOpen = true;
  27461. ERect* rect = 0;
  27462. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27463. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27464. // do this before and after like in the steinberg example
  27465. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27466. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27467. // Install keyboard hooks
  27468. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27469. // double-check it's not too tiny
  27470. int w = 250, h = 150;
  27471. if (rect != 0)
  27472. {
  27473. w = rect->right - rect->left;
  27474. h = rect->bottom - rect->top;
  27475. if (w == 0 || h == 0)
  27476. {
  27477. w = 250;
  27478. h = 150;
  27479. }
  27480. }
  27481. w = jmax (w, 32);
  27482. h = jmax (h, 32);
  27483. setSize (w, h);
  27484. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27485. repaint();
  27486. }
  27487. #else
  27488. void openPluginWindow()
  27489. {
  27490. if (isOpen || getWindowHandle() == 0)
  27491. return;
  27492. log ("Opening VST UI: " + plugin.name);
  27493. isOpen = true;
  27494. ERect* rect = 0;
  27495. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27496. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27497. // do this before and after like in the steinberg example
  27498. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27499. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27500. // Install keyboard hooks
  27501. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27502. #if JUCE_WINDOWS
  27503. originalWndProc = 0;
  27504. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27505. if (pluginHWND == 0)
  27506. {
  27507. isOpen = false;
  27508. setSize (300, 150);
  27509. return;
  27510. }
  27511. #pragma warning (push)
  27512. #pragma warning (disable: 4244)
  27513. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27514. if (! pluginWantsKeys)
  27515. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27516. #pragma warning (pop)
  27517. int w, h;
  27518. RECT r;
  27519. GetWindowRect (pluginHWND, &r);
  27520. w = r.right - r.left;
  27521. h = r.bottom - r.top;
  27522. if (rect != 0)
  27523. {
  27524. const int rw = rect->right - rect->left;
  27525. const int rh = rect->bottom - rect->top;
  27526. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27527. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27528. {
  27529. // very dodgy logic to decide which size is right.
  27530. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27531. {
  27532. SetWindowPos (pluginHWND, 0,
  27533. 0, 0, rw, rh,
  27534. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27535. GetWindowRect (pluginHWND, &r);
  27536. w = r.right - r.left;
  27537. h = r.bottom - r.top;
  27538. pluginRefusesToResize = (w != rw) || (h != rh);
  27539. w = rw;
  27540. h = rh;
  27541. }
  27542. }
  27543. }
  27544. #elif JUCE_LINUX
  27545. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27546. if (pluginWindow != 0)
  27547. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27548. XInternAtom (display, "_XEventProc", False));
  27549. int w = 250, h = 150;
  27550. if (rect != 0)
  27551. {
  27552. w = rect->right - rect->left;
  27553. h = rect->bottom - rect->top;
  27554. if (w == 0 || h == 0)
  27555. {
  27556. w = 250;
  27557. h = 150;
  27558. }
  27559. }
  27560. if (pluginWindow != 0)
  27561. XMapRaised (display, pluginWindow);
  27562. #endif
  27563. // double-check it's not too tiny
  27564. w = jmax (w, 32);
  27565. h = jmax (h, 32);
  27566. setSize (w, h);
  27567. #if JUCE_WINDOWS
  27568. checkPluginWindowSize();
  27569. #endif
  27570. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27571. repaint();
  27572. }
  27573. #endif
  27574. #if ! JUCE_MAC
  27575. void closePluginWindow()
  27576. {
  27577. if (isOpen)
  27578. {
  27579. log ("Closing VST UI: " + plugin.getName());
  27580. isOpen = false;
  27581. dispatch (effEditClose, 0, 0, 0, 0);
  27582. #if JUCE_WINDOWS
  27583. #pragma warning (push)
  27584. #pragma warning (disable: 4244)
  27585. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27586. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27587. #pragma warning (pop)
  27588. stopTimer();
  27589. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27590. DestroyWindow (pluginHWND);
  27591. pluginHWND = 0;
  27592. #elif JUCE_LINUX
  27593. stopTimer();
  27594. pluginWindow = 0;
  27595. pluginProc = 0;
  27596. #endif
  27597. }
  27598. }
  27599. #endif
  27600. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27601. {
  27602. return plugin.dispatch (opcode, index, value, ptr, opt);
  27603. }
  27604. #if JUCE_WINDOWS
  27605. void checkPluginWindowSize()
  27606. {
  27607. RECT r;
  27608. GetWindowRect (pluginHWND, &r);
  27609. const int w = r.right - r.left;
  27610. const int h = r.bottom - r.top;
  27611. if (isShowing() && w > 0 && h > 0
  27612. && (w != getWidth() || h != getHeight())
  27613. && ! pluginRefusesToResize)
  27614. {
  27615. setSize (w, h);
  27616. sizeCheckCount = 0;
  27617. }
  27618. }
  27619. // hooks to get keyboard events from VST windows..
  27620. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27621. {
  27622. for (int i = activeVSTWindows.size(); --i >= 0;)
  27623. {
  27624. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27625. if (w->pluginHWND == hW)
  27626. {
  27627. if (message == WM_CHAR
  27628. || message == WM_KEYDOWN
  27629. || message == WM_SYSKEYDOWN
  27630. || message == WM_KEYUP
  27631. || message == WM_SYSKEYUP
  27632. || message == WM_APPCOMMAND)
  27633. {
  27634. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27635. message, wParam, lParam);
  27636. }
  27637. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27638. (HWND) w->pluginHWND,
  27639. message,
  27640. wParam,
  27641. lParam);
  27642. }
  27643. }
  27644. return DefWindowProc (hW, message, wParam, lParam);
  27645. }
  27646. #endif
  27647. #if JUCE_LINUX
  27648. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27649. void sendEventToChild (XEvent* event)
  27650. {
  27651. if (pluginProc != 0)
  27652. {
  27653. // if the plugin publishes an event procedure, pass the event directly..
  27654. pluginProc (event);
  27655. }
  27656. else if (pluginWindow != 0)
  27657. {
  27658. // if the plugin has a window, then send the event to the window so that
  27659. // its message thread will pick it up..
  27660. XSendEvent (display, pluginWindow, False, 0L, event);
  27661. XFlush (display);
  27662. }
  27663. }
  27664. void mouseEnter (const MouseEvent& e)
  27665. {
  27666. if (pluginWindow != 0)
  27667. {
  27668. XEvent ev;
  27669. zerostruct (ev);
  27670. ev.xcrossing.display = display;
  27671. ev.xcrossing.type = EnterNotify;
  27672. ev.xcrossing.window = pluginWindow;
  27673. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27674. ev.xcrossing.time = CurrentTime;
  27675. ev.xcrossing.x = e.x;
  27676. ev.xcrossing.y = e.y;
  27677. ev.xcrossing.x_root = e.getScreenX();
  27678. ev.xcrossing.y_root = e.getScreenY();
  27679. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27680. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27681. translateJuceToXCrossingModifiers (e, ev);
  27682. sendEventToChild (&ev);
  27683. }
  27684. }
  27685. void mouseExit (const MouseEvent& e)
  27686. {
  27687. if (pluginWindow != 0)
  27688. {
  27689. XEvent ev;
  27690. zerostruct (ev);
  27691. ev.xcrossing.display = display;
  27692. ev.xcrossing.type = LeaveNotify;
  27693. ev.xcrossing.window = pluginWindow;
  27694. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27695. ev.xcrossing.time = CurrentTime;
  27696. ev.xcrossing.x = e.x;
  27697. ev.xcrossing.y = e.y;
  27698. ev.xcrossing.x_root = e.getScreenX();
  27699. ev.xcrossing.y_root = e.getScreenY();
  27700. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27701. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27702. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27703. translateJuceToXCrossingModifiers (e, ev);
  27704. sendEventToChild (&ev);
  27705. }
  27706. }
  27707. void mouseMove (const MouseEvent& e)
  27708. {
  27709. if (pluginWindow != 0)
  27710. {
  27711. XEvent ev;
  27712. zerostruct (ev);
  27713. ev.xmotion.display = display;
  27714. ev.xmotion.type = MotionNotify;
  27715. ev.xmotion.window = pluginWindow;
  27716. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27717. ev.xmotion.time = CurrentTime;
  27718. ev.xmotion.is_hint = NotifyNormal;
  27719. ev.xmotion.x = e.x;
  27720. ev.xmotion.y = e.y;
  27721. ev.xmotion.x_root = e.getScreenX();
  27722. ev.xmotion.y_root = e.getScreenY();
  27723. sendEventToChild (&ev);
  27724. }
  27725. }
  27726. void mouseDrag (const MouseEvent& e)
  27727. {
  27728. if (pluginWindow != 0)
  27729. {
  27730. XEvent ev;
  27731. zerostruct (ev);
  27732. ev.xmotion.display = display;
  27733. ev.xmotion.type = MotionNotify;
  27734. ev.xmotion.window = pluginWindow;
  27735. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27736. ev.xmotion.time = CurrentTime;
  27737. ev.xmotion.x = e.x ;
  27738. ev.xmotion.y = e.y;
  27739. ev.xmotion.x_root = e.getScreenX();
  27740. ev.xmotion.y_root = e.getScreenY();
  27741. ev.xmotion.is_hint = NotifyNormal;
  27742. translateJuceToXMotionModifiers (e, ev);
  27743. sendEventToChild (&ev);
  27744. }
  27745. }
  27746. void mouseUp (const MouseEvent& e)
  27747. {
  27748. if (pluginWindow != 0)
  27749. {
  27750. XEvent ev;
  27751. zerostruct (ev);
  27752. ev.xbutton.display = display;
  27753. ev.xbutton.type = ButtonRelease;
  27754. ev.xbutton.window = pluginWindow;
  27755. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27756. ev.xbutton.time = CurrentTime;
  27757. ev.xbutton.x = e.x;
  27758. ev.xbutton.y = e.y;
  27759. ev.xbutton.x_root = e.getScreenX();
  27760. ev.xbutton.y_root = e.getScreenY();
  27761. translateJuceToXButtonModifiers (e, ev);
  27762. sendEventToChild (&ev);
  27763. }
  27764. }
  27765. void mouseWheelMove (const MouseEvent& e,
  27766. float incrementX,
  27767. float incrementY)
  27768. {
  27769. if (pluginWindow != 0)
  27770. {
  27771. XEvent ev;
  27772. zerostruct (ev);
  27773. ev.xbutton.display = display;
  27774. ev.xbutton.type = ButtonPress;
  27775. ev.xbutton.window = pluginWindow;
  27776. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27777. ev.xbutton.time = CurrentTime;
  27778. ev.xbutton.x = e.x;
  27779. ev.xbutton.y = e.y;
  27780. ev.xbutton.x_root = e.getScreenX();
  27781. ev.xbutton.y_root = e.getScreenY();
  27782. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27783. sendEventToChild (&ev);
  27784. // TODO - put a usleep here ?
  27785. ev.xbutton.type = ButtonRelease;
  27786. sendEventToChild (&ev);
  27787. }
  27788. }
  27789. #endif
  27790. #if JUCE_MAC
  27791. #if ! JUCE_SUPPORT_CARBON
  27792. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27793. #endif
  27794. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27795. {
  27796. public:
  27797. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27798. : owner (owner_),
  27799. alreadyInside (false)
  27800. {
  27801. }
  27802. ~InnerWrapperComponent()
  27803. {
  27804. deleteWindow();
  27805. }
  27806. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27807. {
  27808. owner->openPluginWindow (windowRef);
  27809. return 0;
  27810. }
  27811. void removeView (HIViewRef)
  27812. {
  27813. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27814. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27815. }
  27816. bool getEmbeddedViewSize (int& w, int& h)
  27817. {
  27818. ERect* rect = 0;
  27819. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27820. w = rect->right - rect->left;
  27821. h = rect->bottom - rect->top;
  27822. return true;
  27823. }
  27824. void mouseDown (int x, int y)
  27825. {
  27826. if (! alreadyInside)
  27827. {
  27828. alreadyInside = true;
  27829. getTopLevelComponent()->toFront (true);
  27830. owner->dispatch (effEditMouse, x, y, 0, 0);
  27831. alreadyInside = false;
  27832. }
  27833. else
  27834. {
  27835. PostEvent (::mouseDown, 0);
  27836. }
  27837. }
  27838. void paint()
  27839. {
  27840. ComponentPeer* const peer = getPeer();
  27841. if (peer != 0)
  27842. {
  27843. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27844. ERect r;
  27845. r.left = pos.getX();
  27846. r.right = r.left + getWidth();
  27847. r.top = pos.getY();
  27848. r.bottom = r.top + getHeight();
  27849. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27850. }
  27851. }
  27852. private:
  27853. VSTPluginWindow* const owner;
  27854. bool alreadyInside;
  27855. };
  27856. friend class InnerWrapperComponent;
  27857. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27858. void resized()
  27859. {
  27860. innerWrapper->setSize (getWidth(), getHeight());
  27861. }
  27862. #endif
  27863. };
  27864. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27865. {
  27866. if (hasEditor())
  27867. return new VSTPluginWindow (*this);
  27868. return 0;
  27869. }
  27870. void VSTPluginInstance::handleAsyncUpdate()
  27871. {
  27872. // indicates that something about the plugin has changed..
  27873. updateHostDisplay();
  27874. }
  27875. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27876. {
  27877. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27878. {
  27879. changeProgramName (getCurrentProgram(), prog->prgName);
  27880. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27881. setParameter (i, vst_swapFloat (prog->params[i]));
  27882. return true;
  27883. }
  27884. return false;
  27885. }
  27886. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27887. const int dataSize)
  27888. {
  27889. if (dataSize < 28)
  27890. return false;
  27891. const fxSet* const set = (const fxSet*) data;
  27892. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27893. || vst_swap (set->version) > fxbVersionNum)
  27894. return false;
  27895. if (vst_swap (set->fxMagic) == 'FxBk')
  27896. {
  27897. // bank of programs
  27898. if (vst_swap (set->numPrograms) >= 0)
  27899. {
  27900. const int oldProg = getCurrentProgram();
  27901. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27902. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27903. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27904. {
  27905. if (i != oldProg)
  27906. {
  27907. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27908. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27909. return false;
  27910. if (vst_swap (set->numPrograms) > 0)
  27911. setCurrentProgram (i);
  27912. if (! restoreProgramSettings (prog))
  27913. return false;
  27914. }
  27915. }
  27916. if (vst_swap (set->numPrograms) > 0)
  27917. setCurrentProgram (oldProg);
  27918. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27919. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27920. return false;
  27921. if (! restoreProgramSettings (prog))
  27922. return false;
  27923. }
  27924. }
  27925. else if (vst_swap (set->fxMagic) == 'FxCk')
  27926. {
  27927. // single program
  27928. const fxProgram* const prog = (const fxProgram*) data;
  27929. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27930. return false;
  27931. changeProgramName (getCurrentProgram(), prog->prgName);
  27932. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27933. setParameter (i, vst_swapFloat (prog->params[i]));
  27934. }
  27935. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27936. {
  27937. // non-preset chunk
  27938. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27939. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27940. return false;
  27941. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27942. }
  27943. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27944. {
  27945. // preset chunk
  27946. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27947. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27948. return false;
  27949. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27950. changeProgramName (getCurrentProgram(), cset->name);
  27951. }
  27952. else
  27953. {
  27954. return false;
  27955. }
  27956. return true;
  27957. }
  27958. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27959. {
  27960. const int numParams = getNumParameters();
  27961. prog->chunkMagic = vst_swap ('CcnK');
  27962. prog->byteSize = 0;
  27963. prog->fxMagic = vst_swap ('FxCk');
  27964. prog->version = vst_swap (fxbVersionNum);
  27965. prog->fxID = vst_swap (getUID());
  27966. prog->fxVersion = vst_swap (getVersionNumber());
  27967. prog->numParams = vst_swap (numParams);
  27968. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27969. for (int i = 0; i < numParams; ++i)
  27970. prog->params[i] = vst_swapFloat (getParameter (i));
  27971. }
  27972. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27973. {
  27974. const int numPrograms = getNumPrograms();
  27975. const int numParams = getNumParameters();
  27976. if (usesChunks())
  27977. {
  27978. if (isFXB)
  27979. {
  27980. MemoryBlock chunk;
  27981. getChunkData (chunk, false, maxSizeMB);
  27982. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27983. dest.setSize (totalLen, true);
  27984. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27985. set->chunkMagic = vst_swap ('CcnK');
  27986. set->byteSize = 0;
  27987. set->fxMagic = vst_swap ('FBCh');
  27988. set->version = vst_swap (fxbVersionNum);
  27989. set->fxID = vst_swap (getUID());
  27990. set->fxVersion = vst_swap (getVersionNumber());
  27991. set->numPrograms = vst_swap (numPrograms);
  27992. set->chunkSize = vst_swap ((long) chunk.getSize());
  27993. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27994. }
  27995. else
  27996. {
  27997. MemoryBlock chunk;
  27998. getChunkData (chunk, true, maxSizeMB);
  27999. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28000. dest.setSize (totalLen, true);
  28001. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28002. set->chunkMagic = vst_swap ('CcnK');
  28003. set->byteSize = 0;
  28004. set->fxMagic = vst_swap ('FPCh');
  28005. set->version = vst_swap (fxbVersionNum);
  28006. set->fxID = vst_swap (getUID());
  28007. set->fxVersion = vst_swap (getVersionNumber());
  28008. set->numPrograms = vst_swap (numPrograms);
  28009. set->chunkSize = vst_swap ((long) chunk.getSize());
  28010. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28011. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28012. }
  28013. }
  28014. else
  28015. {
  28016. if (isFXB)
  28017. {
  28018. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28019. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28020. dest.setSize (len, true);
  28021. fxSet* const set = (fxSet*) dest.getData();
  28022. set->chunkMagic = vst_swap ('CcnK');
  28023. set->byteSize = 0;
  28024. set->fxMagic = vst_swap ('FxBk');
  28025. set->version = vst_swap (fxbVersionNum);
  28026. set->fxID = vst_swap (getUID());
  28027. set->fxVersion = vst_swap (getVersionNumber());
  28028. set->numPrograms = vst_swap (numPrograms);
  28029. const int oldProgram = getCurrentProgram();
  28030. MemoryBlock oldSettings;
  28031. createTempParameterStore (oldSettings);
  28032. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28033. for (int i = 0; i < numPrograms; ++i)
  28034. {
  28035. if (i != oldProgram)
  28036. {
  28037. setCurrentProgram (i);
  28038. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28039. }
  28040. }
  28041. setCurrentProgram (oldProgram);
  28042. restoreFromTempParameterStore (oldSettings);
  28043. }
  28044. else
  28045. {
  28046. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28047. dest.setSize (totalLen, true);
  28048. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28049. }
  28050. }
  28051. return true;
  28052. }
  28053. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28054. {
  28055. if (usesChunks())
  28056. {
  28057. void* data = 0;
  28058. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28059. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28060. {
  28061. mb.setSize (bytes);
  28062. mb.copyFrom (data, 0, bytes);
  28063. }
  28064. }
  28065. }
  28066. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28067. {
  28068. if (size > 0 && usesChunks())
  28069. {
  28070. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28071. if (! isPreset)
  28072. updateStoredProgramNames();
  28073. }
  28074. }
  28075. void VSTPluginInstance::timerCallback()
  28076. {
  28077. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28078. stopTimer();
  28079. }
  28080. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28081. {
  28082. const ScopedLock sl (lock);
  28083. ++insideVSTCallback;
  28084. int result = 0;
  28085. try
  28086. {
  28087. if (effect != 0)
  28088. {
  28089. #if JUCE_MAC
  28090. if (module->resFileId != 0)
  28091. UseResFile (module->resFileId);
  28092. #endif
  28093. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28094. #if JUCE_MAC
  28095. module->resFileId = CurResFile();
  28096. #endif
  28097. --insideVSTCallback;
  28098. return result;
  28099. }
  28100. }
  28101. catch (...)
  28102. {
  28103. }
  28104. --insideVSTCallback;
  28105. return result;
  28106. }
  28107. // handles non plugin-specific callbacks..
  28108. static const int defaultVSTSampleRateValue = 16384;
  28109. static const int defaultVSTBlockSizeValue = 512;
  28110. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28111. {
  28112. (void) index;
  28113. (void) value;
  28114. (void) opt;
  28115. switch (opcode)
  28116. {
  28117. case audioMasterCanDo:
  28118. {
  28119. static const char* canDos[] = { "supplyIdle",
  28120. "sendVstEvents",
  28121. "sendVstMidiEvent",
  28122. "sendVstTimeInfo",
  28123. "receiveVstEvents",
  28124. "receiveVstMidiEvent",
  28125. "supportShell",
  28126. "shellCategory" };
  28127. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28128. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28129. return 1;
  28130. return 0;
  28131. }
  28132. case audioMasterVersion: return 0x2400;
  28133. case audioMasterCurrentId: return shellUIDToCreate;
  28134. case audioMasterGetNumAutomatableParameters: return 0;
  28135. case audioMasterGetAutomationState: return 1;
  28136. case audioMasterGetVendorVersion: return 0x0101;
  28137. case audioMasterGetVendorString:
  28138. case audioMasterGetProductString:
  28139. {
  28140. String hostName ("Juce VST Host");
  28141. if (JUCEApplication::getInstance() != 0)
  28142. hostName = JUCEApplication::getInstance()->getApplicationName();
  28143. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28144. break;
  28145. }
  28146. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28147. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28148. case audioMasterSetOutputSampleRate: return 0;
  28149. default:
  28150. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28151. break;
  28152. }
  28153. return 0;
  28154. }
  28155. // handles callbacks for a specific plugin
  28156. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28157. {
  28158. switch (opcode)
  28159. {
  28160. case audioMasterAutomate:
  28161. sendParamChangeMessageToListeners (index, opt);
  28162. break;
  28163. case audioMasterProcessEvents:
  28164. handleMidiFromPlugin ((const VstEvents*) ptr);
  28165. break;
  28166. case audioMasterGetTime:
  28167. #if JUCE_MSVC
  28168. #pragma warning (push)
  28169. #pragma warning (disable: 4311)
  28170. #endif
  28171. return (VstIntPtr) &vstHostTime;
  28172. #if JUCE_MSVC
  28173. #pragma warning (pop)
  28174. #endif
  28175. break;
  28176. case audioMasterIdle:
  28177. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28178. {
  28179. ++insideVSTCallback;
  28180. #if JUCE_MAC
  28181. if (getActiveEditor() != 0)
  28182. dispatch (effEditIdle, 0, 0, 0, 0);
  28183. #endif
  28184. juce_callAnyTimersSynchronously();
  28185. handleUpdateNowIfNeeded();
  28186. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28187. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28188. --insideVSTCallback;
  28189. }
  28190. break;
  28191. case audioMasterUpdateDisplay:
  28192. triggerAsyncUpdate();
  28193. break;
  28194. case audioMasterTempoAt:
  28195. // returns (10000 * bpm)
  28196. break;
  28197. case audioMasterNeedIdle:
  28198. startTimer (50);
  28199. break;
  28200. case audioMasterSizeWindow:
  28201. if (getActiveEditor() != 0)
  28202. getActiveEditor()->setSize (index, value);
  28203. return 1;
  28204. case audioMasterGetSampleRate:
  28205. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28206. case audioMasterGetBlockSize:
  28207. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28208. case audioMasterWantMidi:
  28209. wantsMidiMessages = true;
  28210. break;
  28211. case audioMasterGetDirectory:
  28212. #if JUCE_MAC
  28213. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28214. #else
  28215. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28216. #endif
  28217. case audioMasterGetAutomationState:
  28218. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28219. break;
  28220. // none of these are handled (yet)..
  28221. case audioMasterBeginEdit:
  28222. case audioMasterEndEdit:
  28223. case audioMasterSetTime:
  28224. case audioMasterPinConnected:
  28225. case audioMasterGetParameterQuantization:
  28226. case audioMasterIOChanged:
  28227. case audioMasterGetInputLatency:
  28228. case audioMasterGetOutputLatency:
  28229. case audioMasterGetPreviousPlug:
  28230. case audioMasterGetNextPlug:
  28231. case audioMasterWillReplaceOrAccumulate:
  28232. case audioMasterGetCurrentProcessLevel:
  28233. case audioMasterOfflineStart:
  28234. case audioMasterOfflineRead:
  28235. case audioMasterOfflineWrite:
  28236. case audioMasterOfflineGetCurrentPass:
  28237. case audioMasterOfflineGetCurrentMetaPass:
  28238. case audioMasterVendorSpecific:
  28239. case audioMasterSetIcon:
  28240. case audioMasterGetLanguage:
  28241. case audioMasterOpenWindow:
  28242. case audioMasterCloseWindow:
  28243. break;
  28244. default:
  28245. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28246. }
  28247. return 0;
  28248. }
  28249. // entry point for all callbacks from the plugin
  28250. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28251. {
  28252. try
  28253. {
  28254. if (effect != 0 && effect->resvd2 != 0)
  28255. {
  28256. return ((VSTPluginInstance*)(effect->resvd2))
  28257. ->handleCallback (opcode, index, value, ptr, opt);
  28258. }
  28259. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28260. }
  28261. catch (...)
  28262. {
  28263. return 0;
  28264. }
  28265. }
  28266. const String VSTPluginInstance::getVersion() const
  28267. {
  28268. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28269. String s;
  28270. if (v == 0 || v == -1)
  28271. v = getVersionNumber();
  28272. if (v != 0)
  28273. {
  28274. int versionBits[4];
  28275. int n = 0;
  28276. while (v != 0)
  28277. {
  28278. versionBits [n++] = (v & 0xff);
  28279. v >>= 8;
  28280. }
  28281. s << 'V';
  28282. while (n > 0)
  28283. {
  28284. s << versionBits [--n];
  28285. if (n > 0)
  28286. s << '.';
  28287. }
  28288. }
  28289. return s;
  28290. }
  28291. int VSTPluginInstance::getUID() const
  28292. {
  28293. int uid = effect != 0 ? effect->uniqueID : 0;
  28294. if (uid == 0)
  28295. uid = module->file.hashCode();
  28296. return uid;
  28297. }
  28298. const String VSTPluginInstance::getCategory() const
  28299. {
  28300. const char* result = 0;
  28301. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28302. {
  28303. case kPlugCategEffect: result = "Effect"; break;
  28304. case kPlugCategSynth: result = "Synth"; break;
  28305. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28306. case kPlugCategMastering: result = "Mastering"; break;
  28307. case kPlugCategSpacializer: result = "Spacial"; break;
  28308. case kPlugCategRoomFx: result = "Reverb"; break;
  28309. case kPlugSurroundFx: result = "Surround"; break;
  28310. case kPlugCategRestoration: result = "Restoration"; break;
  28311. case kPlugCategGenerator: result = "Tone generation"; break;
  28312. default: break;
  28313. }
  28314. return result;
  28315. }
  28316. float VSTPluginInstance::getParameter (int index)
  28317. {
  28318. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28319. {
  28320. try
  28321. {
  28322. const ScopedLock sl (lock);
  28323. return effect->getParameter (effect, index);
  28324. }
  28325. catch (...)
  28326. {
  28327. }
  28328. }
  28329. return 0.0f;
  28330. }
  28331. void VSTPluginInstance::setParameter (int index, float newValue)
  28332. {
  28333. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28334. {
  28335. try
  28336. {
  28337. const ScopedLock sl (lock);
  28338. if (effect->getParameter (effect, index) != newValue)
  28339. effect->setParameter (effect, index, newValue);
  28340. }
  28341. catch (...)
  28342. {
  28343. }
  28344. }
  28345. }
  28346. const String VSTPluginInstance::getParameterName (int index)
  28347. {
  28348. if (effect != 0)
  28349. {
  28350. jassert (index >= 0 && index < effect->numParams);
  28351. char nm [256];
  28352. zerostruct (nm);
  28353. dispatch (effGetParamName, index, 0, nm, 0);
  28354. return String (nm).trim();
  28355. }
  28356. return String::empty;
  28357. }
  28358. const String VSTPluginInstance::getParameterLabel (int index) const
  28359. {
  28360. if (effect != 0)
  28361. {
  28362. jassert (index >= 0 && index < effect->numParams);
  28363. char nm [256];
  28364. zerostruct (nm);
  28365. dispatch (effGetParamLabel, index, 0, nm, 0);
  28366. return String (nm).trim();
  28367. }
  28368. return String::empty;
  28369. }
  28370. const String VSTPluginInstance::getParameterText (int index)
  28371. {
  28372. if (effect != 0)
  28373. {
  28374. jassert (index >= 0 && index < effect->numParams);
  28375. char nm [256];
  28376. zerostruct (nm);
  28377. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28378. return String (nm).trim();
  28379. }
  28380. return String::empty;
  28381. }
  28382. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28383. {
  28384. if (effect != 0)
  28385. {
  28386. jassert (index >= 0 && index < effect->numParams);
  28387. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28388. }
  28389. return false;
  28390. }
  28391. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28392. {
  28393. dest.setSize (64 + 4 * getNumParameters());
  28394. dest.fillWith (0);
  28395. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28396. float* const p = (float*) (((char*) dest.getData()) + 64);
  28397. for (int i = 0; i < getNumParameters(); ++i)
  28398. p[i] = getParameter(i);
  28399. }
  28400. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28401. {
  28402. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28403. float* p = (float*) (((char*) m.getData()) + 64);
  28404. for (int i = 0; i < getNumParameters(); ++i)
  28405. setParameter (i, p[i]);
  28406. }
  28407. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28408. {
  28409. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28410. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28411. }
  28412. const String VSTPluginInstance::getProgramName (int index)
  28413. {
  28414. if (index == getCurrentProgram())
  28415. {
  28416. return getCurrentProgramName();
  28417. }
  28418. else if (effect != 0)
  28419. {
  28420. char nm [256];
  28421. zerostruct (nm);
  28422. if (dispatch (effGetProgramNameIndexed,
  28423. jlimit (0, getNumPrograms(), index),
  28424. -1, nm, 0) != 0)
  28425. {
  28426. return String (nm).trim();
  28427. }
  28428. }
  28429. return programNames [index];
  28430. }
  28431. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28432. {
  28433. if (index == getCurrentProgram())
  28434. {
  28435. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28436. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28437. }
  28438. else
  28439. {
  28440. jassertfalse; // xxx not implemented!
  28441. }
  28442. }
  28443. void VSTPluginInstance::updateStoredProgramNames()
  28444. {
  28445. if (effect != 0 && getNumPrograms() > 0)
  28446. {
  28447. char nm [256];
  28448. zerostruct (nm);
  28449. // only do this if the plugin can't use indexed names..
  28450. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28451. {
  28452. const int oldProgram = getCurrentProgram();
  28453. MemoryBlock oldSettings;
  28454. createTempParameterStore (oldSettings);
  28455. for (int i = 0; i < getNumPrograms(); ++i)
  28456. {
  28457. setCurrentProgram (i);
  28458. getCurrentProgramName(); // (this updates the list)
  28459. }
  28460. setCurrentProgram (oldProgram);
  28461. restoreFromTempParameterStore (oldSettings);
  28462. }
  28463. }
  28464. }
  28465. const String VSTPluginInstance::getCurrentProgramName()
  28466. {
  28467. if (effect != 0)
  28468. {
  28469. char nm [256];
  28470. zerostruct (nm);
  28471. dispatch (effGetProgramName, 0, 0, nm, 0);
  28472. const int index = getCurrentProgram();
  28473. if (programNames[index].isEmpty())
  28474. {
  28475. while (programNames.size() < index)
  28476. programNames.add (String::empty);
  28477. programNames.set (index, String (nm).trim());
  28478. }
  28479. return String (nm).trim();
  28480. }
  28481. return String::empty;
  28482. }
  28483. const String VSTPluginInstance::getInputChannelName (int index) const
  28484. {
  28485. if (index >= 0 && index < getNumInputChannels())
  28486. {
  28487. VstPinProperties pinProps;
  28488. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28489. return String (pinProps.label, sizeof (pinProps.label));
  28490. }
  28491. return String::empty;
  28492. }
  28493. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28494. {
  28495. if (index < 0 || index >= getNumInputChannels())
  28496. return false;
  28497. VstPinProperties pinProps;
  28498. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28499. return (pinProps.flags & kVstPinIsStereo) != 0;
  28500. return true;
  28501. }
  28502. const String VSTPluginInstance::getOutputChannelName (int index) const
  28503. {
  28504. if (index >= 0 && index < getNumOutputChannels())
  28505. {
  28506. VstPinProperties pinProps;
  28507. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28508. return String (pinProps.label, sizeof (pinProps.label));
  28509. }
  28510. return String::empty;
  28511. }
  28512. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28513. {
  28514. if (index < 0 || index >= getNumOutputChannels())
  28515. return false;
  28516. VstPinProperties pinProps;
  28517. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28518. return (pinProps.flags & kVstPinIsStereo) != 0;
  28519. return true;
  28520. }
  28521. void VSTPluginInstance::setPower (const bool on)
  28522. {
  28523. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28524. isPowerOn = on;
  28525. }
  28526. const int defaultMaxSizeMB = 64;
  28527. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28528. {
  28529. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28530. }
  28531. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28532. {
  28533. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28534. }
  28535. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28536. {
  28537. loadFromFXBFile (data, sizeInBytes);
  28538. }
  28539. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28540. {
  28541. loadFromFXBFile (data, sizeInBytes);
  28542. }
  28543. VSTPluginFormat::VSTPluginFormat()
  28544. {
  28545. }
  28546. VSTPluginFormat::~VSTPluginFormat()
  28547. {
  28548. }
  28549. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28550. const String& fileOrIdentifier)
  28551. {
  28552. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28553. return;
  28554. PluginDescription desc;
  28555. desc.fileOrIdentifier = fileOrIdentifier;
  28556. desc.uid = 0;
  28557. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28558. if (instance == 0)
  28559. return;
  28560. try
  28561. {
  28562. #if JUCE_MAC
  28563. if (instance->module->resFileId != 0)
  28564. UseResFile (instance->module->resFileId);
  28565. #endif
  28566. instance->fillInPluginDescription (desc);
  28567. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28568. if (category != kPlugCategShell)
  28569. {
  28570. // Normal plugin...
  28571. results.add (new PluginDescription (desc));
  28572. ++insideVSTCallback;
  28573. instance->dispatch (effOpen, 0, 0, 0, 0);
  28574. --insideVSTCallback;
  28575. }
  28576. else
  28577. {
  28578. // It's a shell plugin, so iterate all the subtypes...
  28579. char shellEffectName [64];
  28580. for (;;)
  28581. {
  28582. zerostruct (shellEffectName);
  28583. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28584. if (uid == 0)
  28585. {
  28586. break;
  28587. }
  28588. else
  28589. {
  28590. desc.uid = uid;
  28591. desc.name = shellEffectName;
  28592. bool alreadyThere = false;
  28593. for (int i = results.size(); --i >= 0;)
  28594. {
  28595. PluginDescription* const d = results.getUnchecked(i);
  28596. if (d->isDuplicateOf (desc))
  28597. {
  28598. alreadyThere = true;
  28599. break;
  28600. }
  28601. }
  28602. if (! alreadyThere)
  28603. results.add (new PluginDescription (desc));
  28604. }
  28605. }
  28606. }
  28607. }
  28608. catch (...)
  28609. {
  28610. // crashed while loading...
  28611. }
  28612. }
  28613. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28614. {
  28615. ScopedPointer <VSTPluginInstance> result;
  28616. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28617. {
  28618. File file (desc.fileOrIdentifier);
  28619. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28620. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28621. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28622. if (module != 0)
  28623. {
  28624. shellUIDToCreate = desc.uid;
  28625. result = new VSTPluginInstance (module);
  28626. if (result->effect != 0)
  28627. {
  28628. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28629. result->initialise();
  28630. }
  28631. else
  28632. {
  28633. result = 0;
  28634. }
  28635. }
  28636. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28637. }
  28638. return result.release();
  28639. }
  28640. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28641. {
  28642. const File f (fileOrIdentifier);
  28643. #if JUCE_MAC
  28644. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28645. return true;
  28646. #if JUCE_PPC
  28647. FSRef fileRef;
  28648. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28649. {
  28650. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28651. if (resFileId != -1)
  28652. {
  28653. const int numEffects = Count1Resources ('aEff');
  28654. CloseResFile (resFileId);
  28655. if (numEffects > 0)
  28656. return true;
  28657. }
  28658. }
  28659. #endif
  28660. return false;
  28661. #elif JUCE_WINDOWS
  28662. return f.existsAsFile() && f.hasFileExtension (".dll");
  28663. #elif JUCE_LINUX
  28664. return f.existsAsFile() && f.hasFileExtension (".so");
  28665. #endif
  28666. }
  28667. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28668. {
  28669. return fileOrIdentifier;
  28670. }
  28671. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28672. {
  28673. return File (desc.fileOrIdentifier).exists();
  28674. }
  28675. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28676. {
  28677. StringArray results;
  28678. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28679. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28680. return results;
  28681. }
  28682. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28683. {
  28684. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28685. // .component or .vst directories.
  28686. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28687. while (iter.next())
  28688. {
  28689. const File f (iter.getFile());
  28690. bool isPlugin = false;
  28691. if (fileMightContainThisPluginType (f.getFullPathName()))
  28692. {
  28693. isPlugin = true;
  28694. results.add (f.getFullPathName());
  28695. }
  28696. if (recursive && (! isPlugin) && f.isDirectory())
  28697. recursiveFileSearch (results, f, true);
  28698. }
  28699. }
  28700. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28701. {
  28702. #if JUCE_MAC
  28703. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28704. #elif JUCE_WINDOWS
  28705. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28706. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28707. #elif JUCE_LINUX
  28708. return FileSearchPath ("/usr/lib/vst");
  28709. #endif
  28710. }
  28711. END_JUCE_NAMESPACE
  28712. #endif
  28713. #undef log
  28714. #endif
  28715. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28716. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28717. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28718. BEGIN_JUCE_NAMESPACE
  28719. AudioProcessor::AudioProcessor()
  28720. : playHead (0),
  28721. activeEditor (0),
  28722. sampleRate (0),
  28723. blockSize (0),
  28724. numInputChannels (0),
  28725. numOutputChannels (0),
  28726. latencySamples (0),
  28727. suspended (false),
  28728. nonRealtime (false)
  28729. {
  28730. }
  28731. AudioProcessor::~AudioProcessor()
  28732. {
  28733. // ooh, nasty - the editor should have been deleted before the filter
  28734. // that it refers to is deleted..
  28735. jassert (activeEditor == 0);
  28736. #if JUCE_DEBUG
  28737. // This will fail if you've called beginParameterChangeGesture() for one
  28738. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28739. jassert (changingParams.countNumberOfSetBits() == 0);
  28740. #endif
  28741. }
  28742. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28743. {
  28744. playHead = newPlayHead;
  28745. }
  28746. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28747. {
  28748. const ScopedLock sl (listenerLock);
  28749. listeners.addIfNotAlreadyThere (newListener);
  28750. }
  28751. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28752. {
  28753. const ScopedLock sl (listenerLock);
  28754. listeners.removeValue (listenerToRemove);
  28755. }
  28756. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28757. const int numOuts,
  28758. const double sampleRate_,
  28759. const int blockSize_) throw()
  28760. {
  28761. numInputChannels = numIns;
  28762. numOutputChannels = numOuts;
  28763. sampleRate = sampleRate_;
  28764. blockSize = blockSize_;
  28765. }
  28766. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28767. {
  28768. nonRealtime = nonRealtime_;
  28769. }
  28770. void AudioProcessor::setLatencySamples (const int newLatency)
  28771. {
  28772. if (latencySamples != newLatency)
  28773. {
  28774. latencySamples = newLatency;
  28775. updateHostDisplay();
  28776. }
  28777. }
  28778. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28779. const float newValue)
  28780. {
  28781. setParameter (parameterIndex, newValue);
  28782. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28783. }
  28784. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28785. {
  28786. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28787. for (int i = listeners.size(); --i >= 0;)
  28788. {
  28789. AudioProcessorListener* l;
  28790. {
  28791. const ScopedLock sl (listenerLock);
  28792. l = listeners [i];
  28793. }
  28794. if (l != 0)
  28795. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28796. }
  28797. }
  28798. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28799. {
  28800. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28801. #if JUCE_DEBUG
  28802. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28803. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28804. jassert (! changingParams [parameterIndex]);
  28805. changingParams.setBit (parameterIndex);
  28806. #endif
  28807. for (int i = listeners.size(); --i >= 0;)
  28808. {
  28809. AudioProcessorListener* l;
  28810. {
  28811. const ScopedLock sl (listenerLock);
  28812. l = listeners [i];
  28813. }
  28814. if (l != 0)
  28815. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28816. }
  28817. }
  28818. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28819. {
  28820. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28821. #if JUCE_DEBUG
  28822. // This means you've called endParameterChangeGesture without having previously called
  28823. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28824. // calls matched correctly.
  28825. jassert (changingParams [parameterIndex]);
  28826. changingParams.clearBit (parameterIndex);
  28827. #endif
  28828. for (int i = listeners.size(); --i >= 0;)
  28829. {
  28830. AudioProcessorListener* l;
  28831. {
  28832. const ScopedLock sl (listenerLock);
  28833. l = listeners [i];
  28834. }
  28835. if (l != 0)
  28836. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28837. }
  28838. }
  28839. void AudioProcessor::updateHostDisplay()
  28840. {
  28841. for (int i = listeners.size(); --i >= 0;)
  28842. {
  28843. AudioProcessorListener* l;
  28844. {
  28845. const ScopedLock sl (listenerLock);
  28846. l = listeners [i];
  28847. }
  28848. if (l != 0)
  28849. l->audioProcessorChanged (this);
  28850. }
  28851. }
  28852. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28853. {
  28854. return true;
  28855. }
  28856. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28857. {
  28858. return false;
  28859. }
  28860. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28861. {
  28862. const ScopedLock sl (callbackLock);
  28863. suspended = shouldBeSuspended;
  28864. }
  28865. void AudioProcessor::reset()
  28866. {
  28867. }
  28868. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28869. {
  28870. const ScopedLock sl (callbackLock);
  28871. jassert (activeEditor == editor);
  28872. if (activeEditor == editor)
  28873. activeEditor = 0;
  28874. }
  28875. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28876. {
  28877. if (activeEditor != 0)
  28878. return activeEditor;
  28879. AudioProcessorEditor* const ed = createEditor();
  28880. // You must make your hasEditor() method return a consistent result!
  28881. jassert (hasEditor() == (ed != 0));
  28882. if (ed != 0)
  28883. {
  28884. // you must give your editor comp a size before returning it..
  28885. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28886. const ScopedLock sl (callbackLock);
  28887. activeEditor = ed;
  28888. }
  28889. return ed;
  28890. }
  28891. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28892. {
  28893. getStateInformation (destData);
  28894. }
  28895. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28896. {
  28897. setStateInformation (data, sizeInBytes);
  28898. }
  28899. // magic number to identify memory blocks that we've stored as XML
  28900. const uint32 magicXmlNumber = 0x21324356;
  28901. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28902. JUCE_NAMESPACE::MemoryBlock& destData)
  28903. {
  28904. const String xmlString (xml.createDocument (String::empty, true, false));
  28905. const int stringLength = xmlString.getNumBytesAsUTF8();
  28906. destData.setSize (stringLength + 10);
  28907. char* const d = static_cast<char*> (destData.getData());
  28908. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28909. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28910. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28911. }
  28912. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28913. const int sizeInBytes)
  28914. {
  28915. if (sizeInBytes > 8
  28916. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28917. {
  28918. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28919. if (stringLength > 0)
  28920. {
  28921. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28922. jmin ((sizeInBytes - 8), stringLength)));
  28923. return doc.getDocumentElement();
  28924. }
  28925. }
  28926. return 0;
  28927. }
  28928. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28929. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28930. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28931. {
  28932. return timeInSeconds == other.timeInSeconds
  28933. && ppqPosition == other.ppqPosition
  28934. && editOriginTime == other.editOriginTime
  28935. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28936. && frameRate == other.frameRate
  28937. && isPlaying == other.isPlaying
  28938. && isRecording == other.isRecording
  28939. && bpm == other.bpm
  28940. && timeSigNumerator == other.timeSigNumerator
  28941. && timeSigDenominator == other.timeSigDenominator;
  28942. }
  28943. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28944. {
  28945. return ! operator== (other);
  28946. }
  28947. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28948. {
  28949. zerostruct (*this);
  28950. timeSigNumerator = 4;
  28951. timeSigDenominator = 4;
  28952. bpm = 120;
  28953. }
  28954. END_JUCE_NAMESPACE
  28955. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28956. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28957. BEGIN_JUCE_NAMESPACE
  28958. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28959. : owner (owner_)
  28960. {
  28961. // the filter must be valid..
  28962. jassert (owner != 0);
  28963. }
  28964. AudioProcessorEditor::~AudioProcessorEditor()
  28965. {
  28966. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28967. // filter for some reason..
  28968. jassert (owner->getActiveEditor() != this);
  28969. }
  28970. END_JUCE_NAMESPACE
  28971. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28972. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28973. BEGIN_JUCE_NAMESPACE
  28974. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28975. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28976. : id (id_),
  28977. processor (processor_),
  28978. isPrepared (false)
  28979. {
  28980. jassert (processor_ != 0);
  28981. }
  28982. AudioProcessorGraph::Node::~Node()
  28983. {
  28984. }
  28985. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28986. AudioProcessorGraph* const graph)
  28987. {
  28988. if (! isPrepared)
  28989. {
  28990. isPrepared = true;
  28991. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28992. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28993. if (ioProc != 0)
  28994. ioProc->setParentGraph (graph);
  28995. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28996. processor->getNumOutputChannels(),
  28997. sampleRate, blockSize);
  28998. processor->prepareToPlay (sampleRate, blockSize);
  28999. }
  29000. }
  29001. void AudioProcessorGraph::Node::unprepare()
  29002. {
  29003. if (isPrepared)
  29004. {
  29005. isPrepared = false;
  29006. processor->releaseResources();
  29007. }
  29008. }
  29009. AudioProcessorGraph::AudioProcessorGraph()
  29010. : lastNodeId (0),
  29011. renderingBuffers (1, 1),
  29012. currentAudioOutputBuffer (1, 1)
  29013. {
  29014. }
  29015. AudioProcessorGraph::~AudioProcessorGraph()
  29016. {
  29017. clearRenderingSequence();
  29018. clear();
  29019. }
  29020. const String AudioProcessorGraph::getName() const
  29021. {
  29022. return "Audio Graph";
  29023. }
  29024. void AudioProcessorGraph::clear()
  29025. {
  29026. nodes.clear();
  29027. connections.clear();
  29028. triggerAsyncUpdate();
  29029. }
  29030. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29031. {
  29032. for (int i = nodes.size(); --i >= 0;)
  29033. if (nodes.getUnchecked(i)->id == nodeId)
  29034. return nodes.getUnchecked(i);
  29035. return 0;
  29036. }
  29037. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29038. uint32 nodeId)
  29039. {
  29040. if (newProcessor == 0)
  29041. {
  29042. jassertfalse;
  29043. return 0;
  29044. }
  29045. if (nodeId == 0)
  29046. {
  29047. nodeId = ++lastNodeId;
  29048. }
  29049. else
  29050. {
  29051. // you can't add a node with an id that already exists in the graph..
  29052. jassert (getNodeForId (nodeId) == 0);
  29053. removeNode (nodeId);
  29054. }
  29055. lastNodeId = nodeId;
  29056. Node* const n = new Node (nodeId, newProcessor);
  29057. nodes.add (n);
  29058. triggerAsyncUpdate();
  29059. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29060. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29061. if (ioProc != 0)
  29062. ioProc->setParentGraph (this);
  29063. return n;
  29064. }
  29065. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29066. {
  29067. disconnectNode (nodeId);
  29068. for (int i = nodes.size(); --i >= 0;)
  29069. {
  29070. if (nodes.getUnchecked(i)->id == nodeId)
  29071. {
  29072. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29073. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29074. if (ioProc != 0)
  29075. ioProc->setParentGraph (0);
  29076. nodes.remove (i);
  29077. triggerAsyncUpdate();
  29078. return true;
  29079. }
  29080. }
  29081. return false;
  29082. }
  29083. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29084. const int sourceChannelIndex,
  29085. const uint32 destNodeId,
  29086. const int destChannelIndex) const
  29087. {
  29088. for (int i = connections.size(); --i >= 0;)
  29089. {
  29090. const Connection* const c = connections.getUnchecked(i);
  29091. if (c->sourceNodeId == sourceNodeId
  29092. && c->destNodeId == destNodeId
  29093. && c->sourceChannelIndex == sourceChannelIndex
  29094. && c->destChannelIndex == destChannelIndex)
  29095. {
  29096. return c;
  29097. }
  29098. }
  29099. return 0;
  29100. }
  29101. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29102. const uint32 possibleDestNodeId) const
  29103. {
  29104. for (int i = connections.size(); --i >= 0;)
  29105. {
  29106. const Connection* const c = connections.getUnchecked(i);
  29107. if (c->sourceNodeId == possibleSourceNodeId
  29108. && c->destNodeId == possibleDestNodeId)
  29109. {
  29110. return true;
  29111. }
  29112. }
  29113. return false;
  29114. }
  29115. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29116. const int sourceChannelIndex,
  29117. const uint32 destNodeId,
  29118. const int destChannelIndex) const
  29119. {
  29120. if (sourceChannelIndex < 0
  29121. || destChannelIndex < 0
  29122. || sourceNodeId == destNodeId
  29123. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29124. return false;
  29125. const Node* const source = getNodeForId (sourceNodeId);
  29126. if (source == 0
  29127. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29128. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29129. return false;
  29130. const Node* const dest = getNodeForId (destNodeId);
  29131. if (dest == 0
  29132. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29133. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29134. return false;
  29135. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29136. destNodeId, destChannelIndex) == 0;
  29137. }
  29138. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29139. const int sourceChannelIndex,
  29140. const uint32 destNodeId,
  29141. const int destChannelIndex)
  29142. {
  29143. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29144. return false;
  29145. Connection* const c = new Connection();
  29146. c->sourceNodeId = sourceNodeId;
  29147. c->sourceChannelIndex = sourceChannelIndex;
  29148. c->destNodeId = destNodeId;
  29149. c->destChannelIndex = destChannelIndex;
  29150. connections.add (c);
  29151. triggerAsyncUpdate();
  29152. return true;
  29153. }
  29154. void AudioProcessorGraph::removeConnection (const int index)
  29155. {
  29156. connections.remove (index);
  29157. triggerAsyncUpdate();
  29158. }
  29159. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29160. const uint32 destNodeId, const int destChannelIndex)
  29161. {
  29162. bool doneAnything = false;
  29163. for (int i = connections.size(); --i >= 0;)
  29164. {
  29165. const Connection* const c = connections.getUnchecked(i);
  29166. if (c->sourceNodeId == sourceNodeId
  29167. && c->destNodeId == destNodeId
  29168. && c->sourceChannelIndex == sourceChannelIndex
  29169. && c->destChannelIndex == destChannelIndex)
  29170. {
  29171. removeConnection (i);
  29172. doneAnything = true;
  29173. triggerAsyncUpdate();
  29174. }
  29175. }
  29176. return doneAnything;
  29177. }
  29178. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29179. {
  29180. bool doneAnything = false;
  29181. for (int i = connections.size(); --i >= 0;)
  29182. {
  29183. const Connection* const c = connections.getUnchecked(i);
  29184. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29185. {
  29186. removeConnection (i);
  29187. doneAnything = true;
  29188. triggerAsyncUpdate();
  29189. }
  29190. }
  29191. return doneAnything;
  29192. }
  29193. bool AudioProcessorGraph::removeIllegalConnections()
  29194. {
  29195. bool doneAnything = false;
  29196. for (int i = connections.size(); --i >= 0;)
  29197. {
  29198. const Connection* const c = connections.getUnchecked(i);
  29199. const Node* const source = getNodeForId (c->sourceNodeId);
  29200. const Node* const dest = getNodeForId (c->destNodeId);
  29201. if (source == 0 || dest == 0
  29202. || (c->sourceChannelIndex != midiChannelIndex
  29203. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29204. || (c->sourceChannelIndex == midiChannelIndex
  29205. && ! source->processor->producesMidi())
  29206. || (c->destChannelIndex != midiChannelIndex
  29207. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29208. || (c->destChannelIndex == midiChannelIndex
  29209. && ! dest->processor->acceptsMidi()))
  29210. {
  29211. removeConnection (i);
  29212. doneAnything = true;
  29213. triggerAsyncUpdate();
  29214. }
  29215. }
  29216. return doneAnything;
  29217. }
  29218. namespace GraphRenderingOps
  29219. {
  29220. class AudioGraphRenderingOp
  29221. {
  29222. public:
  29223. AudioGraphRenderingOp() {}
  29224. virtual ~AudioGraphRenderingOp() {}
  29225. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29226. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29227. const int numSamples) = 0;
  29228. juce_UseDebuggingNewOperator
  29229. };
  29230. class ClearChannelOp : public AudioGraphRenderingOp
  29231. {
  29232. public:
  29233. ClearChannelOp (const int channelNum_)
  29234. : channelNum (channelNum_)
  29235. {}
  29236. ~ClearChannelOp() {}
  29237. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29238. {
  29239. sharedBufferChans.clear (channelNum, 0, numSamples);
  29240. }
  29241. private:
  29242. const int channelNum;
  29243. ClearChannelOp (const ClearChannelOp&);
  29244. ClearChannelOp& operator= (const ClearChannelOp&);
  29245. };
  29246. class CopyChannelOp : public AudioGraphRenderingOp
  29247. {
  29248. public:
  29249. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29250. : srcChannelNum (srcChannelNum_),
  29251. dstChannelNum (dstChannelNum_)
  29252. {}
  29253. ~CopyChannelOp() {}
  29254. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29255. {
  29256. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29257. }
  29258. private:
  29259. const int srcChannelNum, dstChannelNum;
  29260. CopyChannelOp (const CopyChannelOp&);
  29261. CopyChannelOp& operator= (const CopyChannelOp&);
  29262. };
  29263. class AddChannelOp : public AudioGraphRenderingOp
  29264. {
  29265. public:
  29266. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29267. : srcChannelNum (srcChannelNum_),
  29268. dstChannelNum (dstChannelNum_)
  29269. {}
  29270. ~AddChannelOp() {}
  29271. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29272. {
  29273. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29274. }
  29275. private:
  29276. const int srcChannelNum, dstChannelNum;
  29277. AddChannelOp (const AddChannelOp&);
  29278. AddChannelOp& operator= (const AddChannelOp&);
  29279. };
  29280. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29281. {
  29282. public:
  29283. ClearMidiBufferOp (const int bufferNum_)
  29284. : bufferNum (bufferNum_)
  29285. {}
  29286. ~ClearMidiBufferOp() {}
  29287. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29288. {
  29289. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29290. }
  29291. private:
  29292. const int bufferNum;
  29293. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29294. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29295. };
  29296. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29297. {
  29298. public:
  29299. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29300. : srcBufferNum (srcBufferNum_),
  29301. dstBufferNum (dstBufferNum_)
  29302. {}
  29303. ~CopyMidiBufferOp() {}
  29304. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29305. {
  29306. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29307. }
  29308. private:
  29309. const int srcBufferNum, dstBufferNum;
  29310. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29311. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29312. };
  29313. class AddMidiBufferOp : public AudioGraphRenderingOp
  29314. {
  29315. public:
  29316. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29317. : srcBufferNum (srcBufferNum_),
  29318. dstBufferNum (dstBufferNum_)
  29319. {}
  29320. ~AddMidiBufferOp() {}
  29321. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29322. {
  29323. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29324. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29325. }
  29326. private:
  29327. const int srcBufferNum, dstBufferNum;
  29328. AddMidiBufferOp (const AddMidiBufferOp&);
  29329. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29330. };
  29331. class ProcessBufferOp : public AudioGraphRenderingOp
  29332. {
  29333. public:
  29334. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29335. const Array <int>& audioChannelsToUse_,
  29336. const int totalChans_,
  29337. const int midiBufferToUse_)
  29338. : node (node_),
  29339. processor (node_->getProcessor()),
  29340. audioChannelsToUse (audioChannelsToUse_),
  29341. totalChans (jmax (1, totalChans_)),
  29342. midiBufferToUse (midiBufferToUse_)
  29343. {
  29344. channels.calloc (totalChans);
  29345. while (audioChannelsToUse.size() < totalChans)
  29346. audioChannelsToUse.add (0);
  29347. }
  29348. ~ProcessBufferOp()
  29349. {
  29350. }
  29351. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29352. {
  29353. for (int i = totalChans; --i >= 0;)
  29354. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29355. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29356. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29357. }
  29358. const AudioProcessorGraph::Node::Ptr node;
  29359. AudioProcessor* const processor;
  29360. private:
  29361. Array <int> audioChannelsToUse;
  29362. HeapBlock <float*> channels;
  29363. int totalChans;
  29364. int midiBufferToUse;
  29365. ProcessBufferOp (const ProcessBufferOp&);
  29366. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29367. };
  29368. /** Used to calculate the correct sequence of rendering ops needed, based on
  29369. the best re-use of shared buffers at each stage.
  29370. */
  29371. class RenderingOpSequenceCalculator
  29372. {
  29373. public:
  29374. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29375. const Array<void*>& orderedNodes_,
  29376. Array<void*>& renderingOps)
  29377. : graph (graph_),
  29378. orderedNodes (orderedNodes_)
  29379. {
  29380. nodeIds.add (-2); // first buffer is read-only zeros
  29381. channels.add (0);
  29382. midiNodeIds.add (-2);
  29383. for (int i = 0; i < orderedNodes.size(); ++i)
  29384. {
  29385. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29386. renderingOps, i);
  29387. markAnyUnusedBuffersAsFree (i);
  29388. }
  29389. }
  29390. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29391. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29392. juce_UseDebuggingNewOperator
  29393. private:
  29394. AudioProcessorGraph& graph;
  29395. const Array<void*>& orderedNodes;
  29396. Array <int> nodeIds, channels, midiNodeIds;
  29397. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29398. Array<void*>& renderingOps,
  29399. const int ourRenderingIndex)
  29400. {
  29401. const int numIns = node->getProcessor()->getNumInputChannels();
  29402. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29403. const int totalChans = jmax (numIns, numOuts);
  29404. Array <int> audioChannelsToUse;
  29405. int midiBufferToUse = -1;
  29406. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29407. {
  29408. // get a list of all the inputs to this node
  29409. Array <int> sourceNodes, sourceOutputChans;
  29410. for (int i = graph.getNumConnections(); --i >= 0;)
  29411. {
  29412. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29413. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29414. {
  29415. sourceNodes.add (c->sourceNodeId);
  29416. sourceOutputChans.add (c->sourceChannelIndex);
  29417. }
  29418. }
  29419. int bufIndex = -1;
  29420. if (sourceNodes.size() == 0)
  29421. {
  29422. // unconnected input channel
  29423. if (inputChan >= numOuts)
  29424. {
  29425. bufIndex = getReadOnlyEmptyBuffer();
  29426. jassert (bufIndex >= 0);
  29427. }
  29428. else
  29429. {
  29430. bufIndex = getFreeBuffer (false);
  29431. renderingOps.add (new ClearChannelOp (bufIndex));
  29432. }
  29433. }
  29434. else if (sourceNodes.size() == 1)
  29435. {
  29436. // channel with a straightforward single input..
  29437. const int srcNode = sourceNodes.getUnchecked(0);
  29438. const int srcChan = sourceOutputChans.getUnchecked(0);
  29439. bufIndex = getBufferContaining (srcNode, srcChan);
  29440. if (bufIndex < 0)
  29441. {
  29442. // if not found, this is probably a feedback loop
  29443. bufIndex = getReadOnlyEmptyBuffer();
  29444. jassert (bufIndex >= 0);
  29445. }
  29446. if (inputChan < numOuts
  29447. && isBufferNeededLater (ourRenderingIndex,
  29448. inputChan,
  29449. srcNode, srcChan))
  29450. {
  29451. // can't mess up this channel because it's needed later by another node, so we
  29452. // need to use a copy of it..
  29453. const int newFreeBuffer = getFreeBuffer (false);
  29454. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29455. bufIndex = newFreeBuffer;
  29456. }
  29457. }
  29458. else
  29459. {
  29460. // channel with a mix of several inputs..
  29461. // try to find a re-usable channel from our inputs..
  29462. int reusableInputIndex = -1;
  29463. for (int i = 0; i < sourceNodes.size(); ++i)
  29464. {
  29465. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29466. sourceOutputChans.getUnchecked(i));
  29467. if (sourceBufIndex >= 0
  29468. && ! isBufferNeededLater (ourRenderingIndex,
  29469. inputChan,
  29470. sourceNodes.getUnchecked(i),
  29471. sourceOutputChans.getUnchecked(i)))
  29472. {
  29473. // we've found one of our input chans that can be re-used..
  29474. reusableInputIndex = i;
  29475. bufIndex = sourceBufIndex;
  29476. break;
  29477. }
  29478. }
  29479. if (reusableInputIndex < 0)
  29480. {
  29481. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29482. bufIndex = getFreeBuffer (false);
  29483. jassert (bufIndex != 0);
  29484. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29485. sourceOutputChans.getUnchecked (0));
  29486. if (srcIndex < 0)
  29487. {
  29488. // if not found, this is probably a feedback loop
  29489. renderingOps.add (new ClearChannelOp (bufIndex));
  29490. }
  29491. else
  29492. {
  29493. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29494. }
  29495. reusableInputIndex = 0;
  29496. }
  29497. for (int j = 0; j < sourceNodes.size(); ++j)
  29498. {
  29499. if (j != reusableInputIndex)
  29500. {
  29501. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29502. sourceOutputChans.getUnchecked(j));
  29503. if (srcIndex >= 0)
  29504. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29505. }
  29506. }
  29507. }
  29508. jassert (bufIndex >= 0);
  29509. audioChannelsToUse.add (bufIndex);
  29510. if (inputChan < numOuts)
  29511. markBufferAsContaining (bufIndex, node->id, inputChan);
  29512. }
  29513. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29514. {
  29515. const int bufIndex = getFreeBuffer (false);
  29516. jassert (bufIndex != 0);
  29517. audioChannelsToUse.add (bufIndex);
  29518. markBufferAsContaining (bufIndex, node->id, outputChan);
  29519. }
  29520. // Now the same thing for midi..
  29521. Array <int> midiSourceNodes;
  29522. for (int i = graph.getNumConnections(); --i >= 0;)
  29523. {
  29524. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29525. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29526. midiSourceNodes.add (c->sourceNodeId);
  29527. }
  29528. if (midiSourceNodes.size() == 0)
  29529. {
  29530. // No midi inputs..
  29531. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29532. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29533. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29534. }
  29535. else if (midiSourceNodes.size() == 1)
  29536. {
  29537. // One midi input..
  29538. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29539. AudioProcessorGraph::midiChannelIndex);
  29540. if (midiBufferToUse >= 0)
  29541. {
  29542. if (isBufferNeededLater (ourRenderingIndex,
  29543. AudioProcessorGraph::midiChannelIndex,
  29544. midiSourceNodes.getUnchecked(0),
  29545. AudioProcessorGraph::midiChannelIndex))
  29546. {
  29547. // can't mess up this channel because it's needed later by another node, so we
  29548. // need to use a copy of it..
  29549. const int newFreeBuffer = getFreeBuffer (true);
  29550. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29551. midiBufferToUse = newFreeBuffer;
  29552. }
  29553. }
  29554. else
  29555. {
  29556. // probably a feedback loop, so just use an empty one..
  29557. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29558. }
  29559. }
  29560. else
  29561. {
  29562. // More than one midi input being mixed..
  29563. int reusableInputIndex = -1;
  29564. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29565. {
  29566. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29567. AudioProcessorGraph::midiChannelIndex);
  29568. if (sourceBufIndex >= 0
  29569. && ! isBufferNeededLater (ourRenderingIndex,
  29570. AudioProcessorGraph::midiChannelIndex,
  29571. midiSourceNodes.getUnchecked(i),
  29572. AudioProcessorGraph::midiChannelIndex))
  29573. {
  29574. // we've found one of our input buffers that can be re-used..
  29575. reusableInputIndex = i;
  29576. midiBufferToUse = sourceBufIndex;
  29577. break;
  29578. }
  29579. }
  29580. if (reusableInputIndex < 0)
  29581. {
  29582. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29583. midiBufferToUse = getFreeBuffer (true);
  29584. jassert (midiBufferToUse >= 0);
  29585. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29586. AudioProcessorGraph::midiChannelIndex);
  29587. if (srcIndex >= 0)
  29588. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29589. else
  29590. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29591. reusableInputIndex = 0;
  29592. }
  29593. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29594. {
  29595. if (j != reusableInputIndex)
  29596. {
  29597. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29598. AudioProcessorGraph::midiChannelIndex);
  29599. if (srcIndex >= 0)
  29600. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29601. }
  29602. }
  29603. }
  29604. if (node->getProcessor()->producesMidi())
  29605. markBufferAsContaining (midiBufferToUse, node->id,
  29606. AudioProcessorGraph::midiChannelIndex);
  29607. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29608. totalChans, midiBufferToUse));
  29609. }
  29610. int getFreeBuffer (const bool forMidi)
  29611. {
  29612. if (forMidi)
  29613. {
  29614. for (int i = 1; i < midiNodeIds.size(); ++i)
  29615. if (midiNodeIds.getUnchecked(i) < 0)
  29616. return i;
  29617. midiNodeIds.add (-1);
  29618. return midiNodeIds.size() - 1;
  29619. }
  29620. else
  29621. {
  29622. for (int i = 1; i < nodeIds.size(); ++i)
  29623. if (nodeIds.getUnchecked(i) < 0)
  29624. return i;
  29625. nodeIds.add (-1);
  29626. channels.add (0);
  29627. return nodeIds.size() - 1;
  29628. }
  29629. }
  29630. int getReadOnlyEmptyBuffer() const
  29631. {
  29632. return 0;
  29633. }
  29634. int getBufferContaining (const int nodeId, const int outputChannel) const
  29635. {
  29636. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29637. {
  29638. for (int i = midiNodeIds.size(); --i >= 0;)
  29639. if (midiNodeIds.getUnchecked(i) == nodeId)
  29640. return i;
  29641. }
  29642. else
  29643. {
  29644. for (int i = nodeIds.size(); --i >= 0;)
  29645. if (nodeIds.getUnchecked(i) == nodeId
  29646. && channels.getUnchecked(i) == outputChannel)
  29647. return i;
  29648. }
  29649. return -1;
  29650. }
  29651. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29652. {
  29653. int i;
  29654. for (i = 0; i < nodeIds.size(); ++i)
  29655. {
  29656. if (nodeIds.getUnchecked(i) >= 0
  29657. && ! isBufferNeededLater (stepIndex, -1,
  29658. nodeIds.getUnchecked(i),
  29659. channels.getUnchecked(i)))
  29660. {
  29661. nodeIds.set (i, -1);
  29662. }
  29663. }
  29664. for (i = 0; i < midiNodeIds.size(); ++i)
  29665. {
  29666. if (midiNodeIds.getUnchecked(i) >= 0
  29667. && ! isBufferNeededLater (stepIndex, -1,
  29668. midiNodeIds.getUnchecked(i),
  29669. AudioProcessorGraph::midiChannelIndex))
  29670. {
  29671. midiNodeIds.set (i, -1);
  29672. }
  29673. }
  29674. }
  29675. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29676. int inputChannelOfIndexToIgnore,
  29677. const int nodeId,
  29678. const int outputChanIndex) const
  29679. {
  29680. while (stepIndexToSearchFrom < orderedNodes.size())
  29681. {
  29682. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29683. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29684. {
  29685. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29686. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29687. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29688. return true;
  29689. }
  29690. else
  29691. {
  29692. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29693. if (i != inputChannelOfIndexToIgnore
  29694. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29695. node->id, i) != 0)
  29696. return true;
  29697. }
  29698. inputChannelOfIndexToIgnore = -1;
  29699. ++stepIndexToSearchFrom;
  29700. }
  29701. return false;
  29702. }
  29703. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29704. {
  29705. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29706. {
  29707. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29708. midiNodeIds.set (bufferNum, nodeId);
  29709. }
  29710. else
  29711. {
  29712. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29713. nodeIds.set (bufferNum, nodeId);
  29714. channels.set (bufferNum, outputIndex);
  29715. }
  29716. }
  29717. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29718. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29719. };
  29720. }
  29721. void AudioProcessorGraph::clearRenderingSequence()
  29722. {
  29723. const ScopedLock sl (renderLock);
  29724. for (int i = renderingOps.size(); --i >= 0;)
  29725. {
  29726. GraphRenderingOps::AudioGraphRenderingOp* const r
  29727. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29728. renderingOps.remove (i);
  29729. delete r;
  29730. }
  29731. }
  29732. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29733. const uint32 possibleDestinationId,
  29734. const int recursionCheck) const
  29735. {
  29736. if (recursionCheck > 0)
  29737. {
  29738. for (int i = connections.size(); --i >= 0;)
  29739. {
  29740. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29741. if (c->destNodeId == possibleDestinationId
  29742. && (c->sourceNodeId == possibleInputId
  29743. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29744. return true;
  29745. }
  29746. }
  29747. return false;
  29748. }
  29749. void AudioProcessorGraph::buildRenderingSequence()
  29750. {
  29751. Array<void*> newRenderingOps;
  29752. int numRenderingBuffersNeeded = 2;
  29753. int numMidiBuffersNeeded = 1;
  29754. {
  29755. MessageManagerLock mml;
  29756. Array<void*> orderedNodes;
  29757. int i;
  29758. for (i = 0; i < nodes.size(); ++i)
  29759. {
  29760. Node* const node = nodes.getUnchecked(i);
  29761. node->prepare (getSampleRate(), getBlockSize(), this);
  29762. int j = 0;
  29763. for (; j < orderedNodes.size(); ++j)
  29764. if (isAnInputTo (node->id,
  29765. ((Node*) orderedNodes.getUnchecked (j))->id,
  29766. nodes.size() + 1))
  29767. break;
  29768. orderedNodes.insert (j, node);
  29769. }
  29770. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29771. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29772. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29773. }
  29774. Array<void*> oldRenderingOps (renderingOps);
  29775. {
  29776. // swap over to the new rendering sequence..
  29777. const ScopedLock sl (renderLock);
  29778. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29779. renderingBuffers.clear();
  29780. for (int i = midiBuffers.size(); --i >= 0;)
  29781. midiBuffers.getUnchecked(i)->clear();
  29782. while (midiBuffers.size() < numMidiBuffersNeeded)
  29783. midiBuffers.add (new MidiBuffer());
  29784. renderingOps = newRenderingOps;
  29785. }
  29786. for (int i = oldRenderingOps.size(); --i >= 0;)
  29787. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29788. }
  29789. void AudioProcessorGraph::handleAsyncUpdate()
  29790. {
  29791. buildRenderingSequence();
  29792. }
  29793. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29794. {
  29795. currentAudioInputBuffer = 0;
  29796. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29797. currentMidiInputBuffer = 0;
  29798. currentMidiOutputBuffer.clear();
  29799. clearRenderingSequence();
  29800. buildRenderingSequence();
  29801. }
  29802. void AudioProcessorGraph::releaseResources()
  29803. {
  29804. for (int i = 0; i < nodes.size(); ++i)
  29805. nodes.getUnchecked(i)->unprepare();
  29806. renderingBuffers.setSize (1, 1);
  29807. midiBuffers.clear();
  29808. currentAudioInputBuffer = 0;
  29809. currentAudioOutputBuffer.setSize (1, 1);
  29810. currentMidiInputBuffer = 0;
  29811. currentMidiOutputBuffer.clear();
  29812. }
  29813. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29814. {
  29815. const int numSamples = buffer.getNumSamples();
  29816. const ScopedLock sl (renderLock);
  29817. currentAudioInputBuffer = &buffer;
  29818. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29819. currentAudioOutputBuffer.clear();
  29820. currentMidiInputBuffer = &midiMessages;
  29821. currentMidiOutputBuffer.clear();
  29822. int i;
  29823. for (i = 0; i < renderingOps.size(); ++i)
  29824. {
  29825. GraphRenderingOps::AudioGraphRenderingOp* const op
  29826. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29827. op->perform (renderingBuffers, midiBuffers, numSamples);
  29828. }
  29829. for (i = 0; i < buffer.getNumChannels(); ++i)
  29830. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29831. midiMessages.clear();
  29832. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29833. }
  29834. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29835. {
  29836. return "Input " + String (channelIndex + 1);
  29837. }
  29838. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29839. {
  29840. return "Output " + String (channelIndex + 1);
  29841. }
  29842. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29843. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29844. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29845. bool AudioProcessorGraph::producesMidi() const { return true; }
  29846. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29847. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29848. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29849. : type (type_),
  29850. graph (0)
  29851. {
  29852. }
  29853. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29854. {
  29855. }
  29856. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29857. {
  29858. switch (type)
  29859. {
  29860. case audioOutputNode: return "Audio Output";
  29861. case audioInputNode: return "Audio Input";
  29862. case midiOutputNode: return "Midi Output";
  29863. case midiInputNode: return "Midi Input";
  29864. default: break;
  29865. }
  29866. return String::empty;
  29867. }
  29868. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29869. {
  29870. d.name = getName();
  29871. d.uid = d.name.hashCode();
  29872. d.category = "I/O devices";
  29873. d.pluginFormatName = "Internal";
  29874. d.manufacturerName = "Raw Material Software";
  29875. d.version = "1.0";
  29876. d.isInstrument = false;
  29877. d.numInputChannels = getNumInputChannels();
  29878. if (type == audioOutputNode && graph != 0)
  29879. d.numInputChannels = graph->getNumInputChannels();
  29880. d.numOutputChannels = getNumOutputChannels();
  29881. if (type == audioInputNode && graph != 0)
  29882. d.numOutputChannels = graph->getNumOutputChannels();
  29883. }
  29884. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29885. {
  29886. jassert (graph != 0);
  29887. }
  29888. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29889. {
  29890. }
  29891. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29892. MidiBuffer& midiMessages)
  29893. {
  29894. jassert (graph != 0);
  29895. switch (type)
  29896. {
  29897. case audioOutputNode:
  29898. {
  29899. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29900. buffer.getNumChannels()); --i >= 0;)
  29901. {
  29902. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29903. }
  29904. break;
  29905. }
  29906. case audioInputNode:
  29907. {
  29908. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29909. buffer.getNumChannels()); --i >= 0;)
  29910. {
  29911. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29912. }
  29913. break;
  29914. }
  29915. case midiOutputNode:
  29916. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29917. break;
  29918. case midiInputNode:
  29919. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29920. break;
  29921. default:
  29922. break;
  29923. }
  29924. }
  29925. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29926. {
  29927. return type == midiOutputNode;
  29928. }
  29929. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29930. {
  29931. return type == midiInputNode;
  29932. }
  29933. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29934. {
  29935. switch (type)
  29936. {
  29937. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29938. case midiOutputNode: return "Midi Output";
  29939. default: break;
  29940. }
  29941. return String::empty;
  29942. }
  29943. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29944. {
  29945. switch (type)
  29946. {
  29947. case audioInputNode: return "Input " + String (channelIndex + 1);
  29948. case midiInputNode: return "Midi Input";
  29949. default: break;
  29950. }
  29951. return String::empty;
  29952. }
  29953. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29954. {
  29955. return type == audioInputNode || type == audioOutputNode;
  29956. }
  29957. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29958. {
  29959. return isInputChannelStereoPair (index);
  29960. }
  29961. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29962. {
  29963. return type == audioInputNode || type == midiInputNode;
  29964. }
  29965. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29966. {
  29967. return type == audioOutputNode || type == midiOutputNode;
  29968. }
  29969. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29970. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29971. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29972. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29973. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29974. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29975. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29976. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29977. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29978. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29979. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29980. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29981. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29982. {
  29983. }
  29984. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29985. {
  29986. }
  29987. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29988. {
  29989. graph = newGraph;
  29990. if (graph != 0)
  29991. {
  29992. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29993. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29994. getSampleRate(),
  29995. getBlockSize());
  29996. updateHostDisplay();
  29997. }
  29998. }
  29999. END_JUCE_NAMESPACE
  30000. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30001. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30002. BEGIN_JUCE_NAMESPACE
  30003. AudioProcessorPlayer::AudioProcessorPlayer()
  30004. : processor (0),
  30005. sampleRate (0),
  30006. blockSize (0),
  30007. isPrepared (false),
  30008. numInputChans (0),
  30009. numOutputChans (0),
  30010. tempBuffer (1, 1)
  30011. {
  30012. }
  30013. AudioProcessorPlayer::~AudioProcessorPlayer()
  30014. {
  30015. setProcessor (0);
  30016. }
  30017. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30018. {
  30019. if (processor != processorToPlay)
  30020. {
  30021. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30022. {
  30023. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30024. sampleRate, blockSize);
  30025. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30026. }
  30027. AudioProcessor* oldOne;
  30028. {
  30029. const ScopedLock sl (lock);
  30030. oldOne = isPrepared ? processor : 0;
  30031. processor = processorToPlay;
  30032. isPrepared = true;
  30033. }
  30034. if (oldOne != 0)
  30035. oldOne->releaseResources();
  30036. }
  30037. }
  30038. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30039. const int numInputChannels,
  30040. float** const outputChannelData,
  30041. const int numOutputChannels,
  30042. const int numSamples)
  30043. {
  30044. // these should have been prepared by audioDeviceAboutToStart()...
  30045. jassert (sampleRate > 0 && blockSize > 0);
  30046. incomingMidi.clear();
  30047. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30048. int i, totalNumChans = 0;
  30049. if (numInputChannels > numOutputChannels)
  30050. {
  30051. // if there aren't enough output channels for the number of
  30052. // inputs, we need to create some temporary extra ones (can't
  30053. // use the input data in case it gets written to)
  30054. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30055. false, false, true);
  30056. for (i = 0; i < numOutputChannels; ++i)
  30057. {
  30058. channels[totalNumChans] = outputChannelData[i];
  30059. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30060. ++totalNumChans;
  30061. }
  30062. for (i = numOutputChannels; i < numInputChannels; ++i)
  30063. {
  30064. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30065. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30066. ++totalNumChans;
  30067. }
  30068. }
  30069. else
  30070. {
  30071. for (i = 0; i < numInputChannels; ++i)
  30072. {
  30073. channels[totalNumChans] = outputChannelData[i];
  30074. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30075. ++totalNumChans;
  30076. }
  30077. for (i = numInputChannels; i < numOutputChannels; ++i)
  30078. {
  30079. channels[totalNumChans] = outputChannelData[i];
  30080. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30081. ++totalNumChans;
  30082. }
  30083. }
  30084. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30085. const ScopedLock sl (lock);
  30086. if (processor != 0)
  30087. {
  30088. const ScopedLock sl (processor->getCallbackLock());
  30089. if (processor->isSuspended())
  30090. {
  30091. for (i = 0; i < numOutputChannels; ++i)
  30092. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30093. }
  30094. else
  30095. {
  30096. processor->processBlock (buffer, incomingMidi);
  30097. }
  30098. }
  30099. }
  30100. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30101. {
  30102. const ScopedLock sl (lock);
  30103. sampleRate = device->getCurrentSampleRate();
  30104. blockSize = device->getCurrentBufferSizeSamples();
  30105. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30106. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30107. messageCollector.reset (sampleRate);
  30108. zeromem (channels, sizeof (channels));
  30109. if (processor != 0)
  30110. {
  30111. if (isPrepared)
  30112. processor->releaseResources();
  30113. AudioProcessor* const oldProcessor = processor;
  30114. setProcessor (0);
  30115. setProcessor (oldProcessor);
  30116. }
  30117. }
  30118. void AudioProcessorPlayer::audioDeviceStopped()
  30119. {
  30120. const ScopedLock sl (lock);
  30121. if (processor != 0 && isPrepared)
  30122. processor->releaseResources();
  30123. sampleRate = 0.0;
  30124. blockSize = 0;
  30125. isPrepared = false;
  30126. tempBuffer.setSize (1, 1);
  30127. }
  30128. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30129. {
  30130. messageCollector.addMessageToQueue (message);
  30131. }
  30132. END_JUCE_NAMESPACE
  30133. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30134. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30135. BEGIN_JUCE_NAMESPACE
  30136. class ProcessorParameterPropertyComp : public PropertyComponent,
  30137. public AudioProcessorListener,
  30138. public AsyncUpdater
  30139. {
  30140. public:
  30141. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, int index_)
  30142. : PropertyComponent (name),
  30143. owner (owner_),
  30144. index (index_),
  30145. slider (owner_, index_)
  30146. {
  30147. addAndMakeVisible (&slider);
  30148. owner_.addListener (this);
  30149. }
  30150. ~ProcessorParameterPropertyComp()
  30151. {
  30152. owner.removeListener (this);
  30153. }
  30154. void refresh()
  30155. {
  30156. slider.setValue (owner.getParameter (index), false);
  30157. }
  30158. void audioProcessorChanged (AudioProcessor*) {}
  30159. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30160. {
  30161. if (parameterIndex == index)
  30162. triggerAsyncUpdate();
  30163. }
  30164. void handleAsyncUpdate()
  30165. {
  30166. refresh();
  30167. }
  30168. juce_UseDebuggingNewOperator
  30169. private:
  30170. class ParamSlider : public Slider
  30171. {
  30172. public:
  30173. ParamSlider (AudioProcessor& owner_, const int index_)
  30174. : Slider (String::empty),
  30175. owner (owner_),
  30176. index (index_)
  30177. {
  30178. setRange (0.0, 1.0, 0.0);
  30179. setSliderStyle (Slider::LinearBar);
  30180. setTextBoxIsEditable (false);
  30181. setScrollWheelEnabled (false);
  30182. }
  30183. ~ParamSlider()
  30184. {
  30185. }
  30186. void valueChanged()
  30187. {
  30188. const float newVal = (float) getValue();
  30189. if (owner.getParameter (index) != newVal)
  30190. owner.setParameter (index, newVal);
  30191. }
  30192. const String getTextFromValue (double /*value*/)
  30193. {
  30194. return owner.getParameterText (index);
  30195. }
  30196. juce_UseDebuggingNewOperator
  30197. private:
  30198. AudioProcessor& owner;
  30199. const int index;
  30200. ParamSlider (const ParamSlider&);
  30201. ParamSlider& operator= (const ParamSlider&);
  30202. };
  30203. AudioProcessor& owner;
  30204. const int index;
  30205. ParamSlider slider;
  30206. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30207. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30208. };
  30209. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30210. : AudioProcessorEditor (owner_)
  30211. {
  30212. jassert (owner_ != 0);
  30213. setOpaque (true);
  30214. addAndMakeVisible (panel = new PropertyPanel());
  30215. Array <PropertyComponent*> params;
  30216. const int numParams = owner_->getNumParameters();
  30217. int totalHeight = 0;
  30218. for (int i = 0; i < numParams; ++i)
  30219. {
  30220. String name (owner_->getParameterName (i));
  30221. if (name.trim().isEmpty())
  30222. name = "Unnamed";
  30223. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30224. params.add (pc);
  30225. totalHeight += pc->getPreferredHeight();
  30226. }
  30227. panel->addProperties (params);
  30228. setSize (400, jlimit (25, 400, totalHeight));
  30229. }
  30230. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30231. {
  30232. deleteAllChildren();
  30233. }
  30234. void GenericAudioProcessorEditor::paint (Graphics& g)
  30235. {
  30236. g.fillAll (Colours::white);
  30237. }
  30238. void GenericAudioProcessorEditor::resized()
  30239. {
  30240. panel->setSize (getWidth(), getHeight());
  30241. }
  30242. END_JUCE_NAMESPACE
  30243. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30244. /*** Start of inlined file: juce_Sampler.cpp ***/
  30245. BEGIN_JUCE_NAMESPACE
  30246. SamplerSound::SamplerSound (const String& name_,
  30247. AudioFormatReader& source,
  30248. const BigInteger& midiNotes_,
  30249. const int midiNoteForNormalPitch,
  30250. const double attackTimeSecs,
  30251. const double releaseTimeSecs,
  30252. const double maxSampleLengthSeconds)
  30253. : name (name_),
  30254. midiNotes (midiNotes_),
  30255. midiRootNote (midiNoteForNormalPitch)
  30256. {
  30257. sourceSampleRate = source.sampleRate;
  30258. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30259. {
  30260. length = 0;
  30261. attackSamples = 0;
  30262. releaseSamples = 0;
  30263. }
  30264. else
  30265. {
  30266. length = jmin ((int) source.lengthInSamples,
  30267. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30268. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30269. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30270. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30271. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30272. }
  30273. }
  30274. SamplerSound::~SamplerSound()
  30275. {
  30276. }
  30277. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30278. {
  30279. return midiNotes [midiNoteNumber];
  30280. }
  30281. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30282. {
  30283. return true;
  30284. }
  30285. SamplerVoice::SamplerVoice()
  30286. : pitchRatio (0.0),
  30287. sourceSamplePosition (0.0),
  30288. lgain (0.0f),
  30289. rgain (0.0f),
  30290. isInAttack (false),
  30291. isInRelease (false)
  30292. {
  30293. }
  30294. SamplerVoice::~SamplerVoice()
  30295. {
  30296. }
  30297. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30298. {
  30299. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30300. }
  30301. void SamplerVoice::startNote (const int midiNoteNumber,
  30302. const float velocity,
  30303. SynthesiserSound* s,
  30304. const int /*currentPitchWheelPosition*/)
  30305. {
  30306. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30307. jassert (sound != 0); // this object can only play SamplerSounds!
  30308. if (sound != 0)
  30309. {
  30310. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30311. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30312. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30313. sourceSamplePosition = 0.0;
  30314. lgain = velocity;
  30315. rgain = velocity;
  30316. isInAttack = (sound->attackSamples > 0);
  30317. isInRelease = false;
  30318. if (isInAttack)
  30319. {
  30320. attackReleaseLevel = 0.0f;
  30321. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30322. }
  30323. else
  30324. {
  30325. attackReleaseLevel = 1.0f;
  30326. attackDelta = 0.0f;
  30327. }
  30328. if (sound->releaseSamples > 0)
  30329. {
  30330. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30331. }
  30332. else
  30333. {
  30334. releaseDelta = 0.0f;
  30335. }
  30336. }
  30337. }
  30338. void SamplerVoice::stopNote (const bool allowTailOff)
  30339. {
  30340. if (allowTailOff)
  30341. {
  30342. isInAttack = false;
  30343. isInRelease = true;
  30344. }
  30345. else
  30346. {
  30347. clearCurrentNote();
  30348. }
  30349. }
  30350. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30351. {
  30352. }
  30353. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30354. const int /*newValue*/)
  30355. {
  30356. }
  30357. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30358. {
  30359. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30360. if (playingSound != 0)
  30361. {
  30362. const float* const inL = playingSound->data->getSampleData (0, 0);
  30363. const float* const inR = playingSound->data->getNumChannels() > 1
  30364. ? playingSound->data->getSampleData (1, 0) : 0;
  30365. float* outL = outputBuffer.getSampleData (0, startSample);
  30366. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30367. while (--numSamples >= 0)
  30368. {
  30369. const int pos = (int) sourceSamplePosition;
  30370. const float alpha = (float) (sourceSamplePosition - pos);
  30371. const float invAlpha = 1.0f - alpha;
  30372. // just using a very simple linear interpolation here..
  30373. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30374. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30375. : l;
  30376. l *= lgain;
  30377. r *= rgain;
  30378. if (isInAttack)
  30379. {
  30380. l *= attackReleaseLevel;
  30381. r *= attackReleaseLevel;
  30382. attackReleaseLevel += attackDelta;
  30383. if (attackReleaseLevel >= 1.0f)
  30384. {
  30385. attackReleaseLevel = 1.0f;
  30386. isInAttack = false;
  30387. }
  30388. }
  30389. else if (isInRelease)
  30390. {
  30391. l *= attackReleaseLevel;
  30392. r *= attackReleaseLevel;
  30393. attackReleaseLevel += releaseDelta;
  30394. if (attackReleaseLevel <= 0.0f)
  30395. {
  30396. stopNote (false);
  30397. break;
  30398. }
  30399. }
  30400. if (outR != 0)
  30401. {
  30402. *outL++ += l;
  30403. *outR++ += r;
  30404. }
  30405. else
  30406. {
  30407. *outL++ += (l + r) * 0.5f;
  30408. }
  30409. sourceSamplePosition += pitchRatio;
  30410. if (sourceSamplePosition > playingSound->length)
  30411. {
  30412. stopNote (false);
  30413. break;
  30414. }
  30415. }
  30416. }
  30417. }
  30418. END_JUCE_NAMESPACE
  30419. /*** End of inlined file: juce_Sampler.cpp ***/
  30420. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30421. BEGIN_JUCE_NAMESPACE
  30422. SynthesiserSound::SynthesiserSound()
  30423. {
  30424. }
  30425. SynthesiserSound::~SynthesiserSound()
  30426. {
  30427. }
  30428. SynthesiserVoice::SynthesiserVoice()
  30429. : currentSampleRate (44100.0),
  30430. currentlyPlayingNote (-1),
  30431. noteOnTime (0),
  30432. currentlyPlayingSound (0)
  30433. {
  30434. }
  30435. SynthesiserVoice::~SynthesiserVoice()
  30436. {
  30437. }
  30438. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30439. {
  30440. return currentlyPlayingSound != 0
  30441. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30442. }
  30443. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30444. {
  30445. currentSampleRate = newRate;
  30446. }
  30447. void SynthesiserVoice::clearCurrentNote()
  30448. {
  30449. currentlyPlayingNote = -1;
  30450. currentlyPlayingSound = 0;
  30451. }
  30452. Synthesiser::Synthesiser()
  30453. : sampleRate (0),
  30454. lastNoteOnCounter (0),
  30455. shouldStealNotes (true)
  30456. {
  30457. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30458. lastPitchWheelValues[i] = 0x2000;
  30459. }
  30460. Synthesiser::~Synthesiser()
  30461. {
  30462. }
  30463. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30464. {
  30465. const ScopedLock sl (lock);
  30466. return voices [index];
  30467. }
  30468. void Synthesiser::clearVoices()
  30469. {
  30470. const ScopedLock sl (lock);
  30471. voices.clear();
  30472. }
  30473. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30474. {
  30475. const ScopedLock sl (lock);
  30476. voices.add (newVoice);
  30477. }
  30478. void Synthesiser::removeVoice (const int index)
  30479. {
  30480. const ScopedLock sl (lock);
  30481. voices.remove (index);
  30482. }
  30483. void Synthesiser::clearSounds()
  30484. {
  30485. const ScopedLock sl (lock);
  30486. sounds.clear();
  30487. }
  30488. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30489. {
  30490. const ScopedLock sl (lock);
  30491. sounds.add (newSound);
  30492. }
  30493. void Synthesiser::removeSound (const int index)
  30494. {
  30495. const ScopedLock sl (lock);
  30496. sounds.remove (index);
  30497. }
  30498. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30499. {
  30500. shouldStealNotes = shouldStealNotes_;
  30501. }
  30502. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30503. {
  30504. if (sampleRate != newRate)
  30505. {
  30506. const ScopedLock sl (lock);
  30507. allNotesOff (0, false);
  30508. sampleRate = newRate;
  30509. for (int i = voices.size(); --i >= 0;)
  30510. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30511. }
  30512. }
  30513. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30514. const MidiBuffer& midiData,
  30515. int startSample,
  30516. int numSamples)
  30517. {
  30518. // must set the sample rate before using this!
  30519. jassert (sampleRate != 0);
  30520. const ScopedLock sl (lock);
  30521. MidiBuffer::Iterator midiIterator (midiData);
  30522. midiIterator.setNextSamplePosition (startSample);
  30523. MidiMessage m (0xf4, 0.0);
  30524. while (numSamples > 0)
  30525. {
  30526. int midiEventPos;
  30527. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30528. && midiEventPos < startSample + numSamples;
  30529. const int numThisTime = useEvent ? midiEventPos - startSample
  30530. : numSamples;
  30531. if (numThisTime > 0)
  30532. {
  30533. for (int i = voices.size(); --i >= 0;)
  30534. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30535. }
  30536. if (useEvent)
  30537. {
  30538. if (m.isNoteOn())
  30539. {
  30540. const int channel = m.getChannel();
  30541. noteOn (channel,
  30542. m.getNoteNumber(),
  30543. m.getFloatVelocity());
  30544. }
  30545. else if (m.isNoteOff())
  30546. {
  30547. noteOff (m.getChannel(),
  30548. m.getNoteNumber(),
  30549. true);
  30550. }
  30551. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30552. {
  30553. allNotesOff (m.getChannel(), true);
  30554. }
  30555. else if (m.isPitchWheel())
  30556. {
  30557. const int channel = m.getChannel();
  30558. const int wheelPos = m.getPitchWheelValue();
  30559. lastPitchWheelValues [channel - 1] = wheelPos;
  30560. handlePitchWheel (channel, wheelPos);
  30561. }
  30562. else if (m.isController())
  30563. {
  30564. handleController (m.getChannel(),
  30565. m.getControllerNumber(),
  30566. m.getControllerValue());
  30567. }
  30568. }
  30569. startSample += numThisTime;
  30570. numSamples -= numThisTime;
  30571. }
  30572. }
  30573. void Synthesiser::noteOn (const int midiChannel,
  30574. const int midiNoteNumber,
  30575. const float velocity)
  30576. {
  30577. const ScopedLock sl (lock);
  30578. for (int i = sounds.size(); --i >= 0;)
  30579. {
  30580. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30581. if (sound->appliesToNote (midiNoteNumber)
  30582. && sound->appliesToChannel (midiChannel))
  30583. {
  30584. startVoice (findFreeVoice (sound, shouldStealNotes),
  30585. sound, midiChannel, midiNoteNumber, velocity);
  30586. }
  30587. }
  30588. }
  30589. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30590. SynthesiserSound* const sound,
  30591. const int midiChannel,
  30592. const int midiNoteNumber,
  30593. const float velocity)
  30594. {
  30595. if (voice != 0 && sound != 0)
  30596. {
  30597. if (voice->currentlyPlayingSound != 0)
  30598. voice->stopNote (false);
  30599. voice->startNote (midiNoteNumber,
  30600. velocity,
  30601. sound,
  30602. lastPitchWheelValues [midiChannel - 1]);
  30603. voice->currentlyPlayingNote = midiNoteNumber;
  30604. voice->noteOnTime = ++lastNoteOnCounter;
  30605. voice->currentlyPlayingSound = sound;
  30606. }
  30607. }
  30608. void Synthesiser::noteOff (const int midiChannel,
  30609. const int midiNoteNumber,
  30610. const bool allowTailOff)
  30611. {
  30612. const ScopedLock sl (lock);
  30613. for (int i = voices.size(); --i >= 0;)
  30614. {
  30615. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30616. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30617. {
  30618. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30619. if (sound != 0
  30620. && sound->appliesToNote (midiNoteNumber)
  30621. && sound->appliesToChannel (midiChannel))
  30622. {
  30623. voice->stopNote (allowTailOff);
  30624. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30625. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30626. }
  30627. }
  30628. }
  30629. }
  30630. void Synthesiser::allNotesOff (const int midiChannel,
  30631. const bool allowTailOff)
  30632. {
  30633. const ScopedLock sl (lock);
  30634. for (int i = voices.size(); --i >= 0;)
  30635. {
  30636. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30637. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30638. voice->stopNote (allowTailOff);
  30639. }
  30640. }
  30641. void Synthesiser::handlePitchWheel (const int midiChannel,
  30642. const int wheelValue)
  30643. {
  30644. const ScopedLock sl (lock);
  30645. for (int i = voices.size(); --i >= 0;)
  30646. {
  30647. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30648. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30649. {
  30650. voice->pitchWheelMoved (wheelValue);
  30651. }
  30652. }
  30653. }
  30654. void Synthesiser::handleController (const int midiChannel,
  30655. const int controllerNumber,
  30656. const int controllerValue)
  30657. {
  30658. const ScopedLock sl (lock);
  30659. for (int i = voices.size(); --i >= 0;)
  30660. {
  30661. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30662. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30663. voice->controllerMoved (controllerNumber, controllerValue);
  30664. }
  30665. }
  30666. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30667. const bool stealIfNoneAvailable) const
  30668. {
  30669. const ScopedLock sl (lock);
  30670. for (int i = voices.size(); --i >= 0;)
  30671. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30672. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30673. return voices.getUnchecked (i);
  30674. if (stealIfNoneAvailable)
  30675. {
  30676. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30677. SynthesiserVoice* oldest = 0;
  30678. for (int i = voices.size(); --i >= 0;)
  30679. {
  30680. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30681. if (voice->canPlaySound (soundToPlay)
  30682. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30683. oldest = voice;
  30684. }
  30685. jassert (oldest != 0);
  30686. return oldest;
  30687. }
  30688. return 0;
  30689. }
  30690. END_JUCE_NAMESPACE
  30691. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30692. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30693. BEGIN_JUCE_NAMESPACE
  30694. ActionBroadcaster::ActionBroadcaster() throw()
  30695. {
  30696. // are you trying to create this object before or after juce has been intialised??
  30697. jassert (MessageManager::instance != 0);
  30698. }
  30699. ActionBroadcaster::~ActionBroadcaster()
  30700. {
  30701. // all event-based objects must be deleted BEFORE juce is shut down!
  30702. jassert (MessageManager::instance != 0);
  30703. }
  30704. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30705. {
  30706. actionListenerList.addActionListener (listener);
  30707. }
  30708. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30709. {
  30710. jassert (actionListenerList.isValidMessageListener());
  30711. if (actionListenerList.isValidMessageListener())
  30712. actionListenerList.removeActionListener (listener);
  30713. }
  30714. void ActionBroadcaster::removeAllActionListeners()
  30715. {
  30716. actionListenerList.removeAllActionListeners();
  30717. }
  30718. void ActionBroadcaster::sendActionMessage (const String& message) const
  30719. {
  30720. actionListenerList.sendActionMessage (message);
  30721. }
  30722. END_JUCE_NAMESPACE
  30723. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30724. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30725. BEGIN_JUCE_NAMESPACE
  30726. // special message of our own with a string in it
  30727. class ActionMessage : public Message
  30728. {
  30729. public:
  30730. const String message;
  30731. ActionMessage (const String& messageText, void* const listener_) throw()
  30732. : message (messageText)
  30733. {
  30734. pointerParameter = listener_;
  30735. }
  30736. ~ActionMessage() throw()
  30737. {
  30738. }
  30739. private:
  30740. ActionMessage (const ActionMessage&);
  30741. ActionMessage& operator= (const ActionMessage&);
  30742. };
  30743. ActionListenerList::ActionListenerList()
  30744. {
  30745. }
  30746. ActionListenerList::~ActionListenerList()
  30747. {
  30748. }
  30749. void ActionListenerList::addActionListener (ActionListener* const listener)
  30750. {
  30751. const ScopedLock sl (actionListenerLock_);
  30752. jassert (listener != 0);
  30753. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30754. if (listener != 0)
  30755. actionListeners_.add (listener);
  30756. }
  30757. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30758. {
  30759. const ScopedLock sl (actionListenerLock_);
  30760. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30761. actionListeners_.removeValue (listener);
  30762. }
  30763. void ActionListenerList::removeAllActionListeners()
  30764. {
  30765. const ScopedLock sl (actionListenerLock_);
  30766. actionListeners_.clear();
  30767. }
  30768. void ActionListenerList::sendActionMessage (const String& message) const
  30769. {
  30770. const ScopedLock sl (actionListenerLock_);
  30771. for (int i = actionListeners_.size(); --i >= 0;)
  30772. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30773. }
  30774. void ActionListenerList::handleMessage (const Message& message)
  30775. {
  30776. const ActionMessage& am = (const ActionMessage&) message;
  30777. if (actionListeners_.contains (am.pointerParameter))
  30778. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30779. }
  30780. END_JUCE_NAMESPACE
  30781. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30782. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30783. BEGIN_JUCE_NAMESPACE
  30784. AsyncUpdater::AsyncUpdater() throw()
  30785. : asyncMessagePending (false)
  30786. {
  30787. internalAsyncHandler.owner = this;
  30788. }
  30789. AsyncUpdater::~AsyncUpdater()
  30790. {
  30791. }
  30792. void AsyncUpdater::triggerAsyncUpdate()
  30793. {
  30794. if (! asyncMessagePending)
  30795. {
  30796. asyncMessagePending = true;
  30797. internalAsyncHandler.postMessage (new Message());
  30798. }
  30799. }
  30800. void AsyncUpdater::cancelPendingUpdate() throw()
  30801. {
  30802. asyncMessagePending = false;
  30803. }
  30804. void AsyncUpdater::handleUpdateNowIfNeeded()
  30805. {
  30806. if (asyncMessagePending)
  30807. {
  30808. asyncMessagePending = false;
  30809. handleAsyncUpdate();
  30810. }
  30811. }
  30812. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30813. {
  30814. owner->handleUpdateNowIfNeeded();
  30815. }
  30816. END_JUCE_NAMESPACE
  30817. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30818. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30819. BEGIN_JUCE_NAMESPACE
  30820. ChangeBroadcaster::ChangeBroadcaster() throw()
  30821. {
  30822. // are you trying to create this object before or after juce has been intialised??
  30823. jassert (MessageManager::instance != 0);
  30824. }
  30825. ChangeBroadcaster::~ChangeBroadcaster()
  30826. {
  30827. // all event-based objects must be deleted BEFORE juce is shut down!
  30828. jassert (MessageManager::instance != 0);
  30829. }
  30830. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30831. {
  30832. changeListenerList.addChangeListener (listener);
  30833. }
  30834. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30835. {
  30836. jassert (changeListenerList.isValidMessageListener());
  30837. if (changeListenerList.isValidMessageListener())
  30838. changeListenerList.removeChangeListener (listener);
  30839. }
  30840. void ChangeBroadcaster::removeAllChangeListeners()
  30841. {
  30842. changeListenerList.removeAllChangeListeners();
  30843. }
  30844. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30845. {
  30846. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30847. }
  30848. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30849. {
  30850. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30851. }
  30852. void ChangeBroadcaster::dispatchPendingMessages()
  30853. {
  30854. changeListenerList.dispatchPendingMessages();
  30855. }
  30856. END_JUCE_NAMESPACE
  30857. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30858. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30859. BEGIN_JUCE_NAMESPACE
  30860. ChangeListenerList::ChangeListenerList()
  30861. : lastChangedObject (0),
  30862. messagePending (false)
  30863. {
  30864. }
  30865. ChangeListenerList::~ChangeListenerList()
  30866. {
  30867. }
  30868. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30869. {
  30870. const ScopedLock sl (lock);
  30871. jassert (listener != 0);
  30872. if (listener != 0)
  30873. listeners.add (listener);
  30874. }
  30875. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30876. {
  30877. const ScopedLock sl (lock);
  30878. listeners.removeValue (listener);
  30879. }
  30880. void ChangeListenerList::removeAllChangeListeners()
  30881. {
  30882. const ScopedLock sl (lock);
  30883. listeners.clear();
  30884. }
  30885. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30886. {
  30887. const ScopedLock sl (lock);
  30888. if ((! messagePending) && (listeners.size() > 0))
  30889. {
  30890. lastChangedObject = objectThatHasChanged;
  30891. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30892. messagePending = true;
  30893. }
  30894. }
  30895. void ChangeListenerList::handleMessage (const Message& message)
  30896. {
  30897. sendSynchronousChangeMessage (message.pointerParameter);
  30898. }
  30899. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30900. {
  30901. const ScopedLock sl (lock);
  30902. messagePending = false;
  30903. for (int i = listeners.size(); --i >= 0;)
  30904. {
  30905. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30906. {
  30907. const ScopedUnlock tempUnlocker (lock);
  30908. l->changeListenerCallback (objectThatHasChanged);
  30909. }
  30910. i = jmin (i, listeners.size());
  30911. }
  30912. }
  30913. void ChangeListenerList::dispatchPendingMessages()
  30914. {
  30915. if (messagePending)
  30916. sendSynchronousChangeMessage (lastChangedObject);
  30917. }
  30918. END_JUCE_NAMESPACE
  30919. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30920. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30921. BEGIN_JUCE_NAMESPACE
  30922. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30923. const uint32 magicMessageHeaderNumber)
  30924. : Thread ("Juce IPC connection"),
  30925. callbackConnectionState (false),
  30926. useMessageThread (callbacksOnMessageThread),
  30927. magicMessageHeader (magicMessageHeaderNumber),
  30928. pipeReceiveMessageTimeout (-1)
  30929. {
  30930. }
  30931. InterprocessConnection::~InterprocessConnection()
  30932. {
  30933. callbackConnectionState = false;
  30934. disconnect();
  30935. }
  30936. bool InterprocessConnection::connectToSocket (const String& hostName,
  30937. const int portNumber,
  30938. const int timeOutMillisecs)
  30939. {
  30940. disconnect();
  30941. const ScopedLock sl (pipeAndSocketLock);
  30942. socket = new StreamingSocket();
  30943. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30944. {
  30945. connectionMadeInt();
  30946. startThread();
  30947. return true;
  30948. }
  30949. else
  30950. {
  30951. socket = 0;
  30952. return false;
  30953. }
  30954. }
  30955. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30956. const int pipeReceiveMessageTimeoutMs)
  30957. {
  30958. disconnect();
  30959. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30960. if (newPipe->openExisting (pipeName))
  30961. {
  30962. const ScopedLock sl (pipeAndSocketLock);
  30963. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30964. initialiseWithPipe (newPipe.release());
  30965. return true;
  30966. }
  30967. return false;
  30968. }
  30969. bool InterprocessConnection::createPipe (const String& pipeName,
  30970. const int pipeReceiveMessageTimeoutMs)
  30971. {
  30972. disconnect();
  30973. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30974. if (newPipe->createNewPipe (pipeName))
  30975. {
  30976. const ScopedLock sl (pipeAndSocketLock);
  30977. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30978. initialiseWithPipe (newPipe.release());
  30979. return true;
  30980. }
  30981. return false;
  30982. }
  30983. void InterprocessConnection::disconnect()
  30984. {
  30985. if (socket != 0)
  30986. socket->close();
  30987. if (pipe != 0)
  30988. {
  30989. pipe->cancelPendingReads();
  30990. pipe->close();
  30991. }
  30992. stopThread (4000);
  30993. {
  30994. const ScopedLock sl (pipeAndSocketLock);
  30995. socket = 0;
  30996. pipe = 0;
  30997. }
  30998. connectionLostInt();
  30999. }
  31000. bool InterprocessConnection::isConnected() const
  31001. {
  31002. const ScopedLock sl (pipeAndSocketLock);
  31003. return ((socket != 0 && socket->isConnected())
  31004. || (pipe != 0 && pipe->isOpen()))
  31005. && isThreadRunning();
  31006. }
  31007. const String InterprocessConnection::getConnectedHostName() const
  31008. {
  31009. if (pipe != 0)
  31010. {
  31011. return "localhost";
  31012. }
  31013. else if (socket != 0)
  31014. {
  31015. if (! socket->isLocal())
  31016. return socket->getHostName();
  31017. return "localhost";
  31018. }
  31019. return String::empty;
  31020. }
  31021. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31022. {
  31023. uint32 messageHeader[2];
  31024. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31025. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31026. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31027. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31028. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31029. size_t bytesWritten = 0;
  31030. const ScopedLock sl (pipeAndSocketLock);
  31031. if (socket != 0)
  31032. {
  31033. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31034. }
  31035. else if (pipe != 0)
  31036. {
  31037. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31038. }
  31039. if (bytesWritten < 0)
  31040. {
  31041. // error..
  31042. return false;
  31043. }
  31044. return (bytesWritten == messageData.getSize());
  31045. }
  31046. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31047. {
  31048. jassert (socket == 0);
  31049. socket = socket_;
  31050. connectionMadeInt();
  31051. startThread();
  31052. }
  31053. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31054. {
  31055. jassert (pipe == 0);
  31056. pipe = pipe_;
  31057. connectionMadeInt();
  31058. startThread();
  31059. }
  31060. const int messageMagicNumber = 0xb734128b;
  31061. void InterprocessConnection::handleMessage (const Message& message)
  31062. {
  31063. if (message.intParameter1 == messageMagicNumber)
  31064. {
  31065. switch (message.intParameter2)
  31066. {
  31067. case 0:
  31068. {
  31069. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31070. messageReceived (*data);
  31071. break;
  31072. }
  31073. case 1:
  31074. connectionMade();
  31075. break;
  31076. case 2:
  31077. connectionLost();
  31078. break;
  31079. }
  31080. }
  31081. }
  31082. void InterprocessConnection::connectionMadeInt()
  31083. {
  31084. if (! callbackConnectionState)
  31085. {
  31086. callbackConnectionState = true;
  31087. if (useMessageThread)
  31088. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31089. else
  31090. connectionMade();
  31091. }
  31092. }
  31093. void InterprocessConnection::connectionLostInt()
  31094. {
  31095. if (callbackConnectionState)
  31096. {
  31097. callbackConnectionState = false;
  31098. if (useMessageThread)
  31099. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31100. else
  31101. connectionLost();
  31102. }
  31103. }
  31104. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31105. {
  31106. jassert (callbackConnectionState);
  31107. if (useMessageThread)
  31108. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31109. else
  31110. messageReceived (data);
  31111. }
  31112. bool InterprocessConnection::readNextMessageInt()
  31113. {
  31114. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31115. uint32 messageHeader[2];
  31116. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31117. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31118. if (bytes == sizeof (messageHeader)
  31119. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31120. {
  31121. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31122. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31123. {
  31124. MemoryBlock messageData (bytesInMessage, true);
  31125. int bytesRead = 0;
  31126. while (bytesInMessage > 0)
  31127. {
  31128. if (threadShouldExit())
  31129. return false;
  31130. const int numThisTime = jmin (bytesInMessage, 65536);
  31131. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31132. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31133. if (bytesIn <= 0)
  31134. break;
  31135. bytesRead += bytesIn;
  31136. bytesInMessage -= bytesIn;
  31137. }
  31138. if (bytesRead >= 0)
  31139. deliverDataInt (messageData);
  31140. }
  31141. }
  31142. else if (bytes < 0)
  31143. {
  31144. {
  31145. const ScopedLock sl (pipeAndSocketLock);
  31146. socket = 0;
  31147. }
  31148. connectionLostInt();
  31149. return false;
  31150. }
  31151. return true;
  31152. }
  31153. void InterprocessConnection::run()
  31154. {
  31155. while (! threadShouldExit())
  31156. {
  31157. if (socket != 0)
  31158. {
  31159. const int ready = socket->waitUntilReady (true, 0);
  31160. if (ready < 0)
  31161. {
  31162. {
  31163. const ScopedLock sl (pipeAndSocketLock);
  31164. socket = 0;
  31165. }
  31166. connectionLostInt();
  31167. break;
  31168. }
  31169. else if (ready > 0)
  31170. {
  31171. if (! readNextMessageInt())
  31172. break;
  31173. }
  31174. else
  31175. {
  31176. Thread::sleep (2);
  31177. }
  31178. }
  31179. else if (pipe != 0)
  31180. {
  31181. if (! pipe->isOpen())
  31182. {
  31183. {
  31184. const ScopedLock sl (pipeAndSocketLock);
  31185. pipe = 0;
  31186. }
  31187. connectionLostInt();
  31188. break;
  31189. }
  31190. else
  31191. {
  31192. if (! readNextMessageInt())
  31193. break;
  31194. }
  31195. }
  31196. else
  31197. {
  31198. break;
  31199. }
  31200. }
  31201. }
  31202. END_JUCE_NAMESPACE
  31203. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31204. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31205. BEGIN_JUCE_NAMESPACE
  31206. InterprocessConnectionServer::InterprocessConnectionServer()
  31207. : Thread ("Juce IPC server")
  31208. {
  31209. }
  31210. InterprocessConnectionServer::~InterprocessConnectionServer()
  31211. {
  31212. stop();
  31213. }
  31214. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31215. {
  31216. stop();
  31217. socket = new StreamingSocket();
  31218. if (socket->createListener (portNumber))
  31219. {
  31220. startThread();
  31221. return true;
  31222. }
  31223. socket = 0;
  31224. return false;
  31225. }
  31226. void InterprocessConnectionServer::stop()
  31227. {
  31228. signalThreadShouldExit();
  31229. if (socket != 0)
  31230. socket->close();
  31231. stopThread (4000);
  31232. socket = 0;
  31233. }
  31234. void InterprocessConnectionServer::run()
  31235. {
  31236. while ((! threadShouldExit()) && socket != 0)
  31237. {
  31238. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31239. if (clientSocket != 0)
  31240. {
  31241. InterprocessConnection* newConnection = createConnectionObject();
  31242. if (newConnection != 0)
  31243. newConnection->initialiseWithSocket (clientSocket.release());
  31244. }
  31245. }
  31246. }
  31247. END_JUCE_NAMESPACE
  31248. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31249. /*** Start of inlined file: juce_Message.cpp ***/
  31250. BEGIN_JUCE_NAMESPACE
  31251. Message::Message() throw()
  31252. : intParameter1 (0),
  31253. intParameter2 (0),
  31254. intParameter3 (0),
  31255. pointerParameter (0)
  31256. {
  31257. }
  31258. Message::Message (const int intParameter1_,
  31259. const int intParameter2_,
  31260. const int intParameter3_,
  31261. void* const pointerParameter_) throw()
  31262. : intParameter1 (intParameter1_),
  31263. intParameter2 (intParameter2_),
  31264. intParameter3 (intParameter3_),
  31265. pointerParameter (pointerParameter_)
  31266. {
  31267. }
  31268. Message::~Message() throw()
  31269. {
  31270. }
  31271. END_JUCE_NAMESPACE
  31272. /*** End of inlined file: juce_Message.cpp ***/
  31273. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31274. BEGIN_JUCE_NAMESPACE
  31275. MessageListener::MessageListener() throw()
  31276. {
  31277. // are you trying to create a messagelistener before or after juce has been intialised??
  31278. jassert (MessageManager::instance != 0);
  31279. if (MessageManager::instance != 0)
  31280. MessageManager::instance->messageListeners.add (this);
  31281. }
  31282. MessageListener::~MessageListener()
  31283. {
  31284. if (MessageManager::instance != 0)
  31285. MessageManager::instance->messageListeners.removeValue (this);
  31286. }
  31287. void MessageListener::postMessage (Message* const message) const throw()
  31288. {
  31289. message->messageRecipient = const_cast <MessageListener*> (this);
  31290. if (MessageManager::instance == 0)
  31291. MessageManager::getInstance();
  31292. MessageManager::instance->postMessageToQueue (message);
  31293. }
  31294. bool MessageListener::isValidMessageListener() const throw()
  31295. {
  31296. return (MessageManager::instance != 0)
  31297. && MessageManager::instance->messageListeners.contains (this);
  31298. }
  31299. END_JUCE_NAMESPACE
  31300. /*** End of inlined file: juce_MessageListener.cpp ***/
  31301. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31302. BEGIN_JUCE_NAMESPACE
  31303. // platform-specific functions..
  31304. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31305. bool juce_postMessageToSystemQueue (Message* message);
  31306. MessageManager* MessageManager::instance = 0;
  31307. static const int quitMessageId = 0xfffff321;
  31308. MessageManager::MessageManager() throw()
  31309. : quitMessagePosted (false),
  31310. quitMessageReceived (false),
  31311. threadWithLock (0)
  31312. {
  31313. messageThreadId = Thread::getCurrentThreadId();
  31314. }
  31315. MessageManager::~MessageManager() throw()
  31316. {
  31317. broadcastListeners = 0;
  31318. doPlatformSpecificShutdown();
  31319. // If you hit this assertion, then you've probably leaked a Component or some other
  31320. // kind of MessageListener object...
  31321. jassert (messageListeners.size() == 0);
  31322. jassert (instance == this);
  31323. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31324. }
  31325. MessageManager* MessageManager::getInstance() throw()
  31326. {
  31327. if (instance == 0)
  31328. {
  31329. instance = new MessageManager();
  31330. doPlatformSpecificInitialisation();
  31331. }
  31332. return instance;
  31333. }
  31334. void MessageManager::postMessageToQueue (Message* const message)
  31335. {
  31336. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31337. delete message;
  31338. }
  31339. CallbackMessage::CallbackMessage() throw() {}
  31340. CallbackMessage::~CallbackMessage() throw() {}
  31341. void CallbackMessage::post()
  31342. {
  31343. if (MessageManager::instance != 0)
  31344. MessageManager::instance->postCallbackMessage (this);
  31345. }
  31346. void MessageManager::postCallbackMessage (Message* const message)
  31347. {
  31348. message->messageRecipient = 0;
  31349. postMessageToQueue (message);
  31350. }
  31351. // not for public use..
  31352. void MessageManager::deliverMessage (Message* const message)
  31353. {
  31354. const ScopedPointer <Message> messageDeleter (message);
  31355. MessageListener* const recipient = message->messageRecipient;
  31356. JUCE_TRY
  31357. {
  31358. if (messageListeners.contains (recipient))
  31359. {
  31360. recipient->handleMessage (*message);
  31361. }
  31362. else if (recipient == 0)
  31363. {
  31364. if (message->intParameter1 == quitMessageId)
  31365. {
  31366. quitMessageReceived = true;
  31367. }
  31368. else
  31369. {
  31370. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31371. if (cm != 0)
  31372. cm->messageCallback();
  31373. }
  31374. }
  31375. }
  31376. JUCE_CATCH_EXCEPTION
  31377. }
  31378. #if ! (JUCE_MAC || JUCE_IOS)
  31379. void MessageManager::runDispatchLoop()
  31380. {
  31381. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31382. runDispatchLoopUntil (-1);
  31383. }
  31384. void MessageManager::stopDispatchLoop()
  31385. {
  31386. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31387. m->messageRecipient = 0;
  31388. postMessageToQueue (m);
  31389. quitMessagePosted = true;
  31390. }
  31391. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31392. {
  31393. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31394. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31395. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31396. && ! quitMessageReceived)
  31397. {
  31398. JUCE_TRY
  31399. {
  31400. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31401. {
  31402. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31403. if (msToWait > 0)
  31404. Thread::sleep (jmin (5, msToWait));
  31405. }
  31406. }
  31407. JUCE_CATCH_EXCEPTION
  31408. }
  31409. return ! quitMessageReceived;
  31410. }
  31411. #endif
  31412. void MessageManager::deliverBroadcastMessage (const String& value)
  31413. {
  31414. if (broadcastListeners != 0)
  31415. broadcastListeners->sendActionMessage (value);
  31416. }
  31417. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31418. {
  31419. if (broadcastListeners == 0)
  31420. broadcastListeners = new ActionListenerList();
  31421. broadcastListeners->addActionListener (listener);
  31422. }
  31423. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31424. {
  31425. if (broadcastListeners != 0)
  31426. broadcastListeners->removeActionListener (listener);
  31427. }
  31428. bool MessageManager::isThisTheMessageThread() const throw()
  31429. {
  31430. return Thread::getCurrentThreadId() == messageThreadId;
  31431. }
  31432. void MessageManager::setCurrentThreadAsMessageThread()
  31433. {
  31434. if (messageThreadId != Thread::getCurrentThreadId())
  31435. {
  31436. messageThreadId = Thread::getCurrentThreadId();
  31437. // This is needed on windows to make sure the message window is created by this thread
  31438. doPlatformSpecificShutdown();
  31439. doPlatformSpecificInitialisation();
  31440. }
  31441. }
  31442. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31443. {
  31444. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31445. return thisThread == messageThreadId || thisThread == threadWithLock;
  31446. }
  31447. /* The only safe way to lock the message thread while another thread does
  31448. some work is by posting a special message, whose purpose is to tie up the event
  31449. loop until the other thread has finished its business.
  31450. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31451. get locked before making an event callback, because if the same OS lock gets indirectly
  31452. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31453. in Cocoa).
  31454. */
  31455. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31456. {
  31457. public:
  31458. SharedEvents() {}
  31459. ~SharedEvents() {}
  31460. /* This class just holds a couple of events to communicate between the BlockingMessage
  31461. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31462. this shared data must be kept in a separate, ref-counted container. */
  31463. WaitableEvent lockedEvent, releaseEvent;
  31464. private:
  31465. SharedEvents (const SharedEvents&);
  31466. SharedEvents& operator= (const SharedEvents&);
  31467. };
  31468. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31469. {
  31470. public:
  31471. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31472. ~BlockingMessage() throw() {}
  31473. void messageCallback()
  31474. {
  31475. events->lockedEvent.signal();
  31476. events->releaseEvent.wait();
  31477. }
  31478. juce_UseDebuggingNewOperator
  31479. private:
  31480. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31481. BlockingMessage (const BlockingMessage&);
  31482. BlockingMessage& operator= (const BlockingMessage&);
  31483. };
  31484. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31485. : sharedEvents (0),
  31486. locked (false)
  31487. {
  31488. init (threadToCheck, 0);
  31489. }
  31490. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31491. : sharedEvents (0),
  31492. locked (false)
  31493. {
  31494. init (0, jobToCheckForExitSignal);
  31495. }
  31496. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31497. {
  31498. if (MessageManager::instance != 0)
  31499. {
  31500. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31501. {
  31502. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31503. }
  31504. else
  31505. {
  31506. if (threadToCheck == 0 && job == 0)
  31507. {
  31508. MessageManager::instance->lockingLock.enter();
  31509. }
  31510. else
  31511. {
  31512. while (! MessageManager::instance->lockingLock.tryEnter())
  31513. {
  31514. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31515. || (job != 0 && job->shouldExit()))
  31516. return;
  31517. Thread::sleep (1);
  31518. }
  31519. }
  31520. sharedEvents = new SharedEvents();
  31521. sharedEvents->incReferenceCount();
  31522. (new BlockingMessage (sharedEvents))->post();
  31523. while (! sharedEvents->lockedEvent.wait (50))
  31524. {
  31525. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31526. || (job != 0 && job->shouldExit()))
  31527. {
  31528. sharedEvents->releaseEvent.signal();
  31529. sharedEvents->decReferenceCount();
  31530. sharedEvents = 0;
  31531. MessageManager::instance->lockingLock.exit();
  31532. return;
  31533. }
  31534. }
  31535. jassert (MessageManager::instance->threadWithLock == 0);
  31536. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31537. locked = true;
  31538. }
  31539. }
  31540. }
  31541. MessageManagerLock::~MessageManagerLock() throw()
  31542. {
  31543. if (sharedEvents != 0)
  31544. {
  31545. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31546. sharedEvents->releaseEvent.signal();
  31547. sharedEvents->decReferenceCount();
  31548. if (MessageManager::instance != 0)
  31549. {
  31550. MessageManager::instance->threadWithLock = 0;
  31551. MessageManager::instance->lockingLock.exit();
  31552. }
  31553. }
  31554. }
  31555. END_JUCE_NAMESPACE
  31556. /*** End of inlined file: juce_MessageManager.cpp ***/
  31557. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31558. BEGIN_JUCE_NAMESPACE
  31559. class MultiTimer::MultiTimerCallback : public Timer
  31560. {
  31561. public:
  31562. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31563. : timerId (timerId_),
  31564. owner (owner_)
  31565. {
  31566. }
  31567. ~MultiTimerCallback()
  31568. {
  31569. }
  31570. void timerCallback()
  31571. {
  31572. owner.timerCallback (timerId);
  31573. }
  31574. const int timerId;
  31575. private:
  31576. MultiTimer& owner;
  31577. };
  31578. MultiTimer::MultiTimer() throw()
  31579. {
  31580. }
  31581. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31582. {
  31583. }
  31584. MultiTimer::~MultiTimer()
  31585. {
  31586. const ScopedLock sl (timerListLock);
  31587. timers.clear();
  31588. }
  31589. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31590. {
  31591. const ScopedLock sl (timerListLock);
  31592. for (int i = timers.size(); --i >= 0;)
  31593. {
  31594. MultiTimerCallback* const t = timers.getUnchecked(i);
  31595. if (t->timerId == timerId)
  31596. {
  31597. t->startTimer (intervalInMilliseconds);
  31598. return;
  31599. }
  31600. }
  31601. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31602. timers.add (newTimer);
  31603. newTimer->startTimer (intervalInMilliseconds);
  31604. }
  31605. void MultiTimer::stopTimer (const int timerId) throw()
  31606. {
  31607. const ScopedLock sl (timerListLock);
  31608. for (int i = timers.size(); --i >= 0;)
  31609. {
  31610. MultiTimerCallback* const t = timers.getUnchecked(i);
  31611. if (t->timerId == timerId)
  31612. t->stopTimer();
  31613. }
  31614. }
  31615. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31616. {
  31617. const ScopedLock sl (timerListLock);
  31618. for (int i = timers.size(); --i >= 0;)
  31619. {
  31620. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31621. if (t->timerId == timerId)
  31622. return t->isTimerRunning();
  31623. }
  31624. return false;
  31625. }
  31626. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31627. {
  31628. const ScopedLock sl (timerListLock);
  31629. for (int i = timers.size(); --i >= 0;)
  31630. {
  31631. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31632. if (t->timerId == timerId)
  31633. return t->getTimerInterval();
  31634. }
  31635. return 0;
  31636. }
  31637. END_JUCE_NAMESPACE
  31638. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31639. /*** Start of inlined file: juce_Timer.cpp ***/
  31640. BEGIN_JUCE_NAMESPACE
  31641. class InternalTimerThread : private Thread,
  31642. private MessageListener,
  31643. private DeletedAtShutdown,
  31644. private AsyncUpdater
  31645. {
  31646. public:
  31647. InternalTimerThread()
  31648. : Thread ("Juce Timer"),
  31649. firstTimer (0),
  31650. callbackNeeded (0)
  31651. {
  31652. triggerAsyncUpdate();
  31653. }
  31654. ~InternalTimerThread() throw()
  31655. {
  31656. stopThread (4000);
  31657. jassert (instance == this || instance == 0);
  31658. if (instance == this)
  31659. instance = 0;
  31660. }
  31661. void run()
  31662. {
  31663. uint32 lastTime = Time::getMillisecondCounter();
  31664. while (! threadShouldExit())
  31665. {
  31666. const uint32 now = Time::getMillisecondCounter();
  31667. if (now <= lastTime)
  31668. {
  31669. wait (2);
  31670. continue;
  31671. }
  31672. const int elapsed = now - lastTime;
  31673. lastTime = now;
  31674. int timeUntilFirstTimer = 1000;
  31675. {
  31676. const ScopedLock sl (lock);
  31677. decrementAllCounters (elapsed);
  31678. if (firstTimer != 0)
  31679. timeUntilFirstTimer = firstTimer->countdownMs;
  31680. }
  31681. if (timeUntilFirstTimer <= 0)
  31682. {
  31683. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31684. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31685. but if it fails it means the message-thread changed the value from under us so at least
  31686. some processing is happenening and we can just loop around and try again
  31687. */
  31688. if (callbackNeeded.compareAndSetBool (1, 0))
  31689. {
  31690. postMessage (new Message());
  31691. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31692. when the app has a modal loop), so this is how long to wait before assuming the
  31693. message has been lost and trying again.
  31694. */
  31695. const uint32 messageDeliveryTimeout = now + 2000;
  31696. while (callbackNeeded.get() != 0)
  31697. {
  31698. wait (4);
  31699. if (threadShouldExit())
  31700. return;
  31701. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31702. break;
  31703. }
  31704. }
  31705. }
  31706. else
  31707. {
  31708. // don't wait for too long because running this loop also helps keep the
  31709. // Time::getApproximateMillisecondTimer value stay up-to-date
  31710. wait (jlimit (1, 50, timeUntilFirstTimer));
  31711. }
  31712. }
  31713. }
  31714. void callTimers()
  31715. {
  31716. const ScopedLock sl (lock);
  31717. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31718. {
  31719. Timer* const t = firstTimer;
  31720. t->countdownMs = t->periodMs;
  31721. removeTimer (t);
  31722. addTimer (t);
  31723. const ScopedUnlock ul (lock);
  31724. JUCE_TRY
  31725. {
  31726. t->timerCallback();
  31727. }
  31728. JUCE_CATCH_EXCEPTION
  31729. }
  31730. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31731. before the boolean is set. This set should never fail since if it was false in the first place,
  31732. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31733. get a message then the value is true and the other thread can only set it to true again and
  31734. we will get another callback to set it to false.
  31735. */
  31736. callbackNeeded.set (0);
  31737. }
  31738. void handleMessage (const Message&)
  31739. {
  31740. callTimers();
  31741. }
  31742. void callTimersSynchronously()
  31743. {
  31744. if (! isThreadRunning())
  31745. {
  31746. // (This is relied on by some plugins in cases where the MM has
  31747. // had to restart and the async callback never started)
  31748. cancelPendingUpdate();
  31749. triggerAsyncUpdate();
  31750. }
  31751. callTimers();
  31752. }
  31753. static void callAnyTimersSynchronously()
  31754. {
  31755. if (InternalTimerThread::instance != 0)
  31756. InternalTimerThread::instance->callTimersSynchronously();
  31757. }
  31758. static inline void add (Timer* const tim) throw()
  31759. {
  31760. if (instance == 0)
  31761. instance = new InternalTimerThread();
  31762. const ScopedLock sl (instance->lock);
  31763. instance->addTimer (tim);
  31764. }
  31765. static inline void remove (Timer* const tim) throw()
  31766. {
  31767. if (instance != 0)
  31768. {
  31769. const ScopedLock sl (instance->lock);
  31770. instance->removeTimer (tim);
  31771. }
  31772. }
  31773. static inline void resetCounter (Timer* const tim,
  31774. const int newCounter) throw()
  31775. {
  31776. if (instance != 0)
  31777. {
  31778. tim->countdownMs = newCounter;
  31779. tim->periodMs = newCounter;
  31780. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31781. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31782. {
  31783. const ScopedLock sl (instance->lock);
  31784. instance->removeTimer (tim);
  31785. instance->addTimer (tim);
  31786. }
  31787. }
  31788. }
  31789. private:
  31790. friend class Timer;
  31791. static InternalTimerThread* instance;
  31792. static CriticalSection lock;
  31793. Timer* volatile firstTimer;
  31794. Atomic <int> callbackNeeded;
  31795. void addTimer (Timer* const t) throw()
  31796. {
  31797. #if JUCE_DEBUG
  31798. Timer* tt = firstTimer;
  31799. while (tt != 0)
  31800. {
  31801. // trying to add a timer that's already here - shouldn't get to this point,
  31802. // so if you get this assertion, let me know!
  31803. jassert (tt != t);
  31804. tt = tt->next;
  31805. }
  31806. jassert (t->previous == 0 && t->next == 0);
  31807. #endif
  31808. Timer* i = firstTimer;
  31809. if (i == 0 || i->countdownMs > t->countdownMs)
  31810. {
  31811. t->next = firstTimer;
  31812. firstTimer = t;
  31813. }
  31814. else
  31815. {
  31816. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31817. i = i->next;
  31818. jassert (i != 0);
  31819. t->next = i->next;
  31820. t->previous = i;
  31821. i->next = t;
  31822. }
  31823. if (t->next != 0)
  31824. t->next->previous = t;
  31825. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31826. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31827. notify();
  31828. }
  31829. void removeTimer (Timer* const t) throw()
  31830. {
  31831. #if JUCE_DEBUG
  31832. Timer* tt = firstTimer;
  31833. bool found = false;
  31834. while (tt != 0)
  31835. {
  31836. if (tt == t)
  31837. {
  31838. found = true;
  31839. break;
  31840. }
  31841. tt = tt->next;
  31842. }
  31843. // trying to remove a timer that's not here - shouldn't get to this point,
  31844. // so if you get this assertion, let me know!
  31845. jassert (found);
  31846. #endif
  31847. if (t->previous != 0)
  31848. {
  31849. jassert (firstTimer != t);
  31850. t->previous->next = t->next;
  31851. }
  31852. else
  31853. {
  31854. jassert (firstTimer == t);
  31855. firstTimer = t->next;
  31856. }
  31857. if (t->next != 0)
  31858. t->next->previous = t->previous;
  31859. t->next = 0;
  31860. t->previous = 0;
  31861. }
  31862. void decrementAllCounters (const int numMillisecs) const
  31863. {
  31864. Timer* t = firstTimer;
  31865. while (t != 0)
  31866. {
  31867. t->countdownMs -= numMillisecs;
  31868. t = t->next;
  31869. }
  31870. }
  31871. void handleAsyncUpdate()
  31872. {
  31873. startThread (7);
  31874. }
  31875. InternalTimerThread (const InternalTimerThread&);
  31876. InternalTimerThread& operator= (const InternalTimerThread&);
  31877. };
  31878. InternalTimerThread* InternalTimerThread::instance = 0;
  31879. CriticalSection InternalTimerThread::lock;
  31880. void juce_callAnyTimersSynchronously()
  31881. {
  31882. InternalTimerThread::callAnyTimersSynchronously();
  31883. }
  31884. #if JUCE_DEBUG
  31885. static SortedSet <Timer*> activeTimers;
  31886. #endif
  31887. Timer::Timer() throw()
  31888. : countdownMs (0),
  31889. periodMs (0),
  31890. previous (0),
  31891. next (0)
  31892. {
  31893. #if JUCE_DEBUG
  31894. activeTimers.add (this);
  31895. #endif
  31896. }
  31897. Timer::Timer (const Timer&) throw()
  31898. : countdownMs (0),
  31899. periodMs (0),
  31900. previous (0),
  31901. next (0)
  31902. {
  31903. #if JUCE_DEBUG
  31904. activeTimers.add (this);
  31905. #endif
  31906. }
  31907. Timer::~Timer()
  31908. {
  31909. stopTimer();
  31910. #if JUCE_DEBUG
  31911. activeTimers.removeValue (this);
  31912. #endif
  31913. }
  31914. void Timer::startTimer (const int interval) throw()
  31915. {
  31916. const ScopedLock sl (InternalTimerThread::lock);
  31917. #if JUCE_DEBUG
  31918. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31919. jassert (activeTimers.contains (this));
  31920. #endif
  31921. if (periodMs == 0)
  31922. {
  31923. countdownMs = interval;
  31924. periodMs = jmax (1, interval);
  31925. InternalTimerThread::add (this);
  31926. }
  31927. else
  31928. {
  31929. InternalTimerThread::resetCounter (this, interval);
  31930. }
  31931. }
  31932. void Timer::stopTimer() throw()
  31933. {
  31934. const ScopedLock sl (InternalTimerThread::lock);
  31935. #if JUCE_DEBUG
  31936. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31937. jassert (activeTimers.contains (this));
  31938. #endif
  31939. if (periodMs > 0)
  31940. {
  31941. InternalTimerThread::remove (this);
  31942. periodMs = 0;
  31943. }
  31944. }
  31945. END_JUCE_NAMESPACE
  31946. /*** End of inlined file: juce_Timer.cpp ***/
  31947. #endif
  31948. #if JUCE_BUILD_GUI
  31949. /*** Start of inlined file: juce_Component.cpp ***/
  31950. BEGIN_JUCE_NAMESPACE
  31951. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31952. enum ComponentMessageNumbers
  31953. {
  31954. customCommandMessage = 0x7fff0001,
  31955. exitModalStateMessage = 0x7fff0002
  31956. };
  31957. static uint32 nextComponentUID = 0;
  31958. Component* Component::currentlyFocusedComponent = 0;
  31959. Component::Component()
  31960. : parentComponent_ (0),
  31961. componentUID (++nextComponentUID),
  31962. numDeepMouseListeners (0),
  31963. lookAndFeel_ (0),
  31964. effect_ (0),
  31965. bufferedImage_ (0),
  31966. mouseListeners_ (0),
  31967. keyListeners_ (0),
  31968. componentFlags_ (0)
  31969. {
  31970. }
  31971. Component::Component (const String& name)
  31972. : componentName_ (name),
  31973. parentComponent_ (0),
  31974. componentUID (++nextComponentUID),
  31975. numDeepMouseListeners (0),
  31976. lookAndFeel_ (0),
  31977. effect_ (0),
  31978. bufferedImage_ (0),
  31979. mouseListeners_ (0),
  31980. keyListeners_ (0),
  31981. componentFlags_ (0)
  31982. {
  31983. }
  31984. Component::~Component()
  31985. {
  31986. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31987. if (parentComponent_ != 0)
  31988. {
  31989. parentComponent_->removeChildComponent (this);
  31990. }
  31991. else if ((currentlyFocusedComponent == this)
  31992. || isParentOf (currentlyFocusedComponent))
  31993. {
  31994. giveAwayFocus();
  31995. }
  31996. if (flags.hasHeavyweightPeerFlag)
  31997. removeFromDesktop();
  31998. for (int i = childComponentList_.size(); --i >= 0;)
  31999. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32000. delete mouseListeners_;
  32001. delete keyListeners_;
  32002. }
  32003. void Component::setName (const String& name)
  32004. {
  32005. // if component methods are being called from threads other than the message
  32006. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32007. checkMessageManagerIsLocked
  32008. if (componentName_ != name)
  32009. {
  32010. componentName_ = name;
  32011. if (flags.hasHeavyweightPeerFlag)
  32012. {
  32013. ComponentPeer* const peer = getPeer();
  32014. jassert (peer != 0);
  32015. if (peer != 0)
  32016. peer->setTitle (name);
  32017. }
  32018. BailOutChecker checker (this);
  32019. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32020. }
  32021. }
  32022. void Component::setVisible (bool shouldBeVisible)
  32023. {
  32024. if (flags.visibleFlag != shouldBeVisible)
  32025. {
  32026. // if component methods are being called from threads other than the message
  32027. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32028. checkMessageManagerIsLocked
  32029. SafePointer<Component> safePointer (this);
  32030. flags.visibleFlag = shouldBeVisible;
  32031. internalRepaint (0, 0, getWidth(), getHeight());
  32032. sendFakeMouseMove();
  32033. if (! shouldBeVisible)
  32034. {
  32035. if (currentlyFocusedComponent == this
  32036. || isParentOf (currentlyFocusedComponent))
  32037. {
  32038. if (parentComponent_ != 0)
  32039. parentComponent_->grabKeyboardFocus();
  32040. else
  32041. giveAwayFocus();
  32042. }
  32043. }
  32044. if (safePointer != 0)
  32045. {
  32046. sendVisibilityChangeMessage();
  32047. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32048. {
  32049. ComponentPeer* const peer = getPeer();
  32050. jassert (peer != 0);
  32051. if (peer != 0)
  32052. {
  32053. peer->setVisible (shouldBeVisible);
  32054. internalHierarchyChanged();
  32055. }
  32056. }
  32057. }
  32058. }
  32059. }
  32060. void Component::visibilityChanged()
  32061. {
  32062. }
  32063. void Component::sendVisibilityChangeMessage()
  32064. {
  32065. BailOutChecker checker (this);
  32066. visibilityChanged();
  32067. if (! checker.shouldBailOut())
  32068. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32069. }
  32070. bool Component::isShowing() const
  32071. {
  32072. if (flags.visibleFlag)
  32073. {
  32074. if (parentComponent_ != 0)
  32075. {
  32076. return parentComponent_->isShowing();
  32077. }
  32078. else
  32079. {
  32080. const ComponentPeer* const peer = getPeer();
  32081. return peer != 0 && ! peer->isMinimised();
  32082. }
  32083. }
  32084. return false;
  32085. }
  32086. class FadeOutProxyComponent : public Component,
  32087. public Timer
  32088. {
  32089. public:
  32090. FadeOutProxyComponent (Component* comp,
  32091. const int fadeLengthMs,
  32092. const int deltaXToMove,
  32093. const int deltaYToMove,
  32094. const float scaleFactorAtEnd)
  32095. : lastTime (0),
  32096. alpha (1.0f),
  32097. scale (1.0f)
  32098. {
  32099. image = comp->createComponentSnapshot (comp->getLocalBounds());
  32100. setBounds (comp->getBounds());
  32101. comp->getParentComponent()->addAndMakeVisible (this);
  32102. toBehind (comp);
  32103. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  32104. centreX = comp->getX() + comp->getWidth() * 0.5f;
  32105. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  32106. centreY = comp->getY() + comp->getHeight() * 0.5f;
  32107. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  32108. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  32109. setInterceptsMouseClicks (false, false);
  32110. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  32111. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  32112. }
  32113. ~FadeOutProxyComponent()
  32114. {
  32115. }
  32116. void paint (Graphics& g)
  32117. {
  32118. g.setOpacity (alpha);
  32119. g.drawImage (image,
  32120. 0, 0, getWidth(), getHeight(),
  32121. 0, 0, image.getWidth(), image.getHeight());
  32122. }
  32123. void timerCallback()
  32124. {
  32125. const uint32 now = Time::getMillisecondCounter();
  32126. if (lastTime == 0)
  32127. lastTime = now;
  32128. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  32129. lastTime = now;
  32130. alpha += alphaChangePerMs * msPassed;
  32131. if (alpha > 0)
  32132. {
  32133. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  32134. {
  32135. centreX += xChangePerMs * msPassed;
  32136. centreY += yChangePerMs * msPassed;
  32137. scale += scaleChangePerMs * msPassed;
  32138. const int w = roundToInt (image.getWidth() * scale);
  32139. const int h = roundToInt (image.getHeight() * scale);
  32140. setBounds (roundToInt (centreX) - w / 2,
  32141. roundToInt (centreY) - h / 2,
  32142. w, h);
  32143. }
  32144. repaint();
  32145. }
  32146. else
  32147. {
  32148. delete this;
  32149. }
  32150. }
  32151. juce_UseDebuggingNewOperator
  32152. private:
  32153. Image image;
  32154. uint32 lastTime;
  32155. float alpha, alphaChangePerMs;
  32156. float centreX, xChangePerMs;
  32157. float centreY, yChangePerMs;
  32158. float scale, scaleChangePerMs;
  32159. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32160. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32161. };
  32162. void Component::fadeOutComponent (const int millisecondsToFade,
  32163. const int deltaXToMove,
  32164. const int deltaYToMove,
  32165. const float scaleFactorAtEnd)
  32166. {
  32167. //xxx won't work for comps without parents
  32168. if (isShowing() && millisecondsToFade > 0)
  32169. new FadeOutProxyComponent (this, millisecondsToFade,
  32170. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32171. setVisible (false);
  32172. }
  32173. bool Component::isValidComponent() const
  32174. {
  32175. return (this != 0) && isValidMessageListener();
  32176. }
  32177. void* Component::getWindowHandle() const
  32178. {
  32179. const ComponentPeer* const peer = getPeer();
  32180. if (peer != 0)
  32181. return peer->getNativeHandle();
  32182. return 0;
  32183. }
  32184. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32185. {
  32186. // if component methods are being called from threads other than the message
  32187. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32188. checkMessageManagerIsLocked
  32189. if (isOpaque())
  32190. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32191. else
  32192. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32193. int currentStyleFlags = 0;
  32194. // don't use getPeer(), so that we only get the peer that's specifically
  32195. // for this comp, and not for one of its parents.
  32196. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32197. if (peer != 0)
  32198. currentStyleFlags = peer->getStyleFlags();
  32199. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32200. {
  32201. SafePointer<Component> safePointer (this);
  32202. #if JUCE_LINUX
  32203. // it's wise to give the component a non-zero size before
  32204. // putting it on the desktop, as X windows get confused by this, and
  32205. // a (1, 1) minimum size is enforced here.
  32206. setSize (jmax (1, getWidth()),
  32207. jmax (1, getHeight()));
  32208. #endif
  32209. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32210. bool wasFullscreen = false;
  32211. bool wasMinimised = false;
  32212. ComponentBoundsConstrainer* currentConstainer = 0;
  32213. Rectangle<int> oldNonFullScreenBounds;
  32214. if (peer != 0)
  32215. {
  32216. wasFullscreen = peer->isFullScreen();
  32217. wasMinimised = peer->isMinimised();
  32218. currentConstainer = peer->getConstrainer();
  32219. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32220. removeFromDesktop();
  32221. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32222. }
  32223. if (parentComponent_ != 0)
  32224. parentComponent_->removeChildComponent (this);
  32225. if (safePointer != 0)
  32226. {
  32227. flags.hasHeavyweightPeerFlag = true;
  32228. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32229. Desktop::getInstance().addDesktopComponent (this);
  32230. bounds_.setPosition (topLeft);
  32231. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32232. peer->setVisible (isVisible());
  32233. if (wasFullscreen)
  32234. {
  32235. peer->setFullScreen (true);
  32236. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32237. }
  32238. if (wasMinimised)
  32239. peer->setMinimised (true);
  32240. if (isAlwaysOnTop())
  32241. peer->setAlwaysOnTop (true);
  32242. peer->setConstrainer (currentConstainer);
  32243. repaint();
  32244. }
  32245. internalHierarchyChanged();
  32246. }
  32247. }
  32248. void Component::removeFromDesktop()
  32249. {
  32250. // if component methods are being called from threads other than the message
  32251. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32252. checkMessageManagerIsLocked
  32253. if (flags.hasHeavyweightPeerFlag)
  32254. {
  32255. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32256. flags.hasHeavyweightPeerFlag = false;
  32257. jassert (peer != 0);
  32258. delete peer;
  32259. Desktop::getInstance().removeDesktopComponent (this);
  32260. }
  32261. }
  32262. bool Component::isOnDesktop() const throw()
  32263. {
  32264. return flags.hasHeavyweightPeerFlag;
  32265. }
  32266. void Component::userTriedToCloseWindow()
  32267. {
  32268. /* This means that the user's trying to get rid of your window with the 'close window' system
  32269. menu option (on windows) or possibly the task manager - you should really handle this
  32270. and delete or hide your component in an appropriate way.
  32271. If you want to ignore the event and don't want to trigger this assertion, just override
  32272. this method and do nothing.
  32273. */
  32274. jassertfalse;
  32275. }
  32276. void Component::minimisationStateChanged (bool)
  32277. {
  32278. }
  32279. void Component::setOpaque (const bool shouldBeOpaque)
  32280. {
  32281. if (shouldBeOpaque != flags.opaqueFlag)
  32282. {
  32283. flags.opaqueFlag = shouldBeOpaque;
  32284. if (flags.hasHeavyweightPeerFlag)
  32285. {
  32286. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32287. if (peer != 0)
  32288. {
  32289. // to make it recreate the heavyweight window
  32290. addToDesktop (peer->getStyleFlags());
  32291. }
  32292. }
  32293. repaint();
  32294. }
  32295. }
  32296. bool Component::isOpaque() const throw()
  32297. {
  32298. return flags.opaqueFlag;
  32299. }
  32300. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32301. {
  32302. if (shouldBeBuffered != flags.bufferToImageFlag)
  32303. {
  32304. bufferedImage_ = Image::null;
  32305. flags.bufferToImageFlag = shouldBeBuffered;
  32306. }
  32307. }
  32308. void Component::toFront (const bool setAsForeground)
  32309. {
  32310. // if component methods are being called from threads other than the message
  32311. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32312. checkMessageManagerIsLocked
  32313. if (flags.hasHeavyweightPeerFlag)
  32314. {
  32315. ComponentPeer* const peer = getPeer();
  32316. if (peer != 0)
  32317. {
  32318. peer->toFront (setAsForeground);
  32319. if (setAsForeground && ! hasKeyboardFocus (true))
  32320. grabKeyboardFocus();
  32321. }
  32322. }
  32323. else if (parentComponent_ != 0)
  32324. {
  32325. Array<Component*>& childList = parentComponent_->childComponentList_;
  32326. if (childList.getLast() != this)
  32327. {
  32328. const int index = childList.indexOf (this);
  32329. if (index >= 0)
  32330. {
  32331. int insertIndex = -1;
  32332. if (! flags.alwaysOnTopFlag)
  32333. {
  32334. insertIndex = childList.size() - 1;
  32335. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32336. --insertIndex;
  32337. }
  32338. if (index != insertIndex)
  32339. {
  32340. childList.move (index, insertIndex);
  32341. sendFakeMouseMove();
  32342. repaintParent();
  32343. }
  32344. }
  32345. }
  32346. if (setAsForeground)
  32347. {
  32348. internalBroughtToFront();
  32349. grabKeyboardFocus();
  32350. }
  32351. }
  32352. }
  32353. void Component::toBehind (Component* const other)
  32354. {
  32355. if (other != 0 && other != this)
  32356. {
  32357. // the two components must belong to the same parent..
  32358. jassert (parentComponent_ == other->parentComponent_);
  32359. if (parentComponent_ != 0)
  32360. {
  32361. Array<Component*>& childList = parentComponent_->childComponentList_;
  32362. const int index = childList.indexOf (this);
  32363. if (index >= 0 && childList [index + 1] != other)
  32364. {
  32365. int otherIndex = childList.indexOf (other);
  32366. if (otherIndex >= 0)
  32367. {
  32368. if (index < otherIndex)
  32369. --otherIndex;
  32370. childList.move (index, otherIndex);
  32371. sendFakeMouseMove();
  32372. repaintParent();
  32373. }
  32374. }
  32375. }
  32376. else if (isOnDesktop())
  32377. {
  32378. jassert (other->isOnDesktop());
  32379. if (other->isOnDesktop())
  32380. {
  32381. ComponentPeer* const us = getPeer();
  32382. ComponentPeer* const them = other->getPeer();
  32383. jassert (us != 0 && them != 0);
  32384. if (us != 0 && them != 0)
  32385. us->toBehind (them);
  32386. }
  32387. }
  32388. }
  32389. }
  32390. void Component::toBack()
  32391. {
  32392. Array<Component*>& childList = parentComponent_->childComponentList_;
  32393. if (isOnDesktop())
  32394. {
  32395. jassertfalse; //xxx need to add this to native window
  32396. }
  32397. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32398. {
  32399. const int index = childList.indexOf (this);
  32400. if (index > 0)
  32401. {
  32402. int insertIndex = 0;
  32403. if (flags.alwaysOnTopFlag)
  32404. {
  32405. while (insertIndex < childList.size()
  32406. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32407. {
  32408. ++insertIndex;
  32409. }
  32410. }
  32411. if (index != insertIndex)
  32412. {
  32413. childList.move (index, insertIndex);
  32414. sendFakeMouseMove();
  32415. repaintParent();
  32416. }
  32417. }
  32418. }
  32419. }
  32420. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32421. {
  32422. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32423. {
  32424. flags.alwaysOnTopFlag = shouldStayOnTop;
  32425. if (isOnDesktop())
  32426. {
  32427. ComponentPeer* const peer = getPeer();
  32428. jassert (peer != 0);
  32429. if (peer != 0)
  32430. {
  32431. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32432. {
  32433. // some kinds of peer can't change their always-on-top status, so
  32434. // for these, we'll need to create a new window
  32435. const int oldFlags = peer->getStyleFlags();
  32436. removeFromDesktop();
  32437. addToDesktop (oldFlags);
  32438. }
  32439. }
  32440. }
  32441. if (shouldStayOnTop)
  32442. toFront (false);
  32443. internalHierarchyChanged();
  32444. }
  32445. }
  32446. bool Component::isAlwaysOnTop() const throw()
  32447. {
  32448. return flags.alwaysOnTopFlag;
  32449. }
  32450. int Component::proportionOfWidth (const float proportion) const throw()
  32451. {
  32452. return roundToInt (proportion * bounds_.getWidth());
  32453. }
  32454. int Component::proportionOfHeight (const float proportion) const throw()
  32455. {
  32456. return roundToInt (proportion * bounds_.getHeight());
  32457. }
  32458. int Component::getParentWidth() const throw()
  32459. {
  32460. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32461. : getParentMonitorArea().getWidth();
  32462. }
  32463. int Component::getParentHeight() const throw()
  32464. {
  32465. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32466. : getParentMonitorArea().getHeight();
  32467. }
  32468. int Component::getScreenX() const
  32469. {
  32470. return getScreenPosition().getX();
  32471. }
  32472. int Component::getScreenY() const
  32473. {
  32474. return getScreenPosition().getY();
  32475. }
  32476. const Point<int> Component::getScreenPosition() const
  32477. {
  32478. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32479. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32480. : getPosition());
  32481. }
  32482. const Rectangle<int> Component::getScreenBounds() const
  32483. {
  32484. return bounds_.withPosition (getScreenPosition());
  32485. }
  32486. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32487. {
  32488. const Component* c = this;
  32489. Point<int> p (relativePosition);
  32490. do
  32491. {
  32492. if (c->flags.hasHeavyweightPeerFlag)
  32493. return c->getPeer()->relativePositionToGlobal (p);
  32494. p += c->getPosition();
  32495. c = c->parentComponent_;
  32496. }
  32497. while (c != 0);
  32498. return p;
  32499. }
  32500. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32501. {
  32502. if (flags.hasHeavyweightPeerFlag)
  32503. {
  32504. return getPeer()->globalPositionToRelative (screenPosition);
  32505. }
  32506. else
  32507. {
  32508. if (parentComponent_ != 0)
  32509. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32510. return screenPosition - getPosition();
  32511. }
  32512. }
  32513. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32514. {
  32515. Point<int> p (positionRelativeToThis);
  32516. if (targetComponent != 0)
  32517. {
  32518. const Component* c = this;
  32519. do
  32520. {
  32521. if (c == targetComponent)
  32522. return p;
  32523. if (c->flags.hasHeavyweightPeerFlag)
  32524. {
  32525. p = c->getPeer()->relativePositionToGlobal (p);
  32526. break;
  32527. }
  32528. p += c->getPosition();
  32529. c = c->parentComponent_;
  32530. }
  32531. while (c != 0);
  32532. p = targetComponent->globalPositionToRelative (p);
  32533. }
  32534. return p;
  32535. }
  32536. void Component::setBounds (const int x, const int y, int w, int h)
  32537. {
  32538. // if component methods are being called from threads other than the message
  32539. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32540. checkMessageManagerIsLocked
  32541. if (w < 0) w = 0;
  32542. if (h < 0) h = 0;
  32543. const bool wasResized = (getWidth() != w || getHeight() != h);
  32544. const bool wasMoved = (getX() != x || getY() != y);
  32545. #if JUCE_DEBUG
  32546. // It's a very bad idea to try to resize a window during its paint() method!
  32547. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32548. #endif
  32549. if (wasMoved || wasResized)
  32550. {
  32551. if (flags.visibleFlag)
  32552. {
  32553. // send a fake mouse move to trigger enter/exit messages if needed..
  32554. sendFakeMouseMove();
  32555. if (! flags.hasHeavyweightPeerFlag)
  32556. repaintParent();
  32557. }
  32558. bounds_.setBounds (x, y, w, h);
  32559. if (wasResized)
  32560. repaint();
  32561. else if (! flags.hasHeavyweightPeerFlag)
  32562. repaintParent();
  32563. if (flags.hasHeavyweightPeerFlag)
  32564. {
  32565. ComponentPeer* const peer = getPeer();
  32566. if (peer != 0)
  32567. {
  32568. if (wasMoved && wasResized)
  32569. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32570. else if (wasMoved)
  32571. peer->setPosition (getX(), getY());
  32572. else if (wasResized)
  32573. peer->setSize (getWidth(), getHeight());
  32574. }
  32575. }
  32576. sendMovedResizedMessages (wasMoved, wasResized);
  32577. }
  32578. }
  32579. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32580. {
  32581. JUCE_TRY
  32582. {
  32583. if (wasMoved)
  32584. moved();
  32585. if (wasResized)
  32586. {
  32587. resized();
  32588. for (int i = childComponentList_.size(); --i >= 0;)
  32589. {
  32590. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32591. i = jmin (i, childComponentList_.size());
  32592. }
  32593. }
  32594. BailOutChecker checker (this);
  32595. if (parentComponent_ != 0)
  32596. parentComponent_->childBoundsChanged (this);
  32597. if (! checker.shouldBailOut())
  32598. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32599. *this, wasMoved, wasResized);
  32600. }
  32601. JUCE_CATCH_EXCEPTION
  32602. }
  32603. void Component::setSize (const int w, const int h)
  32604. {
  32605. setBounds (getX(), getY(), w, h);
  32606. }
  32607. void Component::setTopLeftPosition (const int x, const int y)
  32608. {
  32609. setBounds (x, y, getWidth(), getHeight());
  32610. }
  32611. void Component::setTopRightPosition (const int x, const int y)
  32612. {
  32613. setTopLeftPosition (x - getWidth(), y);
  32614. }
  32615. void Component::setBounds (const Rectangle<int>& r)
  32616. {
  32617. setBounds (r.getX(),
  32618. r.getY(),
  32619. r.getWidth(),
  32620. r.getHeight());
  32621. }
  32622. void Component::setBoundsRelative (const float x, const float y,
  32623. const float w, const float h)
  32624. {
  32625. const int pw = getParentWidth();
  32626. const int ph = getParentHeight();
  32627. setBounds (roundToInt (x * pw),
  32628. roundToInt (y * ph),
  32629. roundToInt (w * pw),
  32630. roundToInt (h * ph));
  32631. }
  32632. void Component::setCentrePosition (const int x, const int y)
  32633. {
  32634. setTopLeftPosition (x - getWidth() / 2,
  32635. y - getHeight() / 2);
  32636. }
  32637. void Component::setCentreRelative (const float x, const float y)
  32638. {
  32639. setCentrePosition (roundToInt (getParentWidth() * x),
  32640. roundToInt (getParentHeight() * y));
  32641. }
  32642. void Component::centreWithSize (const int width, const int height)
  32643. {
  32644. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32645. setBounds (parentArea.getCentreX() - width / 2,
  32646. parentArea.getCentreY() - height / 2,
  32647. width, height);
  32648. }
  32649. void Component::setBoundsInset (const BorderSize& borders)
  32650. {
  32651. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32652. }
  32653. void Component::setBoundsToFit (int x, int y, int width, int height,
  32654. const Justification& justification,
  32655. const bool onlyReduceInSize)
  32656. {
  32657. // it's no good calling this method unless both the component and
  32658. // target rectangle have a finite size.
  32659. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32660. if (getWidth() > 0 && getHeight() > 0
  32661. && width > 0 && height > 0)
  32662. {
  32663. int newW, newH;
  32664. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32665. {
  32666. newW = getWidth();
  32667. newH = getHeight();
  32668. }
  32669. else
  32670. {
  32671. const double imageRatio = getHeight() / (double) getWidth();
  32672. const double targetRatio = height / (double) width;
  32673. if (imageRatio <= targetRatio)
  32674. {
  32675. newW = width;
  32676. newH = jmin (height, roundToInt (newW * imageRatio));
  32677. }
  32678. else
  32679. {
  32680. newH = height;
  32681. newW = jmin (width, roundToInt (newH / imageRatio));
  32682. }
  32683. }
  32684. if (newW > 0 && newH > 0)
  32685. {
  32686. int newX, newY;
  32687. justification.applyToRectangle (newX, newY, newW, newH,
  32688. x, y, width, height);
  32689. setBounds (newX, newY, newW, newH);
  32690. }
  32691. }
  32692. }
  32693. bool Component::hitTest (int x, int y)
  32694. {
  32695. if (! flags.ignoresMouseClicksFlag)
  32696. return true;
  32697. if (flags.allowChildMouseClicksFlag)
  32698. {
  32699. for (int i = getNumChildComponents(); --i >= 0;)
  32700. {
  32701. Component* const c = getChildComponent (i);
  32702. if (c->isVisible()
  32703. && c->bounds_.contains (x, y)
  32704. && c->hitTest (x - c->getX(),
  32705. y - c->getY()))
  32706. {
  32707. return true;
  32708. }
  32709. }
  32710. }
  32711. return false;
  32712. }
  32713. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32714. const bool allowClicksOnChildComponents) throw()
  32715. {
  32716. flags.ignoresMouseClicksFlag = ! allowClicks;
  32717. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32718. }
  32719. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32720. bool& allowsClicksOnChildComponents) const throw()
  32721. {
  32722. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32723. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32724. }
  32725. bool Component::contains (const int x, const int y)
  32726. {
  32727. if (((unsigned int) x) < (unsigned int) getWidth()
  32728. && ((unsigned int) y) < (unsigned int) getHeight()
  32729. && hitTest (x, y))
  32730. {
  32731. if (parentComponent_ != 0)
  32732. {
  32733. return parentComponent_->contains (x + getX(),
  32734. y + getY());
  32735. }
  32736. else if (flags.hasHeavyweightPeerFlag)
  32737. {
  32738. const ComponentPeer* const peer = getPeer();
  32739. if (peer != 0)
  32740. return peer->contains (Point<int> (x, y), true);
  32741. }
  32742. }
  32743. return false;
  32744. }
  32745. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32746. {
  32747. if (! contains (x, y))
  32748. return false;
  32749. Component* p = this;
  32750. while (p->parentComponent_ != 0)
  32751. {
  32752. x += p->getX();
  32753. y += p->getY();
  32754. p = p->parentComponent_;
  32755. }
  32756. const Component* const c = p->getComponentAt (x, y);
  32757. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32758. }
  32759. Component* Component::getComponentAt (const Point<int>& position)
  32760. {
  32761. return getComponentAt (position.getX(), position.getY());
  32762. }
  32763. Component* Component::getComponentAt (const int x, const int y)
  32764. {
  32765. if (flags.visibleFlag
  32766. && ((unsigned int) x) < (unsigned int) getWidth()
  32767. && ((unsigned int) y) < (unsigned int) getHeight()
  32768. && hitTest (x, y))
  32769. {
  32770. for (int i = childComponentList_.size(); --i >= 0;)
  32771. {
  32772. Component* const child = childComponentList_.getUnchecked(i);
  32773. Component* const c = child->getComponentAt (x - child->getX(),
  32774. y - child->getY());
  32775. if (c != 0)
  32776. return c;
  32777. }
  32778. return this;
  32779. }
  32780. return 0;
  32781. }
  32782. void Component::addChildComponent (Component* const child, int zOrder)
  32783. {
  32784. // if component methods are being called from threads other than the message
  32785. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32786. checkMessageManagerIsLocked
  32787. if (child != 0 && child->parentComponent_ != this)
  32788. {
  32789. if (child->parentComponent_ != 0)
  32790. child->parentComponent_->removeChildComponent (child);
  32791. else
  32792. child->removeFromDesktop();
  32793. child->parentComponent_ = this;
  32794. if (child->isVisible())
  32795. child->repaintParent();
  32796. if (! child->isAlwaysOnTop())
  32797. {
  32798. if (zOrder < 0 || zOrder > childComponentList_.size())
  32799. zOrder = childComponentList_.size();
  32800. while (zOrder > 0)
  32801. {
  32802. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32803. break;
  32804. --zOrder;
  32805. }
  32806. }
  32807. childComponentList_.insert (zOrder, child);
  32808. child->internalHierarchyChanged();
  32809. internalChildrenChanged();
  32810. }
  32811. }
  32812. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32813. {
  32814. if (child != 0)
  32815. {
  32816. child->setVisible (true);
  32817. addChildComponent (child, zOrder);
  32818. }
  32819. }
  32820. void Component::removeChildComponent (Component* const child)
  32821. {
  32822. removeChildComponent (childComponentList_.indexOf (child));
  32823. }
  32824. Component* Component::removeChildComponent (const int index)
  32825. {
  32826. // if component methods are being called from threads other than the message
  32827. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32828. checkMessageManagerIsLocked
  32829. Component* const child = childComponentList_ [index];
  32830. if (child != 0)
  32831. {
  32832. sendFakeMouseMove();
  32833. child->repaintParent();
  32834. childComponentList_.remove (index);
  32835. child->parentComponent_ = 0;
  32836. JUCE_TRY
  32837. {
  32838. if ((currentlyFocusedComponent == child)
  32839. || child->isParentOf (currentlyFocusedComponent))
  32840. {
  32841. // get rid first to force the grabKeyboardFocus to change to us.
  32842. giveAwayFocus();
  32843. grabKeyboardFocus();
  32844. }
  32845. }
  32846. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32847. catch (const std::exception& e)
  32848. {
  32849. currentlyFocusedComponent = 0;
  32850. Desktop::getInstance().triggerFocusCallback();
  32851. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32852. }
  32853. catch (...)
  32854. {
  32855. currentlyFocusedComponent = 0;
  32856. Desktop::getInstance().triggerFocusCallback();
  32857. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32858. }
  32859. #endif
  32860. child->internalHierarchyChanged();
  32861. internalChildrenChanged();
  32862. }
  32863. return child;
  32864. }
  32865. void Component::removeAllChildren()
  32866. {
  32867. while (childComponentList_.size() > 0)
  32868. removeChildComponent (childComponentList_.size() - 1);
  32869. }
  32870. void Component::deleteAllChildren()
  32871. {
  32872. while (childComponentList_.size() > 0)
  32873. delete (removeChildComponent (childComponentList_.size() - 1));
  32874. }
  32875. int Component::getNumChildComponents() const throw()
  32876. {
  32877. return childComponentList_.size();
  32878. }
  32879. Component* Component::getChildComponent (const int index) const throw()
  32880. {
  32881. return childComponentList_ [index];
  32882. }
  32883. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32884. {
  32885. return childComponentList_.indexOf (const_cast <Component*> (child));
  32886. }
  32887. Component* Component::getTopLevelComponent() const throw()
  32888. {
  32889. const Component* comp = this;
  32890. while (comp->parentComponent_ != 0)
  32891. comp = comp->parentComponent_;
  32892. return const_cast <Component*> (comp);
  32893. }
  32894. bool Component::isParentOf (const Component* possibleChild) const throw()
  32895. {
  32896. if (! possibleChild->isValidComponent())
  32897. {
  32898. jassert (possibleChild == 0);
  32899. return false;
  32900. }
  32901. while (possibleChild != 0)
  32902. {
  32903. possibleChild = possibleChild->parentComponent_;
  32904. if (possibleChild == this)
  32905. return true;
  32906. }
  32907. return false;
  32908. }
  32909. void Component::parentHierarchyChanged()
  32910. {
  32911. }
  32912. void Component::childrenChanged()
  32913. {
  32914. }
  32915. void Component::internalChildrenChanged()
  32916. {
  32917. if (componentListeners.isEmpty())
  32918. {
  32919. childrenChanged();
  32920. }
  32921. else
  32922. {
  32923. BailOutChecker checker (this);
  32924. childrenChanged();
  32925. if (! checker.shouldBailOut())
  32926. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32927. }
  32928. }
  32929. void Component::internalHierarchyChanged()
  32930. {
  32931. BailOutChecker checker (this);
  32932. parentHierarchyChanged();
  32933. if (checker.shouldBailOut())
  32934. return;
  32935. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32936. if (checker.shouldBailOut())
  32937. return;
  32938. for (int i = childComponentList_.size(); --i >= 0;)
  32939. {
  32940. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32941. if (checker.shouldBailOut())
  32942. {
  32943. // you really shouldn't delete the parent component during a callback telling you
  32944. // that it's changed..
  32945. jassertfalse;
  32946. return;
  32947. }
  32948. i = jmin (i, childComponentList_.size());
  32949. }
  32950. }
  32951. void* Component::runModalLoopCallback (void* userData)
  32952. {
  32953. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32954. }
  32955. int Component::runModalLoop()
  32956. {
  32957. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32958. {
  32959. // use a callback so this can be called from non-gui threads
  32960. return (int) (pointer_sized_int) MessageManager::getInstance()
  32961. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32962. }
  32963. if (! isCurrentlyModal())
  32964. enterModalState (true);
  32965. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32966. }
  32967. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32968. {
  32969. // if component methods are being called from threads other than the message
  32970. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32971. checkMessageManagerIsLocked
  32972. // Check for an attempt to make a component modal when it already is!
  32973. // This can cause nasty problems..
  32974. jassert (! flags.currentlyModalFlag);
  32975. if (! isCurrentlyModal())
  32976. {
  32977. ModalComponentManager::getInstance()->startModal (this, callback);
  32978. flags.currentlyModalFlag = true;
  32979. setVisible (true);
  32980. if (takeKeyboardFocus_)
  32981. grabKeyboardFocus();
  32982. }
  32983. }
  32984. void Component::exitModalState (const int returnValue)
  32985. {
  32986. if (isCurrentlyModal())
  32987. {
  32988. if (MessageManager::getInstance()->isThisTheMessageThread())
  32989. {
  32990. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32991. flags.currentlyModalFlag = false;
  32992. bringModalComponentToFront();
  32993. }
  32994. else
  32995. {
  32996. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32997. }
  32998. }
  32999. }
  33000. bool Component::isCurrentlyModal() const throw()
  33001. {
  33002. return flags.currentlyModalFlag
  33003. && getCurrentlyModalComponent() == this;
  33004. }
  33005. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33006. {
  33007. Component* const mc = getCurrentlyModalComponent();
  33008. return mc != 0
  33009. && mc != this
  33010. && (! mc->isParentOf (this))
  33011. && ! mc->canModalEventBeSentToComponent (this);
  33012. }
  33013. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33014. {
  33015. return ModalComponentManager::getInstance()->getNumModalComponents();
  33016. }
  33017. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33018. {
  33019. return ModalComponentManager::getInstance()->getModalComponent (index);
  33020. }
  33021. void Component::bringModalComponentToFront()
  33022. {
  33023. ComponentPeer* lastOne = 0;
  33024. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  33025. {
  33026. Component* const c = getCurrentlyModalComponent (i);
  33027. if (c == 0)
  33028. break;
  33029. ComponentPeer* peer = c->getPeer();
  33030. if (peer != 0 && peer != lastOne)
  33031. {
  33032. if (lastOne == 0)
  33033. {
  33034. peer->toFront (true);
  33035. peer->grabFocus();
  33036. }
  33037. else
  33038. peer->toBehind (lastOne);
  33039. lastOne = peer;
  33040. }
  33041. }
  33042. }
  33043. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33044. {
  33045. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33046. }
  33047. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33048. {
  33049. return flags.bringToFrontOnClickFlag;
  33050. }
  33051. void Component::setMouseCursor (const MouseCursor& cursor)
  33052. {
  33053. if (cursor_ != cursor)
  33054. {
  33055. cursor_ = cursor;
  33056. if (flags.visibleFlag)
  33057. updateMouseCursor();
  33058. }
  33059. }
  33060. const MouseCursor Component::getMouseCursor()
  33061. {
  33062. return cursor_;
  33063. }
  33064. void Component::updateMouseCursor() const
  33065. {
  33066. sendFakeMouseMove();
  33067. }
  33068. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33069. {
  33070. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33071. }
  33072. void Component::repaintParent()
  33073. {
  33074. if (flags.visibleFlag)
  33075. internalRepaint (0, 0, getWidth(), getHeight());
  33076. }
  33077. void Component::repaint()
  33078. {
  33079. repaint (0, 0, getWidth(), getHeight());
  33080. }
  33081. void Component::repaint (const int x, const int y,
  33082. const int w, const int h)
  33083. {
  33084. bufferedImage_ = Image::null;
  33085. if (flags.visibleFlag)
  33086. internalRepaint (x, y, w, h);
  33087. }
  33088. void Component::repaint (const Rectangle<int>& area)
  33089. {
  33090. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33091. }
  33092. void Component::internalRepaint (int x, int y, int w, int h)
  33093. {
  33094. // if component methods are being called from threads other than the message
  33095. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33096. checkMessageManagerIsLocked
  33097. if (x < 0)
  33098. {
  33099. w += x;
  33100. x = 0;
  33101. }
  33102. if (x + w > getWidth())
  33103. w = getWidth() - x;
  33104. if (w > 0)
  33105. {
  33106. if (y < 0)
  33107. {
  33108. h += y;
  33109. y = 0;
  33110. }
  33111. if (y + h > getHeight())
  33112. h = getHeight() - y;
  33113. if (h > 0)
  33114. {
  33115. if (parentComponent_ != 0)
  33116. {
  33117. x += getX();
  33118. y += getY();
  33119. if (parentComponent_->flags.visibleFlag)
  33120. parentComponent_->internalRepaint (x, y, w, h);
  33121. }
  33122. else if (flags.hasHeavyweightPeerFlag)
  33123. {
  33124. ComponentPeer* const peer = getPeer();
  33125. if (peer != 0)
  33126. peer->repaint (Rectangle<int> (x, y, w, h));
  33127. }
  33128. }
  33129. }
  33130. }
  33131. void Component::renderComponent (Graphics& g)
  33132. {
  33133. const Rectangle<int> clipBounds (g.getClipBounds());
  33134. g.saveState();
  33135. clipObscuredRegions (g, clipBounds, 0, 0);
  33136. if (! g.isClipEmpty())
  33137. {
  33138. if (flags.bufferToImageFlag)
  33139. {
  33140. if (bufferedImage_.isNull())
  33141. {
  33142. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33143. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33144. Graphics imG (bufferedImage_);
  33145. paint (imG);
  33146. }
  33147. g.setColour (Colours::black);
  33148. g.drawImageAt (bufferedImage_, 0, 0);
  33149. }
  33150. else
  33151. {
  33152. paint (g);
  33153. }
  33154. }
  33155. g.restoreState();
  33156. for (int i = 0; i < childComponentList_.size(); ++i)
  33157. {
  33158. Component* const child = childComponentList_.getUnchecked (i);
  33159. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33160. {
  33161. g.saveState();
  33162. if (g.reduceClipRegion (child->getX(), child->getY(),
  33163. child->getWidth(), child->getHeight()))
  33164. {
  33165. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33166. {
  33167. const Component* const sibling = childComponentList_.getUnchecked (j);
  33168. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33169. g.excludeClipRegion (sibling->getBounds());
  33170. }
  33171. if (! g.isClipEmpty())
  33172. {
  33173. g.setOrigin (child->getX(), child->getY());
  33174. child->paintEntireComponent (g);
  33175. }
  33176. }
  33177. g.restoreState();
  33178. }
  33179. }
  33180. g.saveState();
  33181. paintOverChildren (g);
  33182. g.restoreState();
  33183. }
  33184. void Component::paintEntireComponent (Graphics& g)
  33185. {
  33186. jassert (! g.isClipEmpty());
  33187. #if JUCE_DEBUG
  33188. flags.isInsidePaintCall = true;
  33189. #endif
  33190. if (effect_ != 0)
  33191. {
  33192. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33193. getWidth(), getHeight(),
  33194. ! flags.opaqueFlag, Image::NativeImage);
  33195. {
  33196. Graphics g2 (effectImage);
  33197. renderComponent (g2);
  33198. }
  33199. effect_->applyEffect (effectImage, g);
  33200. }
  33201. else
  33202. {
  33203. renderComponent (g);
  33204. }
  33205. #if JUCE_DEBUG
  33206. flags.isInsidePaintCall = false;
  33207. #endif
  33208. }
  33209. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33210. const bool clipImageToComponentBounds)
  33211. {
  33212. Rectangle<int> r (areaToGrab);
  33213. if (clipImageToComponentBounds)
  33214. r = r.getIntersection (getLocalBounds());
  33215. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33216. jmax (1, r.getWidth()),
  33217. jmax (1, r.getHeight()),
  33218. true);
  33219. Graphics imageContext (componentImage);
  33220. imageContext.setOrigin (-r.getX(), -r.getY());
  33221. paintEntireComponent (imageContext);
  33222. return componentImage;
  33223. }
  33224. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33225. {
  33226. if (effect_ != effect)
  33227. {
  33228. effect_ = effect;
  33229. repaint();
  33230. }
  33231. }
  33232. LookAndFeel& Component::getLookAndFeel() const throw()
  33233. {
  33234. const Component* c = this;
  33235. do
  33236. {
  33237. if (c->lookAndFeel_ != 0)
  33238. return *(c->lookAndFeel_);
  33239. c = c->parentComponent_;
  33240. }
  33241. while (c != 0);
  33242. return LookAndFeel::getDefaultLookAndFeel();
  33243. }
  33244. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33245. {
  33246. if (lookAndFeel_ != newLookAndFeel)
  33247. {
  33248. lookAndFeel_ = newLookAndFeel;
  33249. sendLookAndFeelChange();
  33250. }
  33251. }
  33252. void Component::lookAndFeelChanged()
  33253. {
  33254. }
  33255. void Component::sendLookAndFeelChange()
  33256. {
  33257. repaint();
  33258. lookAndFeelChanged();
  33259. // (it's not a great idea to do anything that would delete this component
  33260. // during the lookAndFeelChanged() callback)
  33261. jassert (isValidComponent());
  33262. SafePointer<Component> safePointer (this);
  33263. for (int i = childComponentList_.size(); --i >= 0;)
  33264. {
  33265. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33266. if (safePointer == 0)
  33267. return;
  33268. i = jmin (i, childComponentList_.size());
  33269. }
  33270. }
  33271. static const Identifier getColourPropertyId (const int colourId)
  33272. {
  33273. String s;
  33274. s.preallocateStorage (18);
  33275. s << "jcclr_" << String::toHexString (colourId);
  33276. return s;
  33277. }
  33278. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33279. {
  33280. var* v = properties.getItem (getColourPropertyId (colourId));
  33281. if (v != 0)
  33282. return Colour ((int) *v);
  33283. if (inheritFromParent && parentComponent_ != 0)
  33284. return parentComponent_->findColour (colourId, true);
  33285. return getLookAndFeel().findColour (colourId);
  33286. }
  33287. bool Component::isColourSpecified (const int colourId) const
  33288. {
  33289. return properties.contains (getColourPropertyId (colourId));
  33290. }
  33291. void Component::removeColour (const int colourId)
  33292. {
  33293. if (properties.remove (getColourPropertyId (colourId)))
  33294. colourChanged();
  33295. }
  33296. void Component::setColour (const int colourId, const Colour& colour)
  33297. {
  33298. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33299. colourChanged();
  33300. }
  33301. void Component::copyAllExplicitColoursTo (Component& target) const
  33302. {
  33303. bool changed = false;
  33304. for (int i = properties.size(); --i >= 0;)
  33305. {
  33306. const Identifier name (properties.getName(i));
  33307. if (name.toString().startsWith ("jcclr_"))
  33308. if (target.properties.set (name, properties [name]))
  33309. changed = true;
  33310. }
  33311. if (changed)
  33312. target.colourChanged();
  33313. }
  33314. void Component::colourChanged()
  33315. {
  33316. }
  33317. const Rectangle<int> Component::getLocalBounds() const throw()
  33318. {
  33319. return Rectangle<int> (getWidth(), getHeight());
  33320. }
  33321. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33322. {
  33323. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33324. : Desktop::getInstance().getMainMonitorArea();
  33325. }
  33326. const Rectangle<int> Component::getUnclippedArea() const
  33327. {
  33328. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33329. Component* p = parentComponent_;
  33330. int px = getX();
  33331. int py = getY();
  33332. while (p != 0)
  33333. {
  33334. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33335. return Rectangle<int>();
  33336. px += p->getX();
  33337. py += p->getY();
  33338. p = p->parentComponent_;
  33339. }
  33340. return Rectangle<int> (x, y, w, h);
  33341. }
  33342. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33343. const int deltaX, const int deltaY) const
  33344. {
  33345. for (int i = childComponentList_.size(); --i >= 0;)
  33346. {
  33347. const Component* const c = childComponentList_.getUnchecked(i);
  33348. if (c->isVisible())
  33349. {
  33350. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33351. if (! newClip.isEmpty())
  33352. {
  33353. if (c->isOpaque())
  33354. {
  33355. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33356. }
  33357. else
  33358. {
  33359. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33360. c->getX() + deltaX,
  33361. c->getY() + deltaY);
  33362. }
  33363. }
  33364. }
  33365. }
  33366. }
  33367. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33368. {
  33369. result.clear();
  33370. const Rectangle<int> unclipped (getUnclippedArea());
  33371. if (! unclipped.isEmpty())
  33372. {
  33373. result.add (unclipped);
  33374. if (includeSiblings)
  33375. {
  33376. const Component* const c = getTopLevelComponent();
  33377. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33378. c->getLocalBounds(), this);
  33379. }
  33380. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33381. result.consolidate();
  33382. }
  33383. }
  33384. void Component::subtractObscuredRegions (RectangleList& result,
  33385. const Point<int>& delta,
  33386. const Rectangle<int>& clipRect,
  33387. const Component* const compToAvoid) const
  33388. {
  33389. for (int i = childComponentList_.size(); --i >= 0;)
  33390. {
  33391. const Component* const c = childComponentList_.getUnchecked(i);
  33392. if (c != compToAvoid && c->isVisible())
  33393. {
  33394. if (c->isOpaque())
  33395. {
  33396. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33397. childBounds.translate (delta.getX(), delta.getY());
  33398. result.subtract (childBounds);
  33399. }
  33400. else
  33401. {
  33402. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33403. newClip.translate (-c->getX(), -c->getY());
  33404. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33405. newClip, compToAvoid);
  33406. }
  33407. }
  33408. }
  33409. }
  33410. void Component::mouseEnter (const MouseEvent&)
  33411. {
  33412. // base class does nothing
  33413. }
  33414. void Component::mouseExit (const MouseEvent&)
  33415. {
  33416. // base class does nothing
  33417. }
  33418. void Component::mouseDown (const MouseEvent&)
  33419. {
  33420. // base class does nothing
  33421. }
  33422. void Component::mouseUp (const MouseEvent&)
  33423. {
  33424. // base class does nothing
  33425. }
  33426. void Component::mouseDrag (const MouseEvent&)
  33427. {
  33428. // base class does nothing
  33429. }
  33430. void Component::mouseMove (const MouseEvent&)
  33431. {
  33432. // base class does nothing
  33433. }
  33434. void Component::mouseDoubleClick (const MouseEvent&)
  33435. {
  33436. // base class does nothing
  33437. }
  33438. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33439. {
  33440. // the base class just passes this event up to its parent..
  33441. if (parentComponent_ != 0)
  33442. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33443. wheelIncrementX, wheelIncrementY);
  33444. }
  33445. void Component::resized()
  33446. {
  33447. // base class does nothing
  33448. }
  33449. void Component::moved()
  33450. {
  33451. // base class does nothing
  33452. }
  33453. void Component::childBoundsChanged (Component*)
  33454. {
  33455. // base class does nothing
  33456. }
  33457. void Component::parentSizeChanged()
  33458. {
  33459. // base class does nothing
  33460. }
  33461. void Component::addComponentListener (ComponentListener* const newListener)
  33462. {
  33463. jassert (isValidComponent());
  33464. componentListeners.add (newListener);
  33465. }
  33466. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33467. {
  33468. jassert (isValidComponent());
  33469. componentListeners.remove (listenerToRemove);
  33470. }
  33471. void Component::inputAttemptWhenModal()
  33472. {
  33473. bringModalComponentToFront();
  33474. getLookAndFeel().playAlertSound();
  33475. }
  33476. bool Component::canModalEventBeSentToComponent (const Component*)
  33477. {
  33478. return false;
  33479. }
  33480. void Component::internalModalInputAttempt()
  33481. {
  33482. Component* const current = getCurrentlyModalComponent();
  33483. if (current != 0)
  33484. current->inputAttemptWhenModal();
  33485. }
  33486. void Component::paint (Graphics&)
  33487. {
  33488. // all painting is done in the subclasses
  33489. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33490. }
  33491. void Component::paintOverChildren (Graphics&)
  33492. {
  33493. // all painting is done in the subclasses
  33494. }
  33495. void Component::handleMessage (const Message& message)
  33496. {
  33497. if (message.intParameter1 == exitModalStateMessage)
  33498. {
  33499. exitModalState (message.intParameter2);
  33500. }
  33501. else if (message.intParameter1 == customCommandMessage)
  33502. {
  33503. handleCommandMessage (message.intParameter2);
  33504. }
  33505. }
  33506. void Component::postCommandMessage (const int commandId)
  33507. {
  33508. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33509. }
  33510. void Component::handleCommandMessage (int)
  33511. {
  33512. // used by subclasses
  33513. }
  33514. void Component::addMouseListener (MouseListener* const newListener,
  33515. const bool wantsEventsForAllNestedChildComponents)
  33516. {
  33517. // if component methods are being called from threads other than the message
  33518. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33519. checkMessageManagerIsLocked
  33520. // If you register a component as a mouselistener for itself, it'll receive all the events
  33521. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33522. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33523. if (mouseListeners_ == 0)
  33524. mouseListeners_ = new Array<MouseListener*>();
  33525. if (! mouseListeners_->contains (newListener))
  33526. {
  33527. if (wantsEventsForAllNestedChildComponents)
  33528. {
  33529. mouseListeners_->insert (0, newListener);
  33530. ++numDeepMouseListeners;
  33531. }
  33532. else
  33533. {
  33534. mouseListeners_->add (newListener);
  33535. }
  33536. }
  33537. }
  33538. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33539. {
  33540. // if component methods are being called from threads other than the message
  33541. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33542. checkMessageManagerIsLocked
  33543. if (mouseListeners_ != 0)
  33544. {
  33545. const int index = mouseListeners_->indexOf (listenerToRemove);
  33546. if (index >= 0)
  33547. {
  33548. if (index < numDeepMouseListeners)
  33549. --numDeepMouseListeners;
  33550. mouseListeners_->remove (index);
  33551. }
  33552. }
  33553. }
  33554. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33555. {
  33556. if (isCurrentlyBlockedByAnotherModalComponent())
  33557. {
  33558. // if something else is modal, always just show a normal mouse cursor
  33559. source.showMouseCursor (MouseCursor::NormalCursor);
  33560. return;
  33561. }
  33562. if (! flags.mouseInsideFlag)
  33563. {
  33564. flags.mouseInsideFlag = true;
  33565. flags.mouseOverFlag = true;
  33566. flags.draggingFlag = false;
  33567. BailOutChecker checker (this);
  33568. if (flags.repaintOnMouseActivityFlag)
  33569. repaint();
  33570. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33571. this, this, time, relativePos,
  33572. time, 0, false);
  33573. mouseEnter (me);
  33574. if (checker.shouldBailOut())
  33575. return;
  33576. Desktop::getInstance().resetTimer();
  33577. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33578. if (checker.shouldBailOut())
  33579. return;
  33580. if (mouseListeners_ != 0)
  33581. {
  33582. for (int i = mouseListeners_->size(); --i >= 0;)
  33583. {
  33584. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33585. if (checker.shouldBailOut())
  33586. return;
  33587. i = jmin (i, mouseListeners_->size());
  33588. }
  33589. }
  33590. Component* p = parentComponent_;
  33591. while (p != 0)
  33592. {
  33593. if (p->numDeepMouseListeners > 0)
  33594. {
  33595. BailOutChecker checker2 (this, p);
  33596. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33597. {
  33598. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33599. if (checker2.shouldBailOut())
  33600. return;
  33601. i = jmin (i, p->numDeepMouseListeners);
  33602. }
  33603. }
  33604. p = p->parentComponent_;
  33605. }
  33606. }
  33607. }
  33608. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33609. {
  33610. BailOutChecker checker (this);
  33611. if (flags.draggingFlag)
  33612. {
  33613. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33614. if (checker.shouldBailOut())
  33615. return;
  33616. }
  33617. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33618. {
  33619. flags.mouseInsideFlag = false;
  33620. flags.mouseOverFlag = false;
  33621. flags.draggingFlag = false;
  33622. if (flags.repaintOnMouseActivityFlag)
  33623. repaint();
  33624. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33625. this, this, time, relativePos,
  33626. time, 0, false);
  33627. mouseExit (me);
  33628. if (checker.shouldBailOut())
  33629. return;
  33630. Desktop::getInstance().resetTimer();
  33631. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33632. if (checker.shouldBailOut())
  33633. return;
  33634. if (mouseListeners_ != 0)
  33635. {
  33636. for (int i = mouseListeners_->size(); --i >= 0;)
  33637. {
  33638. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33639. if (checker.shouldBailOut())
  33640. return;
  33641. i = jmin (i, mouseListeners_->size());
  33642. }
  33643. }
  33644. Component* p = parentComponent_;
  33645. while (p != 0)
  33646. {
  33647. if (p->numDeepMouseListeners > 0)
  33648. {
  33649. BailOutChecker checker2 (this, p);
  33650. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33651. {
  33652. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33653. if (checker2.shouldBailOut())
  33654. return;
  33655. i = jmin (i, p->numDeepMouseListeners);
  33656. }
  33657. }
  33658. p = p->parentComponent_;
  33659. }
  33660. }
  33661. }
  33662. class InternalDragRepeater : public Timer
  33663. {
  33664. public:
  33665. InternalDragRepeater()
  33666. {}
  33667. ~InternalDragRepeater()
  33668. {
  33669. clearSingletonInstance();
  33670. }
  33671. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33672. void timerCallback()
  33673. {
  33674. Desktop& desktop = Desktop::getInstance();
  33675. int numMiceDown = 0;
  33676. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33677. {
  33678. MouseInputSource* const source = desktop.getMouseSource(i);
  33679. if (source->isDragging())
  33680. {
  33681. source->triggerFakeMove();
  33682. ++numMiceDown;
  33683. }
  33684. }
  33685. if (numMiceDown == 0)
  33686. deleteInstance();
  33687. }
  33688. juce_UseDebuggingNewOperator
  33689. private:
  33690. InternalDragRepeater (const InternalDragRepeater&);
  33691. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33692. };
  33693. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33694. void Component::beginDragAutoRepeat (const int interval)
  33695. {
  33696. if (interval > 0)
  33697. {
  33698. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33699. InternalDragRepeater::getInstance()->startTimer (interval);
  33700. }
  33701. else
  33702. {
  33703. InternalDragRepeater::deleteInstance();
  33704. }
  33705. }
  33706. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33707. {
  33708. Desktop& desktop = Desktop::getInstance();
  33709. BailOutChecker checker (this);
  33710. if (isCurrentlyBlockedByAnotherModalComponent())
  33711. {
  33712. internalModalInputAttempt();
  33713. if (checker.shouldBailOut())
  33714. return;
  33715. // If processing the input attempt has exited the modal loop, we'll allow the event
  33716. // to be delivered..
  33717. if (isCurrentlyBlockedByAnotherModalComponent())
  33718. {
  33719. // allow blocked mouse-events to go to global listeners..
  33720. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33721. this, this, time, relativePos, time,
  33722. source.getNumberOfMultipleClicks(), false);
  33723. desktop.resetTimer();
  33724. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33725. return;
  33726. }
  33727. }
  33728. {
  33729. Component* c = this;
  33730. while (c != 0)
  33731. {
  33732. if (c->isBroughtToFrontOnMouseClick())
  33733. {
  33734. c->toFront (true);
  33735. if (checker.shouldBailOut())
  33736. return;
  33737. }
  33738. c = c->parentComponent_;
  33739. }
  33740. }
  33741. if (! flags.dontFocusOnMouseClickFlag)
  33742. {
  33743. grabFocusInternal (focusChangedByMouseClick);
  33744. if (checker.shouldBailOut())
  33745. return;
  33746. }
  33747. flags.draggingFlag = true;
  33748. flags.mouseOverFlag = true;
  33749. if (flags.repaintOnMouseActivityFlag)
  33750. repaint();
  33751. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33752. this, this, time, relativePos, time,
  33753. source.getNumberOfMultipleClicks(), false);
  33754. mouseDown (me);
  33755. if (checker.shouldBailOut())
  33756. return;
  33757. desktop.resetTimer();
  33758. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33759. if (checker.shouldBailOut())
  33760. return;
  33761. if (mouseListeners_ != 0)
  33762. {
  33763. for (int i = mouseListeners_->size(); --i >= 0;)
  33764. {
  33765. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33766. if (checker.shouldBailOut())
  33767. return;
  33768. i = jmin (i, mouseListeners_->size());
  33769. }
  33770. }
  33771. Component* p = parentComponent_;
  33772. while (p != 0)
  33773. {
  33774. if (p->numDeepMouseListeners > 0)
  33775. {
  33776. BailOutChecker checker2 (this, p);
  33777. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33778. {
  33779. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33780. if (checker2.shouldBailOut())
  33781. return;
  33782. i = jmin (i, p->numDeepMouseListeners);
  33783. }
  33784. }
  33785. p = p->parentComponent_;
  33786. }
  33787. }
  33788. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33789. {
  33790. if (flags.draggingFlag)
  33791. {
  33792. Desktop& desktop = Desktop::getInstance();
  33793. flags.draggingFlag = false;
  33794. BailOutChecker checker (this);
  33795. if (flags.repaintOnMouseActivityFlag)
  33796. repaint();
  33797. const MouseEvent me (source, relativePos,
  33798. oldModifiers, this, this, time,
  33799. globalPositionToRelative (source.getLastMouseDownPosition()),
  33800. source.getLastMouseDownTime(),
  33801. source.getNumberOfMultipleClicks(),
  33802. source.hasMouseMovedSignificantlySincePressed());
  33803. mouseUp (me);
  33804. if (checker.shouldBailOut())
  33805. return;
  33806. desktop.resetTimer();
  33807. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33808. if (checker.shouldBailOut())
  33809. return;
  33810. if (mouseListeners_ != 0)
  33811. {
  33812. for (int i = mouseListeners_->size(); --i >= 0;)
  33813. {
  33814. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33815. if (checker.shouldBailOut())
  33816. return;
  33817. i = jmin (i, mouseListeners_->size());
  33818. }
  33819. }
  33820. {
  33821. Component* p = parentComponent_;
  33822. while (p != 0)
  33823. {
  33824. if (p->numDeepMouseListeners > 0)
  33825. {
  33826. BailOutChecker checker2 (this, p);
  33827. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33828. {
  33829. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33830. if (checker2.shouldBailOut())
  33831. return;
  33832. i = jmin (i, p->numDeepMouseListeners);
  33833. }
  33834. }
  33835. p = p->parentComponent_;
  33836. }
  33837. }
  33838. // check for double-click
  33839. if (me.getNumberOfClicks() >= 2)
  33840. {
  33841. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33842. mouseDoubleClick (me);
  33843. if (checker.shouldBailOut())
  33844. return;
  33845. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33846. if (checker.shouldBailOut())
  33847. return;
  33848. for (int i = numListeners; --i >= 0;)
  33849. {
  33850. if (checker.shouldBailOut())
  33851. return;
  33852. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33853. if (ml != 0)
  33854. ml->mouseDoubleClick (me);
  33855. }
  33856. if (checker.shouldBailOut())
  33857. return;
  33858. Component* p = parentComponent_;
  33859. while (p != 0)
  33860. {
  33861. if (p->numDeepMouseListeners > 0)
  33862. {
  33863. BailOutChecker checker2 (this, p);
  33864. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33865. {
  33866. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33867. if (checker2.shouldBailOut())
  33868. return;
  33869. i = jmin (i, p->numDeepMouseListeners);
  33870. }
  33871. }
  33872. p = p->parentComponent_;
  33873. }
  33874. }
  33875. }
  33876. }
  33877. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33878. {
  33879. if (flags.draggingFlag)
  33880. {
  33881. Desktop& desktop = Desktop::getInstance();
  33882. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33883. BailOutChecker checker (this);
  33884. const MouseEvent me (source, relativePos,
  33885. source.getCurrentModifiers(), this, this, time,
  33886. globalPositionToRelative (source.getLastMouseDownPosition()),
  33887. source.getLastMouseDownTime(),
  33888. source.getNumberOfMultipleClicks(),
  33889. source.hasMouseMovedSignificantlySincePressed());
  33890. mouseDrag (me);
  33891. if (checker.shouldBailOut())
  33892. return;
  33893. desktop.resetTimer();
  33894. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33895. if (checker.shouldBailOut())
  33896. return;
  33897. if (mouseListeners_ != 0)
  33898. {
  33899. for (int i = mouseListeners_->size(); --i >= 0;)
  33900. {
  33901. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33902. if (checker.shouldBailOut())
  33903. return;
  33904. i = jmin (i, mouseListeners_->size());
  33905. }
  33906. }
  33907. Component* p = parentComponent_;
  33908. while (p != 0)
  33909. {
  33910. if (p->numDeepMouseListeners > 0)
  33911. {
  33912. BailOutChecker checker2 (this, p);
  33913. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33914. {
  33915. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33916. if (checker2.shouldBailOut())
  33917. return;
  33918. i = jmin (i, p->numDeepMouseListeners);
  33919. }
  33920. }
  33921. p = p->parentComponent_;
  33922. }
  33923. }
  33924. }
  33925. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33926. {
  33927. Desktop& desktop = Desktop::getInstance();
  33928. BailOutChecker checker (this);
  33929. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33930. this, this, time, relativePos,
  33931. time, 0, false);
  33932. if (isCurrentlyBlockedByAnotherModalComponent())
  33933. {
  33934. // allow blocked mouse-events to go to global listeners..
  33935. desktop.sendMouseMove();
  33936. }
  33937. else
  33938. {
  33939. flags.mouseOverFlag = true;
  33940. mouseMove (me);
  33941. if (checker.shouldBailOut())
  33942. return;
  33943. desktop.resetTimer();
  33944. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33945. if (checker.shouldBailOut())
  33946. return;
  33947. if (mouseListeners_ != 0)
  33948. {
  33949. for (int i = mouseListeners_->size(); --i >= 0;)
  33950. {
  33951. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33952. if (checker.shouldBailOut())
  33953. return;
  33954. i = jmin (i, mouseListeners_->size());
  33955. }
  33956. }
  33957. Component* p = parentComponent_;
  33958. while (p != 0)
  33959. {
  33960. if (p->numDeepMouseListeners > 0)
  33961. {
  33962. BailOutChecker checker2 (this, p);
  33963. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33964. {
  33965. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33966. if (checker2.shouldBailOut())
  33967. return;
  33968. i = jmin (i, p->numDeepMouseListeners);
  33969. }
  33970. }
  33971. p = p->parentComponent_;
  33972. }
  33973. }
  33974. }
  33975. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33976. const Time& time, const float amountX, const float amountY)
  33977. {
  33978. Desktop& desktop = Desktop::getInstance();
  33979. BailOutChecker checker (this);
  33980. const float wheelIncrementX = amountX / 256.0f;
  33981. const float wheelIncrementY = amountY / 256.0f;
  33982. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33983. this, this, time, relativePos, time, 0, false);
  33984. if (isCurrentlyBlockedByAnotherModalComponent())
  33985. {
  33986. // allow blocked mouse-events to go to global listeners..
  33987. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33988. }
  33989. else
  33990. {
  33991. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33992. if (checker.shouldBailOut())
  33993. return;
  33994. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33995. if (checker.shouldBailOut())
  33996. return;
  33997. if (mouseListeners_ != 0)
  33998. {
  33999. for (int i = mouseListeners_->size(); --i >= 0;)
  34000. {
  34001. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34002. if (checker.shouldBailOut())
  34003. return;
  34004. i = jmin (i, mouseListeners_->size());
  34005. }
  34006. }
  34007. Component* p = parentComponent_;
  34008. while (p != 0)
  34009. {
  34010. if (p->numDeepMouseListeners > 0)
  34011. {
  34012. BailOutChecker checker2 (this, p);
  34013. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34014. {
  34015. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34016. if (checker2.shouldBailOut())
  34017. return;
  34018. i = jmin (i, p->numDeepMouseListeners);
  34019. }
  34020. }
  34021. p = p->parentComponent_;
  34022. }
  34023. }
  34024. }
  34025. void Component::sendFakeMouseMove() const
  34026. {
  34027. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  34028. }
  34029. void Component::broughtToFront()
  34030. {
  34031. }
  34032. void Component::internalBroughtToFront()
  34033. {
  34034. if (! isValidComponent())
  34035. return;
  34036. if (flags.hasHeavyweightPeerFlag)
  34037. Desktop::getInstance().componentBroughtToFront (this);
  34038. BailOutChecker checker (this);
  34039. broughtToFront();
  34040. if (checker.shouldBailOut())
  34041. return;
  34042. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  34043. if (checker.shouldBailOut())
  34044. return;
  34045. // When brought to the front and there's a modal component blocking this one,
  34046. // we need to bring the modal one to the front instead..
  34047. Component* const cm = getCurrentlyModalComponent();
  34048. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  34049. bringModalComponentToFront();
  34050. }
  34051. void Component::focusGained (FocusChangeType)
  34052. {
  34053. // base class does nothing
  34054. }
  34055. void Component::internalFocusGain (const FocusChangeType cause)
  34056. {
  34057. SafePointer<Component> safePointer (this);
  34058. focusGained (cause);
  34059. if (safePointer != 0)
  34060. internalChildFocusChange (cause);
  34061. }
  34062. void Component::focusLost (FocusChangeType)
  34063. {
  34064. // base class does nothing
  34065. }
  34066. void Component::internalFocusLoss (const FocusChangeType cause)
  34067. {
  34068. SafePointer<Component> safePointer (this);
  34069. focusLost (focusChangedDirectly);
  34070. if (safePointer != 0)
  34071. internalChildFocusChange (cause);
  34072. }
  34073. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34074. {
  34075. // base class does nothing
  34076. }
  34077. void Component::internalChildFocusChange (FocusChangeType cause)
  34078. {
  34079. const bool childIsNowFocused = hasKeyboardFocus (true);
  34080. if (flags.childCompFocusedFlag != childIsNowFocused)
  34081. {
  34082. flags.childCompFocusedFlag = childIsNowFocused;
  34083. SafePointer<Component> safePointer (this);
  34084. focusOfChildComponentChanged (cause);
  34085. if (safePointer == 0)
  34086. return;
  34087. }
  34088. if (parentComponent_ != 0)
  34089. parentComponent_->internalChildFocusChange (cause);
  34090. }
  34091. bool Component::isEnabled() const throw()
  34092. {
  34093. return (! flags.isDisabledFlag)
  34094. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34095. }
  34096. void Component::setEnabled (const bool shouldBeEnabled)
  34097. {
  34098. if (flags.isDisabledFlag == shouldBeEnabled)
  34099. {
  34100. flags.isDisabledFlag = ! shouldBeEnabled;
  34101. // if any parent components are disabled, setting our flag won't make a difference,
  34102. // so no need to send a change message
  34103. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34104. sendEnablementChangeMessage();
  34105. }
  34106. }
  34107. void Component::sendEnablementChangeMessage()
  34108. {
  34109. SafePointer<Component> safePointer (this);
  34110. enablementChanged();
  34111. if (safePointer == 0)
  34112. return;
  34113. for (int i = getNumChildComponents(); --i >= 0;)
  34114. {
  34115. Component* const c = getChildComponent (i);
  34116. if (c != 0)
  34117. {
  34118. c->sendEnablementChangeMessage();
  34119. if (safePointer == 0)
  34120. return;
  34121. }
  34122. }
  34123. }
  34124. void Component::enablementChanged()
  34125. {
  34126. }
  34127. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34128. {
  34129. flags.wantsFocusFlag = wantsFocus;
  34130. }
  34131. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34132. {
  34133. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34134. }
  34135. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34136. {
  34137. return ! flags.dontFocusOnMouseClickFlag;
  34138. }
  34139. bool Component::getWantsKeyboardFocus() const throw()
  34140. {
  34141. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34142. }
  34143. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34144. {
  34145. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34146. }
  34147. bool Component::isFocusContainer() const throw()
  34148. {
  34149. return flags.isFocusContainerFlag;
  34150. }
  34151. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34152. int Component::getExplicitFocusOrder() const
  34153. {
  34154. return properties [juce_explicitFocusOrderId];
  34155. }
  34156. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34157. {
  34158. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34159. }
  34160. KeyboardFocusTraverser* Component::createFocusTraverser()
  34161. {
  34162. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34163. return new KeyboardFocusTraverser();
  34164. return parentComponent_->createFocusTraverser();
  34165. }
  34166. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34167. {
  34168. // give the focus to this component
  34169. if (currentlyFocusedComponent != this)
  34170. {
  34171. JUCE_TRY
  34172. {
  34173. // get the focus onto our desktop window
  34174. ComponentPeer* const peer = getPeer();
  34175. if (peer != 0)
  34176. {
  34177. SafePointer<Component> safePointer (this);
  34178. peer->grabFocus();
  34179. if (peer->isFocused() && currentlyFocusedComponent != this)
  34180. {
  34181. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34182. currentlyFocusedComponent = this;
  34183. Desktop::getInstance().triggerFocusCallback();
  34184. // call this after setting currentlyFocusedComponent so that the one that's
  34185. // losing it has a chance to see where focus is going
  34186. if (componentLosingFocus != 0)
  34187. componentLosingFocus->internalFocusLoss (cause);
  34188. if (currentlyFocusedComponent == this)
  34189. {
  34190. focusGained (cause);
  34191. if (safePointer != 0)
  34192. internalChildFocusChange (cause);
  34193. }
  34194. }
  34195. }
  34196. }
  34197. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34198. catch (const std::exception& e)
  34199. {
  34200. currentlyFocusedComponent = 0;
  34201. Desktop::getInstance().triggerFocusCallback();
  34202. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34203. }
  34204. catch (...)
  34205. {
  34206. currentlyFocusedComponent = 0;
  34207. Desktop::getInstance().triggerFocusCallback();
  34208. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34209. }
  34210. #endif
  34211. }
  34212. }
  34213. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34214. {
  34215. if (isShowing())
  34216. {
  34217. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34218. {
  34219. takeKeyboardFocus (cause);
  34220. }
  34221. else
  34222. {
  34223. if (isParentOf (currentlyFocusedComponent)
  34224. && currentlyFocusedComponent->isShowing())
  34225. {
  34226. // do nothing if the focused component is actually a child of ours..
  34227. }
  34228. else
  34229. {
  34230. // find the default child component..
  34231. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34232. if (traverser != 0)
  34233. {
  34234. Component* const defaultComp = traverser->getDefaultComponent (this);
  34235. traverser = 0;
  34236. if (defaultComp != 0)
  34237. {
  34238. defaultComp->grabFocusInternal (cause, false);
  34239. return;
  34240. }
  34241. }
  34242. if (canTryParent && parentComponent_ != 0)
  34243. {
  34244. // if no children want it and we're allowed to try our parent comp,
  34245. // then pass up to parent, which will try our siblings.
  34246. parentComponent_->grabFocusInternal (cause, true);
  34247. }
  34248. }
  34249. }
  34250. }
  34251. }
  34252. void Component::grabKeyboardFocus()
  34253. {
  34254. // if component methods are being called from threads other than the message
  34255. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34256. checkMessageManagerIsLocked
  34257. grabFocusInternal (focusChangedDirectly);
  34258. }
  34259. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34260. {
  34261. // if component methods are being called from threads other than the message
  34262. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34263. checkMessageManagerIsLocked
  34264. if (parentComponent_ != 0)
  34265. {
  34266. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34267. if (traverser != 0)
  34268. {
  34269. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34270. : traverser->getPreviousComponent (this);
  34271. traverser = 0;
  34272. if (nextComp != 0)
  34273. {
  34274. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34275. {
  34276. SafePointer<Component> nextCompPointer (nextComp);
  34277. internalModalInputAttempt();
  34278. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34279. return;
  34280. }
  34281. nextComp->grabFocusInternal (focusChangedByTabKey);
  34282. return;
  34283. }
  34284. }
  34285. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34286. }
  34287. }
  34288. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34289. {
  34290. return (currentlyFocusedComponent == this)
  34291. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34292. }
  34293. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34294. {
  34295. return currentlyFocusedComponent;
  34296. }
  34297. void Component::giveAwayFocus()
  34298. {
  34299. // use a copy so we can clear the value before the call
  34300. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34301. currentlyFocusedComponent = 0;
  34302. Desktop::getInstance().triggerFocusCallback();
  34303. if (componentLosingFocus != 0)
  34304. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34305. }
  34306. bool Component::isMouseOver() const throw()
  34307. {
  34308. return flags.mouseOverFlag;
  34309. }
  34310. bool Component::isMouseButtonDown() const throw()
  34311. {
  34312. return flags.draggingFlag;
  34313. }
  34314. bool Component::isMouseOverOrDragging() const throw()
  34315. {
  34316. return flags.mouseOverFlag || flags.draggingFlag;
  34317. }
  34318. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34319. {
  34320. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34321. }
  34322. const Point<int> Component::getMouseXYRelative() const
  34323. {
  34324. return globalPositionToRelative (Desktop::getMousePosition());
  34325. }
  34326. const Rectangle<int> Component::getParentMonitorArea() const
  34327. {
  34328. return Desktop::getInstance()
  34329. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34330. }
  34331. void Component::addKeyListener (KeyListener* const newListener)
  34332. {
  34333. if (keyListeners_ == 0)
  34334. keyListeners_ = new Array <KeyListener*>();
  34335. keyListeners_->addIfNotAlreadyThere (newListener);
  34336. }
  34337. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34338. {
  34339. if (keyListeners_ != 0)
  34340. keyListeners_->removeValue (listenerToRemove);
  34341. }
  34342. bool Component::keyPressed (const KeyPress&)
  34343. {
  34344. return false;
  34345. }
  34346. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34347. {
  34348. return false;
  34349. }
  34350. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34351. {
  34352. if (parentComponent_ != 0)
  34353. parentComponent_->modifierKeysChanged (modifiers);
  34354. }
  34355. void Component::internalModifierKeysChanged()
  34356. {
  34357. sendFakeMouseMove();
  34358. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34359. }
  34360. ComponentPeer* Component::getPeer() const
  34361. {
  34362. if (flags.hasHeavyweightPeerFlag)
  34363. return ComponentPeer::getPeerFor (this);
  34364. else if (parentComponent_ != 0)
  34365. return parentComponent_->getPeer();
  34366. else
  34367. return 0;
  34368. }
  34369. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34370. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34371. {
  34372. jassert (component1 != 0);
  34373. }
  34374. bool Component::BailOutChecker::shouldBailOut() const throw()
  34375. {
  34376. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34377. }
  34378. END_JUCE_NAMESPACE
  34379. /*** End of inlined file: juce_Component.cpp ***/
  34380. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34381. BEGIN_JUCE_NAMESPACE
  34382. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34383. void ComponentListener::componentBroughtToFront (Component&) {}
  34384. void ComponentListener::componentVisibilityChanged (Component&) {}
  34385. void ComponentListener::componentChildrenChanged (Component&) {}
  34386. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34387. void ComponentListener::componentNameChanged (Component&) {}
  34388. void ComponentListener::componentBeingDeleted (Component&) {}
  34389. END_JUCE_NAMESPACE
  34390. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34391. /*** Start of inlined file: juce_Desktop.cpp ***/
  34392. BEGIN_JUCE_NAMESPACE
  34393. Desktop::Desktop()
  34394. : mouseClickCounter (0),
  34395. kioskModeComponent (0),
  34396. allowedOrientations (allOrientations)
  34397. {
  34398. createMouseInputSources();
  34399. refreshMonitorSizes();
  34400. }
  34401. Desktop::~Desktop()
  34402. {
  34403. jassert (instance == this);
  34404. instance = 0;
  34405. // doh! If you don't delete all your windows before exiting, you're going to
  34406. // be leaking memory!
  34407. jassert (desktopComponents.size() == 0);
  34408. }
  34409. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34410. {
  34411. if (instance == 0)
  34412. instance = new Desktop();
  34413. return *instance;
  34414. }
  34415. Desktop* Desktop::instance = 0;
  34416. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34417. const bool clipToWorkArea);
  34418. void Desktop::refreshMonitorSizes()
  34419. {
  34420. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34421. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34422. monitorCoordsClipped.clear();
  34423. monitorCoordsUnclipped.clear();
  34424. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34425. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34426. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34427. if (oldClipped != monitorCoordsClipped
  34428. || oldUnclipped != monitorCoordsUnclipped)
  34429. {
  34430. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34431. {
  34432. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34433. if (p != 0)
  34434. p->handleScreenSizeChange();
  34435. }
  34436. }
  34437. }
  34438. int Desktop::getNumDisplayMonitors() const throw()
  34439. {
  34440. return monitorCoordsClipped.size();
  34441. }
  34442. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34443. {
  34444. return clippedToWorkArea ? monitorCoordsClipped [index]
  34445. : monitorCoordsUnclipped [index];
  34446. }
  34447. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34448. {
  34449. RectangleList rl;
  34450. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34451. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34452. return rl;
  34453. }
  34454. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34455. {
  34456. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34457. }
  34458. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34459. {
  34460. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34461. double bestDistance = 1.0e10;
  34462. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34463. {
  34464. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34465. if (rect.contains (position))
  34466. return rect;
  34467. const double distance = rect.getCentre().getDistanceFrom (position);
  34468. if (distance < bestDistance)
  34469. {
  34470. bestDistance = distance;
  34471. best = rect;
  34472. }
  34473. }
  34474. return best;
  34475. }
  34476. int Desktop::getNumComponents() const throw()
  34477. {
  34478. return desktopComponents.size();
  34479. }
  34480. Component* Desktop::getComponent (const int index) const throw()
  34481. {
  34482. return desktopComponents [index];
  34483. }
  34484. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34485. {
  34486. for (int i = desktopComponents.size(); --i >= 0;)
  34487. {
  34488. Component* const c = desktopComponents.getUnchecked(i);
  34489. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34490. if (c->contains (relative.getX(), relative.getY()))
  34491. return c->getComponentAt (relative.getX(), relative.getY());
  34492. }
  34493. return 0;
  34494. }
  34495. void Desktop::addDesktopComponent (Component* const c)
  34496. {
  34497. jassert (c != 0);
  34498. jassert (! desktopComponents.contains (c));
  34499. desktopComponents.addIfNotAlreadyThere (c);
  34500. }
  34501. void Desktop::removeDesktopComponent (Component* const c)
  34502. {
  34503. desktopComponents.removeValue (c);
  34504. }
  34505. void Desktop::componentBroughtToFront (Component* const c)
  34506. {
  34507. const int index = desktopComponents.indexOf (c);
  34508. jassert (index >= 0);
  34509. if (index >= 0)
  34510. {
  34511. int newIndex = -1;
  34512. if (! c->isAlwaysOnTop())
  34513. {
  34514. newIndex = desktopComponents.size();
  34515. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34516. --newIndex;
  34517. --newIndex;
  34518. }
  34519. desktopComponents.move (index, newIndex);
  34520. }
  34521. }
  34522. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34523. {
  34524. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34525. }
  34526. int Desktop::getMouseButtonClickCounter() throw()
  34527. {
  34528. return getInstance().mouseClickCounter;
  34529. }
  34530. void Desktop::incrementMouseClickCounter() throw()
  34531. {
  34532. ++mouseClickCounter;
  34533. }
  34534. int Desktop::getNumDraggingMouseSources() const throw()
  34535. {
  34536. int num = 0;
  34537. for (int i = mouseSources.size(); --i >= 0;)
  34538. if (mouseSources.getUnchecked(i)->isDragging())
  34539. ++num;
  34540. return num;
  34541. }
  34542. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34543. {
  34544. int num = 0;
  34545. for (int i = mouseSources.size(); --i >= 0;)
  34546. {
  34547. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34548. if (mi->isDragging())
  34549. {
  34550. if (index == num)
  34551. return mi;
  34552. ++num;
  34553. }
  34554. }
  34555. return 0;
  34556. }
  34557. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34558. {
  34559. focusListeners.add (listener);
  34560. }
  34561. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34562. {
  34563. focusListeners.remove (listener);
  34564. }
  34565. void Desktop::triggerFocusCallback()
  34566. {
  34567. triggerAsyncUpdate();
  34568. }
  34569. void Desktop::handleAsyncUpdate()
  34570. {
  34571. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34572. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34573. }
  34574. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34575. {
  34576. mouseListeners.add (listener);
  34577. resetTimer();
  34578. }
  34579. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34580. {
  34581. mouseListeners.remove (listener);
  34582. resetTimer();
  34583. }
  34584. void Desktop::timerCallback()
  34585. {
  34586. if (lastFakeMouseMove != getMousePosition())
  34587. sendMouseMove();
  34588. }
  34589. void Desktop::sendMouseMove()
  34590. {
  34591. if (! mouseListeners.isEmpty())
  34592. {
  34593. startTimer (20);
  34594. lastFakeMouseMove = getMousePosition();
  34595. Component* const target = findComponentAt (lastFakeMouseMove);
  34596. if (target != 0)
  34597. {
  34598. Component::BailOutChecker checker (target);
  34599. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34600. const Time now (Time::getCurrentTime());
  34601. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34602. target, target, now, pos, now, 0, false);
  34603. if (me.mods.isAnyMouseButtonDown())
  34604. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34605. else
  34606. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34607. }
  34608. }
  34609. }
  34610. void Desktop::resetTimer()
  34611. {
  34612. if (mouseListeners.size() == 0)
  34613. stopTimer();
  34614. else
  34615. startTimer (100);
  34616. lastFakeMouseMove = getMousePosition();
  34617. }
  34618. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34619. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34620. {
  34621. if (kioskModeComponent != componentToUse)
  34622. {
  34623. // agh! Don't delete a component without first stopping it being the kiosk comp
  34624. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34625. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34626. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34627. if (kioskModeComponent->isValidComponent())
  34628. {
  34629. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34630. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34631. }
  34632. kioskModeComponent = componentToUse;
  34633. if (kioskModeComponent != 0)
  34634. {
  34635. jassert (kioskModeComponent->isValidComponent());
  34636. // Only components that are already on the desktop can be put into kiosk mode!
  34637. jassert (kioskModeComponent->isOnDesktop());
  34638. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34639. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34640. }
  34641. }
  34642. }
  34643. void Desktop::setOrientationsEnabled (const int newOrientations)
  34644. {
  34645. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34646. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34647. allowedOrientations = newOrientations;
  34648. }
  34649. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34650. {
  34651. // Make sure you only pass one valid flag in here...
  34652. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34653. return (allowedOrientations & orientation) != 0;
  34654. }
  34655. END_JUCE_NAMESPACE
  34656. /*** End of inlined file: juce_Desktop.cpp ***/
  34657. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34658. BEGIN_JUCE_NAMESPACE
  34659. class ModalComponentManager::ModalItem : public ComponentListener
  34660. {
  34661. public:
  34662. ModalItem (Component* const comp, Callback* const callback)
  34663. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34664. {
  34665. if (callback != 0)
  34666. callbacks.add (callback);
  34667. jassert (comp != 0);
  34668. component->addComponentListener (this);
  34669. }
  34670. ~ModalItem()
  34671. {
  34672. if (! isDeleted)
  34673. component->removeComponentListener (this);
  34674. }
  34675. void componentBeingDeleted (Component&)
  34676. {
  34677. isDeleted = true;
  34678. cancel();
  34679. }
  34680. void componentVisibilityChanged (Component&)
  34681. {
  34682. if (! component->isShowing())
  34683. cancel();
  34684. }
  34685. void componentParentHierarchyChanged (Component&)
  34686. {
  34687. if (! component->isShowing())
  34688. cancel();
  34689. }
  34690. void cancel()
  34691. {
  34692. if (isActive)
  34693. {
  34694. isActive = false;
  34695. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34696. }
  34697. }
  34698. Component* component;
  34699. OwnedArray<Callback> callbacks;
  34700. int returnValue;
  34701. bool isActive, isDeleted;
  34702. private:
  34703. ModalItem (const ModalItem&);
  34704. ModalItem& operator= (const ModalItem&);
  34705. };
  34706. ModalComponentManager::ModalComponentManager()
  34707. {
  34708. }
  34709. ModalComponentManager::~ModalComponentManager()
  34710. {
  34711. clearSingletonInstance();
  34712. }
  34713. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34714. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34715. {
  34716. if (component != 0)
  34717. stack.add (new ModalItem (component, callback));
  34718. }
  34719. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34720. {
  34721. if (callback != 0)
  34722. {
  34723. ScopedPointer<Callback> callbackDeleter (callback);
  34724. for (int i = stack.size(); --i >= 0;)
  34725. {
  34726. ModalItem* const item = stack.getUnchecked(i);
  34727. if (item->component == component)
  34728. {
  34729. item->callbacks.add (callback);
  34730. callbackDeleter.release();
  34731. break;
  34732. }
  34733. }
  34734. }
  34735. }
  34736. void ModalComponentManager::endModal (Component* component)
  34737. {
  34738. for (int i = stack.size(); --i >= 0;)
  34739. {
  34740. ModalItem* const item = stack.getUnchecked(i);
  34741. if (item->component == component)
  34742. item->cancel();
  34743. }
  34744. }
  34745. void ModalComponentManager::endModal (Component* component, int returnValue)
  34746. {
  34747. for (int i = stack.size(); --i >= 0;)
  34748. {
  34749. ModalItem* const item = stack.getUnchecked(i);
  34750. if (item->component == component)
  34751. {
  34752. item->returnValue = returnValue;
  34753. item->cancel();
  34754. }
  34755. }
  34756. }
  34757. int ModalComponentManager::getNumModalComponents() const
  34758. {
  34759. int n = 0;
  34760. for (int i = 0; i < stack.size(); ++i)
  34761. if (stack.getUnchecked(i)->isActive)
  34762. ++n;
  34763. return n;
  34764. }
  34765. Component* ModalComponentManager::getModalComponent (const int index) const
  34766. {
  34767. int n = 0;
  34768. for (int i = stack.size(); --i >= 0;)
  34769. {
  34770. const ModalItem* const item = stack.getUnchecked(i);
  34771. if (item->isActive)
  34772. if (n++ == index)
  34773. return item->component;
  34774. }
  34775. return 0;
  34776. }
  34777. bool ModalComponentManager::isModal (Component* const comp) const
  34778. {
  34779. for (int i = stack.size(); --i >= 0;)
  34780. {
  34781. const ModalItem* const item = stack.getUnchecked(i);
  34782. if (item->isActive && item->component == comp)
  34783. return true;
  34784. }
  34785. return false;
  34786. }
  34787. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34788. {
  34789. return comp == getModalComponent (0);
  34790. }
  34791. void ModalComponentManager::handleAsyncUpdate()
  34792. {
  34793. for (int i = stack.size(); --i >= 0;)
  34794. {
  34795. const ModalItem* const item = stack.getUnchecked(i);
  34796. if (! item->isActive)
  34797. {
  34798. for (int j = item->callbacks.size(); --j >= 0;)
  34799. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34800. stack.remove (i);
  34801. }
  34802. }
  34803. }
  34804. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34805. {
  34806. public:
  34807. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34808. ~ReturnValueRetriever() {}
  34809. void modalStateFinished (int returnValue)
  34810. {
  34811. finished = true;
  34812. value = returnValue;
  34813. }
  34814. private:
  34815. int& value;
  34816. bool& finished;
  34817. ReturnValueRetriever (const ReturnValueRetriever&);
  34818. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34819. };
  34820. int ModalComponentManager::runEventLoopForCurrentComponent()
  34821. {
  34822. // This can only be run from the message thread!
  34823. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34824. Component* currentlyModal = getModalComponent (0);
  34825. if (currentlyModal == 0)
  34826. return 0;
  34827. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34828. int returnValue = 0;
  34829. bool finished = false;
  34830. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34831. JUCE_TRY
  34832. {
  34833. while (! finished)
  34834. {
  34835. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34836. break;
  34837. }
  34838. }
  34839. JUCE_CATCH_EXCEPTION
  34840. if (prevFocused != 0)
  34841. prevFocused->grabKeyboardFocus();
  34842. return returnValue;
  34843. }
  34844. END_JUCE_NAMESPACE
  34845. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34846. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34847. BEGIN_JUCE_NAMESPACE
  34848. ArrowButton::ArrowButton (const String& name,
  34849. float arrowDirectionInRadians,
  34850. const Colour& arrowColour)
  34851. : Button (name),
  34852. colour (arrowColour)
  34853. {
  34854. path.lineTo (0.0f, 1.0f);
  34855. path.lineTo (1.0f, 0.5f);
  34856. path.closeSubPath();
  34857. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34858. 0.5f, 0.5f));
  34859. setComponentEffect (&shadow);
  34860. buttonStateChanged();
  34861. }
  34862. ArrowButton::~ArrowButton()
  34863. {
  34864. }
  34865. void ArrowButton::paintButton (Graphics& g,
  34866. bool /*isMouseOverButton*/,
  34867. bool /*isButtonDown*/)
  34868. {
  34869. g.setColour (colour);
  34870. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34871. (float) offset,
  34872. (float) (getWidth() - 3),
  34873. (float) (getHeight() - 3),
  34874. false));
  34875. }
  34876. void ArrowButton::buttonStateChanged()
  34877. {
  34878. offset = (isDown()) ? 1 : 0;
  34879. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34880. 0.3f, -1, 0);
  34881. }
  34882. END_JUCE_NAMESPACE
  34883. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34884. /*** Start of inlined file: juce_Button.cpp ***/
  34885. BEGIN_JUCE_NAMESPACE
  34886. class Button::RepeatTimer : public Timer
  34887. {
  34888. public:
  34889. RepeatTimer (Button& owner_) : owner (owner_) {}
  34890. void timerCallback() { owner.repeatTimerCallback(); }
  34891. juce_UseDebuggingNewOperator
  34892. private:
  34893. Button& owner;
  34894. RepeatTimer (const RepeatTimer&);
  34895. RepeatTimer& operator= (const RepeatTimer&);
  34896. };
  34897. Button::Button (const String& name)
  34898. : Component (name),
  34899. text (name),
  34900. buttonPressTime (0),
  34901. lastTimeCallbackTime (0),
  34902. commandManagerToUse (0),
  34903. autoRepeatDelay (-1),
  34904. autoRepeatSpeed (0),
  34905. autoRepeatMinimumDelay (-1),
  34906. radioGroupId (0),
  34907. commandID (0),
  34908. connectedEdgeFlags (0),
  34909. buttonState (buttonNormal),
  34910. lastToggleState (false),
  34911. clickTogglesState (false),
  34912. needsToRelease (false),
  34913. needsRepainting (false),
  34914. isKeyDown (false),
  34915. triggerOnMouseDown (false),
  34916. generateTooltip (false)
  34917. {
  34918. setWantsKeyboardFocus (true);
  34919. isOn.addListener (this);
  34920. }
  34921. Button::~Button()
  34922. {
  34923. isOn.removeListener (this);
  34924. if (commandManagerToUse != 0)
  34925. commandManagerToUse->removeListener (this);
  34926. repeatTimer = 0;
  34927. clearShortcuts();
  34928. }
  34929. void Button::setButtonText (const String& newText)
  34930. {
  34931. if (text != newText)
  34932. {
  34933. text = newText;
  34934. repaint();
  34935. }
  34936. }
  34937. void Button::setTooltip (const String& newTooltip)
  34938. {
  34939. SettableTooltipClient::setTooltip (newTooltip);
  34940. generateTooltip = false;
  34941. }
  34942. const String Button::getTooltip()
  34943. {
  34944. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34945. {
  34946. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34947. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34948. for (int i = 0; i < keyPresses.size(); ++i)
  34949. {
  34950. const String key (keyPresses.getReference(i).getTextDescription());
  34951. tt << " [";
  34952. if (key.length() == 1)
  34953. tt << TRANS("shortcut") << ": '" << key << "']";
  34954. else
  34955. tt << key << ']';
  34956. }
  34957. return tt;
  34958. }
  34959. return SettableTooltipClient::getTooltip();
  34960. }
  34961. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34962. {
  34963. if (connectedEdgeFlags != connectedEdgeFlags_)
  34964. {
  34965. connectedEdgeFlags = connectedEdgeFlags_;
  34966. repaint();
  34967. }
  34968. }
  34969. void Button::setToggleState (const bool shouldBeOn,
  34970. const bool sendChangeNotification)
  34971. {
  34972. if (shouldBeOn != lastToggleState)
  34973. {
  34974. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34975. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34976. lastToggleState = shouldBeOn;
  34977. repaint();
  34978. if (sendChangeNotification)
  34979. {
  34980. Component::SafePointer<Component> deletionWatcher (this);
  34981. sendClickMessage (ModifierKeys());
  34982. if (deletionWatcher == 0)
  34983. return;
  34984. }
  34985. if (lastToggleState)
  34986. turnOffOtherButtonsInGroup (sendChangeNotification);
  34987. }
  34988. }
  34989. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34990. {
  34991. clickTogglesState = shouldToggle;
  34992. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34993. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34994. // it is that this button represents, and the button will update its state to reflect this
  34995. // in the applicationCommandListChanged() method.
  34996. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34997. }
  34998. bool Button::getClickingTogglesState() const throw()
  34999. {
  35000. return clickTogglesState;
  35001. }
  35002. void Button::valueChanged (Value& value)
  35003. {
  35004. if (value.refersToSameSourceAs (isOn))
  35005. setToggleState (isOn.getValue(), true);
  35006. }
  35007. void Button::setRadioGroupId (const int newGroupId)
  35008. {
  35009. if (radioGroupId != newGroupId)
  35010. {
  35011. radioGroupId = newGroupId;
  35012. if (lastToggleState)
  35013. turnOffOtherButtonsInGroup (true);
  35014. }
  35015. }
  35016. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  35017. {
  35018. Component* const p = getParentComponent();
  35019. if (p != 0 && radioGroupId != 0)
  35020. {
  35021. Component::SafePointer<Component> deletionWatcher (this);
  35022. for (int i = p->getNumChildComponents(); --i >= 0;)
  35023. {
  35024. Component* const c = p->getChildComponent (i);
  35025. if (c != this)
  35026. {
  35027. Button* const b = dynamic_cast <Button*> (c);
  35028. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  35029. {
  35030. b->setToggleState (false, sendChangeNotification);
  35031. if (deletionWatcher == 0)
  35032. return;
  35033. }
  35034. }
  35035. }
  35036. }
  35037. }
  35038. void Button::enablementChanged()
  35039. {
  35040. updateState (0);
  35041. repaint();
  35042. }
  35043. Button::ButtonState Button::updateState (const MouseEvent* const e)
  35044. {
  35045. ButtonState state = buttonNormal;
  35046. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  35047. {
  35048. Point<int> mousePos;
  35049. if (e == 0)
  35050. mousePos = getMouseXYRelative();
  35051. else
  35052. mousePos = e->getEventRelativeTo (this).getPosition();
  35053. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  35054. const bool down = isMouseButtonDown();
  35055. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  35056. state = buttonDown;
  35057. else if (over)
  35058. state = buttonOver;
  35059. }
  35060. setState (state);
  35061. return state;
  35062. }
  35063. void Button::setState (const ButtonState newState)
  35064. {
  35065. if (buttonState != newState)
  35066. {
  35067. buttonState = newState;
  35068. repaint();
  35069. if (buttonState == buttonDown)
  35070. {
  35071. buttonPressTime = Time::getApproximateMillisecondCounter();
  35072. lastTimeCallbackTime = buttonPressTime;
  35073. }
  35074. sendStateMessage();
  35075. }
  35076. }
  35077. bool Button::isDown() const throw()
  35078. {
  35079. return buttonState == buttonDown;
  35080. }
  35081. bool Button::isOver() const throw()
  35082. {
  35083. return buttonState != buttonNormal;
  35084. }
  35085. void Button::buttonStateChanged()
  35086. {
  35087. }
  35088. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35089. {
  35090. const uint32 now = Time::getApproximateMillisecondCounter();
  35091. return now > buttonPressTime ? now - buttonPressTime : 0;
  35092. }
  35093. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35094. {
  35095. triggerOnMouseDown = isTriggeredOnMouseDown;
  35096. }
  35097. void Button::clicked()
  35098. {
  35099. }
  35100. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35101. {
  35102. clicked();
  35103. }
  35104. static const int clickMessageId = 0x2f3f4f99;
  35105. void Button::triggerClick()
  35106. {
  35107. postCommandMessage (clickMessageId);
  35108. }
  35109. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35110. {
  35111. if (clickTogglesState)
  35112. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35113. sendClickMessage (modifiers);
  35114. }
  35115. void Button::flashButtonState()
  35116. {
  35117. if (isEnabled())
  35118. {
  35119. needsToRelease = true;
  35120. setState (buttonDown);
  35121. getRepeatTimer().startTimer (100);
  35122. }
  35123. }
  35124. void Button::handleCommandMessage (int commandId)
  35125. {
  35126. if (commandId == clickMessageId)
  35127. {
  35128. if (isEnabled())
  35129. {
  35130. flashButtonState();
  35131. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35132. }
  35133. }
  35134. else
  35135. {
  35136. Component::handleCommandMessage (commandId);
  35137. }
  35138. }
  35139. void Button::addButtonListener (Listener* const newListener)
  35140. {
  35141. buttonListeners.add (newListener);
  35142. }
  35143. void Button::removeButtonListener (Listener* const listener)
  35144. {
  35145. buttonListeners.remove (listener);
  35146. }
  35147. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35148. {
  35149. Component::BailOutChecker checker (this);
  35150. if (commandManagerToUse != 0 && commandID != 0)
  35151. {
  35152. ApplicationCommandTarget::InvocationInfo info (commandID);
  35153. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35154. info.originatingComponent = this;
  35155. commandManagerToUse->invoke (info, true);
  35156. }
  35157. clicked (modifiers);
  35158. if (! checker.shouldBailOut())
  35159. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35160. }
  35161. void Button::sendStateMessage()
  35162. {
  35163. Component::BailOutChecker checker (this);
  35164. buttonStateChanged();
  35165. if (! checker.shouldBailOut())
  35166. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35167. }
  35168. void Button::paint (Graphics& g)
  35169. {
  35170. if (needsToRelease && isEnabled())
  35171. {
  35172. needsToRelease = false;
  35173. needsRepainting = true;
  35174. }
  35175. paintButton (g, isOver(), isDown());
  35176. }
  35177. void Button::mouseEnter (const MouseEvent& e)
  35178. {
  35179. updateState (&e);
  35180. }
  35181. void Button::mouseExit (const MouseEvent& e)
  35182. {
  35183. updateState (&e);
  35184. }
  35185. void Button::mouseDown (const MouseEvent& e)
  35186. {
  35187. updateState (&e);
  35188. if (isDown())
  35189. {
  35190. if (autoRepeatDelay >= 0)
  35191. getRepeatTimer().startTimer (autoRepeatDelay);
  35192. if (triggerOnMouseDown)
  35193. internalClickCallback (e.mods);
  35194. }
  35195. }
  35196. void Button::mouseUp (const MouseEvent& e)
  35197. {
  35198. const bool wasDown = isDown();
  35199. updateState (&e);
  35200. if (wasDown && isOver() && ! triggerOnMouseDown)
  35201. internalClickCallback (e.mods);
  35202. }
  35203. void Button::mouseDrag (const MouseEvent& e)
  35204. {
  35205. const ButtonState oldState = buttonState;
  35206. updateState (&e);
  35207. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35208. getRepeatTimer().startTimer (autoRepeatSpeed);
  35209. }
  35210. void Button::focusGained (FocusChangeType)
  35211. {
  35212. updateState (0);
  35213. repaint();
  35214. }
  35215. void Button::focusLost (FocusChangeType)
  35216. {
  35217. updateState (0);
  35218. repaint();
  35219. }
  35220. void Button::setVisible (bool shouldBeVisible)
  35221. {
  35222. if (shouldBeVisible != isVisible())
  35223. {
  35224. Component::setVisible (shouldBeVisible);
  35225. if (! shouldBeVisible)
  35226. needsToRelease = false;
  35227. updateState (0);
  35228. }
  35229. else
  35230. {
  35231. Component::setVisible (shouldBeVisible);
  35232. }
  35233. }
  35234. void Button::parentHierarchyChanged()
  35235. {
  35236. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35237. if (newKeySource != keySource.getComponent())
  35238. {
  35239. if (keySource != 0)
  35240. keySource->removeKeyListener (this);
  35241. keySource = newKeySource;
  35242. if (keySource != 0)
  35243. keySource->addKeyListener (this);
  35244. }
  35245. }
  35246. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35247. const int commandID_,
  35248. const bool generateTooltip_)
  35249. {
  35250. commandID = commandID_;
  35251. generateTooltip = generateTooltip_;
  35252. if (commandManagerToUse != commandManagerToUse_)
  35253. {
  35254. if (commandManagerToUse != 0)
  35255. commandManagerToUse->removeListener (this);
  35256. commandManagerToUse = commandManagerToUse_;
  35257. if (commandManagerToUse != 0)
  35258. commandManagerToUse->addListener (this);
  35259. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35260. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35261. // it is that this button represents, and the button will update its state to reflect this
  35262. // in the applicationCommandListChanged() method.
  35263. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35264. }
  35265. if (commandManagerToUse != 0)
  35266. applicationCommandListChanged();
  35267. else
  35268. setEnabled (true);
  35269. }
  35270. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35271. {
  35272. if (info.commandID == commandID
  35273. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35274. {
  35275. flashButtonState();
  35276. }
  35277. }
  35278. void Button::applicationCommandListChanged()
  35279. {
  35280. if (commandManagerToUse != 0)
  35281. {
  35282. ApplicationCommandInfo info (0);
  35283. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35284. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35285. if (target != 0)
  35286. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35287. }
  35288. }
  35289. void Button::addShortcut (const KeyPress& key)
  35290. {
  35291. if (key.isValid())
  35292. {
  35293. jassert (! isRegisteredForShortcut (key)); // already registered!
  35294. shortcuts.add (key);
  35295. parentHierarchyChanged();
  35296. }
  35297. }
  35298. void Button::clearShortcuts()
  35299. {
  35300. shortcuts.clear();
  35301. parentHierarchyChanged();
  35302. }
  35303. bool Button::isShortcutPressed() const
  35304. {
  35305. if (! isCurrentlyBlockedByAnotherModalComponent())
  35306. {
  35307. for (int i = shortcuts.size(); --i >= 0;)
  35308. if (shortcuts.getReference(i).isCurrentlyDown())
  35309. return true;
  35310. }
  35311. return false;
  35312. }
  35313. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35314. {
  35315. for (int i = shortcuts.size(); --i >= 0;)
  35316. if (key == shortcuts.getReference(i))
  35317. return true;
  35318. return false;
  35319. }
  35320. bool Button::keyStateChanged (const bool, Component*)
  35321. {
  35322. if (! isEnabled())
  35323. return false;
  35324. const bool wasDown = isKeyDown;
  35325. isKeyDown = isShortcutPressed();
  35326. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35327. getRepeatTimer().startTimer (autoRepeatDelay);
  35328. updateState (0);
  35329. if (isEnabled() && wasDown && ! isKeyDown)
  35330. {
  35331. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35332. // (return immediately - this button may now have been deleted)
  35333. return true;
  35334. }
  35335. return wasDown || isKeyDown;
  35336. }
  35337. bool Button::keyPressed (const KeyPress&, Component*)
  35338. {
  35339. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35340. return isShortcutPressed();
  35341. }
  35342. bool Button::keyPressed (const KeyPress& key)
  35343. {
  35344. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35345. {
  35346. triggerClick();
  35347. return true;
  35348. }
  35349. return false;
  35350. }
  35351. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35352. const int repeatMillisecs,
  35353. const int minimumDelayInMillisecs) throw()
  35354. {
  35355. autoRepeatDelay = initialDelayMillisecs;
  35356. autoRepeatSpeed = repeatMillisecs;
  35357. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35358. }
  35359. void Button::repeatTimerCallback()
  35360. {
  35361. if (needsRepainting)
  35362. {
  35363. getRepeatTimer().stopTimer();
  35364. updateState (0);
  35365. needsRepainting = false;
  35366. }
  35367. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35368. {
  35369. int repeatSpeed = autoRepeatSpeed;
  35370. if (autoRepeatMinimumDelay >= 0)
  35371. {
  35372. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35373. timeHeldDown *= timeHeldDown;
  35374. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35375. }
  35376. repeatSpeed = jmax (1, repeatSpeed);
  35377. getRepeatTimer().startTimer (repeatSpeed);
  35378. const uint32 now = Time::getApproximateMillisecondCounter();
  35379. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35380. lastTimeCallbackTime = now;
  35381. Component::SafePointer<Component> deletionWatcher (this);
  35382. for (int i = numTimesToCallback; --i >= 0;)
  35383. {
  35384. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35385. if (deletionWatcher == 0 || ! isDown())
  35386. return;
  35387. }
  35388. }
  35389. else if (! needsToRelease)
  35390. {
  35391. getRepeatTimer().stopTimer();
  35392. }
  35393. }
  35394. Button::RepeatTimer& Button::getRepeatTimer()
  35395. {
  35396. if (repeatTimer == 0)
  35397. repeatTimer = new RepeatTimer (*this);
  35398. return *repeatTimer;
  35399. }
  35400. END_JUCE_NAMESPACE
  35401. /*** End of inlined file: juce_Button.cpp ***/
  35402. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35403. BEGIN_JUCE_NAMESPACE
  35404. DrawableButton::DrawableButton (const String& name,
  35405. const DrawableButton::ButtonStyle buttonStyle)
  35406. : Button (name),
  35407. style (buttonStyle),
  35408. edgeIndent (3)
  35409. {
  35410. if (buttonStyle == ImageOnButtonBackground)
  35411. {
  35412. backgroundOff = Colour (0xffbbbbff);
  35413. backgroundOn = Colour (0xff3333ff);
  35414. }
  35415. else
  35416. {
  35417. backgroundOff = Colours::transparentBlack;
  35418. backgroundOn = Colour (0xaabbbbff);
  35419. }
  35420. }
  35421. DrawableButton::~DrawableButton()
  35422. {
  35423. deleteImages();
  35424. }
  35425. void DrawableButton::deleteImages()
  35426. {
  35427. }
  35428. void DrawableButton::setImages (const Drawable* normal,
  35429. const Drawable* over,
  35430. const Drawable* down,
  35431. const Drawable* disabled,
  35432. const Drawable* normalOn,
  35433. const Drawable* overOn,
  35434. const Drawable* downOn,
  35435. const Drawable* disabledOn)
  35436. {
  35437. deleteImages();
  35438. jassert (normal != 0); // you really need to give it at least a normal image..
  35439. if (normal != 0)
  35440. normalImage = normal->createCopy();
  35441. if (over != 0)
  35442. overImage = over->createCopy();
  35443. if (down != 0)
  35444. downImage = down->createCopy();
  35445. if (disabled != 0)
  35446. disabledImage = disabled->createCopy();
  35447. if (normalOn != 0)
  35448. normalImageOn = normalOn->createCopy();
  35449. if (overOn != 0)
  35450. overImageOn = overOn->createCopy();
  35451. if (downOn != 0)
  35452. downImageOn = downOn->createCopy();
  35453. if (disabledOn != 0)
  35454. disabledImageOn = disabledOn->createCopy();
  35455. repaint();
  35456. }
  35457. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35458. {
  35459. if (style != newStyle)
  35460. {
  35461. style = newStyle;
  35462. repaint();
  35463. }
  35464. }
  35465. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35466. const Colour& toggledOnColour)
  35467. {
  35468. if (backgroundOff != toggledOffColour
  35469. || backgroundOn != toggledOnColour)
  35470. {
  35471. backgroundOff = toggledOffColour;
  35472. backgroundOn = toggledOnColour;
  35473. repaint();
  35474. }
  35475. }
  35476. const Colour& DrawableButton::getBackgroundColour() const throw()
  35477. {
  35478. return getToggleState() ? backgroundOn
  35479. : backgroundOff;
  35480. }
  35481. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35482. {
  35483. edgeIndent = numPixelsIndent;
  35484. repaint();
  35485. }
  35486. void DrawableButton::paintButton (Graphics& g,
  35487. bool isMouseOverButton,
  35488. bool isButtonDown)
  35489. {
  35490. Rectangle<int> imageSpace;
  35491. if (style == ImageOnButtonBackground)
  35492. {
  35493. const int insetX = getWidth() / 4;
  35494. const int insetY = getHeight() / 4;
  35495. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35496. getLookAndFeel().drawButtonBackground (g, *this,
  35497. getBackgroundColour(),
  35498. isMouseOverButton,
  35499. isButtonDown);
  35500. }
  35501. else
  35502. {
  35503. g.fillAll (getBackgroundColour());
  35504. const int textH = (style == ImageAboveTextLabel)
  35505. ? jmin (16, proportionOfHeight (0.25f))
  35506. : 0;
  35507. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35508. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35509. imageSpace.setBounds (indentX, indentY,
  35510. getWidth() - indentX * 2,
  35511. getHeight() - indentY * 2 - textH);
  35512. if (textH > 0)
  35513. {
  35514. g.setFont ((float) textH);
  35515. g.setColour (findColour (DrawableButton::textColourId)
  35516. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35517. g.drawFittedText (getButtonText(),
  35518. 2, getHeight() - textH - 1,
  35519. getWidth() - 4, textH,
  35520. Justification::centred, 1);
  35521. }
  35522. }
  35523. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35524. g.setOpacity (1.0f);
  35525. const Drawable* imageToDraw = 0;
  35526. if (isEnabled())
  35527. {
  35528. imageToDraw = getCurrentImage();
  35529. }
  35530. else
  35531. {
  35532. imageToDraw = getToggleState() ? disabledImageOn
  35533. : disabledImage;
  35534. if (imageToDraw == 0)
  35535. {
  35536. g.setOpacity (0.4f);
  35537. imageToDraw = getNormalImage();
  35538. }
  35539. }
  35540. if (imageToDraw != 0)
  35541. {
  35542. if (style == ImageRaw)
  35543. imageToDraw->draw (g, 1.0f);
  35544. else
  35545. imageToDraw->drawWithin (g, imageSpace.toFloat(), RectanglePlacement::centred, 1.0f);
  35546. }
  35547. }
  35548. const Drawable* DrawableButton::getCurrentImage() const throw()
  35549. {
  35550. if (isDown())
  35551. return getDownImage();
  35552. if (isOver())
  35553. return getOverImage();
  35554. return getNormalImage();
  35555. }
  35556. const Drawable* DrawableButton::getNormalImage() const throw()
  35557. {
  35558. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35559. : normalImage;
  35560. }
  35561. const Drawable* DrawableButton::getOverImage() const throw()
  35562. {
  35563. const Drawable* d = normalImage;
  35564. if (getToggleState())
  35565. {
  35566. if (overImageOn != 0)
  35567. d = overImageOn;
  35568. else if (normalImageOn != 0)
  35569. d = normalImageOn;
  35570. else if (overImage != 0)
  35571. d = overImage;
  35572. }
  35573. else
  35574. {
  35575. if (overImage != 0)
  35576. d = overImage;
  35577. }
  35578. return d;
  35579. }
  35580. const Drawable* DrawableButton::getDownImage() const throw()
  35581. {
  35582. const Drawable* d = normalImage;
  35583. if (getToggleState())
  35584. {
  35585. if (downImageOn != 0)
  35586. d = downImageOn;
  35587. else if (overImageOn != 0)
  35588. d = overImageOn;
  35589. else if (normalImageOn != 0)
  35590. d = normalImageOn;
  35591. else if (downImage != 0)
  35592. d = downImage;
  35593. else
  35594. d = getOverImage();
  35595. }
  35596. else
  35597. {
  35598. if (downImage != 0)
  35599. d = downImage;
  35600. else
  35601. d = getOverImage();
  35602. }
  35603. return d;
  35604. }
  35605. END_JUCE_NAMESPACE
  35606. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35607. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35608. BEGIN_JUCE_NAMESPACE
  35609. HyperlinkButton::HyperlinkButton (const String& linkText,
  35610. const URL& linkURL)
  35611. : Button (linkText),
  35612. url (linkURL),
  35613. font (14.0f, Font::underlined),
  35614. resizeFont (true),
  35615. justification (Justification::centred)
  35616. {
  35617. setMouseCursor (MouseCursor::PointingHandCursor);
  35618. setTooltip (linkURL.toString (false));
  35619. }
  35620. HyperlinkButton::~HyperlinkButton()
  35621. {
  35622. }
  35623. void HyperlinkButton::setFont (const Font& newFont,
  35624. const bool resizeToMatchComponentHeight,
  35625. const Justification& justificationType)
  35626. {
  35627. font = newFont;
  35628. resizeFont = resizeToMatchComponentHeight;
  35629. justification = justificationType;
  35630. repaint();
  35631. }
  35632. void HyperlinkButton::setURL (const URL& newURL) throw()
  35633. {
  35634. url = newURL;
  35635. setTooltip (newURL.toString (false));
  35636. }
  35637. const Font HyperlinkButton::getFontToUse() const
  35638. {
  35639. Font f (font);
  35640. if (resizeFont)
  35641. f.setHeight (getHeight() * 0.7f);
  35642. return f;
  35643. }
  35644. void HyperlinkButton::changeWidthToFitText()
  35645. {
  35646. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35647. }
  35648. void HyperlinkButton::colourChanged()
  35649. {
  35650. repaint();
  35651. }
  35652. void HyperlinkButton::clicked()
  35653. {
  35654. if (url.isWellFormed())
  35655. url.launchInDefaultBrowser();
  35656. }
  35657. void HyperlinkButton::paintButton (Graphics& g,
  35658. bool isMouseOverButton,
  35659. bool isButtonDown)
  35660. {
  35661. const Colour textColour (findColour (textColourId));
  35662. if (isEnabled())
  35663. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35664. : textColour);
  35665. else
  35666. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35667. g.setFont (getFontToUse());
  35668. g.drawText (getButtonText(),
  35669. 2, 0, getWidth() - 2, getHeight(),
  35670. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35671. true);
  35672. }
  35673. END_JUCE_NAMESPACE
  35674. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35675. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35676. BEGIN_JUCE_NAMESPACE
  35677. ImageButton::ImageButton (const String& text_)
  35678. : Button (text_),
  35679. scaleImageToFit (true),
  35680. preserveProportions (true),
  35681. alphaThreshold (0),
  35682. imageX (0),
  35683. imageY (0),
  35684. imageW (0),
  35685. imageH (0),
  35686. normalImage (0),
  35687. overImage (0),
  35688. downImage (0)
  35689. {
  35690. }
  35691. ImageButton::~ImageButton()
  35692. {
  35693. }
  35694. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35695. const bool rescaleImagesWhenButtonSizeChanges,
  35696. const bool preserveImageProportions,
  35697. const Image& normalImage_,
  35698. const float imageOpacityWhenNormal,
  35699. const Colour& overlayColourWhenNormal,
  35700. const Image& overImage_,
  35701. const float imageOpacityWhenOver,
  35702. const Colour& overlayColourWhenOver,
  35703. const Image& downImage_,
  35704. const float imageOpacityWhenDown,
  35705. const Colour& overlayColourWhenDown,
  35706. const float hitTestAlphaThreshold)
  35707. {
  35708. normalImage = normalImage_;
  35709. overImage = overImage_;
  35710. downImage = downImage_;
  35711. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35712. {
  35713. imageW = normalImage.getWidth();
  35714. imageH = normalImage.getHeight();
  35715. setSize (imageW, imageH);
  35716. }
  35717. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35718. preserveProportions = preserveImageProportions;
  35719. normalOpacity = imageOpacityWhenNormal;
  35720. normalOverlay = overlayColourWhenNormal;
  35721. overOpacity = imageOpacityWhenOver;
  35722. overOverlay = overlayColourWhenOver;
  35723. downOpacity = imageOpacityWhenDown;
  35724. downOverlay = overlayColourWhenDown;
  35725. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35726. repaint();
  35727. }
  35728. const Image ImageButton::getCurrentImage() const
  35729. {
  35730. if (isDown() || getToggleState())
  35731. return getDownImage();
  35732. if (isOver())
  35733. return getOverImage();
  35734. return getNormalImage();
  35735. }
  35736. const Image ImageButton::getNormalImage() const
  35737. {
  35738. return normalImage;
  35739. }
  35740. const Image ImageButton::getOverImage() const
  35741. {
  35742. return overImage.isValid() ? overImage
  35743. : normalImage;
  35744. }
  35745. const Image ImageButton::getDownImage() const
  35746. {
  35747. return downImage.isValid() ? downImage
  35748. : getOverImage();
  35749. }
  35750. void ImageButton::paintButton (Graphics& g,
  35751. bool isMouseOverButton,
  35752. bool isButtonDown)
  35753. {
  35754. if (! isEnabled())
  35755. {
  35756. isMouseOverButton = false;
  35757. isButtonDown = false;
  35758. }
  35759. Image im (getCurrentImage());
  35760. if (im.isValid())
  35761. {
  35762. const int iw = im.getWidth();
  35763. const int ih = im.getHeight();
  35764. imageW = getWidth();
  35765. imageH = getHeight();
  35766. imageX = (imageW - iw) >> 1;
  35767. imageY = (imageH - ih) >> 1;
  35768. if (scaleImageToFit)
  35769. {
  35770. if (preserveProportions)
  35771. {
  35772. int newW, newH;
  35773. const float imRatio = ih / (float)iw;
  35774. const float destRatio = imageH / (float)imageW;
  35775. if (imRatio > destRatio)
  35776. {
  35777. newW = roundToInt (imageH / imRatio);
  35778. newH = imageH;
  35779. }
  35780. else
  35781. {
  35782. newW = imageW;
  35783. newH = roundToInt (imageW * imRatio);
  35784. }
  35785. imageX = (imageW - newW) / 2;
  35786. imageY = (imageH - newH) / 2;
  35787. imageW = newW;
  35788. imageH = newH;
  35789. }
  35790. else
  35791. {
  35792. imageX = 0;
  35793. imageY = 0;
  35794. }
  35795. }
  35796. if (! scaleImageToFit)
  35797. {
  35798. imageW = iw;
  35799. imageH = ih;
  35800. }
  35801. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35802. isButtonDown ? downOverlay
  35803. : (isMouseOverButton ? overOverlay
  35804. : normalOverlay),
  35805. isButtonDown ? downOpacity
  35806. : (isMouseOverButton ? overOpacity
  35807. : normalOpacity),
  35808. *this);
  35809. }
  35810. }
  35811. bool ImageButton::hitTest (int x, int y)
  35812. {
  35813. if (alphaThreshold == 0)
  35814. return true;
  35815. Image im (getCurrentImage());
  35816. return im.isNull() || (imageW > 0 && imageH > 0
  35817. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35818. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35819. }
  35820. END_JUCE_NAMESPACE
  35821. /*** End of inlined file: juce_ImageButton.cpp ***/
  35822. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35823. BEGIN_JUCE_NAMESPACE
  35824. ShapeButton::ShapeButton (const String& text_,
  35825. const Colour& normalColour_,
  35826. const Colour& overColour_,
  35827. const Colour& downColour_)
  35828. : Button (text_),
  35829. normalColour (normalColour_),
  35830. overColour (overColour_),
  35831. downColour (downColour_),
  35832. maintainShapeProportions (false),
  35833. outlineWidth (0.0f)
  35834. {
  35835. }
  35836. ShapeButton::~ShapeButton()
  35837. {
  35838. }
  35839. void ShapeButton::setColours (const Colour& newNormalColour,
  35840. const Colour& newOverColour,
  35841. const Colour& newDownColour)
  35842. {
  35843. normalColour = newNormalColour;
  35844. overColour = newOverColour;
  35845. downColour = newDownColour;
  35846. }
  35847. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35848. const float newOutlineWidth)
  35849. {
  35850. outlineColour = newOutlineColour;
  35851. outlineWidth = newOutlineWidth;
  35852. }
  35853. void ShapeButton::setShape (const Path& newShape,
  35854. const bool resizeNowToFitThisShape,
  35855. const bool maintainShapeProportions_,
  35856. const bool hasShadow)
  35857. {
  35858. shape = newShape;
  35859. maintainShapeProportions = maintainShapeProportions_;
  35860. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35861. setComponentEffect ((hasShadow) ? &shadow : 0);
  35862. if (resizeNowToFitThisShape)
  35863. {
  35864. Rectangle<float> bounds (shape.getBounds());
  35865. if (hasShadow)
  35866. bounds.expand (4.0f, 4.0f);
  35867. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35868. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35869. 1 + (int) (bounds.getHeight() + outlineWidth));
  35870. }
  35871. }
  35872. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35873. {
  35874. if (! isEnabled())
  35875. {
  35876. isMouseOverButton = false;
  35877. isButtonDown = false;
  35878. }
  35879. g.setColour ((isButtonDown) ? downColour
  35880. : (isMouseOverButton) ? overColour
  35881. : normalColour);
  35882. int w = getWidth();
  35883. int h = getHeight();
  35884. if (getComponentEffect() != 0)
  35885. {
  35886. w -= 4;
  35887. h -= 4;
  35888. }
  35889. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35890. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35891. w - offset - outlineWidth,
  35892. h - offset - outlineWidth,
  35893. maintainShapeProportions));
  35894. g.fillPath (shape, trans);
  35895. if (outlineWidth > 0.0f)
  35896. {
  35897. g.setColour (outlineColour);
  35898. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35899. }
  35900. }
  35901. END_JUCE_NAMESPACE
  35902. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35903. /*** Start of inlined file: juce_TextButton.cpp ***/
  35904. BEGIN_JUCE_NAMESPACE
  35905. TextButton::TextButton (const String& name,
  35906. const String& toolTip)
  35907. : Button (name)
  35908. {
  35909. setTooltip (toolTip);
  35910. }
  35911. TextButton::~TextButton()
  35912. {
  35913. }
  35914. void TextButton::paintButton (Graphics& g,
  35915. bool isMouseOverButton,
  35916. bool isButtonDown)
  35917. {
  35918. getLookAndFeel().drawButtonBackground (g, *this,
  35919. findColour (getToggleState() ? buttonOnColourId
  35920. : buttonColourId),
  35921. isMouseOverButton,
  35922. isButtonDown);
  35923. getLookAndFeel().drawButtonText (g, *this,
  35924. isMouseOverButton,
  35925. isButtonDown);
  35926. }
  35927. void TextButton::colourChanged()
  35928. {
  35929. repaint();
  35930. }
  35931. const Font TextButton::getFont()
  35932. {
  35933. return Font (jmin (15.0f, getHeight() * 0.6f));
  35934. }
  35935. void TextButton::changeWidthToFitText (const int newHeight)
  35936. {
  35937. if (newHeight >= 0)
  35938. setSize (jmax (1, getWidth()), newHeight);
  35939. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35940. getHeight());
  35941. }
  35942. END_JUCE_NAMESPACE
  35943. /*** End of inlined file: juce_TextButton.cpp ***/
  35944. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35945. BEGIN_JUCE_NAMESPACE
  35946. ToggleButton::ToggleButton (const String& buttonText)
  35947. : Button (buttonText)
  35948. {
  35949. setClickingTogglesState (true);
  35950. }
  35951. ToggleButton::~ToggleButton()
  35952. {
  35953. }
  35954. void ToggleButton::paintButton (Graphics& g,
  35955. bool isMouseOverButton,
  35956. bool isButtonDown)
  35957. {
  35958. getLookAndFeel().drawToggleButton (g, *this,
  35959. isMouseOverButton,
  35960. isButtonDown);
  35961. }
  35962. void ToggleButton::changeWidthToFitText()
  35963. {
  35964. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35965. }
  35966. void ToggleButton::colourChanged()
  35967. {
  35968. repaint();
  35969. }
  35970. END_JUCE_NAMESPACE
  35971. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35972. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35973. BEGIN_JUCE_NAMESPACE
  35974. ToolbarButton::ToolbarButton (const int itemId_,
  35975. const String& buttonText,
  35976. Drawable* const normalImage_,
  35977. Drawable* const toggledOnImage_)
  35978. : ToolbarItemComponent (itemId_, buttonText, true),
  35979. normalImage (normalImage_),
  35980. toggledOnImage (toggledOnImage_)
  35981. {
  35982. jassert (normalImage_ != 0);
  35983. }
  35984. ToolbarButton::~ToolbarButton()
  35985. {
  35986. }
  35987. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35988. bool /*isToolbarVertical*/,
  35989. int& preferredSize,
  35990. int& minSize, int& maxSize)
  35991. {
  35992. preferredSize = minSize = maxSize = toolbarDepth;
  35993. return true;
  35994. }
  35995. void ToolbarButton::paintButtonArea (Graphics& g,
  35996. int width, int height,
  35997. bool /*isMouseOver*/,
  35998. bool /*isMouseDown*/)
  35999. {
  36000. Drawable* d = normalImage;
  36001. if (getToggleState() && toggledOnImage != 0)
  36002. d = toggledOnImage;
  36003. const Rectangle<float> area (0.0f, 0.0f, (float) width, (float) height);
  36004. if (! isEnabled())
  36005. {
  36006. Image im (Image::ARGB, width, height, true);
  36007. {
  36008. Graphics g2 (im);
  36009. d->drawWithin (g2, area, RectanglePlacement::centred, 1.0f);
  36010. }
  36011. im.desaturate();
  36012. g.drawImageAt (im, 0, 0);
  36013. }
  36014. else
  36015. {
  36016. d->drawWithin (g, area, RectanglePlacement::centred, 1.0f);
  36017. }
  36018. }
  36019. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  36020. {
  36021. }
  36022. END_JUCE_NAMESPACE
  36023. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  36024. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  36025. BEGIN_JUCE_NAMESPACE
  36026. class CodeDocumentLine
  36027. {
  36028. public:
  36029. CodeDocumentLine (const juce_wchar* const line_,
  36030. const int lineLength_,
  36031. const int numNewLineChars,
  36032. const int lineStartInFile_)
  36033. : line (line_, lineLength_),
  36034. lineStartInFile (lineStartInFile_),
  36035. lineLength (lineLength_),
  36036. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  36037. {
  36038. }
  36039. ~CodeDocumentLine()
  36040. {
  36041. }
  36042. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  36043. {
  36044. const juce_wchar* const t = text;
  36045. int pos = 0;
  36046. while (t [pos] != 0)
  36047. {
  36048. const int startOfLine = pos;
  36049. int numNewLineChars = 0;
  36050. while (t[pos] != 0)
  36051. {
  36052. if (t[pos] == '\r')
  36053. {
  36054. ++numNewLineChars;
  36055. ++pos;
  36056. if (t[pos] == '\n')
  36057. {
  36058. ++numNewLineChars;
  36059. ++pos;
  36060. }
  36061. break;
  36062. }
  36063. if (t[pos] == '\n')
  36064. {
  36065. ++numNewLineChars;
  36066. ++pos;
  36067. break;
  36068. }
  36069. ++pos;
  36070. }
  36071. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36072. numNewLineChars, startOfLine));
  36073. }
  36074. jassert (pos == text.length());
  36075. }
  36076. bool endsWithLineBreak() const throw()
  36077. {
  36078. return lineLengthWithoutNewLines != lineLength;
  36079. }
  36080. void updateLength() throw()
  36081. {
  36082. lineLengthWithoutNewLines = lineLength = line.length();
  36083. while (lineLengthWithoutNewLines > 0
  36084. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36085. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36086. {
  36087. --lineLengthWithoutNewLines;
  36088. }
  36089. }
  36090. String line;
  36091. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36092. };
  36093. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36094. : document (document_),
  36095. currentLine (document_->lines[0]),
  36096. line (0),
  36097. position (0)
  36098. {
  36099. }
  36100. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36101. : document (other.document),
  36102. currentLine (other.currentLine),
  36103. line (other.line),
  36104. position (other.position)
  36105. {
  36106. }
  36107. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36108. {
  36109. document = other.document;
  36110. currentLine = other.currentLine;
  36111. line = other.line;
  36112. position = other.position;
  36113. return *this;
  36114. }
  36115. CodeDocument::Iterator::~Iterator() throw()
  36116. {
  36117. }
  36118. juce_wchar CodeDocument::Iterator::nextChar()
  36119. {
  36120. if (currentLine == 0)
  36121. return 0;
  36122. jassert (currentLine == document->lines.getUnchecked (line));
  36123. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36124. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36125. {
  36126. ++line;
  36127. currentLine = document->lines [line];
  36128. }
  36129. return result;
  36130. }
  36131. void CodeDocument::Iterator::skip()
  36132. {
  36133. if (currentLine != 0)
  36134. {
  36135. jassert (currentLine == document->lines.getUnchecked (line));
  36136. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36137. {
  36138. ++line;
  36139. currentLine = document->lines [line];
  36140. }
  36141. }
  36142. }
  36143. void CodeDocument::Iterator::skipToEndOfLine()
  36144. {
  36145. if (currentLine != 0)
  36146. {
  36147. jassert (currentLine == document->lines.getUnchecked (line));
  36148. ++line;
  36149. currentLine = document->lines [line];
  36150. if (currentLine != 0)
  36151. position = currentLine->lineStartInFile;
  36152. else
  36153. position = document->getNumCharacters();
  36154. }
  36155. }
  36156. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36157. {
  36158. if (currentLine == 0)
  36159. return 0;
  36160. jassert (currentLine == document->lines.getUnchecked (line));
  36161. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36162. }
  36163. void CodeDocument::Iterator::skipWhitespace()
  36164. {
  36165. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36166. skip();
  36167. }
  36168. bool CodeDocument::Iterator::isEOF() const throw()
  36169. {
  36170. return currentLine == 0;
  36171. }
  36172. CodeDocument::Position::Position() throw()
  36173. : owner (0), characterPos (0), line (0),
  36174. indexInLine (0), positionMaintained (false)
  36175. {
  36176. }
  36177. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36178. const int line_, const int indexInLine_) throw()
  36179. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36180. characterPos (0), line (line_),
  36181. indexInLine (indexInLine_), positionMaintained (false)
  36182. {
  36183. setLineAndIndex (line_, indexInLine_);
  36184. }
  36185. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36186. const int characterPos_) throw()
  36187. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36188. positionMaintained (false)
  36189. {
  36190. setPosition (characterPos_);
  36191. }
  36192. CodeDocument::Position::Position (const Position& other) throw()
  36193. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36194. indexInLine (other.indexInLine), positionMaintained (false)
  36195. {
  36196. jassert (*this == other);
  36197. }
  36198. CodeDocument::Position::~Position()
  36199. {
  36200. setPositionMaintained (false);
  36201. }
  36202. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36203. {
  36204. if (this != &other)
  36205. {
  36206. const bool wasPositionMaintained = positionMaintained;
  36207. if (owner != other.owner)
  36208. setPositionMaintained (false);
  36209. owner = other.owner;
  36210. line = other.line;
  36211. indexInLine = other.indexInLine;
  36212. characterPos = other.characterPos;
  36213. setPositionMaintained (wasPositionMaintained);
  36214. jassert (*this == other);
  36215. }
  36216. return *this;
  36217. }
  36218. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36219. {
  36220. jassert ((characterPos == other.characterPos)
  36221. == (line == other.line && indexInLine == other.indexInLine));
  36222. return characterPos == other.characterPos
  36223. && line == other.line
  36224. && indexInLine == other.indexInLine
  36225. && owner == other.owner;
  36226. }
  36227. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36228. {
  36229. return ! operator== (other);
  36230. }
  36231. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36232. {
  36233. jassert (owner != 0);
  36234. if (owner->lines.size() == 0)
  36235. {
  36236. line = 0;
  36237. indexInLine = 0;
  36238. characterPos = 0;
  36239. }
  36240. else
  36241. {
  36242. if (newLine >= owner->lines.size())
  36243. {
  36244. line = owner->lines.size() - 1;
  36245. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36246. jassert (l != 0);
  36247. indexInLine = l->lineLengthWithoutNewLines;
  36248. characterPos = l->lineStartInFile + indexInLine;
  36249. }
  36250. else
  36251. {
  36252. line = jmax (0, newLine);
  36253. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36254. jassert (l != 0);
  36255. if (l->lineLengthWithoutNewLines > 0)
  36256. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36257. else
  36258. indexInLine = 0;
  36259. characterPos = l->lineStartInFile + indexInLine;
  36260. }
  36261. }
  36262. }
  36263. void CodeDocument::Position::setPosition (const int newPosition)
  36264. {
  36265. jassert (owner != 0);
  36266. line = 0;
  36267. indexInLine = 0;
  36268. characterPos = 0;
  36269. if (newPosition > 0)
  36270. {
  36271. int lineStart = 0;
  36272. int lineEnd = owner->lines.size();
  36273. for (;;)
  36274. {
  36275. if (lineEnd - lineStart < 4)
  36276. {
  36277. for (int i = lineStart; i < lineEnd; ++i)
  36278. {
  36279. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36280. int index = newPosition - l->lineStartInFile;
  36281. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36282. {
  36283. line = i;
  36284. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36285. characterPos = l->lineStartInFile + indexInLine;
  36286. }
  36287. }
  36288. break;
  36289. }
  36290. else
  36291. {
  36292. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36293. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36294. if (newPosition >= mid->lineStartInFile)
  36295. lineStart = midIndex;
  36296. else
  36297. lineEnd = midIndex;
  36298. }
  36299. }
  36300. }
  36301. }
  36302. void CodeDocument::Position::moveBy (int characterDelta)
  36303. {
  36304. jassert (owner != 0);
  36305. if (characterDelta == 1)
  36306. {
  36307. setPosition (getPosition());
  36308. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36309. if (line < owner->lines.size())
  36310. {
  36311. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36312. if (indexInLine + characterDelta < l->lineLength
  36313. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36314. ++characterDelta;
  36315. }
  36316. }
  36317. setPosition (characterPos + characterDelta);
  36318. }
  36319. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36320. {
  36321. CodeDocument::Position p (*this);
  36322. p.moveBy (characterDelta);
  36323. return p;
  36324. }
  36325. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36326. {
  36327. CodeDocument::Position p (*this);
  36328. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36329. return p;
  36330. }
  36331. const juce_wchar CodeDocument::Position::getCharacter() const
  36332. {
  36333. const CodeDocumentLine* const l = owner->lines [line];
  36334. return l == 0 ? 0 : l->line [getIndexInLine()];
  36335. }
  36336. const String CodeDocument::Position::getLineText() const
  36337. {
  36338. const CodeDocumentLine* const l = owner->lines [line];
  36339. return l == 0 ? String::empty : l->line;
  36340. }
  36341. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36342. {
  36343. if (isMaintained != positionMaintained)
  36344. {
  36345. positionMaintained = isMaintained;
  36346. if (owner != 0)
  36347. {
  36348. if (isMaintained)
  36349. {
  36350. jassert (! owner->positionsToMaintain.contains (this));
  36351. owner->positionsToMaintain.add (this);
  36352. }
  36353. else
  36354. {
  36355. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36356. jassert (owner->positionsToMaintain.contains (this));
  36357. owner->positionsToMaintain.removeValue (this);
  36358. }
  36359. }
  36360. }
  36361. }
  36362. CodeDocument::CodeDocument()
  36363. : undoManager (std::numeric_limits<int>::max(), 10000),
  36364. currentActionIndex (0),
  36365. indexOfSavedState (-1),
  36366. maximumLineLength (-1),
  36367. newLineChars ("\r\n")
  36368. {
  36369. }
  36370. CodeDocument::~CodeDocument()
  36371. {
  36372. }
  36373. const String CodeDocument::getAllContent() const
  36374. {
  36375. return getTextBetween (Position (this, 0),
  36376. Position (this, lines.size(), 0));
  36377. }
  36378. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36379. {
  36380. if (end.getPosition() <= start.getPosition())
  36381. return String::empty;
  36382. const int startLine = start.getLineNumber();
  36383. const int endLine = end.getLineNumber();
  36384. if (startLine == endLine)
  36385. {
  36386. CodeDocumentLine* const line = lines [startLine];
  36387. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36388. }
  36389. String result;
  36390. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36391. String::Concatenator concatenator (result);
  36392. const int maxLine = jmin (lines.size() - 1, endLine);
  36393. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36394. {
  36395. const CodeDocumentLine* line = lines.getUnchecked(i);
  36396. int len = line->lineLength;
  36397. if (i == startLine)
  36398. {
  36399. const int index = start.getIndexInLine();
  36400. concatenator.append (line->line.substring (index, len));
  36401. }
  36402. else if (i == endLine)
  36403. {
  36404. len = end.getIndexInLine();
  36405. concatenator.append (line->line.substring (0, len));
  36406. }
  36407. else
  36408. {
  36409. concatenator.append (line->line);
  36410. }
  36411. }
  36412. return result;
  36413. }
  36414. int CodeDocument::getNumCharacters() const throw()
  36415. {
  36416. const CodeDocumentLine* const lastLine = lines.getLast();
  36417. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36418. }
  36419. const String CodeDocument::getLine (const int lineIndex) const throw()
  36420. {
  36421. const CodeDocumentLine* const line = lines [lineIndex];
  36422. return (line == 0) ? String::empty : line->line;
  36423. }
  36424. int CodeDocument::getMaximumLineLength() throw()
  36425. {
  36426. if (maximumLineLength < 0)
  36427. {
  36428. maximumLineLength = 0;
  36429. for (int i = lines.size(); --i >= 0;)
  36430. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36431. }
  36432. return maximumLineLength;
  36433. }
  36434. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36435. {
  36436. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36437. }
  36438. void CodeDocument::insertText (const Position& position, const String& text)
  36439. {
  36440. insert (text, position.getPosition(), true);
  36441. }
  36442. void CodeDocument::replaceAllContent (const String& newContent)
  36443. {
  36444. remove (0, getNumCharacters(), true);
  36445. insert (newContent, 0, true);
  36446. }
  36447. bool CodeDocument::loadFromStream (InputStream& stream)
  36448. {
  36449. replaceAllContent (stream.readEntireStreamAsString());
  36450. setSavePoint();
  36451. clearUndoHistory();
  36452. return true;
  36453. }
  36454. bool CodeDocument::writeToStream (OutputStream& stream)
  36455. {
  36456. for (int i = 0; i < lines.size(); ++i)
  36457. {
  36458. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36459. const char* utf8 = temp.toUTF8();
  36460. if (! stream.write (utf8, (int) strlen (utf8)))
  36461. return false;
  36462. }
  36463. return true;
  36464. }
  36465. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36466. {
  36467. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36468. newLineChars = newLine;
  36469. }
  36470. void CodeDocument::newTransaction()
  36471. {
  36472. undoManager.beginNewTransaction (String::empty);
  36473. }
  36474. void CodeDocument::undo()
  36475. {
  36476. newTransaction();
  36477. undoManager.undo();
  36478. }
  36479. void CodeDocument::redo()
  36480. {
  36481. undoManager.redo();
  36482. }
  36483. void CodeDocument::clearUndoHistory()
  36484. {
  36485. undoManager.clearUndoHistory();
  36486. }
  36487. void CodeDocument::setSavePoint() throw()
  36488. {
  36489. indexOfSavedState = currentActionIndex;
  36490. }
  36491. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36492. {
  36493. return currentActionIndex != indexOfSavedState;
  36494. }
  36495. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36496. {
  36497. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36498. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36499. }
  36500. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36501. {
  36502. Position p (position);
  36503. const int maxDistance = 256;
  36504. int i = 0;
  36505. while (i < maxDistance
  36506. && CharacterFunctions::isWhitespace (p.getCharacter())
  36507. && (i == 0 || (p.getCharacter() != '\n'
  36508. && p.getCharacter() != '\r')))
  36509. {
  36510. ++i;
  36511. p.moveBy (1);
  36512. }
  36513. if (i == 0)
  36514. {
  36515. const int type = getCodeCharacterCategory (p.getCharacter());
  36516. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36517. {
  36518. ++i;
  36519. p.moveBy (1);
  36520. }
  36521. while (i < maxDistance
  36522. && CharacterFunctions::isWhitespace (p.getCharacter())
  36523. && (i == 0 || (p.getCharacter() != '\n'
  36524. && p.getCharacter() != '\r')))
  36525. {
  36526. ++i;
  36527. p.moveBy (1);
  36528. }
  36529. }
  36530. return p;
  36531. }
  36532. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36533. {
  36534. Position p (position);
  36535. const int maxDistance = 256;
  36536. int i = 0;
  36537. bool stoppedAtLineStart = false;
  36538. while (i < maxDistance)
  36539. {
  36540. const juce_wchar c = p.movedBy (-1).getCharacter();
  36541. if (c == '\r' || c == '\n')
  36542. {
  36543. stoppedAtLineStart = true;
  36544. if (i > 0)
  36545. break;
  36546. }
  36547. if (! CharacterFunctions::isWhitespace (c))
  36548. break;
  36549. p.moveBy (-1);
  36550. ++i;
  36551. }
  36552. if (i < maxDistance && ! stoppedAtLineStart)
  36553. {
  36554. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36555. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36556. {
  36557. p.moveBy (-1);
  36558. ++i;
  36559. }
  36560. }
  36561. return p;
  36562. }
  36563. void CodeDocument::checkLastLineStatus()
  36564. {
  36565. while (lines.size() > 0
  36566. && lines.getLast()->lineLength == 0
  36567. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36568. {
  36569. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36570. lines.removeLast();
  36571. }
  36572. const CodeDocumentLine* const lastLine = lines.getLast();
  36573. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36574. {
  36575. // check that there's an empty line at the end if the preceding one ends in a newline..
  36576. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36577. }
  36578. }
  36579. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36580. {
  36581. listeners.add (listener);
  36582. }
  36583. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36584. {
  36585. listeners.remove (listener);
  36586. }
  36587. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36588. {
  36589. Position startPos (this, startLine, 0);
  36590. Position endPos (this, endLine, 0);
  36591. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36592. }
  36593. class CodeDocumentInsertAction : public UndoableAction
  36594. {
  36595. CodeDocument& owner;
  36596. const String text;
  36597. int insertPos;
  36598. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36599. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36600. public:
  36601. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36602. : owner (owner_),
  36603. text (text_),
  36604. insertPos (insertPos_)
  36605. {
  36606. }
  36607. ~CodeDocumentInsertAction() {}
  36608. bool perform()
  36609. {
  36610. owner.currentActionIndex++;
  36611. owner.insert (text, insertPos, false);
  36612. return true;
  36613. }
  36614. bool undo()
  36615. {
  36616. owner.currentActionIndex--;
  36617. owner.remove (insertPos, insertPos + text.length(), false);
  36618. return true;
  36619. }
  36620. int getSizeInUnits() { return text.length() + 32; }
  36621. };
  36622. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36623. {
  36624. if (text.isEmpty())
  36625. return;
  36626. if (undoable)
  36627. {
  36628. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36629. }
  36630. else
  36631. {
  36632. Position pos (this, insertPos);
  36633. const int firstAffectedLine = pos.getLineNumber();
  36634. int lastAffectedLine = firstAffectedLine + 1;
  36635. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36636. String textInsideOriginalLine (text);
  36637. if (firstLine != 0)
  36638. {
  36639. const int index = pos.getIndexInLine();
  36640. textInsideOriginalLine = firstLine->line.substring (0, index)
  36641. + textInsideOriginalLine
  36642. + firstLine->line.substring (index);
  36643. }
  36644. maximumLineLength = -1;
  36645. Array <CodeDocumentLine*> newLines;
  36646. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36647. jassert (newLines.size() > 0);
  36648. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36649. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36650. lines.set (firstAffectedLine, newFirstLine);
  36651. if (newLines.size() > 1)
  36652. {
  36653. for (int i = 1; i < newLines.size(); ++i)
  36654. {
  36655. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36656. lines.insert (firstAffectedLine + i, l);
  36657. }
  36658. lastAffectedLine = lines.size();
  36659. }
  36660. int i, lineStart = newFirstLine->lineStartInFile;
  36661. for (i = firstAffectedLine; i < lines.size(); ++i)
  36662. {
  36663. CodeDocumentLine* const l = lines.getUnchecked (i);
  36664. l->lineStartInFile = lineStart;
  36665. lineStart += l->lineLength;
  36666. }
  36667. checkLastLineStatus();
  36668. const int newTextLength = text.length();
  36669. for (i = 0; i < positionsToMaintain.size(); ++i)
  36670. {
  36671. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36672. if (p->getPosition() >= insertPos)
  36673. p->setPosition (p->getPosition() + newTextLength);
  36674. }
  36675. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36676. }
  36677. }
  36678. class CodeDocumentDeleteAction : public UndoableAction
  36679. {
  36680. CodeDocument& owner;
  36681. int startPos, endPos;
  36682. String removedText;
  36683. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36684. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36685. public:
  36686. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36687. : owner (owner_),
  36688. startPos (startPos_),
  36689. endPos (endPos_)
  36690. {
  36691. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36692. CodeDocument::Position (&owner, endPos));
  36693. }
  36694. ~CodeDocumentDeleteAction() {}
  36695. bool perform()
  36696. {
  36697. owner.currentActionIndex++;
  36698. owner.remove (startPos, endPos, false);
  36699. return true;
  36700. }
  36701. bool undo()
  36702. {
  36703. owner.currentActionIndex--;
  36704. owner.insert (removedText, startPos, false);
  36705. return true;
  36706. }
  36707. int getSizeInUnits() { return removedText.length() + 32; }
  36708. };
  36709. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36710. {
  36711. if (endPos <= startPos)
  36712. return;
  36713. if (undoable)
  36714. {
  36715. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36716. }
  36717. else
  36718. {
  36719. Position startPosition (this, startPos);
  36720. Position endPosition (this, endPos);
  36721. maximumLineLength = -1;
  36722. const int firstAffectedLine = startPosition.getLineNumber();
  36723. const int endLine = endPosition.getLineNumber();
  36724. int lastAffectedLine = firstAffectedLine + 1;
  36725. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36726. if (firstAffectedLine == endLine)
  36727. {
  36728. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36729. + firstLine->line.substring (endPosition.getIndexInLine());
  36730. firstLine->updateLength();
  36731. }
  36732. else
  36733. {
  36734. lastAffectedLine = lines.size();
  36735. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36736. jassert (lastLine != 0);
  36737. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36738. + lastLine->line.substring (endPosition.getIndexInLine());
  36739. firstLine->updateLength();
  36740. int numLinesToRemove = endLine - firstAffectedLine;
  36741. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36742. }
  36743. int i;
  36744. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36745. {
  36746. CodeDocumentLine* const l = lines.getUnchecked (i);
  36747. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36748. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36749. }
  36750. checkLastLineStatus();
  36751. const int totalChars = getNumCharacters();
  36752. for (i = 0; i < positionsToMaintain.size(); ++i)
  36753. {
  36754. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36755. if (p->getPosition() > startPosition.getPosition())
  36756. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36757. if (p->getPosition() > totalChars)
  36758. p->setPosition (totalChars);
  36759. }
  36760. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36761. }
  36762. }
  36763. END_JUCE_NAMESPACE
  36764. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36765. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36766. BEGIN_JUCE_NAMESPACE
  36767. class CodeEditorComponent::CaretComponent : public Component,
  36768. public Timer
  36769. {
  36770. public:
  36771. CaretComponent (CodeEditorComponent& owner_)
  36772. : owner (owner_)
  36773. {
  36774. setAlwaysOnTop (true);
  36775. setInterceptsMouseClicks (false, false);
  36776. }
  36777. ~CaretComponent()
  36778. {
  36779. }
  36780. void paint (Graphics& g)
  36781. {
  36782. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36783. }
  36784. void timerCallback()
  36785. {
  36786. setVisible (shouldBeShown() && ! isVisible());
  36787. }
  36788. void updatePosition()
  36789. {
  36790. startTimer (400);
  36791. setVisible (shouldBeShown());
  36792. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36793. }
  36794. private:
  36795. CodeEditorComponent& owner;
  36796. CaretComponent (const CaretComponent&);
  36797. CaretComponent& operator= (const CaretComponent&);
  36798. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36799. };
  36800. class CodeEditorComponent::CodeEditorLine
  36801. {
  36802. public:
  36803. CodeEditorLine() throw()
  36804. : highlightColumnStart (0), highlightColumnEnd (0)
  36805. {
  36806. }
  36807. ~CodeEditorLine() throw()
  36808. {
  36809. }
  36810. bool update (CodeDocument& document, int lineNum,
  36811. CodeDocument::Iterator& source,
  36812. CodeTokeniser* analyser, const int spacesPerTab,
  36813. const CodeDocument::Position& selectionStart,
  36814. const CodeDocument::Position& selectionEnd)
  36815. {
  36816. Array <SyntaxToken> newTokens;
  36817. newTokens.ensureStorageAllocated (8);
  36818. if (analyser == 0)
  36819. {
  36820. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36821. }
  36822. else if (lineNum < document.getNumLines())
  36823. {
  36824. const CodeDocument::Position pos (&document, lineNum, 0);
  36825. createTokens (pos.getPosition(), pos.getLineText(),
  36826. source, analyser, newTokens);
  36827. }
  36828. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36829. int newHighlightStart = 0;
  36830. int newHighlightEnd = 0;
  36831. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36832. {
  36833. const String line (document.getLine (lineNum));
  36834. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36835. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36836. line, spacesPerTab);
  36837. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36838. line, spacesPerTab);
  36839. }
  36840. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36841. {
  36842. highlightColumnStart = newHighlightStart;
  36843. highlightColumnEnd = newHighlightEnd;
  36844. }
  36845. else
  36846. {
  36847. if (tokens.size() == newTokens.size())
  36848. {
  36849. bool allTheSame = true;
  36850. for (int i = newTokens.size(); --i >= 0;)
  36851. {
  36852. if (tokens.getReference(i) != newTokens.getReference(i))
  36853. {
  36854. allTheSame = false;
  36855. break;
  36856. }
  36857. }
  36858. if (allTheSame)
  36859. return false;
  36860. }
  36861. }
  36862. tokens.swapWithArray (newTokens);
  36863. return true;
  36864. }
  36865. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36866. float x, const int y, const int baselineOffset, const int lineHeight,
  36867. const Colour& highlightColour) const
  36868. {
  36869. if (highlightColumnStart < highlightColumnEnd)
  36870. {
  36871. g.setColour (highlightColour);
  36872. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36873. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36874. }
  36875. int lastType = std::numeric_limits<int>::min();
  36876. for (int i = 0; i < tokens.size(); ++i)
  36877. {
  36878. SyntaxToken& token = tokens.getReference(i);
  36879. if (lastType != token.tokenType)
  36880. {
  36881. lastType = token.tokenType;
  36882. g.setColour (owner.getColourForTokenType (lastType));
  36883. }
  36884. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36885. if (i < tokens.size() - 1)
  36886. {
  36887. if (token.width < 0)
  36888. token.width = font.getStringWidthFloat (token.text);
  36889. x += token.width;
  36890. }
  36891. }
  36892. }
  36893. private:
  36894. struct SyntaxToken
  36895. {
  36896. String text;
  36897. int tokenType;
  36898. float width;
  36899. SyntaxToken (const String& text_, const int type) throw()
  36900. : text (text_), tokenType (type), width (-1.0f)
  36901. {
  36902. }
  36903. bool operator!= (const SyntaxToken& other) const throw()
  36904. {
  36905. return text != other.text || tokenType != other.tokenType;
  36906. }
  36907. };
  36908. Array <SyntaxToken> tokens;
  36909. int highlightColumnStart, highlightColumnEnd;
  36910. static void createTokens (int startPosition, const String& lineText,
  36911. CodeDocument::Iterator& source,
  36912. CodeTokeniser* analyser,
  36913. Array <SyntaxToken>& newTokens)
  36914. {
  36915. CodeDocument::Iterator lastIterator (source);
  36916. const int lineLength = lineText.length();
  36917. for (;;)
  36918. {
  36919. int tokenType = analyser->readNextToken (source);
  36920. int tokenStart = lastIterator.getPosition();
  36921. int tokenEnd = source.getPosition();
  36922. if (tokenEnd <= tokenStart)
  36923. break;
  36924. tokenEnd -= startPosition;
  36925. if (tokenEnd > 0)
  36926. {
  36927. tokenStart -= startPosition;
  36928. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36929. tokenType));
  36930. if (tokenEnd >= lineLength)
  36931. break;
  36932. }
  36933. lastIterator = source;
  36934. }
  36935. source = lastIterator;
  36936. }
  36937. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36938. {
  36939. int x = 0;
  36940. for (int i = 0; i < tokens.size(); ++i)
  36941. {
  36942. SyntaxToken& t = tokens.getReference(i);
  36943. for (;;)
  36944. {
  36945. int tabPos = t.text.indexOfChar ('\t');
  36946. if (tabPos < 0)
  36947. break;
  36948. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36949. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36950. }
  36951. x += t.text.length();
  36952. }
  36953. }
  36954. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36955. {
  36956. jassert (index <= line.length());
  36957. int col = 0;
  36958. for (int i = 0; i < index; ++i)
  36959. {
  36960. if (line[i] != '\t')
  36961. ++col;
  36962. else
  36963. col += spacesPerTab - (col % spacesPerTab);
  36964. }
  36965. return col;
  36966. }
  36967. };
  36968. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36969. CodeTokeniser* const codeTokeniser_)
  36970. : document (document_),
  36971. firstLineOnScreen (0),
  36972. gutter (5),
  36973. spacesPerTab (4),
  36974. lineHeight (0),
  36975. linesOnScreen (0),
  36976. columnsOnScreen (0),
  36977. scrollbarThickness (16),
  36978. columnToTryToMaintain (-1),
  36979. useSpacesForTabs (false),
  36980. xOffset (0),
  36981. codeTokeniser (codeTokeniser_)
  36982. {
  36983. caretPos = CodeDocument::Position (&document_, 0, 0);
  36984. caretPos.setPositionMaintained (true);
  36985. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36986. selectionStart.setPositionMaintained (true);
  36987. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36988. selectionEnd.setPositionMaintained (true);
  36989. setOpaque (true);
  36990. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36991. setWantsKeyboardFocus (true);
  36992. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36993. verticalScrollBar->setSingleStepSize (1.0);
  36994. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36995. horizontalScrollBar->setSingleStepSize (1.0);
  36996. addAndMakeVisible (caret = new CaretComponent (*this));
  36997. Font f (12.0f);
  36998. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36999. setFont (f);
  37000. resetToDefaultColours();
  37001. verticalScrollBar->addListener (this);
  37002. horizontalScrollBar->addListener (this);
  37003. document.addListener (this);
  37004. }
  37005. CodeEditorComponent::~CodeEditorComponent()
  37006. {
  37007. document.removeListener (this);
  37008. deleteAllChildren();
  37009. }
  37010. void CodeEditorComponent::loadContent (const String& newContent)
  37011. {
  37012. clearCachedIterators (0);
  37013. document.replaceAllContent (newContent);
  37014. document.clearUndoHistory();
  37015. document.setSavePoint();
  37016. caretPos.setPosition (0);
  37017. selectionStart.setPosition (0);
  37018. selectionEnd.setPosition (0);
  37019. scrollToLine (0);
  37020. }
  37021. bool CodeEditorComponent::isTextInputActive() const
  37022. {
  37023. return true;
  37024. }
  37025. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  37026. const CodeDocument::Position& affectedTextEnd)
  37027. {
  37028. clearCachedIterators (affectedTextStart.getLineNumber());
  37029. triggerAsyncUpdate();
  37030. caret->updatePosition();
  37031. columnToTryToMaintain = -1;
  37032. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  37033. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  37034. deselectAll();
  37035. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  37036. || caretPos.getPosition() < affectedTextStart.getPosition())
  37037. moveCaretTo (affectedTextStart, false);
  37038. updateScrollBars();
  37039. }
  37040. void CodeEditorComponent::resized()
  37041. {
  37042. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  37043. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  37044. lines.clear();
  37045. rebuildLineTokens();
  37046. caret->updatePosition();
  37047. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37048. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37049. updateScrollBars();
  37050. }
  37051. void CodeEditorComponent::paint (Graphics& g)
  37052. {
  37053. handleUpdateNowIfNeeded();
  37054. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37055. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  37056. g.setFont (font);
  37057. const int baselineOffset = (int) font.getAscent();
  37058. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37059. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37060. const Rectangle<int> clip (g.getClipBounds());
  37061. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37062. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37063. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37064. {
  37065. lines.getUnchecked(j)->draw (*this, g, font,
  37066. (float) (gutter - xOffset * charWidth),
  37067. lineHeight * j, baselineOffset, lineHeight,
  37068. highlightColour);
  37069. }
  37070. }
  37071. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37072. {
  37073. if (scrollbarThickness != thickness)
  37074. {
  37075. scrollbarThickness = thickness;
  37076. resized();
  37077. }
  37078. }
  37079. void CodeEditorComponent::handleAsyncUpdate()
  37080. {
  37081. rebuildLineTokens();
  37082. }
  37083. void CodeEditorComponent::rebuildLineTokens()
  37084. {
  37085. cancelPendingUpdate();
  37086. const int numNeeded = linesOnScreen + 1;
  37087. int minLineToRepaint = numNeeded;
  37088. int maxLineToRepaint = 0;
  37089. if (numNeeded != lines.size())
  37090. {
  37091. lines.clear();
  37092. for (int i = numNeeded; --i >= 0;)
  37093. lines.add (new CodeEditorLine());
  37094. minLineToRepaint = 0;
  37095. maxLineToRepaint = numNeeded;
  37096. }
  37097. jassert (numNeeded == lines.size());
  37098. CodeDocument::Iterator source (&document);
  37099. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37100. for (int i = 0; i < numNeeded; ++i)
  37101. {
  37102. CodeEditorLine* const line = lines.getUnchecked(i);
  37103. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37104. selectionStart, selectionEnd))
  37105. {
  37106. minLineToRepaint = jmin (minLineToRepaint, i);
  37107. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37108. }
  37109. }
  37110. if (minLineToRepaint <= maxLineToRepaint)
  37111. {
  37112. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37113. verticalScrollBar->getX() - gutter,
  37114. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37115. }
  37116. }
  37117. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37118. {
  37119. caretPos = newPos;
  37120. columnToTryToMaintain = -1;
  37121. if (highlighting)
  37122. {
  37123. if (dragType == notDragging)
  37124. {
  37125. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37126. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37127. dragType = draggingSelectionStart;
  37128. else
  37129. dragType = draggingSelectionEnd;
  37130. }
  37131. if (dragType == draggingSelectionStart)
  37132. {
  37133. selectionStart = caretPos;
  37134. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37135. {
  37136. const CodeDocument::Position temp (selectionStart);
  37137. selectionStart = selectionEnd;
  37138. selectionEnd = temp;
  37139. dragType = draggingSelectionEnd;
  37140. }
  37141. }
  37142. else
  37143. {
  37144. selectionEnd = caretPos;
  37145. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37146. {
  37147. const CodeDocument::Position temp (selectionStart);
  37148. selectionStart = selectionEnd;
  37149. selectionEnd = temp;
  37150. dragType = draggingSelectionStart;
  37151. }
  37152. }
  37153. triggerAsyncUpdate();
  37154. }
  37155. else
  37156. {
  37157. deselectAll();
  37158. }
  37159. caret->updatePosition();
  37160. scrollToKeepCaretOnScreen();
  37161. updateScrollBars();
  37162. }
  37163. void CodeEditorComponent::deselectAll()
  37164. {
  37165. if (selectionStart != selectionEnd)
  37166. triggerAsyncUpdate();
  37167. selectionStart = caretPos;
  37168. selectionEnd = caretPos;
  37169. }
  37170. void CodeEditorComponent::updateScrollBars()
  37171. {
  37172. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37173. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37174. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37175. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37176. }
  37177. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37178. {
  37179. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37180. newFirstLineOnScreen);
  37181. if (newFirstLineOnScreen != firstLineOnScreen)
  37182. {
  37183. firstLineOnScreen = newFirstLineOnScreen;
  37184. caret->updatePosition();
  37185. updateCachedIterators (firstLineOnScreen);
  37186. triggerAsyncUpdate();
  37187. }
  37188. }
  37189. void CodeEditorComponent::scrollToColumnInternal (double column)
  37190. {
  37191. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37192. if (xOffset != newOffset)
  37193. {
  37194. xOffset = newOffset;
  37195. caret->updatePosition();
  37196. repaint();
  37197. }
  37198. }
  37199. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37200. {
  37201. scrollToLineInternal (newFirstLineOnScreen);
  37202. updateScrollBars();
  37203. }
  37204. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37205. {
  37206. scrollToColumnInternal (newFirstColumnOnScreen);
  37207. updateScrollBars();
  37208. }
  37209. void CodeEditorComponent::scrollBy (int deltaLines)
  37210. {
  37211. scrollToLine (firstLineOnScreen + deltaLines);
  37212. }
  37213. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37214. {
  37215. if (caretPos.getLineNumber() < firstLineOnScreen)
  37216. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37217. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37218. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37219. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37220. if (column >= xOffset + columnsOnScreen - 1)
  37221. scrollToColumn (column + 1 - columnsOnScreen);
  37222. else if (column < xOffset)
  37223. scrollToColumn (column);
  37224. }
  37225. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37226. {
  37227. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37228. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37229. roundToInt (charWidth),
  37230. lineHeight);
  37231. }
  37232. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37233. {
  37234. const int line = y / lineHeight + firstLineOnScreen;
  37235. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37236. const int index = columnToIndex (line, column);
  37237. return CodeDocument::Position (&document, line, index);
  37238. }
  37239. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37240. {
  37241. document.deleteSection (selectionStart, selectionEnd);
  37242. if (newText.isNotEmpty())
  37243. document.insertText (caretPos, newText);
  37244. scrollToKeepCaretOnScreen();
  37245. }
  37246. void CodeEditorComponent::insertTabAtCaret()
  37247. {
  37248. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37249. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37250. {
  37251. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37252. }
  37253. if (useSpacesForTabs)
  37254. {
  37255. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37256. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37257. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37258. }
  37259. else
  37260. {
  37261. insertTextAtCaret ("\t");
  37262. }
  37263. }
  37264. void CodeEditorComponent::cut()
  37265. {
  37266. insertTextAtCaret (String::empty);
  37267. }
  37268. void CodeEditorComponent::copy()
  37269. {
  37270. newTransaction();
  37271. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37272. if (selection.isNotEmpty())
  37273. SystemClipboard::copyTextToClipboard (selection);
  37274. }
  37275. void CodeEditorComponent::copyThenCut()
  37276. {
  37277. copy();
  37278. cut();
  37279. newTransaction();
  37280. }
  37281. void CodeEditorComponent::paste()
  37282. {
  37283. newTransaction();
  37284. const String clip (SystemClipboard::getTextFromClipboard());
  37285. if (clip.isNotEmpty())
  37286. insertTextAtCaret (clip);
  37287. newTransaction();
  37288. }
  37289. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37290. {
  37291. newTransaction();
  37292. if (moveInWholeWordSteps)
  37293. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37294. else
  37295. moveCaretTo (caretPos.movedBy (-1), selecting);
  37296. }
  37297. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37298. {
  37299. newTransaction();
  37300. if (moveInWholeWordSteps)
  37301. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37302. else
  37303. moveCaretTo (caretPos.movedBy (1), selecting);
  37304. }
  37305. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37306. {
  37307. CodeDocument::Position pos (caretPos);
  37308. const int newLineNum = pos.getLineNumber() + delta;
  37309. if (columnToTryToMaintain < 0)
  37310. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37311. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37312. const int colToMaintain = columnToTryToMaintain;
  37313. moveCaretTo (pos, selecting);
  37314. columnToTryToMaintain = colToMaintain;
  37315. }
  37316. void CodeEditorComponent::cursorDown (const bool selecting)
  37317. {
  37318. newTransaction();
  37319. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37320. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37321. else
  37322. moveLineDelta (1, selecting);
  37323. }
  37324. void CodeEditorComponent::cursorUp (const bool selecting)
  37325. {
  37326. newTransaction();
  37327. if (caretPos.getLineNumber() == 0)
  37328. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37329. else
  37330. moveLineDelta (-1, selecting);
  37331. }
  37332. void CodeEditorComponent::pageDown (const bool selecting)
  37333. {
  37334. newTransaction();
  37335. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37336. moveLineDelta (linesOnScreen, selecting);
  37337. }
  37338. void CodeEditorComponent::pageUp (const bool selecting)
  37339. {
  37340. newTransaction();
  37341. scrollBy (-linesOnScreen);
  37342. moveLineDelta (-linesOnScreen, selecting);
  37343. }
  37344. void CodeEditorComponent::scrollUp()
  37345. {
  37346. newTransaction();
  37347. scrollBy (1);
  37348. if (caretPos.getLineNumber() < firstLineOnScreen)
  37349. moveLineDelta (1, false);
  37350. }
  37351. void CodeEditorComponent::scrollDown()
  37352. {
  37353. newTransaction();
  37354. scrollBy (-1);
  37355. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37356. moveLineDelta (-1, false);
  37357. }
  37358. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37359. {
  37360. newTransaction();
  37361. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37362. }
  37363. static int findFirstNonWhitespaceChar (const String& line) throw()
  37364. {
  37365. const int len = line.length();
  37366. for (int i = 0; i < len; ++i)
  37367. if (! CharacterFunctions::isWhitespace (line [i]))
  37368. return i;
  37369. return 0;
  37370. }
  37371. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37372. {
  37373. newTransaction();
  37374. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37375. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37376. index = 0;
  37377. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37378. }
  37379. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37380. {
  37381. newTransaction();
  37382. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37383. }
  37384. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37385. {
  37386. newTransaction();
  37387. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37388. }
  37389. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37390. {
  37391. if (moveInWholeWordSteps)
  37392. {
  37393. cut(); // in case something is already highlighted
  37394. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37395. }
  37396. else
  37397. {
  37398. if (selectionStart == selectionEnd)
  37399. selectionStart.moveBy (-1);
  37400. }
  37401. cut();
  37402. }
  37403. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37404. {
  37405. if (moveInWholeWordSteps)
  37406. {
  37407. cut(); // in case something is already highlighted
  37408. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37409. }
  37410. else
  37411. {
  37412. if (selectionStart == selectionEnd)
  37413. selectionEnd.moveBy (1);
  37414. else
  37415. newTransaction();
  37416. }
  37417. cut();
  37418. }
  37419. void CodeEditorComponent::selectAll()
  37420. {
  37421. newTransaction();
  37422. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37423. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37424. }
  37425. void CodeEditorComponent::undo()
  37426. {
  37427. document.undo();
  37428. scrollToKeepCaretOnScreen();
  37429. }
  37430. void CodeEditorComponent::redo()
  37431. {
  37432. document.redo();
  37433. scrollToKeepCaretOnScreen();
  37434. }
  37435. void CodeEditorComponent::newTransaction()
  37436. {
  37437. document.newTransaction();
  37438. startTimer (600);
  37439. }
  37440. void CodeEditorComponent::timerCallback()
  37441. {
  37442. newTransaction();
  37443. }
  37444. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37445. {
  37446. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37447. }
  37448. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37449. {
  37450. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37451. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37452. }
  37453. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37454. {
  37455. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37456. CodeDocument::Position (&document, range.getEnd()));
  37457. }
  37458. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37459. {
  37460. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37461. const bool shiftDown = key.getModifiers().isShiftDown();
  37462. if (key.isKeyCode (KeyPress::leftKey))
  37463. {
  37464. cursorLeft (moveInWholeWordSteps, shiftDown);
  37465. }
  37466. else if (key.isKeyCode (KeyPress::rightKey))
  37467. {
  37468. cursorRight (moveInWholeWordSteps, shiftDown);
  37469. }
  37470. else if (key.isKeyCode (KeyPress::upKey))
  37471. {
  37472. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37473. scrollDown();
  37474. #if JUCE_MAC
  37475. else if (key.getModifiers().isCommandDown())
  37476. goToStartOfDocument (shiftDown);
  37477. #endif
  37478. else
  37479. cursorUp (shiftDown);
  37480. }
  37481. else if (key.isKeyCode (KeyPress::downKey))
  37482. {
  37483. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37484. scrollUp();
  37485. #if JUCE_MAC
  37486. else if (key.getModifiers().isCommandDown())
  37487. goToEndOfDocument (shiftDown);
  37488. #endif
  37489. else
  37490. cursorDown (shiftDown);
  37491. }
  37492. else if (key.isKeyCode (KeyPress::pageDownKey))
  37493. {
  37494. pageDown (shiftDown);
  37495. }
  37496. else if (key.isKeyCode (KeyPress::pageUpKey))
  37497. {
  37498. pageUp (shiftDown);
  37499. }
  37500. else if (key.isKeyCode (KeyPress::homeKey))
  37501. {
  37502. if (moveInWholeWordSteps)
  37503. goToStartOfDocument (shiftDown);
  37504. else
  37505. goToStartOfLine (shiftDown);
  37506. }
  37507. else if (key.isKeyCode (KeyPress::endKey))
  37508. {
  37509. if (moveInWholeWordSteps)
  37510. goToEndOfDocument (shiftDown);
  37511. else
  37512. goToEndOfLine (shiftDown);
  37513. }
  37514. else if (key.isKeyCode (KeyPress::backspaceKey))
  37515. {
  37516. backspace (moveInWholeWordSteps);
  37517. }
  37518. else if (key.isKeyCode (KeyPress::deleteKey))
  37519. {
  37520. deleteForward (moveInWholeWordSteps);
  37521. }
  37522. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37523. {
  37524. copy();
  37525. }
  37526. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37527. {
  37528. copyThenCut();
  37529. }
  37530. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37531. {
  37532. paste();
  37533. }
  37534. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37535. {
  37536. undo();
  37537. }
  37538. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37539. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37540. {
  37541. redo();
  37542. }
  37543. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37544. {
  37545. selectAll();
  37546. }
  37547. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37548. {
  37549. insertTabAtCaret();
  37550. }
  37551. else if (key == KeyPress::returnKey)
  37552. {
  37553. newTransaction();
  37554. insertTextAtCaret (document.getNewLineCharacters());
  37555. }
  37556. else if (key.isKeyCode (KeyPress::escapeKey))
  37557. {
  37558. newTransaction();
  37559. }
  37560. else if (key.getTextCharacter() >= ' ')
  37561. {
  37562. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37563. }
  37564. else
  37565. {
  37566. return false;
  37567. }
  37568. return true;
  37569. }
  37570. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37571. {
  37572. newTransaction();
  37573. dragType = notDragging;
  37574. if (! e.mods.isPopupMenu())
  37575. {
  37576. beginDragAutoRepeat (100);
  37577. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37578. }
  37579. else
  37580. {
  37581. /*PopupMenu m;
  37582. addPopupMenuItems (m, &e);
  37583. const int result = m.show();
  37584. if (result != 0)
  37585. performPopupMenuAction (result);
  37586. */
  37587. }
  37588. }
  37589. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37590. {
  37591. if (! e.mods.isPopupMenu())
  37592. moveCaretTo (getPositionAt (e.x, e.y), true);
  37593. }
  37594. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37595. {
  37596. newTransaction();
  37597. beginDragAutoRepeat (0);
  37598. dragType = notDragging;
  37599. }
  37600. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37601. {
  37602. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37603. CodeDocument::Position tokenEnd (tokenStart);
  37604. if (e.getNumberOfClicks() > 2)
  37605. {
  37606. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37607. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37608. }
  37609. else
  37610. {
  37611. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37612. tokenEnd.moveBy (1);
  37613. tokenStart = tokenEnd;
  37614. while (tokenStart.getIndexInLine() > 0
  37615. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37616. tokenStart.moveBy (-1);
  37617. }
  37618. moveCaretTo (tokenEnd, false);
  37619. moveCaretTo (tokenStart, true);
  37620. }
  37621. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37622. {
  37623. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37624. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37625. {
  37626. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37627. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37628. }
  37629. else
  37630. {
  37631. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37632. }
  37633. }
  37634. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37635. {
  37636. if (scrollBarThatHasMoved == verticalScrollBar)
  37637. scrollToLineInternal ((int) newRangeStart);
  37638. else
  37639. scrollToColumnInternal (newRangeStart);
  37640. }
  37641. void CodeEditorComponent::focusGained (FocusChangeType)
  37642. {
  37643. caret->updatePosition();
  37644. }
  37645. void CodeEditorComponent::focusLost (FocusChangeType)
  37646. {
  37647. caret->updatePosition();
  37648. }
  37649. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37650. {
  37651. useSpacesForTabs = insertSpaces;
  37652. if (spacesPerTab != numSpaces)
  37653. {
  37654. spacesPerTab = numSpaces;
  37655. triggerAsyncUpdate();
  37656. }
  37657. }
  37658. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37659. {
  37660. const String line (document.getLine (lineNum));
  37661. jassert (index <= line.length());
  37662. int col = 0;
  37663. for (int i = 0; i < index; ++i)
  37664. {
  37665. if (line[i] != '\t')
  37666. ++col;
  37667. else
  37668. col += getTabSize() - (col % getTabSize());
  37669. }
  37670. return col;
  37671. }
  37672. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37673. {
  37674. const String line (document.getLine (lineNum));
  37675. const int lineLength = line.length();
  37676. int i, col = 0;
  37677. for (i = 0; i < lineLength; ++i)
  37678. {
  37679. if (line[i] != '\t')
  37680. ++col;
  37681. else
  37682. col += getTabSize() - (col % getTabSize());
  37683. if (col > column)
  37684. break;
  37685. }
  37686. return i;
  37687. }
  37688. void CodeEditorComponent::setFont (const Font& newFont)
  37689. {
  37690. font = newFont;
  37691. charWidth = font.getStringWidthFloat ("0");
  37692. lineHeight = roundToInt (font.getHeight());
  37693. resized();
  37694. }
  37695. void CodeEditorComponent::resetToDefaultColours()
  37696. {
  37697. coloursForTokenCategories.clear();
  37698. if (codeTokeniser != 0)
  37699. {
  37700. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37701. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37702. }
  37703. }
  37704. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37705. {
  37706. jassert (tokenType < 256);
  37707. while (coloursForTokenCategories.size() < tokenType)
  37708. coloursForTokenCategories.add (Colours::black);
  37709. coloursForTokenCategories.set (tokenType, colour);
  37710. repaint();
  37711. }
  37712. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37713. {
  37714. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37715. return findColour (CodeEditorComponent::defaultTextColourId);
  37716. return coloursForTokenCategories.getReference (tokenType);
  37717. }
  37718. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37719. {
  37720. int i;
  37721. for (i = cachedIterators.size(); --i >= 0;)
  37722. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37723. break;
  37724. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37725. }
  37726. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37727. {
  37728. const int maxNumCachedPositions = 5000;
  37729. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37730. if (cachedIterators.size() == 0)
  37731. cachedIterators.add (new CodeDocument::Iterator (&document));
  37732. if (codeTokeniser == 0)
  37733. return;
  37734. for (;;)
  37735. {
  37736. CodeDocument::Iterator* last = cachedIterators.getLast();
  37737. if (last->getLine() >= maxLineNum)
  37738. break;
  37739. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37740. cachedIterators.add (t);
  37741. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37742. for (;;)
  37743. {
  37744. codeTokeniser->readNextToken (*t);
  37745. if (t->getLine() >= targetLine)
  37746. break;
  37747. if (t->isEOF())
  37748. return;
  37749. }
  37750. }
  37751. }
  37752. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37753. {
  37754. if (codeTokeniser == 0)
  37755. return;
  37756. for (int i = cachedIterators.size(); --i >= 0;)
  37757. {
  37758. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37759. if (t->getPosition() <= position)
  37760. {
  37761. source = *t;
  37762. break;
  37763. }
  37764. }
  37765. while (source.getPosition() < position)
  37766. {
  37767. const CodeDocument::Iterator original (source);
  37768. codeTokeniser->readNextToken (source);
  37769. if (source.getPosition() > position || source.isEOF())
  37770. {
  37771. source = original;
  37772. break;
  37773. }
  37774. }
  37775. }
  37776. END_JUCE_NAMESPACE
  37777. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37778. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37779. BEGIN_JUCE_NAMESPACE
  37780. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37781. {
  37782. }
  37783. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37784. {
  37785. }
  37786. namespace CppTokeniser
  37787. {
  37788. static bool isIdentifierStart (const juce_wchar c) throw()
  37789. {
  37790. return CharacterFunctions::isLetter (c)
  37791. || c == '_' || c == '@';
  37792. }
  37793. static bool isIdentifierBody (const juce_wchar c) throw()
  37794. {
  37795. return CharacterFunctions::isLetterOrDigit (c)
  37796. || c == '_' || c == '@';
  37797. }
  37798. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37799. {
  37800. static const juce_wchar* const keywords2Char[] =
  37801. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37802. static const juce_wchar* const keywords3Char[] =
  37803. { 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 };
  37804. static const juce_wchar* const keywords4Char[] =
  37805. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37806. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37807. static const juce_wchar* const keywords5Char[] =
  37808. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37809. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37810. static const juce_wchar* const keywords6Char[] =
  37811. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37812. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37813. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37814. static const juce_wchar* const keywordsOther[] =
  37815. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37816. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37817. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37818. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37819. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37820. const juce_wchar* const* k;
  37821. switch (tokenLength)
  37822. {
  37823. case 2: k = keywords2Char; break;
  37824. case 3: k = keywords3Char; break;
  37825. case 4: k = keywords4Char; break;
  37826. case 5: k = keywords5Char; break;
  37827. case 6: k = keywords6Char; break;
  37828. default:
  37829. if (tokenLength < 2 || tokenLength > 16)
  37830. return false;
  37831. k = keywordsOther;
  37832. break;
  37833. }
  37834. int i = 0;
  37835. while (k[i] != 0)
  37836. {
  37837. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37838. return true;
  37839. ++i;
  37840. }
  37841. return false;
  37842. }
  37843. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37844. {
  37845. int tokenLength = 0;
  37846. juce_wchar possibleIdentifier [19];
  37847. while (isIdentifierBody (source.peekNextChar()))
  37848. {
  37849. const juce_wchar c = source.nextChar();
  37850. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37851. possibleIdentifier [tokenLength] = c;
  37852. ++tokenLength;
  37853. }
  37854. if (tokenLength > 1 && tokenLength <= 16)
  37855. {
  37856. possibleIdentifier [tokenLength] = 0;
  37857. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37858. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37859. }
  37860. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37861. }
  37862. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37863. {
  37864. const juce_wchar c = source.peekNextChar();
  37865. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37866. source.skip();
  37867. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37868. return false;
  37869. return true;
  37870. }
  37871. static bool isHexDigit (const juce_wchar c) throw()
  37872. {
  37873. return (c >= '0' && c <= '9')
  37874. || (c >= 'a' && c <= 'f')
  37875. || (c >= 'A' && c <= 'F');
  37876. }
  37877. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37878. {
  37879. if (source.nextChar() != '0')
  37880. return false;
  37881. juce_wchar c = source.nextChar();
  37882. if (c != 'x' && c != 'X')
  37883. return false;
  37884. int numDigits = 0;
  37885. while (isHexDigit (source.peekNextChar()))
  37886. {
  37887. ++numDigits;
  37888. source.skip();
  37889. }
  37890. if (numDigits == 0)
  37891. return false;
  37892. return skipNumberSuffix (source);
  37893. }
  37894. static bool isOctalDigit (const juce_wchar c) throw()
  37895. {
  37896. return c >= '0' && c <= '7';
  37897. }
  37898. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37899. {
  37900. if (source.nextChar() != '0')
  37901. return false;
  37902. if (! isOctalDigit (source.nextChar()))
  37903. return false;
  37904. while (isOctalDigit (source.peekNextChar()))
  37905. source.skip();
  37906. return skipNumberSuffix (source);
  37907. }
  37908. static bool isDecimalDigit (const juce_wchar c) throw()
  37909. {
  37910. return c >= '0' && c <= '9';
  37911. }
  37912. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37913. {
  37914. int numChars = 0;
  37915. while (isDecimalDigit (source.peekNextChar()))
  37916. {
  37917. ++numChars;
  37918. source.skip();
  37919. }
  37920. if (numChars == 0)
  37921. return false;
  37922. return skipNumberSuffix (source);
  37923. }
  37924. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37925. {
  37926. int numDigits = 0;
  37927. while (isDecimalDigit (source.peekNextChar()))
  37928. {
  37929. source.skip();
  37930. ++numDigits;
  37931. }
  37932. const bool hasPoint = (source.peekNextChar() == '.');
  37933. if (hasPoint)
  37934. {
  37935. source.skip();
  37936. while (isDecimalDigit (source.peekNextChar()))
  37937. {
  37938. source.skip();
  37939. ++numDigits;
  37940. }
  37941. }
  37942. if (numDigits == 0)
  37943. return false;
  37944. juce_wchar c = source.peekNextChar();
  37945. const bool hasExponent = (c == 'e' || c == 'E');
  37946. if (hasExponent)
  37947. {
  37948. source.skip();
  37949. c = source.peekNextChar();
  37950. if (c == '+' || c == '-')
  37951. source.skip();
  37952. int numExpDigits = 0;
  37953. while (isDecimalDigit (source.peekNextChar()))
  37954. {
  37955. source.skip();
  37956. ++numExpDigits;
  37957. }
  37958. if (numExpDigits == 0)
  37959. return false;
  37960. }
  37961. c = source.peekNextChar();
  37962. if (c == 'f' || c == 'F')
  37963. source.skip();
  37964. else if (! (hasExponent || hasPoint))
  37965. return false;
  37966. return true;
  37967. }
  37968. static int parseNumber (CodeDocument::Iterator& source)
  37969. {
  37970. const CodeDocument::Iterator original (source);
  37971. if (parseFloatLiteral (source))
  37972. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37973. source = original;
  37974. if (parseHexLiteral (source))
  37975. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37976. source = original;
  37977. if (parseOctalLiteral (source))
  37978. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37979. source = original;
  37980. if (parseDecimalLiteral (source))
  37981. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37982. source = original;
  37983. source.skip();
  37984. return CPlusPlusCodeTokeniser::tokenType_error;
  37985. }
  37986. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37987. {
  37988. const juce_wchar quote = source.nextChar();
  37989. for (;;)
  37990. {
  37991. const juce_wchar c = source.nextChar();
  37992. if (c == quote || c == 0)
  37993. break;
  37994. if (c == '\\')
  37995. source.skip();
  37996. }
  37997. }
  37998. static void skipComment (CodeDocument::Iterator& source) throw()
  37999. {
  38000. bool lastWasStar = false;
  38001. for (;;)
  38002. {
  38003. const juce_wchar c = source.nextChar();
  38004. if (c == 0 || (c == '/' && lastWasStar))
  38005. break;
  38006. lastWasStar = (c == '*');
  38007. }
  38008. }
  38009. }
  38010. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  38011. {
  38012. int result = tokenType_error;
  38013. source.skipWhitespace();
  38014. juce_wchar firstChar = source.peekNextChar();
  38015. switch (firstChar)
  38016. {
  38017. case 0:
  38018. source.skip();
  38019. break;
  38020. case '0':
  38021. case '1':
  38022. case '2':
  38023. case '3':
  38024. case '4':
  38025. case '5':
  38026. case '6':
  38027. case '7':
  38028. case '8':
  38029. case '9':
  38030. result = CppTokeniser::parseNumber (source);
  38031. break;
  38032. case '.':
  38033. result = CppTokeniser::parseNumber (source);
  38034. if (result == tokenType_error)
  38035. result = tokenType_punctuation;
  38036. break;
  38037. case ',':
  38038. case ';':
  38039. case ':':
  38040. source.skip();
  38041. result = tokenType_punctuation;
  38042. break;
  38043. case '(':
  38044. case ')':
  38045. case '{':
  38046. case '}':
  38047. case '[':
  38048. case ']':
  38049. source.skip();
  38050. result = tokenType_bracket;
  38051. break;
  38052. case '"':
  38053. case '\'':
  38054. CppTokeniser::skipQuotedString (source);
  38055. result = tokenType_stringLiteral;
  38056. break;
  38057. case '+':
  38058. result = tokenType_operator;
  38059. source.skip();
  38060. if (source.peekNextChar() == '+')
  38061. source.skip();
  38062. else if (source.peekNextChar() == '=')
  38063. source.skip();
  38064. break;
  38065. case '-':
  38066. source.skip();
  38067. result = CppTokeniser::parseNumber (source);
  38068. if (result == tokenType_error)
  38069. {
  38070. result = tokenType_operator;
  38071. if (source.peekNextChar() == '-')
  38072. source.skip();
  38073. else if (source.peekNextChar() == '=')
  38074. source.skip();
  38075. }
  38076. break;
  38077. case '*':
  38078. case '%':
  38079. case '=':
  38080. case '!':
  38081. result = tokenType_operator;
  38082. source.skip();
  38083. if (source.peekNextChar() == '=')
  38084. source.skip();
  38085. break;
  38086. case '/':
  38087. result = tokenType_operator;
  38088. source.skip();
  38089. if (source.peekNextChar() == '=')
  38090. {
  38091. source.skip();
  38092. }
  38093. else if (source.peekNextChar() == '/')
  38094. {
  38095. result = tokenType_comment;
  38096. source.skipToEndOfLine();
  38097. }
  38098. else if (source.peekNextChar() == '*')
  38099. {
  38100. source.skip();
  38101. result = tokenType_comment;
  38102. CppTokeniser::skipComment (source);
  38103. }
  38104. break;
  38105. case '?':
  38106. case '~':
  38107. source.skip();
  38108. result = tokenType_operator;
  38109. break;
  38110. case '<':
  38111. source.skip();
  38112. result = tokenType_operator;
  38113. if (source.peekNextChar() == '=')
  38114. {
  38115. source.skip();
  38116. }
  38117. else if (source.peekNextChar() == '<')
  38118. {
  38119. source.skip();
  38120. if (source.peekNextChar() == '=')
  38121. source.skip();
  38122. }
  38123. break;
  38124. case '>':
  38125. source.skip();
  38126. result = tokenType_operator;
  38127. if (source.peekNextChar() == '=')
  38128. {
  38129. source.skip();
  38130. }
  38131. else if (source.peekNextChar() == '<')
  38132. {
  38133. source.skip();
  38134. if (source.peekNextChar() == '=')
  38135. source.skip();
  38136. }
  38137. break;
  38138. case '|':
  38139. source.skip();
  38140. result = tokenType_operator;
  38141. if (source.peekNextChar() == '=')
  38142. {
  38143. source.skip();
  38144. }
  38145. else if (source.peekNextChar() == '|')
  38146. {
  38147. source.skip();
  38148. if (source.peekNextChar() == '=')
  38149. source.skip();
  38150. }
  38151. break;
  38152. case '&':
  38153. source.skip();
  38154. result = tokenType_operator;
  38155. if (source.peekNextChar() == '=')
  38156. {
  38157. source.skip();
  38158. }
  38159. else if (source.peekNextChar() == '&')
  38160. {
  38161. source.skip();
  38162. if (source.peekNextChar() == '=')
  38163. source.skip();
  38164. }
  38165. break;
  38166. case '^':
  38167. source.skip();
  38168. result = tokenType_operator;
  38169. if (source.peekNextChar() == '=')
  38170. {
  38171. source.skip();
  38172. }
  38173. else if (source.peekNextChar() == '^')
  38174. {
  38175. source.skip();
  38176. if (source.peekNextChar() == '=')
  38177. source.skip();
  38178. }
  38179. break;
  38180. case '#':
  38181. result = tokenType_preprocessor;
  38182. source.skipToEndOfLine();
  38183. break;
  38184. default:
  38185. if (CppTokeniser::isIdentifierStart (firstChar))
  38186. result = CppTokeniser::parseIdentifier (source);
  38187. else
  38188. source.skip();
  38189. break;
  38190. }
  38191. return result;
  38192. }
  38193. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38194. {
  38195. const char* const types[] =
  38196. {
  38197. "Error",
  38198. "Comment",
  38199. "C++ keyword",
  38200. "Identifier",
  38201. "Integer literal",
  38202. "Float literal",
  38203. "String literal",
  38204. "Operator",
  38205. "Bracket",
  38206. "Punctuation",
  38207. "Preprocessor line",
  38208. 0
  38209. };
  38210. return StringArray (types);
  38211. }
  38212. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38213. {
  38214. const uint32 colours[] =
  38215. {
  38216. 0xffcc0000, // error
  38217. 0xff00aa00, // comment
  38218. 0xff0000cc, // keyword
  38219. 0xff000000, // identifier
  38220. 0xff880000, // int literal
  38221. 0xff885500, // float literal
  38222. 0xff990099, // string literal
  38223. 0xff225500, // operator
  38224. 0xff000055, // bracket
  38225. 0xff004400, // punctuation
  38226. 0xff660000 // preprocessor
  38227. };
  38228. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38229. return Colour (colours [tokenType]);
  38230. return Colours::black;
  38231. }
  38232. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38233. {
  38234. return CppTokeniser::isReservedKeyword (token, token.length());
  38235. }
  38236. END_JUCE_NAMESPACE
  38237. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38238. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38239. BEGIN_JUCE_NAMESPACE
  38240. ComboBox::ComboBox (const String& name)
  38241. : Component (name),
  38242. lastCurrentId (0),
  38243. isButtonDown (false),
  38244. separatorPending (false),
  38245. menuActive (false),
  38246. label (0)
  38247. {
  38248. noChoicesMessage = TRANS("(no choices)");
  38249. setRepaintsOnMouseActivity (true);
  38250. lookAndFeelChanged();
  38251. currentId.addListener (this);
  38252. }
  38253. ComboBox::~ComboBox()
  38254. {
  38255. currentId.removeListener (this);
  38256. if (menuActive)
  38257. PopupMenu::dismissAllActiveMenus();
  38258. label = 0;
  38259. deleteAllChildren();
  38260. }
  38261. void ComboBox::setEditableText (const bool isEditable)
  38262. {
  38263. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38264. {
  38265. label->setEditable (isEditable, isEditable, false);
  38266. setWantsKeyboardFocus (! isEditable);
  38267. resized();
  38268. }
  38269. }
  38270. bool ComboBox::isTextEditable() const throw()
  38271. {
  38272. return label->isEditable();
  38273. }
  38274. void ComboBox::setJustificationType (const Justification& justification)
  38275. {
  38276. label->setJustificationType (justification);
  38277. }
  38278. const Justification ComboBox::getJustificationType() const throw()
  38279. {
  38280. return label->getJustificationType();
  38281. }
  38282. void ComboBox::setTooltip (const String& newTooltip)
  38283. {
  38284. SettableTooltipClient::setTooltip (newTooltip);
  38285. label->setTooltip (newTooltip);
  38286. }
  38287. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38288. {
  38289. // you can't add empty strings to the list..
  38290. jassert (newItemText.isNotEmpty());
  38291. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38292. jassert (newItemId != 0);
  38293. // you shouldn't use duplicate item IDs!
  38294. jassert (getItemForId (newItemId) == 0);
  38295. if (newItemText.isNotEmpty() && newItemId != 0)
  38296. {
  38297. if (separatorPending)
  38298. {
  38299. separatorPending = false;
  38300. ItemInfo* const item = new ItemInfo();
  38301. item->itemId = 0;
  38302. item->isEnabled = false;
  38303. item->isHeading = false;
  38304. items.add (item);
  38305. }
  38306. ItemInfo* const item = new ItemInfo();
  38307. item->name = newItemText;
  38308. item->itemId = newItemId;
  38309. item->isEnabled = true;
  38310. item->isHeading = false;
  38311. items.add (item);
  38312. }
  38313. }
  38314. void ComboBox::addSeparator()
  38315. {
  38316. separatorPending = (items.size() > 0);
  38317. }
  38318. void ComboBox::addSectionHeading (const String& headingName)
  38319. {
  38320. // you can't add empty strings to the list..
  38321. jassert (headingName.isNotEmpty());
  38322. if (headingName.isNotEmpty())
  38323. {
  38324. if (separatorPending)
  38325. {
  38326. separatorPending = false;
  38327. ItemInfo* const item = new ItemInfo();
  38328. item->itemId = 0;
  38329. item->isEnabled = false;
  38330. item->isHeading = false;
  38331. items.add (item);
  38332. }
  38333. ItemInfo* const item = new ItemInfo();
  38334. item->name = headingName;
  38335. item->itemId = 0;
  38336. item->isEnabled = true;
  38337. item->isHeading = true;
  38338. items.add (item);
  38339. }
  38340. }
  38341. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38342. {
  38343. ItemInfo* const item = getItemForId (itemId);
  38344. if (item != 0)
  38345. item->isEnabled = shouldBeEnabled;
  38346. }
  38347. void ComboBox::changeItemText (const int itemId, const String& newText)
  38348. {
  38349. ItemInfo* const item = getItemForId (itemId);
  38350. jassert (item != 0);
  38351. if (item != 0)
  38352. item->name = newText;
  38353. }
  38354. void ComboBox::clear (const bool dontSendChangeMessage)
  38355. {
  38356. items.clear();
  38357. separatorPending = false;
  38358. if (! label->isEditable())
  38359. setSelectedItemIndex (-1, dontSendChangeMessage);
  38360. }
  38361. bool ComboBox::ItemInfo::isSeparator() const throw()
  38362. {
  38363. return name.isEmpty();
  38364. }
  38365. bool ComboBox::ItemInfo::isRealItem() const throw()
  38366. {
  38367. return ! (isHeading || name.isEmpty());
  38368. }
  38369. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38370. {
  38371. if (itemId != 0)
  38372. {
  38373. for (int i = items.size(); --i >= 0;)
  38374. if (items.getUnchecked(i)->itemId == itemId)
  38375. return items.getUnchecked(i);
  38376. }
  38377. return 0;
  38378. }
  38379. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38380. {
  38381. int n = 0;
  38382. for (int i = 0; i < items.size(); ++i)
  38383. {
  38384. ItemInfo* const item = items.getUnchecked(i);
  38385. if (item->isRealItem())
  38386. if (n++ == index)
  38387. return item;
  38388. }
  38389. return 0;
  38390. }
  38391. int ComboBox::getNumItems() const throw()
  38392. {
  38393. int n = 0;
  38394. for (int i = items.size(); --i >= 0;)
  38395. if (items.getUnchecked(i)->isRealItem())
  38396. ++n;
  38397. return n;
  38398. }
  38399. const String ComboBox::getItemText (const int index) const
  38400. {
  38401. const ItemInfo* const item = getItemForIndex (index);
  38402. if (item != 0)
  38403. return item->name;
  38404. return String::empty;
  38405. }
  38406. int ComboBox::getItemId (const int index) const throw()
  38407. {
  38408. const ItemInfo* const item = getItemForIndex (index);
  38409. return (item != 0) ? item->itemId : 0;
  38410. }
  38411. int ComboBox::indexOfItemId (const int itemId) const throw()
  38412. {
  38413. int n = 0;
  38414. for (int i = 0; i < items.size(); ++i)
  38415. {
  38416. const ItemInfo* const item = items.getUnchecked(i);
  38417. if (item->isRealItem())
  38418. {
  38419. if (item->itemId == itemId)
  38420. return n;
  38421. ++n;
  38422. }
  38423. }
  38424. return -1;
  38425. }
  38426. int ComboBox::getSelectedItemIndex() const
  38427. {
  38428. int index = indexOfItemId (currentId.getValue());
  38429. if (getText() != getItemText (index))
  38430. index = -1;
  38431. return index;
  38432. }
  38433. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38434. {
  38435. setSelectedId (getItemId (index), dontSendChangeMessage);
  38436. }
  38437. int ComboBox::getSelectedId() const throw()
  38438. {
  38439. const ItemInfo* const item = getItemForId (currentId.getValue());
  38440. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38441. }
  38442. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38443. {
  38444. const ItemInfo* const item = getItemForId (newItemId);
  38445. const String newItemText (item != 0 ? item->name : String::empty);
  38446. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38447. {
  38448. if (! dontSendChangeMessage)
  38449. triggerAsyncUpdate();
  38450. label->setText (newItemText, false);
  38451. lastCurrentId = newItemId;
  38452. currentId = newItemId;
  38453. repaint(); // for the benefit of the 'none selected' text
  38454. }
  38455. }
  38456. void ComboBox::valueChanged (Value&)
  38457. {
  38458. if (lastCurrentId != (int) currentId.getValue())
  38459. setSelectedId (currentId.getValue(), false);
  38460. }
  38461. const String ComboBox::getText() const
  38462. {
  38463. return label->getText();
  38464. }
  38465. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38466. {
  38467. for (int i = items.size(); --i >= 0;)
  38468. {
  38469. const ItemInfo* const item = items.getUnchecked(i);
  38470. if (item->isRealItem()
  38471. && item->name == newText)
  38472. {
  38473. setSelectedId (item->itemId, dontSendChangeMessage);
  38474. return;
  38475. }
  38476. }
  38477. lastCurrentId = 0;
  38478. currentId = 0;
  38479. if (label->getText() != newText)
  38480. {
  38481. label->setText (newText, false);
  38482. if (! dontSendChangeMessage)
  38483. triggerAsyncUpdate();
  38484. }
  38485. repaint();
  38486. }
  38487. void ComboBox::showEditor()
  38488. {
  38489. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38490. label->showEditor();
  38491. }
  38492. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38493. {
  38494. if (textWhenNothingSelected != newMessage)
  38495. {
  38496. textWhenNothingSelected = newMessage;
  38497. repaint();
  38498. }
  38499. }
  38500. const String ComboBox::getTextWhenNothingSelected() const
  38501. {
  38502. return textWhenNothingSelected;
  38503. }
  38504. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38505. {
  38506. noChoicesMessage = newMessage;
  38507. }
  38508. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38509. {
  38510. return noChoicesMessage;
  38511. }
  38512. void ComboBox::paint (Graphics& g)
  38513. {
  38514. getLookAndFeel().drawComboBox (g,
  38515. getWidth(),
  38516. getHeight(),
  38517. isButtonDown,
  38518. label->getRight(),
  38519. 0,
  38520. getWidth() - label->getRight(),
  38521. getHeight(),
  38522. *this);
  38523. if (textWhenNothingSelected.isNotEmpty()
  38524. && label->getText().isEmpty()
  38525. && ! label->isBeingEdited())
  38526. {
  38527. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38528. g.setFont (label->getFont());
  38529. g.drawFittedText (textWhenNothingSelected,
  38530. label->getX() + 2, label->getY() + 1,
  38531. label->getWidth() - 4, label->getHeight() - 2,
  38532. label->getJustificationType(),
  38533. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38534. }
  38535. }
  38536. void ComboBox::resized()
  38537. {
  38538. if (getHeight() > 0 && getWidth() > 0)
  38539. getLookAndFeel().positionComboBoxText (*this, *label);
  38540. }
  38541. void ComboBox::enablementChanged()
  38542. {
  38543. repaint();
  38544. }
  38545. void ComboBox::lookAndFeelChanged()
  38546. {
  38547. repaint();
  38548. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38549. if (label != 0)
  38550. {
  38551. newLabel->setEditable (label->isEditable());
  38552. newLabel->setJustificationType (label->getJustificationType());
  38553. newLabel->setTooltip (label->getTooltip());
  38554. newLabel->setText (label->getText(), false);
  38555. }
  38556. label = newLabel;
  38557. addAndMakeVisible (newLabel);
  38558. newLabel->addListener (this);
  38559. newLabel->addMouseListener (this, false);
  38560. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38561. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38562. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38563. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38564. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38565. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38566. resized();
  38567. }
  38568. void ComboBox::colourChanged()
  38569. {
  38570. lookAndFeelChanged();
  38571. }
  38572. bool ComboBox::keyPressed (const KeyPress& key)
  38573. {
  38574. bool used = false;
  38575. if (key.isKeyCode (KeyPress::upKey)
  38576. || key.isKeyCode (KeyPress::leftKey))
  38577. {
  38578. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38579. used = true;
  38580. }
  38581. else if (key.isKeyCode (KeyPress::downKey)
  38582. || key.isKeyCode (KeyPress::rightKey))
  38583. {
  38584. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38585. used = true;
  38586. }
  38587. else if (key.isKeyCode (KeyPress::returnKey))
  38588. {
  38589. showPopup();
  38590. used = true;
  38591. }
  38592. return used;
  38593. }
  38594. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38595. {
  38596. // only forward key events that aren't used by this component
  38597. return isKeyDown
  38598. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38599. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38600. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38601. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38602. }
  38603. void ComboBox::focusGained (FocusChangeType)
  38604. {
  38605. repaint();
  38606. }
  38607. void ComboBox::focusLost (FocusChangeType)
  38608. {
  38609. repaint();
  38610. }
  38611. void ComboBox::labelTextChanged (Label*)
  38612. {
  38613. triggerAsyncUpdate();
  38614. }
  38615. class ComboBox::Callback : public ModalComponentManager::Callback
  38616. {
  38617. public:
  38618. Callback (ComboBox* const box_)
  38619. : box (box_)
  38620. {
  38621. }
  38622. void modalStateFinished (int returnValue)
  38623. {
  38624. if (box != 0)
  38625. {
  38626. box->menuActive = false;
  38627. if (returnValue != 0)
  38628. box->setSelectedId (returnValue);
  38629. }
  38630. }
  38631. private:
  38632. Component::SafePointer<ComboBox> box;
  38633. Callback (const Callback&);
  38634. Callback& operator= (const Callback&);
  38635. };
  38636. void ComboBox::showPopup()
  38637. {
  38638. if (! menuActive)
  38639. {
  38640. const int selectedId = getSelectedId();
  38641. PopupMenu menu;
  38642. menu.setLookAndFeel (&getLookAndFeel());
  38643. for (int i = 0; i < items.size(); ++i)
  38644. {
  38645. const ItemInfo* const item = items.getUnchecked(i);
  38646. if (item->isSeparator())
  38647. menu.addSeparator();
  38648. else if (item->isHeading)
  38649. menu.addSectionHeader (item->name);
  38650. else
  38651. menu.addItem (item->itemId, item->name,
  38652. item->isEnabled, item->itemId == selectedId);
  38653. }
  38654. if (items.size() == 0)
  38655. menu.addItem (1, noChoicesMessage, false);
  38656. menuActive = true;
  38657. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38658. new Callback (this));
  38659. }
  38660. }
  38661. void ComboBox::mouseDown (const MouseEvent& e)
  38662. {
  38663. beginDragAutoRepeat (300);
  38664. isButtonDown = isEnabled();
  38665. if (isButtonDown
  38666. && (e.eventComponent == this || ! label->isEditable()))
  38667. {
  38668. showPopup();
  38669. }
  38670. }
  38671. void ComboBox::mouseDrag (const MouseEvent& e)
  38672. {
  38673. beginDragAutoRepeat (50);
  38674. if (isButtonDown && ! e.mouseWasClicked())
  38675. showPopup();
  38676. }
  38677. void ComboBox::mouseUp (const MouseEvent& e2)
  38678. {
  38679. if (isButtonDown)
  38680. {
  38681. isButtonDown = false;
  38682. repaint();
  38683. const MouseEvent e (e2.getEventRelativeTo (this));
  38684. if (reallyContains (e.x, e.y, true)
  38685. && (e2.eventComponent == this || ! label->isEditable()))
  38686. {
  38687. showPopup();
  38688. }
  38689. }
  38690. }
  38691. void ComboBox::addListener (Listener* const listener)
  38692. {
  38693. listeners.add (listener);
  38694. }
  38695. void ComboBox::removeListener (Listener* const listener)
  38696. {
  38697. listeners.remove (listener);
  38698. }
  38699. void ComboBox::handleAsyncUpdate()
  38700. {
  38701. Component::BailOutChecker checker (this);
  38702. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38703. }
  38704. END_JUCE_NAMESPACE
  38705. /*** End of inlined file: juce_ComboBox.cpp ***/
  38706. /*** Start of inlined file: juce_Label.cpp ***/
  38707. BEGIN_JUCE_NAMESPACE
  38708. Label::Label (const String& componentName,
  38709. const String& labelText)
  38710. : Component (componentName),
  38711. textValue (labelText),
  38712. lastTextValue (labelText),
  38713. font (15.0f),
  38714. justification (Justification::centredLeft),
  38715. ownerComponent (0),
  38716. horizontalBorderSize (5),
  38717. verticalBorderSize (1),
  38718. minimumHorizontalScale (0.7f),
  38719. editSingleClick (false),
  38720. editDoubleClick (false),
  38721. lossOfFocusDiscardsChanges (false)
  38722. {
  38723. setColour (TextEditor::textColourId, Colours::black);
  38724. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38725. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38726. textValue.addListener (this);
  38727. }
  38728. Label::~Label()
  38729. {
  38730. textValue.removeListener (this);
  38731. if (ownerComponent != 0)
  38732. ownerComponent->removeComponentListener (this);
  38733. editor = 0;
  38734. }
  38735. void Label::setText (const String& newText,
  38736. const bool broadcastChangeMessage)
  38737. {
  38738. hideEditor (true);
  38739. if (lastTextValue != newText)
  38740. {
  38741. lastTextValue = newText;
  38742. textValue = newText;
  38743. repaint();
  38744. textWasChanged();
  38745. if (ownerComponent != 0)
  38746. componentMovedOrResized (*ownerComponent, true, true);
  38747. if (broadcastChangeMessage)
  38748. callChangeListeners();
  38749. }
  38750. }
  38751. const String Label::getText (const bool returnActiveEditorContents) const
  38752. {
  38753. return (returnActiveEditorContents && isBeingEdited())
  38754. ? editor->getText()
  38755. : textValue.toString();
  38756. }
  38757. void Label::valueChanged (Value&)
  38758. {
  38759. if (lastTextValue != textValue.toString())
  38760. setText (textValue.toString(), true);
  38761. }
  38762. void Label::setFont (const Font& newFont)
  38763. {
  38764. if (font != newFont)
  38765. {
  38766. font = newFont;
  38767. repaint();
  38768. }
  38769. }
  38770. const Font& Label::getFont() const throw()
  38771. {
  38772. return font;
  38773. }
  38774. void Label::setEditable (const bool editOnSingleClick,
  38775. const bool editOnDoubleClick,
  38776. const bool lossOfFocusDiscardsChanges_)
  38777. {
  38778. editSingleClick = editOnSingleClick;
  38779. editDoubleClick = editOnDoubleClick;
  38780. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38781. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38782. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38783. }
  38784. void Label::setJustificationType (const Justification& newJustification)
  38785. {
  38786. if (justification != newJustification)
  38787. {
  38788. justification = newJustification;
  38789. repaint();
  38790. }
  38791. }
  38792. void Label::setBorderSize (int h, int v)
  38793. {
  38794. if (horizontalBorderSize != h || verticalBorderSize != v)
  38795. {
  38796. horizontalBorderSize = h;
  38797. verticalBorderSize = v;
  38798. repaint();
  38799. }
  38800. }
  38801. Component* Label::getAttachedComponent() const
  38802. {
  38803. return static_cast<Component*> (ownerComponent);
  38804. }
  38805. void Label::attachToComponent (Component* owner,
  38806. const bool onLeft)
  38807. {
  38808. if (ownerComponent != 0)
  38809. ownerComponent->removeComponentListener (this);
  38810. ownerComponent = owner;
  38811. leftOfOwnerComp = onLeft;
  38812. if (ownerComponent != 0)
  38813. {
  38814. setVisible (owner->isVisible());
  38815. ownerComponent->addComponentListener (this);
  38816. componentParentHierarchyChanged (*ownerComponent);
  38817. componentMovedOrResized (*ownerComponent, true, true);
  38818. }
  38819. }
  38820. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38821. {
  38822. if (leftOfOwnerComp)
  38823. {
  38824. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38825. component.getHeight());
  38826. setTopRightPosition (component.getX(), component.getY());
  38827. }
  38828. else
  38829. {
  38830. setSize (component.getWidth(),
  38831. 8 + roundToInt (getFont().getHeight()));
  38832. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38833. }
  38834. }
  38835. void Label::componentParentHierarchyChanged (Component& component)
  38836. {
  38837. if (component.getParentComponent() != 0)
  38838. component.getParentComponent()->addChildComponent (this);
  38839. }
  38840. void Label::componentVisibilityChanged (Component& component)
  38841. {
  38842. setVisible (component.isVisible());
  38843. }
  38844. void Label::textWasEdited()
  38845. {
  38846. }
  38847. void Label::textWasChanged()
  38848. {
  38849. }
  38850. void Label::showEditor()
  38851. {
  38852. if (editor == 0)
  38853. {
  38854. addAndMakeVisible (editor = createEditorComponent());
  38855. editor->setText (getText(), false);
  38856. editor->addListener (this);
  38857. editor->grabKeyboardFocus();
  38858. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38859. editor->addListener (this);
  38860. resized();
  38861. repaint();
  38862. editorShown (editor);
  38863. enterModalState (false);
  38864. editor->grabKeyboardFocus();
  38865. }
  38866. }
  38867. void Label::editorShown (TextEditor* /*editorComponent*/)
  38868. {
  38869. }
  38870. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38871. {
  38872. }
  38873. bool Label::updateFromTextEditorContents()
  38874. {
  38875. jassert (editor != 0);
  38876. const String newText (editor->getText());
  38877. if (textValue.toString() != newText)
  38878. {
  38879. lastTextValue = newText;
  38880. textValue = newText;
  38881. repaint();
  38882. textWasChanged();
  38883. if (ownerComponent != 0)
  38884. componentMovedOrResized (*ownerComponent, true, true);
  38885. return true;
  38886. }
  38887. return false;
  38888. }
  38889. void Label::hideEditor (const bool discardCurrentEditorContents)
  38890. {
  38891. if (editor != 0)
  38892. {
  38893. Component::SafePointer<Component> deletionChecker (this);
  38894. editorAboutToBeHidden (editor);
  38895. const bool changed = (! discardCurrentEditorContents)
  38896. && updateFromTextEditorContents();
  38897. editor = 0;
  38898. repaint();
  38899. if (changed)
  38900. textWasEdited();
  38901. if (deletionChecker != 0)
  38902. exitModalState (0);
  38903. if (changed && deletionChecker != 0)
  38904. callChangeListeners();
  38905. }
  38906. }
  38907. void Label::inputAttemptWhenModal()
  38908. {
  38909. if (editor != 0)
  38910. {
  38911. if (lossOfFocusDiscardsChanges)
  38912. textEditorEscapeKeyPressed (*editor);
  38913. else
  38914. textEditorReturnKeyPressed (*editor);
  38915. }
  38916. }
  38917. bool Label::isBeingEdited() const throw()
  38918. {
  38919. return editor != 0;
  38920. }
  38921. TextEditor* Label::createEditorComponent()
  38922. {
  38923. TextEditor* const ed = new TextEditor (getName());
  38924. ed->setFont (font);
  38925. // copy these colours from our own settings..
  38926. const int cols[] = { TextEditor::backgroundColourId,
  38927. TextEditor::textColourId,
  38928. TextEditor::highlightColourId,
  38929. TextEditor::highlightedTextColourId,
  38930. TextEditor::caretColourId,
  38931. TextEditor::outlineColourId,
  38932. TextEditor::focusedOutlineColourId,
  38933. TextEditor::shadowColourId };
  38934. for (int i = 0; i < numElementsInArray (cols); ++i)
  38935. ed->setColour (cols[i], findColour (cols[i]));
  38936. return ed;
  38937. }
  38938. void Label::paint (Graphics& g)
  38939. {
  38940. getLookAndFeel().drawLabel (g, *this);
  38941. }
  38942. void Label::mouseUp (const MouseEvent& e)
  38943. {
  38944. if (editSingleClick
  38945. && e.mouseWasClicked()
  38946. && contains (e.x, e.y)
  38947. && ! e.mods.isPopupMenu())
  38948. {
  38949. showEditor();
  38950. }
  38951. }
  38952. void Label::mouseDoubleClick (const MouseEvent& e)
  38953. {
  38954. if (editDoubleClick && ! e.mods.isPopupMenu())
  38955. showEditor();
  38956. }
  38957. void Label::resized()
  38958. {
  38959. if (editor != 0)
  38960. editor->setBoundsInset (BorderSize (0));
  38961. }
  38962. void Label::focusGained (FocusChangeType cause)
  38963. {
  38964. if (editSingleClick && cause == focusChangedByTabKey)
  38965. showEditor();
  38966. }
  38967. void Label::enablementChanged()
  38968. {
  38969. repaint();
  38970. }
  38971. void Label::colourChanged()
  38972. {
  38973. repaint();
  38974. }
  38975. void Label::setMinimumHorizontalScale (const float newScale)
  38976. {
  38977. if (minimumHorizontalScale != newScale)
  38978. {
  38979. minimumHorizontalScale = newScale;
  38980. repaint();
  38981. }
  38982. }
  38983. // We'll use a custom focus traverser here to make sure focus goes from the
  38984. // text editor to another component rather than back to the label itself.
  38985. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38986. {
  38987. public:
  38988. LabelKeyboardFocusTraverser() {}
  38989. Component* getNextComponent (Component* current)
  38990. {
  38991. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38992. ? current->getParentComponent() : current);
  38993. }
  38994. Component* getPreviousComponent (Component* current)
  38995. {
  38996. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38997. ? current->getParentComponent() : current);
  38998. }
  38999. };
  39000. KeyboardFocusTraverser* Label::createFocusTraverser()
  39001. {
  39002. return new LabelKeyboardFocusTraverser();
  39003. }
  39004. void Label::addListener (Listener* const listener)
  39005. {
  39006. listeners.add (listener);
  39007. }
  39008. void Label::removeListener (Listener* const listener)
  39009. {
  39010. listeners.remove (listener);
  39011. }
  39012. void Label::callChangeListeners()
  39013. {
  39014. Component::BailOutChecker checker (this);
  39015. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  39016. }
  39017. void Label::textEditorTextChanged (TextEditor& ed)
  39018. {
  39019. if (editor != 0)
  39020. {
  39021. jassert (&ed == editor);
  39022. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  39023. {
  39024. if (lossOfFocusDiscardsChanges)
  39025. textEditorEscapeKeyPressed (ed);
  39026. else
  39027. textEditorReturnKeyPressed (ed);
  39028. }
  39029. }
  39030. }
  39031. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  39032. {
  39033. if (editor != 0)
  39034. {
  39035. jassert (&ed == editor);
  39036. (void) ed;
  39037. const bool changed = updateFromTextEditorContents();
  39038. hideEditor (true);
  39039. if (changed)
  39040. {
  39041. Component::SafePointer<Component> deletionChecker (this);
  39042. textWasEdited();
  39043. if (deletionChecker != 0)
  39044. callChangeListeners();
  39045. }
  39046. }
  39047. }
  39048. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  39049. {
  39050. if (editor != 0)
  39051. {
  39052. jassert (&ed == editor);
  39053. (void) ed;
  39054. editor->setText (textValue.toString(), false);
  39055. hideEditor (true);
  39056. }
  39057. }
  39058. void Label::textEditorFocusLost (TextEditor& ed)
  39059. {
  39060. textEditorTextChanged (ed);
  39061. }
  39062. END_JUCE_NAMESPACE
  39063. /*** End of inlined file: juce_Label.cpp ***/
  39064. /*** Start of inlined file: juce_ListBox.cpp ***/
  39065. BEGIN_JUCE_NAMESPACE
  39066. class ListBoxRowComponent : public Component,
  39067. public TooltipClient
  39068. {
  39069. public:
  39070. ListBoxRowComponent (ListBox& owner_)
  39071. : owner (owner_),
  39072. row (-1),
  39073. selected (false),
  39074. isDragging (false)
  39075. {
  39076. }
  39077. ~ListBoxRowComponent()
  39078. {
  39079. deleteAllChildren();
  39080. }
  39081. void paint (Graphics& g)
  39082. {
  39083. if (owner.getModel() != 0)
  39084. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39085. }
  39086. void update (const int row_, const bool selected_)
  39087. {
  39088. if (row != row_ || selected != selected_)
  39089. {
  39090. repaint();
  39091. row = row_;
  39092. selected = selected_;
  39093. }
  39094. if (owner.getModel() != 0)
  39095. {
  39096. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  39097. if (customComp != 0)
  39098. {
  39099. addAndMakeVisible (customComp);
  39100. customComp->setBounds (getLocalBounds());
  39101. for (int i = getNumChildComponents(); --i >= 0;)
  39102. if (getChildComponent (i) != customComp)
  39103. delete getChildComponent (i);
  39104. }
  39105. else
  39106. {
  39107. deleteAllChildren();
  39108. }
  39109. }
  39110. }
  39111. void mouseDown (const MouseEvent& e)
  39112. {
  39113. isDragging = false;
  39114. selectRowOnMouseUp = false;
  39115. if (isEnabled())
  39116. {
  39117. if (! selected)
  39118. {
  39119. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39120. if (owner.getModel() != 0)
  39121. owner.getModel()->listBoxItemClicked (row, e);
  39122. }
  39123. else
  39124. {
  39125. selectRowOnMouseUp = true;
  39126. }
  39127. }
  39128. }
  39129. void mouseUp (const MouseEvent& e)
  39130. {
  39131. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39132. {
  39133. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39134. if (owner.getModel() != 0)
  39135. owner.getModel()->listBoxItemClicked (row, e);
  39136. }
  39137. }
  39138. void mouseDoubleClick (const MouseEvent& e)
  39139. {
  39140. if (owner.getModel() != 0 && isEnabled())
  39141. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39142. }
  39143. void mouseDrag (const MouseEvent& e)
  39144. {
  39145. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39146. {
  39147. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39148. if (selectedRows.size() > 0)
  39149. {
  39150. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39151. if (dragDescription.isNotEmpty())
  39152. {
  39153. isDragging = true;
  39154. owner.startDragAndDrop (e, dragDescription);
  39155. }
  39156. }
  39157. }
  39158. }
  39159. void resized()
  39160. {
  39161. if (getNumChildComponents() > 0)
  39162. getChildComponent(0)->setBounds (getLocalBounds());
  39163. }
  39164. const String getTooltip()
  39165. {
  39166. if (owner.getModel() != 0)
  39167. return owner.getModel()->getTooltipForRow (row);
  39168. return String::empty;
  39169. }
  39170. juce_UseDebuggingNewOperator
  39171. bool neededFlag;
  39172. private:
  39173. ListBox& owner;
  39174. int row;
  39175. bool selected, isDragging, selectRowOnMouseUp;
  39176. ListBoxRowComponent (const ListBoxRowComponent&);
  39177. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39178. };
  39179. class ListViewport : public Viewport
  39180. {
  39181. public:
  39182. int firstIndex, firstWholeIndex, lastWholeIndex;
  39183. bool hasUpdated;
  39184. ListViewport (ListBox& owner_)
  39185. : owner (owner_)
  39186. {
  39187. setWantsKeyboardFocus (false);
  39188. setViewedComponent (new Component());
  39189. getViewedComponent()->addMouseListener (this, false);
  39190. getViewedComponent()->setWantsKeyboardFocus (false);
  39191. }
  39192. ~ListViewport()
  39193. {
  39194. getViewedComponent()->removeMouseListener (this);
  39195. getViewedComponent()->deleteAllChildren();
  39196. }
  39197. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39198. {
  39199. return static_cast <ListBoxRowComponent*>
  39200. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39201. }
  39202. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39203. {
  39204. const int index = getIndexOfChildComponent (rowComponent);
  39205. const int num = getViewedComponent()->getNumChildComponents();
  39206. for (int i = num; --i >= 0;)
  39207. if (((firstIndex + i) % jmax (1, num)) == index)
  39208. return firstIndex + i;
  39209. return -1;
  39210. }
  39211. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39212. {
  39213. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39214. ? getComponentForRow (row) : 0;
  39215. }
  39216. void visibleAreaChanged (int, int, int, int)
  39217. {
  39218. updateVisibleArea (true);
  39219. if (owner.getModel() != 0)
  39220. owner.getModel()->listWasScrolled();
  39221. }
  39222. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39223. {
  39224. hasUpdated = false;
  39225. const int newX = getViewedComponent()->getX();
  39226. int newY = getViewedComponent()->getY();
  39227. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39228. const int newH = owner.totalItems * owner.getRowHeight();
  39229. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39230. newY = getMaximumVisibleHeight() - newH;
  39231. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39232. if (makeSureItUpdatesContent && ! hasUpdated)
  39233. updateContents();
  39234. }
  39235. void updateContents()
  39236. {
  39237. hasUpdated = true;
  39238. const int rowHeight = owner.getRowHeight();
  39239. if (rowHeight > 0)
  39240. {
  39241. const int y = getViewPositionY();
  39242. const int w = getViewedComponent()->getWidth();
  39243. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39244. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39245. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39246. jassert (numNeeded >= 0);
  39247. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39248. {
  39249. Component* const rowToRemove
  39250. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39251. delete rowToRemove;
  39252. }
  39253. firstIndex = y / rowHeight;
  39254. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39255. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39256. for (int i = 0; i < numNeeded; ++i)
  39257. {
  39258. const int row = i + firstIndex;
  39259. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39260. if (rowComp != 0)
  39261. {
  39262. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39263. rowComp->update (row, owner.isRowSelected (row));
  39264. }
  39265. }
  39266. }
  39267. if (owner.headerComponent != 0)
  39268. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39269. owner.outlineThickness,
  39270. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39271. getViewedComponent()->getWidth()),
  39272. owner.headerComponent->getHeight());
  39273. }
  39274. void paint (Graphics& g)
  39275. {
  39276. if (isOpaque())
  39277. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39278. }
  39279. bool keyPressed (const KeyPress& key)
  39280. {
  39281. if (key.isKeyCode (KeyPress::upKey)
  39282. || key.isKeyCode (KeyPress::downKey)
  39283. || key.isKeyCode (KeyPress::pageUpKey)
  39284. || key.isKeyCode (KeyPress::pageDownKey)
  39285. || key.isKeyCode (KeyPress::homeKey)
  39286. || key.isKeyCode (KeyPress::endKey))
  39287. {
  39288. // we want to avoid these keypresses going to the viewport, and instead allow
  39289. // them to pass up to our listbox..
  39290. return false;
  39291. }
  39292. return Viewport::keyPressed (key);
  39293. }
  39294. juce_UseDebuggingNewOperator
  39295. private:
  39296. ListBox& owner;
  39297. ListViewport (const ListViewport&);
  39298. ListViewport& operator= (const ListViewport&);
  39299. };
  39300. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39301. : Component (name),
  39302. model (model_),
  39303. totalItems (0),
  39304. rowHeight (22),
  39305. minimumRowWidth (0),
  39306. outlineThickness (0),
  39307. lastRowSelected (-1),
  39308. mouseMoveSelects (false),
  39309. multipleSelection (false),
  39310. hasDoneInitialUpdate (false)
  39311. {
  39312. addAndMakeVisible (viewport = new ListViewport (*this));
  39313. setWantsKeyboardFocus (true);
  39314. colourChanged();
  39315. }
  39316. ListBox::~ListBox()
  39317. {
  39318. headerComponent = 0;
  39319. viewport = 0;
  39320. }
  39321. void ListBox::setModel (ListBoxModel* const newModel)
  39322. {
  39323. if (model != newModel)
  39324. {
  39325. model = newModel;
  39326. updateContent();
  39327. }
  39328. }
  39329. void ListBox::setMultipleSelectionEnabled (bool b)
  39330. {
  39331. multipleSelection = b;
  39332. }
  39333. void ListBox::setMouseMoveSelectsRows (bool b)
  39334. {
  39335. mouseMoveSelects = b;
  39336. if (b)
  39337. addMouseListener (this, true);
  39338. }
  39339. void ListBox::paint (Graphics& g)
  39340. {
  39341. if (! hasDoneInitialUpdate)
  39342. updateContent();
  39343. g.fillAll (findColour (backgroundColourId));
  39344. }
  39345. void ListBox::paintOverChildren (Graphics& g)
  39346. {
  39347. if (outlineThickness > 0)
  39348. {
  39349. g.setColour (findColour (outlineColourId));
  39350. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39351. }
  39352. }
  39353. void ListBox::resized()
  39354. {
  39355. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39356. outlineThickness,
  39357. outlineThickness,
  39358. outlineThickness));
  39359. viewport->setSingleStepSizes (20, getRowHeight());
  39360. viewport->updateVisibleArea (false);
  39361. }
  39362. void ListBox::visibilityChanged()
  39363. {
  39364. viewport->updateVisibleArea (true);
  39365. }
  39366. Viewport* ListBox::getViewport() const throw()
  39367. {
  39368. return viewport;
  39369. }
  39370. void ListBox::updateContent()
  39371. {
  39372. hasDoneInitialUpdate = true;
  39373. totalItems = (model != 0) ? model->getNumRows() : 0;
  39374. bool selectionChanged = false;
  39375. if (selected [selected.size() - 1] >= totalItems)
  39376. {
  39377. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39378. lastRowSelected = getSelectedRow (0);
  39379. selectionChanged = true;
  39380. }
  39381. viewport->updateVisibleArea (isVisible());
  39382. viewport->resized();
  39383. if (selectionChanged && model != 0)
  39384. model->selectedRowsChanged (lastRowSelected);
  39385. }
  39386. void ListBox::selectRow (const int row,
  39387. bool dontScroll,
  39388. bool deselectOthersFirst)
  39389. {
  39390. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39391. }
  39392. void ListBox::selectRowInternal (const int row,
  39393. bool dontScroll,
  39394. bool deselectOthersFirst,
  39395. bool isMouseClick)
  39396. {
  39397. if (! multipleSelection)
  39398. deselectOthersFirst = true;
  39399. if ((! isRowSelected (row))
  39400. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39401. {
  39402. if (((unsigned int) row) < (unsigned int) totalItems)
  39403. {
  39404. if (deselectOthersFirst)
  39405. selected.clear();
  39406. selected.addRange (Range<int> (row, row + 1));
  39407. if (getHeight() == 0 || getWidth() == 0)
  39408. dontScroll = true;
  39409. viewport->hasUpdated = false;
  39410. if (row < viewport->firstWholeIndex && ! dontScroll)
  39411. {
  39412. viewport->setViewPosition (viewport->getViewPositionX(),
  39413. row * getRowHeight());
  39414. }
  39415. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39416. {
  39417. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39418. if (row >= lastRowSelected + rowsOnScreen
  39419. && rowsOnScreen < totalItems - 1
  39420. && ! isMouseClick)
  39421. {
  39422. viewport->setViewPosition (viewport->getViewPositionX(),
  39423. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39424. * getRowHeight());
  39425. }
  39426. else
  39427. {
  39428. viewport->setViewPosition (viewport->getViewPositionX(),
  39429. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39430. }
  39431. }
  39432. if (! viewport->hasUpdated)
  39433. viewport->updateContents();
  39434. lastRowSelected = row;
  39435. model->selectedRowsChanged (row);
  39436. }
  39437. else
  39438. {
  39439. if (deselectOthersFirst)
  39440. deselectAllRows();
  39441. }
  39442. }
  39443. }
  39444. void ListBox::deselectRow (const int row)
  39445. {
  39446. if (selected.contains (row))
  39447. {
  39448. selected.removeRange (Range <int> (row, row + 1));
  39449. if (row == lastRowSelected)
  39450. lastRowSelected = getSelectedRow (0);
  39451. viewport->updateContents();
  39452. model->selectedRowsChanged (lastRowSelected);
  39453. }
  39454. }
  39455. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39456. const bool sendNotificationEventToModel)
  39457. {
  39458. selected = setOfRowsToBeSelected;
  39459. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39460. if (! isRowSelected (lastRowSelected))
  39461. lastRowSelected = getSelectedRow (0);
  39462. viewport->updateContents();
  39463. if ((model != 0) && sendNotificationEventToModel)
  39464. model->selectedRowsChanged (lastRowSelected);
  39465. }
  39466. const SparseSet<int> ListBox::getSelectedRows() const
  39467. {
  39468. return selected;
  39469. }
  39470. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39471. {
  39472. if (multipleSelection && (firstRow != lastRow))
  39473. {
  39474. const int numRows = totalItems - 1;
  39475. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39476. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39477. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39478. jmax (firstRow, lastRow) + 1));
  39479. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39480. }
  39481. selectRowInternal (lastRow, false, false, true);
  39482. }
  39483. void ListBox::flipRowSelection (const int row)
  39484. {
  39485. if (isRowSelected (row))
  39486. deselectRow (row);
  39487. else
  39488. selectRowInternal (row, false, false, true);
  39489. }
  39490. void ListBox::deselectAllRows()
  39491. {
  39492. if (! selected.isEmpty())
  39493. {
  39494. selected.clear();
  39495. lastRowSelected = -1;
  39496. viewport->updateContents();
  39497. if (model != 0)
  39498. model->selectedRowsChanged (lastRowSelected);
  39499. }
  39500. }
  39501. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39502. const ModifierKeys& mods)
  39503. {
  39504. if (multipleSelection && mods.isCommandDown())
  39505. {
  39506. flipRowSelection (row);
  39507. }
  39508. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39509. {
  39510. selectRangeOfRows (lastRowSelected, row);
  39511. }
  39512. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39513. {
  39514. selectRowInternal (row, false, true, true);
  39515. }
  39516. }
  39517. int ListBox::getNumSelectedRows() const
  39518. {
  39519. return selected.size();
  39520. }
  39521. int ListBox::getSelectedRow (const int index) const
  39522. {
  39523. return (((unsigned int) index) < (unsigned int) selected.size())
  39524. ? selected [index] : -1;
  39525. }
  39526. bool ListBox::isRowSelected (const int row) const
  39527. {
  39528. return selected.contains (row);
  39529. }
  39530. int ListBox::getLastRowSelected() const
  39531. {
  39532. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39533. }
  39534. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39535. {
  39536. if (((unsigned int) x) < (unsigned int) getWidth())
  39537. {
  39538. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39539. if (((unsigned int) row) < (unsigned int) totalItems)
  39540. return row;
  39541. }
  39542. return -1;
  39543. }
  39544. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39545. {
  39546. if (((unsigned int) x) < (unsigned int) getWidth())
  39547. {
  39548. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39549. return jlimit (0, totalItems, row);
  39550. }
  39551. return -1;
  39552. }
  39553. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39554. {
  39555. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39556. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39557. }
  39558. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39559. {
  39560. return viewport->getRowNumberOfComponent (rowComponent);
  39561. }
  39562. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39563. const bool relativeToComponentTopLeft) const throw()
  39564. {
  39565. int y = viewport->getY() + rowHeight * rowNumber;
  39566. if (relativeToComponentTopLeft)
  39567. y -= viewport->getViewPositionY();
  39568. return Rectangle<int> (viewport->getX(), y,
  39569. viewport->getViewedComponent()->getWidth(), rowHeight);
  39570. }
  39571. void ListBox::setVerticalPosition (const double proportion)
  39572. {
  39573. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39574. viewport->setViewPosition (viewport->getViewPositionX(),
  39575. jmax (0, roundToInt (proportion * offscreen)));
  39576. }
  39577. double ListBox::getVerticalPosition() const
  39578. {
  39579. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39580. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39581. : 0;
  39582. }
  39583. int ListBox::getVisibleRowWidth() const throw()
  39584. {
  39585. return viewport->getViewWidth();
  39586. }
  39587. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39588. {
  39589. if (row < viewport->firstWholeIndex)
  39590. {
  39591. viewport->setViewPosition (viewport->getViewPositionX(),
  39592. row * getRowHeight());
  39593. }
  39594. else if (row >= viewport->lastWholeIndex)
  39595. {
  39596. viewport->setViewPosition (viewport->getViewPositionX(),
  39597. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39598. }
  39599. }
  39600. bool ListBox::keyPressed (const KeyPress& key)
  39601. {
  39602. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39603. const bool multiple = multipleSelection
  39604. && (lastRowSelected >= 0)
  39605. && (key.getModifiers().isShiftDown()
  39606. || key.getModifiers().isCtrlDown()
  39607. || key.getModifiers().isCommandDown());
  39608. if (key.isKeyCode (KeyPress::upKey))
  39609. {
  39610. if (multiple)
  39611. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39612. else
  39613. selectRow (jmax (0, lastRowSelected - 1));
  39614. }
  39615. else if (key.isKeyCode (KeyPress::returnKey)
  39616. && isRowSelected (lastRowSelected))
  39617. {
  39618. if (model != 0)
  39619. model->returnKeyPressed (lastRowSelected);
  39620. }
  39621. else if (key.isKeyCode (KeyPress::pageUpKey))
  39622. {
  39623. if (multiple)
  39624. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39625. else
  39626. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39627. }
  39628. else if (key.isKeyCode (KeyPress::pageDownKey))
  39629. {
  39630. if (multiple)
  39631. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39632. else
  39633. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39634. }
  39635. else if (key.isKeyCode (KeyPress::homeKey))
  39636. {
  39637. if (multiple && key.getModifiers().isShiftDown())
  39638. selectRangeOfRows (lastRowSelected, 0);
  39639. else
  39640. selectRow (0);
  39641. }
  39642. else if (key.isKeyCode (KeyPress::endKey))
  39643. {
  39644. if (multiple && key.getModifiers().isShiftDown())
  39645. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39646. else
  39647. selectRow (totalItems - 1);
  39648. }
  39649. else if (key.isKeyCode (KeyPress::downKey))
  39650. {
  39651. if (multiple)
  39652. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39653. else
  39654. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39655. }
  39656. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39657. && isRowSelected (lastRowSelected))
  39658. {
  39659. if (model != 0)
  39660. model->deleteKeyPressed (lastRowSelected);
  39661. }
  39662. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39663. {
  39664. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39665. }
  39666. else
  39667. {
  39668. return false;
  39669. }
  39670. return true;
  39671. }
  39672. bool ListBox::keyStateChanged (const bool isKeyDown)
  39673. {
  39674. return isKeyDown
  39675. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39676. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39677. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39678. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39679. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39680. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39681. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39682. }
  39683. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39684. {
  39685. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39686. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39687. }
  39688. void ListBox::mouseMove (const MouseEvent& e)
  39689. {
  39690. if (mouseMoveSelects)
  39691. {
  39692. const MouseEvent e2 (e.getEventRelativeTo (this));
  39693. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39694. }
  39695. }
  39696. void ListBox::mouseExit (const MouseEvent& e)
  39697. {
  39698. mouseMove (e);
  39699. }
  39700. void ListBox::mouseUp (const MouseEvent& e)
  39701. {
  39702. if (e.mouseWasClicked() && model != 0)
  39703. model->backgroundClicked();
  39704. }
  39705. void ListBox::setRowHeight (const int newHeight)
  39706. {
  39707. rowHeight = jmax (1, newHeight);
  39708. viewport->setSingleStepSizes (20, rowHeight);
  39709. updateContent();
  39710. }
  39711. int ListBox::getNumRowsOnScreen() const throw()
  39712. {
  39713. return viewport->getMaximumVisibleHeight() / rowHeight;
  39714. }
  39715. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39716. {
  39717. minimumRowWidth = newMinimumWidth;
  39718. updateContent();
  39719. }
  39720. int ListBox::getVisibleContentWidth() const throw()
  39721. {
  39722. return viewport->getMaximumVisibleWidth();
  39723. }
  39724. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39725. {
  39726. return viewport->getVerticalScrollBar();
  39727. }
  39728. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39729. {
  39730. return viewport->getHorizontalScrollBar();
  39731. }
  39732. void ListBox::colourChanged()
  39733. {
  39734. setOpaque (findColour (backgroundColourId).isOpaque());
  39735. viewport->setOpaque (isOpaque());
  39736. repaint();
  39737. }
  39738. void ListBox::setOutlineThickness (const int outlineThickness_)
  39739. {
  39740. outlineThickness = outlineThickness_;
  39741. resized();
  39742. }
  39743. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39744. {
  39745. if (newHeaderComponent != headerComponent)
  39746. {
  39747. headerComponent = newHeaderComponent;
  39748. addAndMakeVisible (newHeaderComponent);
  39749. ListBox::resized();
  39750. }
  39751. }
  39752. void ListBox::repaintRow (const int rowNumber) throw()
  39753. {
  39754. repaint (getRowPosition (rowNumber, true));
  39755. }
  39756. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39757. {
  39758. Rectangle<int> imageArea;
  39759. const int firstRow = getRowContainingPosition (0, 0);
  39760. int i;
  39761. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39762. {
  39763. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39764. if (rowComp != 0 && isRowSelected (firstRow + i))
  39765. {
  39766. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39767. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39768. imageArea = imageArea.getUnion (rowRect);
  39769. }
  39770. }
  39771. imageArea = imageArea.getIntersection (getLocalBounds());
  39772. imageX = imageArea.getX();
  39773. imageY = imageArea.getY();
  39774. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39775. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39776. {
  39777. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39778. if (rowComp != 0 && isRowSelected (firstRow + i))
  39779. {
  39780. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39781. Graphics g (snapshot);
  39782. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39783. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39784. rowComp->paintEntireComponent (g);
  39785. }
  39786. }
  39787. return snapshot;
  39788. }
  39789. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39790. {
  39791. DragAndDropContainer* const dragContainer
  39792. = DragAndDropContainer::findParentDragContainerFor (this);
  39793. if (dragContainer != 0)
  39794. {
  39795. int x, y;
  39796. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39797. dragImage.multiplyAllAlphas (0.6f);
  39798. MouseEvent e2 (e.getEventRelativeTo (this));
  39799. const Point<int> p (x - e2.x, y - e2.y);
  39800. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39801. }
  39802. else
  39803. {
  39804. // to be able to do a drag-and-drop operation, the listbox needs to
  39805. // be inside a component which is also a DragAndDropContainer.
  39806. jassertfalse;
  39807. }
  39808. }
  39809. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39810. {
  39811. (void) existingComponentToUpdate;
  39812. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39813. return 0;
  39814. }
  39815. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39816. {
  39817. }
  39818. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39819. {
  39820. }
  39821. void ListBoxModel::backgroundClicked()
  39822. {
  39823. }
  39824. void ListBoxModel::selectedRowsChanged (int)
  39825. {
  39826. }
  39827. void ListBoxModel::deleteKeyPressed (int)
  39828. {
  39829. }
  39830. void ListBoxModel::returnKeyPressed (int)
  39831. {
  39832. }
  39833. void ListBoxModel::listWasScrolled()
  39834. {
  39835. }
  39836. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39837. {
  39838. return String::empty;
  39839. }
  39840. const String ListBoxModel::getTooltipForRow (int)
  39841. {
  39842. return String::empty;
  39843. }
  39844. END_JUCE_NAMESPACE
  39845. /*** End of inlined file: juce_ListBox.cpp ***/
  39846. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39847. BEGIN_JUCE_NAMESPACE
  39848. ProgressBar::ProgressBar (double& progress_)
  39849. : progress (progress_),
  39850. displayPercentage (true),
  39851. lastCallbackTime (0)
  39852. {
  39853. currentValue = jlimit (0.0, 1.0, progress);
  39854. }
  39855. ProgressBar::~ProgressBar()
  39856. {
  39857. }
  39858. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39859. {
  39860. displayPercentage = shouldDisplayPercentage;
  39861. repaint();
  39862. }
  39863. void ProgressBar::setTextToDisplay (const String& text)
  39864. {
  39865. displayPercentage = false;
  39866. displayedMessage = text;
  39867. }
  39868. void ProgressBar::lookAndFeelChanged()
  39869. {
  39870. setOpaque (findColour (backgroundColourId).isOpaque());
  39871. }
  39872. void ProgressBar::colourChanged()
  39873. {
  39874. lookAndFeelChanged();
  39875. }
  39876. void ProgressBar::paint (Graphics& g)
  39877. {
  39878. String text;
  39879. if (displayPercentage)
  39880. {
  39881. if (currentValue >= 0 && currentValue <= 1.0)
  39882. text << roundToInt (currentValue * 100.0) << '%';
  39883. }
  39884. else
  39885. {
  39886. text = displayedMessage;
  39887. }
  39888. getLookAndFeel().drawProgressBar (g, *this,
  39889. getWidth(), getHeight(),
  39890. currentValue, text);
  39891. }
  39892. void ProgressBar::visibilityChanged()
  39893. {
  39894. if (isVisible())
  39895. startTimer (30);
  39896. else
  39897. stopTimer();
  39898. }
  39899. void ProgressBar::timerCallback()
  39900. {
  39901. double newProgress = progress;
  39902. const uint32 now = Time::getMillisecondCounter();
  39903. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39904. lastCallbackTime = now;
  39905. if (currentValue != newProgress
  39906. || newProgress < 0 || newProgress >= 1.0
  39907. || currentMessage != displayedMessage)
  39908. {
  39909. if (currentValue < newProgress
  39910. && newProgress >= 0 && newProgress < 1.0
  39911. && currentValue >= 0 && currentValue < 1.0)
  39912. {
  39913. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39914. newProgress);
  39915. }
  39916. currentValue = newProgress;
  39917. currentMessage = displayedMessage;
  39918. repaint();
  39919. }
  39920. }
  39921. END_JUCE_NAMESPACE
  39922. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39923. /*** Start of inlined file: juce_Slider.cpp ***/
  39924. BEGIN_JUCE_NAMESPACE
  39925. class SliderPopupDisplayComponent : public BubbleComponent
  39926. {
  39927. public:
  39928. SliderPopupDisplayComponent (Slider* const owner_)
  39929. : owner (owner_),
  39930. font (15.0f, Font::bold)
  39931. {
  39932. setAlwaysOnTop (true);
  39933. }
  39934. ~SliderPopupDisplayComponent()
  39935. {
  39936. }
  39937. void paintContent (Graphics& g, int w, int h)
  39938. {
  39939. g.setFont (font);
  39940. g.setColour (Colours::black);
  39941. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39942. }
  39943. void getContentSize (int& w, int& h)
  39944. {
  39945. w = font.getStringWidth (text) + 18;
  39946. h = (int) (font.getHeight() * 1.6f);
  39947. }
  39948. void updatePosition (const String& newText)
  39949. {
  39950. if (text != newText)
  39951. {
  39952. text = newText;
  39953. repaint();
  39954. }
  39955. BubbleComponent::setPosition (owner);
  39956. }
  39957. juce_UseDebuggingNewOperator
  39958. private:
  39959. Slider* owner;
  39960. Font font;
  39961. String text;
  39962. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39963. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39964. };
  39965. Slider::Slider (const String& name)
  39966. : Component (name),
  39967. lastCurrentValue (0),
  39968. lastValueMin (0),
  39969. lastValueMax (0),
  39970. minimum (0),
  39971. maximum (10),
  39972. interval (0),
  39973. skewFactor (1.0),
  39974. velocityModeSensitivity (1.0),
  39975. velocityModeOffset (0.0),
  39976. velocityModeThreshold (1),
  39977. rotaryStart (float_Pi * 1.2f),
  39978. rotaryEnd (float_Pi * 2.8f),
  39979. numDecimalPlaces (7),
  39980. sliderRegionStart (0),
  39981. sliderRegionSize (1),
  39982. sliderBeingDragged (-1),
  39983. pixelsForFullDragExtent (250),
  39984. style (LinearHorizontal),
  39985. textBoxPos (TextBoxLeft),
  39986. textBoxWidth (80),
  39987. textBoxHeight (20),
  39988. incDecButtonMode (incDecButtonsNotDraggable),
  39989. editableText (true),
  39990. doubleClickToValue (false),
  39991. isVelocityBased (false),
  39992. userKeyOverridesVelocity (true),
  39993. rotaryStop (true),
  39994. incDecButtonsSideBySide (false),
  39995. sendChangeOnlyOnRelease (false),
  39996. popupDisplayEnabled (false),
  39997. menuEnabled (false),
  39998. menuShown (false),
  39999. scrollWheelEnabled (true),
  40000. snapsToMousePos (true),
  40001. valueBox (0),
  40002. incButton (0),
  40003. decButton (0),
  40004. popupDisplay (0),
  40005. parentForPopupDisplay (0)
  40006. {
  40007. setWantsKeyboardFocus (false);
  40008. setRepaintsOnMouseActivity (true);
  40009. lookAndFeelChanged();
  40010. updateText();
  40011. currentValue.addListener (this);
  40012. valueMin.addListener (this);
  40013. valueMax.addListener (this);
  40014. }
  40015. Slider::~Slider()
  40016. {
  40017. currentValue.removeListener (this);
  40018. valueMin.removeListener (this);
  40019. valueMax.removeListener (this);
  40020. popupDisplay = 0;
  40021. deleteAllChildren();
  40022. }
  40023. void Slider::handleAsyncUpdate()
  40024. {
  40025. cancelPendingUpdate();
  40026. Component::BailOutChecker checker (this);
  40027. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  40028. }
  40029. void Slider::sendDragStart()
  40030. {
  40031. startedDragging();
  40032. Component::BailOutChecker checker (this);
  40033. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  40034. }
  40035. void Slider::sendDragEnd()
  40036. {
  40037. stoppedDragging();
  40038. sliderBeingDragged = -1;
  40039. Component::BailOutChecker checker (this);
  40040. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  40041. }
  40042. void Slider::addListener (Listener* const listener)
  40043. {
  40044. listeners.add (listener);
  40045. }
  40046. void Slider::removeListener (Listener* const listener)
  40047. {
  40048. listeners.remove (listener);
  40049. }
  40050. void Slider::setSliderStyle (const SliderStyle newStyle)
  40051. {
  40052. if (style != newStyle)
  40053. {
  40054. style = newStyle;
  40055. repaint();
  40056. lookAndFeelChanged();
  40057. }
  40058. }
  40059. void Slider::setRotaryParameters (const float startAngleRadians,
  40060. const float endAngleRadians,
  40061. const bool stopAtEnd)
  40062. {
  40063. // make sure the values are sensible..
  40064. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40065. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40066. jassert (rotaryStart < rotaryEnd);
  40067. rotaryStart = startAngleRadians;
  40068. rotaryEnd = endAngleRadians;
  40069. rotaryStop = stopAtEnd;
  40070. }
  40071. void Slider::setVelocityBasedMode (const bool velBased)
  40072. {
  40073. isVelocityBased = velBased;
  40074. }
  40075. void Slider::setVelocityModeParameters (const double sensitivity,
  40076. const int threshold,
  40077. const double offset,
  40078. const bool userCanPressKeyToSwapMode)
  40079. {
  40080. jassert (threshold >= 0);
  40081. jassert (sensitivity > 0);
  40082. jassert (offset >= 0);
  40083. velocityModeSensitivity = sensitivity;
  40084. velocityModeOffset = offset;
  40085. velocityModeThreshold = threshold;
  40086. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40087. }
  40088. void Slider::setSkewFactor (const double factor)
  40089. {
  40090. skewFactor = factor;
  40091. }
  40092. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40093. {
  40094. if (maximum > minimum)
  40095. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40096. / (maximum - minimum));
  40097. }
  40098. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40099. {
  40100. jassert (distanceForFullScaleDrag > 0);
  40101. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40102. }
  40103. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40104. {
  40105. if (incDecButtonMode != mode)
  40106. {
  40107. incDecButtonMode = mode;
  40108. lookAndFeelChanged();
  40109. }
  40110. }
  40111. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40112. const bool isReadOnly,
  40113. const int textEntryBoxWidth,
  40114. const int textEntryBoxHeight)
  40115. {
  40116. if (textBoxPos != newPosition
  40117. || editableText != (! isReadOnly)
  40118. || textBoxWidth != textEntryBoxWidth
  40119. || textBoxHeight != textEntryBoxHeight)
  40120. {
  40121. textBoxPos = newPosition;
  40122. editableText = ! isReadOnly;
  40123. textBoxWidth = textEntryBoxWidth;
  40124. textBoxHeight = textEntryBoxHeight;
  40125. repaint();
  40126. lookAndFeelChanged();
  40127. }
  40128. }
  40129. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40130. {
  40131. editableText = shouldBeEditable;
  40132. if (valueBox != 0)
  40133. valueBox->setEditable (shouldBeEditable && isEnabled());
  40134. }
  40135. void Slider::showTextBox()
  40136. {
  40137. jassert (editableText); // this should probably be avoided in read-only sliders.
  40138. if (valueBox != 0)
  40139. valueBox->showEditor();
  40140. }
  40141. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40142. {
  40143. if (valueBox != 0)
  40144. {
  40145. valueBox->hideEditor (discardCurrentEditorContents);
  40146. if (discardCurrentEditorContents)
  40147. updateText();
  40148. }
  40149. }
  40150. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40151. {
  40152. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40153. }
  40154. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40155. {
  40156. snapsToMousePos = shouldSnapToMouse;
  40157. }
  40158. void Slider::setPopupDisplayEnabled (const bool enabled,
  40159. Component* const parentComponentToUse)
  40160. {
  40161. popupDisplayEnabled = enabled;
  40162. parentForPopupDisplay = parentComponentToUse;
  40163. }
  40164. void Slider::colourChanged()
  40165. {
  40166. lookAndFeelChanged();
  40167. }
  40168. void Slider::lookAndFeelChanged()
  40169. {
  40170. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40171. : getTextFromValue (currentValue.getValue()));
  40172. deleteAllChildren();
  40173. valueBox = 0;
  40174. LookAndFeel& lf = getLookAndFeel();
  40175. if (textBoxPos != NoTextBox)
  40176. {
  40177. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40178. valueBox->setWantsKeyboardFocus (false);
  40179. valueBox->setText (previousTextBoxContent, false);
  40180. valueBox->setEditable (editableText && isEnabled());
  40181. valueBox->addListener (this);
  40182. if (style == LinearBar)
  40183. valueBox->addMouseListener (this, false);
  40184. valueBox->setTooltip (getTooltip());
  40185. }
  40186. if (style == IncDecButtons)
  40187. {
  40188. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40189. incButton->addButtonListener (this);
  40190. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40191. decButton->addButtonListener (this);
  40192. if (incDecButtonMode != incDecButtonsNotDraggable)
  40193. {
  40194. incButton->addMouseListener (this, false);
  40195. decButton->addMouseListener (this, false);
  40196. }
  40197. else
  40198. {
  40199. incButton->setRepeatSpeed (300, 100, 20);
  40200. incButton->addMouseListener (decButton, false);
  40201. decButton->setRepeatSpeed (300, 100, 20);
  40202. decButton->addMouseListener (incButton, false);
  40203. }
  40204. incButton->setTooltip (getTooltip());
  40205. decButton->setTooltip (getTooltip());
  40206. }
  40207. setComponentEffect (lf.getSliderEffect());
  40208. resized();
  40209. repaint();
  40210. }
  40211. void Slider::setRange (const double newMin,
  40212. const double newMax,
  40213. const double newInt)
  40214. {
  40215. if (minimum != newMin
  40216. || maximum != newMax
  40217. || interval != newInt)
  40218. {
  40219. minimum = newMin;
  40220. maximum = newMax;
  40221. interval = newInt;
  40222. // figure out the number of DPs needed to display all values at this
  40223. // interval setting.
  40224. numDecimalPlaces = 7;
  40225. if (newInt != 0)
  40226. {
  40227. int v = abs ((int) (newInt * 10000000));
  40228. while ((v % 10) == 0)
  40229. {
  40230. --numDecimalPlaces;
  40231. v /= 10;
  40232. }
  40233. }
  40234. // keep the current values inside the new range..
  40235. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40236. {
  40237. setValue (getValue(), false, false);
  40238. }
  40239. else
  40240. {
  40241. setMinValue (getMinValue(), false, false);
  40242. setMaxValue (getMaxValue(), false, false);
  40243. }
  40244. updateText();
  40245. }
  40246. }
  40247. void Slider::triggerChangeMessage (const bool synchronous)
  40248. {
  40249. if (synchronous)
  40250. handleAsyncUpdate();
  40251. else
  40252. triggerAsyncUpdate();
  40253. valueChanged();
  40254. }
  40255. void Slider::valueChanged (Value& value)
  40256. {
  40257. if (value.refersToSameSourceAs (currentValue))
  40258. {
  40259. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40260. setValue (currentValue.getValue(), false, false);
  40261. }
  40262. else if (value.refersToSameSourceAs (valueMin))
  40263. setMinValue (valueMin.getValue(), false, false, true);
  40264. else if (value.refersToSameSourceAs (valueMax))
  40265. setMaxValue (valueMax.getValue(), false, false, true);
  40266. }
  40267. double Slider::getValue() const
  40268. {
  40269. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40270. // methods to get the two values.
  40271. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40272. return currentValue.getValue();
  40273. }
  40274. void Slider::setValue (double newValue,
  40275. const bool sendUpdateMessage,
  40276. const bool sendMessageSynchronously)
  40277. {
  40278. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40279. // methods to set the two values.
  40280. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40281. newValue = constrainedValue (newValue);
  40282. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40283. {
  40284. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40285. newValue = jlimit ((double) valueMin.getValue(),
  40286. (double) valueMax.getValue(),
  40287. newValue);
  40288. }
  40289. if (newValue != lastCurrentValue)
  40290. {
  40291. if (valueBox != 0)
  40292. valueBox->hideEditor (true);
  40293. lastCurrentValue = newValue;
  40294. currentValue = newValue;
  40295. updateText();
  40296. repaint();
  40297. if (popupDisplay != 0)
  40298. {
  40299. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40300. ->updatePosition (getTextFromValue (newValue));
  40301. popupDisplay->repaint();
  40302. }
  40303. if (sendUpdateMessage)
  40304. triggerChangeMessage (sendMessageSynchronously);
  40305. }
  40306. }
  40307. double Slider::getMinValue() const
  40308. {
  40309. // The minimum value only applies to sliders that are in two- or three-value mode.
  40310. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40311. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40312. return valueMin.getValue();
  40313. }
  40314. double Slider::getMaxValue() const
  40315. {
  40316. // The maximum value only applies to sliders that are in two- or three-value mode.
  40317. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40318. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40319. return valueMax.getValue();
  40320. }
  40321. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40322. {
  40323. // The minimum value only applies to sliders that are in two- or three-value mode.
  40324. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40325. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40326. newValue = constrainedValue (newValue);
  40327. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40328. {
  40329. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40330. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40331. newValue = jmin ((double) valueMax.getValue(), newValue);
  40332. }
  40333. else
  40334. {
  40335. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40336. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40337. newValue = jmin (lastCurrentValue, newValue);
  40338. }
  40339. if (lastValueMin != newValue)
  40340. {
  40341. lastValueMin = newValue;
  40342. valueMin = newValue;
  40343. repaint();
  40344. if (popupDisplay != 0)
  40345. {
  40346. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40347. ->updatePosition (getTextFromValue (newValue));
  40348. popupDisplay->repaint();
  40349. }
  40350. if (sendUpdateMessage)
  40351. triggerChangeMessage (sendMessageSynchronously);
  40352. }
  40353. }
  40354. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40355. {
  40356. // The maximum value only applies to sliders that are in two- or three-value mode.
  40357. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40358. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40359. newValue = constrainedValue (newValue);
  40360. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40361. {
  40362. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40363. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40364. newValue = jmax ((double) valueMin.getValue(), newValue);
  40365. }
  40366. else
  40367. {
  40368. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40369. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40370. newValue = jmax (lastCurrentValue, newValue);
  40371. }
  40372. if (lastValueMax != newValue)
  40373. {
  40374. lastValueMax = newValue;
  40375. valueMax = newValue;
  40376. repaint();
  40377. if (popupDisplay != 0)
  40378. {
  40379. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40380. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40381. popupDisplay->repaint();
  40382. }
  40383. if (sendUpdateMessage)
  40384. triggerChangeMessage (sendMessageSynchronously);
  40385. }
  40386. }
  40387. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40388. const double valueToSetOnDoubleClick)
  40389. {
  40390. doubleClickToValue = isDoubleClickEnabled;
  40391. doubleClickReturnValue = valueToSetOnDoubleClick;
  40392. }
  40393. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40394. {
  40395. isEnabled_ = doubleClickToValue;
  40396. return doubleClickReturnValue;
  40397. }
  40398. void Slider::updateText()
  40399. {
  40400. if (valueBox != 0)
  40401. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40402. }
  40403. void Slider::setTextValueSuffix (const String& suffix)
  40404. {
  40405. if (textSuffix != suffix)
  40406. {
  40407. textSuffix = suffix;
  40408. updateText();
  40409. }
  40410. }
  40411. const String Slider::getTextValueSuffix() const
  40412. {
  40413. return textSuffix;
  40414. }
  40415. const String Slider::getTextFromValue (double v)
  40416. {
  40417. if (getNumDecimalPlacesToDisplay() > 0)
  40418. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40419. else
  40420. return String (roundToInt (v)) + getTextValueSuffix();
  40421. }
  40422. double Slider::getValueFromText (const String& text)
  40423. {
  40424. String t (text.trimStart());
  40425. if (t.endsWith (textSuffix))
  40426. t = t.substring (0, t.length() - textSuffix.length());
  40427. while (t.startsWithChar ('+'))
  40428. t = t.substring (1).trimStart();
  40429. return t.initialSectionContainingOnly ("0123456789.,-")
  40430. .getDoubleValue();
  40431. }
  40432. double Slider::proportionOfLengthToValue (double proportion)
  40433. {
  40434. if (skewFactor != 1.0 && proportion > 0.0)
  40435. proportion = exp (log (proportion) / skewFactor);
  40436. return minimum + (maximum - minimum) * proportion;
  40437. }
  40438. double Slider::valueToProportionOfLength (double value)
  40439. {
  40440. const double n = (value - minimum) / (maximum - minimum);
  40441. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40442. }
  40443. double Slider::snapValue (double attemptedValue, const bool)
  40444. {
  40445. return attemptedValue;
  40446. }
  40447. void Slider::startedDragging()
  40448. {
  40449. }
  40450. void Slider::stoppedDragging()
  40451. {
  40452. }
  40453. void Slider::valueChanged()
  40454. {
  40455. }
  40456. void Slider::enablementChanged()
  40457. {
  40458. repaint();
  40459. }
  40460. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40461. {
  40462. menuEnabled = menuEnabled_;
  40463. }
  40464. void Slider::setScrollWheelEnabled (const bool enabled)
  40465. {
  40466. scrollWheelEnabled = enabled;
  40467. }
  40468. void Slider::labelTextChanged (Label* label)
  40469. {
  40470. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40471. if (newValue != (double) currentValue.getValue())
  40472. {
  40473. sendDragStart();
  40474. setValue (newValue, true, true);
  40475. sendDragEnd();
  40476. }
  40477. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40478. }
  40479. void Slider::buttonClicked (Button* button)
  40480. {
  40481. if (style == IncDecButtons)
  40482. {
  40483. sendDragStart();
  40484. if (button == incButton)
  40485. setValue (snapValue (getValue() + interval, false), true, true);
  40486. else if (button == decButton)
  40487. setValue (snapValue (getValue() - interval, false), true, true);
  40488. sendDragEnd();
  40489. }
  40490. }
  40491. double Slider::constrainedValue (double value) const
  40492. {
  40493. if (interval > 0)
  40494. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40495. if (value <= minimum || maximum <= minimum)
  40496. value = minimum;
  40497. else if (value >= maximum)
  40498. value = maximum;
  40499. return value;
  40500. }
  40501. float Slider::getLinearSliderPos (const double value)
  40502. {
  40503. double sliderPosProportional;
  40504. if (maximum > minimum)
  40505. {
  40506. if (value < minimum)
  40507. {
  40508. sliderPosProportional = 0.0;
  40509. }
  40510. else if (value > maximum)
  40511. {
  40512. sliderPosProportional = 1.0;
  40513. }
  40514. else
  40515. {
  40516. sliderPosProportional = valueToProportionOfLength (value);
  40517. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40518. }
  40519. }
  40520. else
  40521. {
  40522. sliderPosProportional = 0.5;
  40523. }
  40524. if (isVertical() || style == IncDecButtons)
  40525. sliderPosProportional = 1.0 - sliderPosProportional;
  40526. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40527. }
  40528. bool Slider::isHorizontal() const
  40529. {
  40530. return style == LinearHorizontal
  40531. || style == LinearBar
  40532. || style == TwoValueHorizontal
  40533. || style == ThreeValueHorizontal;
  40534. }
  40535. bool Slider::isVertical() const
  40536. {
  40537. return style == LinearVertical
  40538. || style == TwoValueVertical
  40539. || style == ThreeValueVertical;
  40540. }
  40541. bool Slider::incDecDragDirectionIsHorizontal() const
  40542. {
  40543. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40544. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40545. }
  40546. float Slider::getPositionOfValue (const double value)
  40547. {
  40548. if (isHorizontal() || isVertical())
  40549. {
  40550. return getLinearSliderPos (value);
  40551. }
  40552. else
  40553. {
  40554. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40555. return 0.0f;
  40556. }
  40557. }
  40558. void Slider::paint (Graphics& g)
  40559. {
  40560. if (style != IncDecButtons)
  40561. {
  40562. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40563. {
  40564. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40565. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40566. getLookAndFeel().drawRotarySlider (g,
  40567. sliderRect.getX(),
  40568. sliderRect.getY(),
  40569. sliderRect.getWidth(),
  40570. sliderRect.getHeight(),
  40571. sliderPos,
  40572. rotaryStart, rotaryEnd,
  40573. *this);
  40574. }
  40575. else
  40576. {
  40577. getLookAndFeel().drawLinearSlider (g,
  40578. sliderRect.getX(),
  40579. sliderRect.getY(),
  40580. sliderRect.getWidth(),
  40581. sliderRect.getHeight(),
  40582. getLinearSliderPos (lastCurrentValue),
  40583. getLinearSliderPos (lastValueMin),
  40584. getLinearSliderPos (lastValueMax),
  40585. style,
  40586. *this);
  40587. }
  40588. if (style == LinearBar && valueBox == 0)
  40589. {
  40590. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40591. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40592. }
  40593. }
  40594. }
  40595. void Slider::resized()
  40596. {
  40597. int minXSpace = 0;
  40598. int minYSpace = 0;
  40599. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40600. minXSpace = 30;
  40601. else
  40602. minYSpace = 15;
  40603. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40604. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40605. if (style == LinearBar)
  40606. {
  40607. if (valueBox != 0)
  40608. valueBox->setBounds (getLocalBounds());
  40609. }
  40610. else
  40611. {
  40612. if (textBoxPos == NoTextBox)
  40613. {
  40614. sliderRect = getLocalBounds();
  40615. }
  40616. else if (textBoxPos == TextBoxLeft)
  40617. {
  40618. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40619. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40620. }
  40621. else if (textBoxPos == TextBoxRight)
  40622. {
  40623. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40624. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40625. }
  40626. else if (textBoxPos == TextBoxAbove)
  40627. {
  40628. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40629. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40630. }
  40631. else if (textBoxPos == TextBoxBelow)
  40632. {
  40633. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40634. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40635. }
  40636. }
  40637. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40638. if (style == LinearBar)
  40639. {
  40640. const int barIndent = 1;
  40641. sliderRegionStart = barIndent;
  40642. sliderRegionSize = getWidth() - barIndent * 2;
  40643. sliderRect.setBounds (sliderRegionStart, barIndent,
  40644. sliderRegionSize, getHeight() - barIndent * 2);
  40645. }
  40646. else if (isHorizontal())
  40647. {
  40648. sliderRegionStart = sliderRect.getX() + indent;
  40649. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40650. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40651. sliderRegionSize, sliderRect.getHeight());
  40652. }
  40653. else if (isVertical())
  40654. {
  40655. sliderRegionStart = sliderRect.getY() + indent;
  40656. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40657. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40658. sliderRect.getWidth(), sliderRegionSize);
  40659. }
  40660. else
  40661. {
  40662. sliderRegionStart = 0;
  40663. sliderRegionSize = 100;
  40664. }
  40665. if (style == IncDecButtons)
  40666. {
  40667. Rectangle<int> buttonRect (sliderRect);
  40668. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40669. buttonRect.expand (-2, 0);
  40670. else
  40671. buttonRect.expand (0, -2);
  40672. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40673. if (incDecButtonsSideBySide)
  40674. {
  40675. decButton->setBounds (buttonRect.getX(),
  40676. buttonRect.getY(),
  40677. buttonRect.getWidth() / 2,
  40678. buttonRect.getHeight());
  40679. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40680. incButton->setBounds (buttonRect.getCentreX(),
  40681. buttonRect.getY(),
  40682. buttonRect.getWidth() / 2,
  40683. buttonRect.getHeight());
  40684. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40685. }
  40686. else
  40687. {
  40688. incButton->setBounds (buttonRect.getX(),
  40689. buttonRect.getY(),
  40690. buttonRect.getWidth(),
  40691. buttonRect.getHeight() / 2);
  40692. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40693. decButton->setBounds (buttonRect.getX(),
  40694. buttonRect.getCentreY(),
  40695. buttonRect.getWidth(),
  40696. buttonRect.getHeight() / 2);
  40697. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40698. }
  40699. }
  40700. }
  40701. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40702. {
  40703. repaint();
  40704. }
  40705. void Slider::mouseDown (const MouseEvent& e)
  40706. {
  40707. mouseWasHidden = false;
  40708. incDecDragged = false;
  40709. mouseXWhenLastDragged = e.x;
  40710. mouseYWhenLastDragged = e.y;
  40711. mouseDragStartX = e.getMouseDownX();
  40712. mouseDragStartY = e.getMouseDownY();
  40713. if (isEnabled())
  40714. {
  40715. if (e.mods.isPopupMenu() && menuEnabled)
  40716. {
  40717. menuShown = true;
  40718. PopupMenu m;
  40719. m.setLookAndFeel (&getLookAndFeel());
  40720. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40721. m.addSeparator();
  40722. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40723. {
  40724. PopupMenu rotaryMenu;
  40725. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40726. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40727. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40728. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40729. }
  40730. const int r = m.show();
  40731. if (r == 1)
  40732. {
  40733. setVelocityBasedMode (! isVelocityBased);
  40734. }
  40735. else if (r == 2)
  40736. {
  40737. setSliderStyle (Rotary);
  40738. }
  40739. else if (r == 3)
  40740. {
  40741. setSliderStyle (RotaryHorizontalDrag);
  40742. }
  40743. else if (r == 4)
  40744. {
  40745. setSliderStyle (RotaryVerticalDrag);
  40746. }
  40747. }
  40748. else if (maximum > minimum)
  40749. {
  40750. menuShown = false;
  40751. if (valueBox != 0)
  40752. valueBox->hideEditor (true);
  40753. sliderBeingDragged = 0;
  40754. if (style == TwoValueHorizontal
  40755. || style == TwoValueVertical
  40756. || style == ThreeValueHorizontal
  40757. || style == ThreeValueVertical)
  40758. {
  40759. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40760. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40761. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40762. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40763. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40764. {
  40765. if (maxPosDistance <= minPosDistance)
  40766. sliderBeingDragged = 2;
  40767. else
  40768. sliderBeingDragged = 1;
  40769. }
  40770. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40771. {
  40772. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40773. sliderBeingDragged = 1;
  40774. else if (normalPosDistance >= maxPosDistance)
  40775. sliderBeingDragged = 2;
  40776. }
  40777. }
  40778. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40779. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40780. * valueToProportionOfLength (currentValue.getValue());
  40781. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40782. : ((sliderBeingDragged == 1) ? valueMin
  40783. : currentValue)).getValue();
  40784. valueOnMouseDown = valueWhenLastDragged;
  40785. if (popupDisplayEnabled)
  40786. {
  40787. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40788. popupDisplay = popup;
  40789. if (parentForPopupDisplay != 0)
  40790. {
  40791. parentForPopupDisplay->addChildComponent (popup);
  40792. }
  40793. else
  40794. {
  40795. popup->addToDesktop (0);
  40796. }
  40797. popup->setVisible (true);
  40798. }
  40799. sendDragStart();
  40800. mouseDrag (e);
  40801. }
  40802. }
  40803. }
  40804. void Slider::mouseUp (const MouseEvent&)
  40805. {
  40806. if (isEnabled()
  40807. && (! menuShown)
  40808. && (maximum > minimum)
  40809. && (style != IncDecButtons || incDecDragged))
  40810. {
  40811. restoreMouseIfHidden();
  40812. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40813. triggerChangeMessage (false);
  40814. sendDragEnd();
  40815. popupDisplay = 0;
  40816. if (style == IncDecButtons)
  40817. {
  40818. incButton->setState (Button::buttonNormal);
  40819. decButton->setState (Button::buttonNormal);
  40820. }
  40821. }
  40822. }
  40823. void Slider::restoreMouseIfHidden()
  40824. {
  40825. if (mouseWasHidden)
  40826. {
  40827. mouseWasHidden = false;
  40828. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40829. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40830. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40831. : ((sliderBeingDragged == 1) ? getMinValue()
  40832. : (double) currentValue.getValue());
  40833. Point<int> mousePos;
  40834. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40835. {
  40836. mousePos = Desktop::getLastMouseDownPosition();
  40837. if (style == RotaryHorizontalDrag)
  40838. {
  40839. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40840. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40841. }
  40842. else
  40843. {
  40844. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40845. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40846. }
  40847. }
  40848. else
  40849. {
  40850. const int pixelPos = (int) getLinearSliderPos (pos);
  40851. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40852. isVertical() ? pixelPos : (getHeight() / 2)));
  40853. }
  40854. Desktop::setMousePosition (mousePos);
  40855. }
  40856. }
  40857. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40858. {
  40859. if (isEnabled()
  40860. && style != IncDecButtons
  40861. && style != Rotary
  40862. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40863. {
  40864. restoreMouseIfHidden();
  40865. }
  40866. }
  40867. static double smallestAngleBetween (double a1, double a2)
  40868. {
  40869. return jmin (std::abs (a1 - a2),
  40870. std::abs (a1 + double_Pi * 2.0 - a2),
  40871. std::abs (a2 + double_Pi * 2.0 - a1));
  40872. }
  40873. void Slider::mouseDrag (const MouseEvent& e)
  40874. {
  40875. if (isEnabled()
  40876. && (! menuShown)
  40877. && (maximum > minimum))
  40878. {
  40879. if (style == Rotary)
  40880. {
  40881. int dx = e.x - sliderRect.getCentreX();
  40882. int dy = e.y - sliderRect.getCentreY();
  40883. if (dx * dx + dy * dy > 25)
  40884. {
  40885. double angle = std::atan2 ((double) dx, (double) -dy);
  40886. while (angle < 0.0)
  40887. angle += double_Pi * 2.0;
  40888. if (rotaryStop && ! e.mouseWasClicked())
  40889. {
  40890. if (std::abs (angle - lastAngle) > double_Pi)
  40891. {
  40892. if (angle >= lastAngle)
  40893. angle -= double_Pi * 2.0;
  40894. else
  40895. angle += double_Pi * 2.0;
  40896. }
  40897. if (angle >= lastAngle)
  40898. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40899. else
  40900. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40901. }
  40902. else
  40903. {
  40904. while (angle < rotaryStart)
  40905. angle += double_Pi * 2.0;
  40906. if (angle > rotaryEnd)
  40907. {
  40908. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40909. angle = rotaryStart;
  40910. else
  40911. angle = rotaryEnd;
  40912. }
  40913. }
  40914. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40915. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40916. lastAngle = angle;
  40917. }
  40918. }
  40919. else
  40920. {
  40921. if (style == LinearBar && e.mouseWasClicked()
  40922. && valueBox != 0 && valueBox->isEditable())
  40923. return;
  40924. if (style == IncDecButtons && ! incDecDragged)
  40925. {
  40926. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40927. return;
  40928. incDecDragged = true;
  40929. mouseDragStartX = e.x;
  40930. mouseDragStartY = e.y;
  40931. }
  40932. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40933. : false))
  40934. || ((maximum - minimum) / sliderRegionSize < interval))
  40935. {
  40936. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40937. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40938. if (style == RotaryHorizontalDrag
  40939. || style == RotaryVerticalDrag
  40940. || style == IncDecButtons
  40941. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40942. && ! snapsToMousePos))
  40943. {
  40944. const int mouseDiff = (style == RotaryHorizontalDrag
  40945. || style == LinearHorizontal
  40946. || style == LinearBar
  40947. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40948. ? e.x - mouseDragStartX
  40949. : mouseDragStartY - e.y;
  40950. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40951. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40952. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40953. if (style == IncDecButtons)
  40954. {
  40955. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40956. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40957. }
  40958. }
  40959. else
  40960. {
  40961. if (isVertical())
  40962. scaledMousePos = 1.0 - scaledMousePos;
  40963. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40964. }
  40965. }
  40966. else
  40967. {
  40968. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40969. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40970. ? e.x - mouseXWhenLastDragged
  40971. : e.y - mouseYWhenLastDragged;
  40972. const double maxSpeed = jmax (200, sliderRegionSize);
  40973. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40974. if (speed != 0)
  40975. {
  40976. speed = 0.2 * velocityModeSensitivity
  40977. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40978. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40979. / maxSpeed))));
  40980. if (mouseDiff < 0)
  40981. speed = -speed;
  40982. if (isVertical() || style == RotaryVerticalDrag
  40983. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40984. speed = -speed;
  40985. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40986. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40987. e.source.enableUnboundedMouseMovement (true, false);
  40988. mouseWasHidden = true;
  40989. }
  40990. }
  40991. }
  40992. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40993. if (sliderBeingDragged == 0)
  40994. {
  40995. setValue (snapValue (valueWhenLastDragged, true),
  40996. ! sendChangeOnlyOnRelease, true);
  40997. }
  40998. else if (sliderBeingDragged == 1)
  40999. {
  41000. setMinValue (snapValue (valueWhenLastDragged, true),
  41001. ! sendChangeOnlyOnRelease, false, true);
  41002. if (e.mods.isShiftDown())
  41003. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  41004. else
  41005. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41006. }
  41007. else
  41008. {
  41009. jassert (sliderBeingDragged == 2);
  41010. setMaxValue (snapValue (valueWhenLastDragged, true),
  41011. ! sendChangeOnlyOnRelease, false, true);
  41012. if (e.mods.isShiftDown())
  41013. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  41014. else
  41015. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41016. }
  41017. mouseXWhenLastDragged = e.x;
  41018. mouseYWhenLastDragged = e.y;
  41019. }
  41020. }
  41021. void Slider::mouseDoubleClick (const MouseEvent&)
  41022. {
  41023. if (doubleClickToValue
  41024. && isEnabled()
  41025. && style != IncDecButtons
  41026. && minimum <= doubleClickReturnValue
  41027. && maximum >= doubleClickReturnValue)
  41028. {
  41029. sendDragStart();
  41030. setValue (doubleClickReturnValue, true, true);
  41031. sendDragEnd();
  41032. }
  41033. }
  41034. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  41035. {
  41036. if (scrollWheelEnabled && isEnabled()
  41037. && style != TwoValueHorizontal
  41038. && style != TwoValueVertical)
  41039. {
  41040. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  41041. {
  41042. if (valueBox != 0)
  41043. valueBox->hideEditor (false);
  41044. const double value = (double) currentValue.getValue();
  41045. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  41046. const double currentPos = valueToProportionOfLength (value);
  41047. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  41048. double delta = (newValue != value)
  41049. ? jmax (std::abs (newValue - value), interval) : 0;
  41050. if (value > newValue)
  41051. delta = -delta;
  41052. sendDragStart();
  41053. setValue (snapValue (value + delta, false), true, true);
  41054. sendDragEnd();
  41055. }
  41056. }
  41057. else
  41058. {
  41059. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  41060. }
  41061. }
  41062. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  41063. {
  41064. }
  41065. void SliderListener::sliderDragEnded (Slider*)
  41066. {
  41067. }
  41068. END_JUCE_NAMESPACE
  41069. /*** End of inlined file: juce_Slider.cpp ***/
  41070. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41071. BEGIN_JUCE_NAMESPACE
  41072. class DragOverlayComp : public Component
  41073. {
  41074. public:
  41075. DragOverlayComp (const Image& image_)
  41076. : image (image_)
  41077. {
  41078. image.duplicateIfShared();
  41079. image.multiplyAllAlphas (0.8f);
  41080. setAlwaysOnTop (true);
  41081. }
  41082. ~DragOverlayComp()
  41083. {
  41084. }
  41085. void paint (Graphics& g)
  41086. {
  41087. g.drawImageAt (image, 0, 0);
  41088. }
  41089. private:
  41090. Image image;
  41091. DragOverlayComp (const DragOverlayComp&);
  41092. DragOverlayComp& operator= (const DragOverlayComp&);
  41093. };
  41094. TableHeaderComponent::TableHeaderComponent()
  41095. : columnsChanged (false),
  41096. columnsResized (false),
  41097. sortChanged (false),
  41098. menuActive (true),
  41099. stretchToFit (false),
  41100. columnIdBeingResized (0),
  41101. columnIdBeingDragged (0),
  41102. columnIdUnderMouse (0),
  41103. lastDeliberateWidth (0)
  41104. {
  41105. }
  41106. TableHeaderComponent::~TableHeaderComponent()
  41107. {
  41108. dragOverlayComp = 0;
  41109. }
  41110. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41111. {
  41112. menuActive = hasMenu;
  41113. }
  41114. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41115. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41116. {
  41117. if (onlyCountVisibleColumns)
  41118. {
  41119. int num = 0;
  41120. for (int i = columns.size(); --i >= 0;)
  41121. if (columns.getUnchecked(i)->isVisible())
  41122. ++num;
  41123. return num;
  41124. }
  41125. else
  41126. {
  41127. return columns.size();
  41128. }
  41129. }
  41130. const String TableHeaderComponent::getColumnName (const int columnId) const
  41131. {
  41132. const ColumnInfo* const ci = getInfoForId (columnId);
  41133. return ci != 0 ? ci->name : String::empty;
  41134. }
  41135. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41136. {
  41137. ColumnInfo* const ci = getInfoForId (columnId);
  41138. if (ci != 0 && ci->name != newName)
  41139. {
  41140. ci->name = newName;
  41141. sendColumnsChanged();
  41142. }
  41143. }
  41144. void TableHeaderComponent::addColumn (const String& columnName,
  41145. const int columnId,
  41146. const int width,
  41147. const int minimumWidth,
  41148. const int maximumWidth,
  41149. const int propertyFlags,
  41150. const int insertIndex)
  41151. {
  41152. // can't have a duplicate or null ID!
  41153. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41154. jassert (width > 0);
  41155. ColumnInfo* const ci = new ColumnInfo();
  41156. ci->name = columnName;
  41157. ci->id = columnId;
  41158. ci->width = width;
  41159. ci->lastDeliberateWidth = width;
  41160. ci->minimumWidth = minimumWidth;
  41161. ci->maximumWidth = maximumWidth;
  41162. if (ci->maximumWidth < 0)
  41163. ci->maximumWidth = std::numeric_limits<int>::max();
  41164. jassert (ci->maximumWidth >= ci->minimumWidth);
  41165. ci->propertyFlags = propertyFlags;
  41166. columns.insert (insertIndex, ci);
  41167. sendColumnsChanged();
  41168. }
  41169. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41170. {
  41171. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41172. if (index >= 0)
  41173. {
  41174. columns.remove (index);
  41175. sortChanged = true;
  41176. sendColumnsChanged();
  41177. }
  41178. }
  41179. void TableHeaderComponent::removeAllColumns()
  41180. {
  41181. if (columns.size() > 0)
  41182. {
  41183. columns.clear();
  41184. sendColumnsChanged();
  41185. }
  41186. }
  41187. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41188. {
  41189. const int currentIndex = getIndexOfColumnId (columnId, false);
  41190. newIndex = visibleIndexToTotalIndex (newIndex);
  41191. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41192. {
  41193. columns.move (currentIndex, newIndex);
  41194. sendColumnsChanged();
  41195. }
  41196. }
  41197. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41198. {
  41199. const ColumnInfo* const ci = getInfoForId (columnId);
  41200. return ci != 0 ? ci->width : 0;
  41201. }
  41202. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41203. {
  41204. ColumnInfo* const ci = getInfoForId (columnId);
  41205. if (ci != 0 && ci->width != newWidth)
  41206. {
  41207. const int numColumns = getNumColumns (true);
  41208. ci->lastDeliberateWidth = ci->width
  41209. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41210. if (stretchToFit)
  41211. {
  41212. const int index = getIndexOfColumnId (columnId, true) + 1;
  41213. if (((unsigned int) index) < (unsigned int) numColumns)
  41214. {
  41215. const int x = getColumnPosition (index).getX();
  41216. if (lastDeliberateWidth == 0)
  41217. lastDeliberateWidth = getTotalWidth();
  41218. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41219. }
  41220. }
  41221. repaint();
  41222. columnsResized = true;
  41223. triggerAsyncUpdate();
  41224. }
  41225. }
  41226. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41227. {
  41228. int n = 0;
  41229. for (int i = 0; i < columns.size(); ++i)
  41230. {
  41231. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41232. {
  41233. if (columns.getUnchecked(i)->id == columnId)
  41234. return n;
  41235. ++n;
  41236. }
  41237. }
  41238. return -1;
  41239. }
  41240. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41241. {
  41242. if (onlyCountVisibleColumns)
  41243. index = visibleIndexToTotalIndex (index);
  41244. const ColumnInfo* const ci = columns [index];
  41245. return (ci != 0) ? ci->id : 0;
  41246. }
  41247. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41248. {
  41249. int x = 0, width = 0, n = 0;
  41250. for (int i = 0; i < columns.size(); ++i)
  41251. {
  41252. x += width;
  41253. if (columns.getUnchecked(i)->isVisible())
  41254. {
  41255. width = columns.getUnchecked(i)->width;
  41256. if (n++ == index)
  41257. break;
  41258. }
  41259. else
  41260. {
  41261. width = 0;
  41262. }
  41263. }
  41264. return Rectangle<int> (x, 0, width, getHeight());
  41265. }
  41266. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41267. {
  41268. if (xToFind >= 0)
  41269. {
  41270. int x = 0;
  41271. for (int i = 0; i < columns.size(); ++i)
  41272. {
  41273. const ColumnInfo* const ci = columns.getUnchecked(i);
  41274. if (ci->isVisible())
  41275. {
  41276. x += ci->width;
  41277. if (xToFind < x)
  41278. return ci->id;
  41279. }
  41280. }
  41281. }
  41282. return 0;
  41283. }
  41284. int TableHeaderComponent::getTotalWidth() const
  41285. {
  41286. int w = 0;
  41287. for (int i = columns.size(); --i >= 0;)
  41288. if (columns.getUnchecked(i)->isVisible())
  41289. w += columns.getUnchecked(i)->width;
  41290. return w;
  41291. }
  41292. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41293. {
  41294. stretchToFit = shouldStretchToFit;
  41295. lastDeliberateWidth = getTotalWidth();
  41296. resized();
  41297. }
  41298. bool TableHeaderComponent::isStretchToFitActive() const
  41299. {
  41300. return stretchToFit;
  41301. }
  41302. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41303. {
  41304. if (stretchToFit && getWidth() > 0
  41305. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41306. {
  41307. lastDeliberateWidth = targetTotalWidth;
  41308. resizeColumnsToFit (0, targetTotalWidth);
  41309. }
  41310. }
  41311. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41312. {
  41313. targetTotalWidth = jmax (targetTotalWidth, 0);
  41314. StretchableObjectResizer sor;
  41315. int i;
  41316. for (i = firstColumnIndex; i < columns.size(); ++i)
  41317. {
  41318. ColumnInfo* const ci = columns.getUnchecked(i);
  41319. if (ci->isVisible())
  41320. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41321. }
  41322. sor.resizeToFit (targetTotalWidth);
  41323. int visIndex = 0;
  41324. for (i = firstColumnIndex; i < columns.size(); ++i)
  41325. {
  41326. ColumnInfo* const ci = columns.getUnchecked(i);
  41327. if (ci->isVisible())
  41328. {
  41329. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41330. (int) std::floor (sor.getItemSize (visIndex++)));
  41331. if (newWidth != ci->width)
  41332. {
  41333. ci->width = newWidth;
  41334. repaint();
  41335. columnsResized = true;
  41336. triggerAsyncUpdate();
  41337. }
  41338. }
  41339. }
  41340. }
  41341. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41342. {
  41343. ColumnInfo* const ci = getInfoForId (columnId);
  41344. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41345. {
  41346. if (shouldBeVisible)
  41347. ci->propertyFlags |= visible;
  41348. else
  41349. ci->propertyFlags &= ~visible;
  41350. sendColumnsChanged();
  41351. resized();
  41352. }
  41353. }
  41354. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41355. {
  41356. const ColumnInfo* const ci = getInfoForId (columnId);
  41357. return ci != 0 && ci->isVisible();
  41358. }
  41359. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41360. {
  41361. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41362. {
  41363. for (int i = columns.size(); --i >= 0;)
  41364. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41365. ColumnInfo* const ci = getInfoForId (columnId);
  41366. if (ci != 0)
  41367. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41368. reSortTable();
  41369. }
  41370. }
  41371. int TableHeaderComponent::getSortColumnId() const
  41372. {
  41373. for (int i = columns.size(); --i >= 0;)
  41374. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41375. return columns.getUnchecked(i)->id;
  41376. return 0;
  41377. }
  41378. bool TableHeaderComponent::isSortedForwards() const
  41379. {
  41380. for (int i = columns.size(); --i >= 0;)
  41381. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41382. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41383. return true;
  41384. }
  41385. void TableHeaderComponent::reSortTable()
  41386. {
  41387. sortChanged = true;
  41388. repaint();
  41389. triggerAsyncUpdate();
  41390. }
  41391. const String TableHeaderComponent::toString() const
  41392. {
  41393. String s;
  41394. XmlElement doc ("TABLELAYOUT");
  41395. doc.setAttribute ("sortedCol", getSortColumnId());
  41396. doc.setAttribute ("sortForwards", isSortedForwards());
  41397. for (int i = 0; i < columns.size(); ++i)
  41398. {
  41399. const ColumnInfo* const ci = columns.getUnchecked (i);
  41400. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41401. e->setAttribute ("id", ci->id);
  41402. e->setAttribute ("visible", ci->isVisible());
  41403. e->setAttribute ("width", ci->width);
  41404. }
  41405. return doc.createDocument (String::empty, true, false);
  41406. }
  41407. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41408. {
  41409. XmlDocument doc (storedVersion);
  41410. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41411. int index = 0;
  41412. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41413. {
  41414. forEachXmlChildElement (*storedXml, col)
  41415. {
  41416. const int tabId = col->getIntAttribute ("id");
  41417. ColumnInfo* const ci = getInfoForId (tabId);
  41418. if (ci != 0)
  41419. {
  41420. columns.move (columns.indexOf (ci), index);
  41421. ci->width = col->getIntAttribute ("width");
  41422. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41423. }
  41424. ++index;
  41425. }
  41426. columnsResized = true;
  41427. sendColumnsChanged();
  41428. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41429. storedXml->getBoolAttribute ("sortForwards", true));
  41430. }
  41431. }
  41432. void TableHeaderComponent::addListener (Listener* const newListener)
  41433. {
  41434. listeners.addIfNotAlreadyThere (newListener);
  41435. }
  41436. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41437. {
  41438. listeners.removeValue (listenerToRemove);
  41439. }
  41440. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41441. {
  41442. const ColumnInfo* const ci = getInfoForId (columnId);
  41443. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41444. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41445. }
  41446. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41447. {
  41448. for (int i = 0; i < columns.size(); ++i)
  41449. {
  41450. const ColumnInfo* const ci = columns.getUnchecked(i);
  41451. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41452. menu.addItem (ci->id, ci->name,
  41453. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41454. isColumnVisible (ci->id));
  41455. }
  41456. }
  41457. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41458. {
  41459. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41460. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41461. }
  41462. void TableHeaderComponent::paint (Graphics& g)
  41463. {
  41464. LookAndFeel& lf = getLookAndFeel();
  41465. lf.drawTableHeaderBackground (g, *this);
  41466. const Rectangle<int> clip (g.getClipBounds());
  41467. int x = 0;
  41468. for (int i = 0; i < columns.size(); ++i)
  41469. {
  41470. const ColumnInfo* const ci = columns.getUnchecked(i);
  41471. if (ci->isVisible())
  41472. {
  41473. if (x + ci->width > clip.getX()
  41474. && (ci->id != columnIdBeingDragged
  41475. || dragOverlayComp == 0
  41476. || ! dragOverlayComp->isVisible()))
  41477. {
  41478. g.saveState();
  41479. g.setOrigin (x, 0);
  41480. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41481. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41482. ci->id == columnIdUnderMouse,
  41483. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41484. ci->propertyFlags);
  41485. g.restoreState();
  41486. }
  41487. x += ci->width;
  41488. if (x >= clip.getRight())
  41489. break;
  41490. }
  41491. }
  41492. }
  41493. void TableHeaderComponent::resized()
  41494. {
  41495. }
  41496. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41497. {
  41498. updateColumnUnderMouse (e.x, e.y);
  41499. }
  41500. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41501. {
  41502. updateColumnUnderMouse (e.x, e.y);
  41503. }
  41504. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41505. {
  41506. updateColumnUnderMouse (e.x, e.y);
  41507. }
  41508. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41509. {
  41510. repaint();
  41511. columnIdBeingResized = 0;
  41512. columnIdBeingDragged = 0;
  41513. if (columnIdUnderMouse != 0)
  41514. {
  41515. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41516. if (e.mods.isPopupMenu())
  41517. columnClicked (columnIdUnderMouse, e.mods);
  41518. }
  41519. if (menuActive && e.mods.isPopupMenu())
  41520. showColumnChooserMenu (columnIdUnderMouse);
  41521. }
  41522. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41523. {
  41524. if (columnIdBeingResized == 0
  41525. && columnIdBeingDragged == 0
  41526. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41527. {
  41528. dragOverlayComp = 0;
  41529. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41530. if (columnIdBeingResized != 0)
  41531. {
  41532. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41533. initialColumnWidth = ci->width;
  41534. }
  41535. else
  41536. {
  41537. beginDrag (e);
  41538. }
  41539. }
  41540. if (columnIdBeingResized != 0)
  41541. {
  41542. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41543. if (ci != 0)
  41544. {
  41545. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41546. initialColumnWidth + e.getDistanceFromDragStartX());
  41547. if (stretchToFit)
  41548. {
  41549. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41550. int minWidthOnRight = 0;
  41551. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41552. if (columns.getUnchecked (i)->isVisible())
  41553. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41554. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41555. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41556. }
  41557. setColumnWidth (columnIdBeingResized, w);
  41558. }
  41559. }
  41560. else if (columnIdBeingDragged != 0)
  41561. {
  41562. if (e.y >= -50 && e.y < getHeight() + 50)
  41563. {
  41564. if (dragOverlayComp != 0)
  41565. {
  41566. dragOverlayComp->setVisible (true);
  41567. dragOverlayComp->setBounds (jlimit (0,
  41568. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41569. e.x - draggingColumnOffset),
  41570. 0,
  41571. dragOverlayComp->getWidth(),
  41572. getHeight());
  41573. for (int i = columns.size(); --i >= 0;)
  41574. {
  41575. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41576. int newIndex = currentIndex;
  41577. if (newIndex > 0)
  41578. {
  41579. // if the previous column isn't draggable, we can't move our column
  41580. // past it, because that'd change the undraggable column's position..
  41581. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41582. if ((previous->propertyFlags & draggable) != 0)
  41583. {
  41584. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41585. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41586. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41587. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41588. {
  41589. --newIndex;
  41590. }
  41591. }
  41592. }
  41593. if (newIndex < columns.size() - 1)
  41594. {
  41595. // if the next column isn't draggable, we can't move our column
  41596. // past it, because that'd change the undraggable column's position..
  41597. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41598. if ((nextCol->propertyFlags & draggable) != 0)
  41599. {
  41600. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41601. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41602. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41603. > abs (dragOverlayComp->getRight() - rightOfNext))
  41604. {
  41605. ++newIndex;
  41606. }
  41607. }
  41608. }
  41609. if (newIndex != currentIndex)
  41610. moveColumn (columnIdBeingDragged, newIndex);
  41611. else
  41612. break;
  41613. }
  41614. }
  41615. }
  41616. else
  41617. {
  41618. endDrag (draggingColumnOriginalIndex);
  41619. }
  41620. }
  41621. }
  41622. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41623. {
  41624. if (columnIdBeingDragged == 0)
  41625. {
  41626. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41627. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41628. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41629. {
  41630. columnIdBeingDragged = 0;
  41631. }
  41632. else
  41633. {
  41634. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41635. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41636. const int temp = columnIdBeingDragged;
  41637. columnIdBeingDragged = 0;
  41638. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41639. columnIdBeingDragged = temp;
  41640. dragOverlayComp->setBounds (columnRect);
  41641. for (int i = listeners.size(); --i >= 0;)
  41642. {
  41643. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41644. i = jmin (i, listeners.size() - 1);
  41645. }
  41646. }
  41647. }
  41648. }
  41649. void TableHeaderComponent::endDrag (const int finalIndex)
  41650. {
  41651. if (columnIdBeingDragged != 0)
  41652. {
  41653. moveColumn (columnIdBeingDragged, finalIndex);
  41654. columnIdBeingDragged = 0;
  41655. repaint();
  41656. for (int i = listeners.size(); --i >= 0;)
  41657. {
  41658. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41659. i = jmin (i, listeners.size() - 1);
  41660. }
  41661. }
  41662. }
  41663. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41664. {
  41665. mouseDrag (e);
  41666. for (int i = columns.size(); --i >= 0;)
  41667. if (columns.getUnchecked (i)->isVisible())
  41668. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41669. columnIdBeingResized = 0;
  41670. repaint();
  41671. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41672. updateColumnUnderMouse (e.x, e.y);
  41673. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41674. columnClicked (columnIdUnderMouse, e.mods);
  41675. dragOverlayComp = 0;
  41676. }
  41677. const MouseCursor TableHeaderComponent::getMouseCursor()
  41678. {
  41679. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41680. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41681. return Component::getMouseCursor();
  41682. }
  41683. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41684. {
  41685. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41686. }
  41687. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41688. {
  41689. for (int i = columns.size(); --i >= 0;)
  41690. if (columns.getUnchecked(i)->id == id)
  41691. return columns.getUnchecked(i);
  41692. return 0;
  41693. }
  41694. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41695. {
  41696. int n = 0;
  41697. for (int i = 0; i < columns.size(); ++i)
  41698. {
  41699. if (columns.getUnchecked(i)->isVisible())
  41700. {
  41701. if (n == visibleIndex)
  41702. return i;
  41703. ++n;
  41704. }
  41705. }
  41706. return -1;
  41707. }
  41708. void TableHeaderComponent::sendColumnsChanged()
  41709. {
  41710. if (stretchToFit && lastDeliberateWidth > 0)
  41711. resizeAllColumnsToFit (lastDeliberateWidth);
  41712. repaint();
  41713. columnsChanged = true;
  41714. triggerAsyncUpdate();
  41715. }
  41716. void TableHeaderComponent::handleAsyncUpdate()
  41717. {
  41718. const bool changed = columnsChanged || sortChanged;
  41719. const bool sized = columnsResized || changed;
  41720. const bool sorted = sortChanged;
  41721. columnsChanged = false;
  41722. columnsResized = false;
  41723. sortChanged = false;
  41724. if (sorted)
  41725. {
  41726. for (int i = listeners.size(); --i >= 0;)
  41727. {
  41728. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41729. i = jmin (i, listeners.size() - 1);
  41730. }
  41731. }
  41732. if (changed)
  41733. {
  41734. for (int i = listeners.size(); --i >= 0;)
  41735. {
  41736. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41737. i = jmin (i, listeners.size() - 1);
  41738. }
  41739. }
  41740. if (sized)
  41741. {
  41742. for (int i = listeners.size(); --i >= 0;)
  41743. {
  41744. listeners.getUnchecked(i)->tableColumnsResized (this);
  41745. i = jmin (i, listeners.size() - 1);
  41746. }
  41747. }
  41748. }
  41749. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41750. {
  41751. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41752. {
  41753. const int draggableDistance = 3;
  41754. int x = 0;
  41755. for (int i = 0; i < columns.size(); ++i)
  41756. {
  41757. const ColumnInfo* const ci = columns.getUnchecked(i);
  41758. if (ci->isVisible())
  41759. {
  41760. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41761. && (ci->propertyFlags & resizable) != 0)
  41762. return ci->id;
  41763. x += ci->width;
  41764. }
  41765. }
  41766. }
  41767. return 0;
  41768. }
  41769. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41770. {
  41771. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41772. ? getColumnIdAtX (x) : 0;
  41773. if (newCol != columnIdUnderMouse)
  41774. {
  41775. columnIdUnderMouse = newCol;
  41776. repaint();
  41777. }
  41778. }
  41779. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41780. {
  41781. PopupMenu m;
  41782. addMenuItems (m, columnIdClicked);
  41783. if (m.getNumItems() > 0)
  41784. {
  41785. m.setLookAndFeel (&getLookAndFeel());
  41786. const int result = m.show();
  41787. if (result != 0)
  41788. reactToMenuItem (result, columnIdClicked);
  41789. }
  41790. }
  41791. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41792. {
  41793. }
  41794. END_JUCE_NAMESPACE
  41795. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41796. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41797. BEGIN_JUCE_NAMESPACE
  41798. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41799. class TableListRowComp : public Component,
  41800. public TooltipClient
  41801. {
  41802. public:
  41803. TableListRowComp (TableListBox& owner_)
  41804. : owner (owner_),
  41805. row (-1),
  41806. isSelected (false)
  41807. {
  41808. }
  41809. ~TableListRowComp()
  41810. {
  41811. deleteAllChildren();
  41812. }
  41813. void paint (Graphics& g)
  41814. {
  41815. TableListBoxModel* const model = owner.getModel();
  41816. if (model != 0)
  41817. {
  41818. const TableHeaderComponent* const header = owner.getHeader();
  41819. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41820. const int numColumns = header->getNumColumns (true);
  41821. for (int i = 0; i < numColumns; ++i)
  41822. {
  41823. if (! columnsWithComponents [i])
  41824. {
  41825. const int columnId = header->getColumnIdOfIndex (i, true);
  41826. Rectangle<int> columnRect (header->getColumnPosition (i));
  41827. columnRect.setSize (columnRect.getWidth(), getHeight());
  41828. g.saveState();
  41829. g.reduceClipRegion (columnRect);
  41830. g.setOrigin (columnRect.getX(), 0);
  41831. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41832. g.restoreState();
  41833. }
  41834. }
  41835. }
  41836. }
  41837. void update (const int newRow, const bool isNowSelected)
  41838. {
  41839. if (newRow != row || isNowSelected != isSelected)
  41840. {
  41841. row = newRow;
  41842. isSelected = isNowSelected;
  41843. repaint();
  41844. deleteAllChildren();
  41845. }
  41846. if (row < owner.getNumRows())
  41847. {
  41848. jassert (row >= 0);
  41849. const Identifier tagPropertyName ("_tableLastUseNum");
  41850. const int newTag = Random::getSystemRandom().nextInt();
  41851. const TableHeaderComponent* const header = owner.getHeader();
  41852. const int numColumns = header->getNumColumns (true);
  41853. columnsWithComponents.clear();
  41854. if (owner.getModel() != 0)
  41855. {
  41856. for (int i = 0; i < numColumns; ++i)
  41857. {
  41858. const int columnId = header->getColumnIdOfIndex (i, true);
  41859. Component* const newComp
  41860. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41861. findChildComponentForColumn (columnId));
  41862. if (newComp != 0)
  41863. {
  41864. addAndMakeVisible (newComp);
  41865. newComp->getProperties().set (tagPropertyName, newTag);
  41866. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41867. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41868. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41869. columnsWithComponents.setBit (i);
  41870. }
  41871. }
  41872. }
  41873. for (int i = getNumChildComponents(); --i >= 0;)
  41874. {
  41875. Component* const c = getChildComponent (i);
  41876. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41877. delete c;
  41878. }
  41879. }
  41880. else
  41881. {
  41882. columnsWithComponents.clear();
  41883. deleteAllChildren();
  41884. }
  41885. }
  41886. void resized()
  41887. {
  41888. for (int i = getNumChildComponents(); --i >= 0;)
  41889. {
  41890. Component* const c = getChildComponent (i);
  41891. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41892. if (columnId != 0)
  41893. {
  41894. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41895. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41896. }
  41897. }
  41898. }
  41899. void mouseDown (const MouseEvent& e)
  41900. {
  41901. isDragging = false;
  41902. selectRowOnMouseUp = false;
  41903. if (isEnabled())
  41904. {
  41905. if (! isSelected)
  41906. {
  41907. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41908. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41909. if (columnId != 0 && owner.getModel() != 0)
  41910. owner.getModel()->cellClicked (row, columnId, e);
  41911. }
  41912. else
  41913. {
  41914. selectRowOnMouseUp = true;
  41915. }
  41916. }
  41917. }
  41918. void mouseDrag (const MouseEvent& e)
  41919. {
  41920. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41921. {
  41922. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41923. if (selectedRows.size() > 0)
  41924. {
  41925. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41926. if (dragDescription.isNotEmpty())
  41927. {
  41928. isDragging = true;
  41929. owner.startDragAndDrop (e, dragDescription);
  41930. }
  41931. }
  41932. }
  41933. }
  41934. void mouseUp (const MouseEvent& e)
  41935. {
  41936. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41937. {
  41938. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41939. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41940. if (columnId != 0 && owner.getModel() != 0)
  41941. owner.getModel()->cellClicked (row, columnId, e);
  41942. }
  41943. }
  41944. void mouseDoubleClick (const MouseEvent& e)
  41945. {
  41946. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41947. if (columnId != 0 && owner.getModel() != 0)
  41948. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41949. }
  41950. const String getTooltip()
  41951. {
  41952. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41953. if (columnId != 0 && owner.getModel() != 0)
  41954. return owner.getModel()->getCellTooltip (row, columnId);
  41955. return String::empty;
  41956. }
  41957. Component* findChildComponentForColumn (const int columnId) const
  41958. {
  41959. for (int i = getNumChildComponents(); --i >= 0;)
  41960. {
  41961. Component* const c = getChildComponent (i);
  41962. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41963. return c;
  41964. }
  41965. return 0;
  41966. }
  41967. juce_UseDebuggingNewOperator
  41968. private:
  41969. TableListBox& owner;
  41970. int row;
  41971. bool isSelected, isDragging, selectRowOnMouseUp;
  41972. BigInteger columnsWithComponents;
  41973. TableListRowComp (const TableListRowComp&);
  41974. TableListRowComp& operator= (const TableListRowComp&);
  41975. };
  41976. class TableListBoxHeader : public TableHeaderComponent
  41977. {
  41978. public:
  41979. TableListBoxHeader (TableListBox& owner_)
  41980. : owner (owner_)
  41981. {
  41982. }
  41983. ~TableListBoxHeader()
  41984. {
  41985. }
  41986. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41987. {
  41988. if (owner.isAutoSizeMenuOptionShown())
  41989. {
  41990. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41991. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41992. menu.addSeparator();
  41993. }
  41994. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41995. }
  41996. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41997. {
  41998. if (menuReturnId == 0xf836743)
  41999. {
  42000. owner.autoSizeColumn (columnIdClicked);
  42001. }
  42002. else if (menuReturnId == 0xf836744)
  42003. {
  42004. owner.autoSizeAllColumns();
  42005. }
  42006. else
  42007. {
  42008. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  42009. }
  42010. }
  42011. juce_UseDebuggingNewOperator
  42012. private:
  42013. TableListBox& owner;
  42014. TableListBoxHeader (const TableListBoxHeader&);
  42015. TableListBoxHeader& operator= (const TableListBoxHeader&);
  42016. };
  42017. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  42018. : ListBox (name, 0),
  42019. model (model_),
  42020. autoSizeOptionsShown (true)
  42021. {
  42022. ListBox::model = this;
  42023. header = new TableListBoxHeader (*this);
  42024. header->setSize (100, 28);
  42025. header->addListener (this);
  42026. setHeaderComponent (header);
  42027. }
  42028. TableListBox::~TableListBox()
  42029. {
  42030. header = 0;
  42031. }
  42032. void TableListBox::setModel (TableListBoxModel* const newModel)
  42033. {
  42034. if (model != newModel)
  42035. {
  42036. model = newModel;
  42037. updateContent();
  42038. }
  42039. }
  42040. int TableListBox::getHeaderHeight() const
  42041. {
  42042. return header->getHeight();
  42043. }
  42044. void TableListBox::setHeaderHeight (const int newHeight)
  42045. {
  42046. header->setSize (header->getWidth(), newHeight);
  42047. resized();
  42048. }
  42049. void TableListBox::autoSizeColumn (const int columnId)
  42050. {
  42051. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  42052. if (width > 0)
  42053. header->setColumnWidth (columnId, width);
  42054. }
  42055. void TableListBox::autoSizeAllColumns()
  42056. {
  42057. for (int i = 0; i < header->getNumColumns (true); ++i)
  42058. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  42059. }
  42060. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  42061. {
  42062. autoSizeOptionsShown = shouldBeShown;
  42063. }
  42064. bool TableListBox::isAutoSizeMenuOptionShown() const
  42065. {
  42066. return autoSizeOptionsShown;
  42067. }
  42068. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42069. const int rowNumber,
  42070. const bool relativeToComponentTopLeft) const
  42071. {
  42072. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42073. if (relativeToComponentTopLeft)
  42074. headerCell.translate (header->getX(), 0);
  42075. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42076. return Rectangle<int> (headerCell.getX(), row.getY(),
  42077. headerCell.getWidth(), row.getHeight());
  42078. }
  42079. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42080. {
  42081. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42082. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42083. }
  42084. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42085. {
  42086. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42087. if (scrollbar != 0)
  42088. {
  42089. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42090. double x = scrollbar->getCurrentRangeStart();
  42091. const double w = scrollbar->getCurrentRangeSize();
  42092. if (pos.getX() < x)
  42093. x = pos.getX();
  42094. else if (pos.getRight() > x + w)
  42095. x += jmax (0.0, pos.getRight() - (x + w));
  42096. scrollbar->setCurrentRangeStart (x);
  42097. }
  42098. }
  42099. int TableListBox::getNumRows()
  42100. {
  42101. return model != 0 ? model->getNumRows() : 0;
  42102. }
  42103. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42104. {
  42105. }
  42106. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42107. {
  42108. if (existingComponentToUpdate == 0)
  42109. existingComponentToUpdate = new TableListRowComp (*this);
  42110. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42111. return existingComponentToUpdate;
  42112. }
  42113. void TableListBox::selectedRowsChanged (int row)
  42114. {
  42115. if (model != 0)
  42116. model->selectedRowsChanged (row);
  42117. }
  42118. void TableListBox::deleteKeyPressed (int row)
  42119. {
  42120. if (model != 0)
  42121. model->deleteKeyPressed (row);
  42122. }
  42123. void TableListBox::returnKeyPressed (int row)
  42124. {
  42125. if (model != 0)
  42126. model->returnKeyPressed (row);
  42127. }
  42128. void TableListBox::backgroundClicked()
  42129. {
  42130. if (model != 0)
  42131. model->backgroundClicked();
  42132. }
  42133. void TableListBox::listWasScrolled()
  42134. {
  42135. if (model != 0)
  42136. model->listWasScrolled();
  42137. }
  42138. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42139. {
  42140. setMinimumContentWidth (header->getTotalWidth());
  42141. repaint();
  42142. updateColumnComponents();
  42143. }
  42144. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42145. {
  42146. setMinimumContentWidth (header->getTotalWidth());
  42147. repaint();
  42148. updateColumnComponents();
  42149. }
  42150. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42151. {
  42152. if (model != 0)
  42153. model->sortOrderChanged (header->getSortColumnId(),
  42154. header->isSortedForwards());
  42155. }
  42156. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42157. {
  42158. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42159. repaint();
  42160. }
  42161. void TableListBox::resized()
  42162. {
  42163. ListBox::resized();
  42164. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42165. setMinimumContentWidth (header->getTotalWidth());
  42166. }
  42167. void TableListBox::updateColumnComponents() const
  42168. {
  42169. const int firstRow = getRowContainingPosition (0, 0);
  42170. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42171. {
  42172. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42173. if (rowComp != 0)
  42174. rowComp->resized();
  42175. }
  42176. }
  42177. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42178. {
  42179. }
  42180. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42181. {
  42182. }
  42183. void TableListBoxModel::backgroundClicked()
  42184. {
  42185. }
  42186. void TableListBoxModel::sortOrderChanged (int, const bool)
  42187. {
  42188. }
  42189. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42190. {
  42191. return 0;
  42192. }
  42193. void TableListBoxModel::selectedRowsChanged (int)
  42194. {
  42195. }
  42196. void TableListBoxModel::deleteKeyPressed (int)
  42197. {
  42198. }
  42199. void TableListBoxModel::returnKeyPressed (int)
  42200. {
  42201. }
  42202. void TableListBoxModel::listWasScrolled()
  42203. {
  42204. }
  42205. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42206. {
  42207. return String::empty;
  42208. }
  42209. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42210. {
  42211. return String::empty;
  42212. }
  42213. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42214. {
  42215. (void) existingComponentToUpdate;
  42216. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42217. return 0;
  42218. }
  42219. END_JUCE_NAMESPACE
  42220. /*** End of inlined file: juce_TableListBox.cpp ***/
  42221. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42222. BEGIN_JUCE_NAMESPACE
  42223. // a word or space that can't be broken down any further
  42224. struct TextAtom
  42225. {
  42226. String atomText;
  42227. float width;
  42228. int numChars;
  42229. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42230. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42231. const String getText (const juce_wchar passwordCharacter) const
  42232. {
  42233. if (passwordCharacter == 0)
  42234. return atomText;
  42235. else
  42236. return String::repeatedString (String::charToString (passwordCharacter),
  42237. atomText.length());
  42238. }
  42239. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42240. {
  42241. if (passwordCharacter == 0)
  42242. return atomText.substring (0, numChars);
  42243. else if (isNewLine())
  42244. return String::empty;
  42245. else
  42246. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42247. }
  42248. };
  42249. // a run of text with a single font and colour
  42250. class TextEditor::UniformTextSection
  42251. {
  42252. public:
  42253. UniformTextSection (const String& text,
  42254. const Font& font_,
  42255. const Colour& colour_,
  42256. const juce_wchar passwordCharacter)
  42257. : font (font_),
  42258. colour (colour_)
  42259. {
  42260. initialiseAtoms (text, passwordCharacter);
  42261. }
  42262. UniformTextSection (const UniformTextSection& other)
  42263. : font (other.font),
  42264. colour (other.colour)
  42265. {
  42266. atoms.ensureStorageAllocated (other.atoms.size());
  42267. for (int i = 0; i < other.atoms.size(); ++i)
  42268. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42269. }
  42270. ~UniformTextSection()
  42271. {
  42272. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42273. }
  42274. void clear()
  42275. {
  42276. for (int i = atoms.size(); --i >= 0;)
  42277. delete getAtom(i);
  42278. atoms.clear();
  42279. }
  42280. int getNumAtoms() const
  42281. {
  42282. return atoms.size();
  42283. }
  42284. TextAtom* getAtom (const int index) const throw()
  42285. {
  42286. return atoms.getUnchecked (index);
  42287. }
  42288. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42289. {
  42290. if (other.atoms.size() > 0)
  42291. {
  42292. TextAtom* const lastAtom = atoms.getLast();
  42293. int i = 0;
  42294. if (lastAtom != 0)
  42295. {
  42296. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42297. {
  42298. TextAtom* const first = other.getAtom(0);
  42299. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42300. {
  42301. lastAtom->atomText += first->atomText;
  42302. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42303. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42304. delete first;
  42305. ++i;
  42306. }
  42307. }
  42308. }
  42309. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42310. while (i < other.atoms.size())
  42311. {
  42312. atoms.add (other.getAtom(i));
  42313. ++i;
  42314. }
  42315. }
  42316. }
  42317. UniformTextSection* split (const int indexToBreakAt,
  42318. const juce_wchar passwordCharacter)
  42319. {
  42320. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42321. font, colour,
  42322. passwordCharacter);
  42323. int index = 0;
  42324. for (int i = 0; i < atoms.size(); ++i)
  42325. {
  42326. TextAtom* const atom = getAtom(i);
  42327. const int nextIndex = index + atom->numChars;
  42328. if (index == indexToBreakAt)
  42329. {
  42330. int j;
  42331. for (j = i; j < atoms.size(); ++j)
  42332. section2->atoms.add (getAtom (j));
  42333. for (j = atoms.size(); --j >= i;)
  42334. atoms.remove (j);
  42335. break;
  42336. }
  42337. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42338. {
  42339. TextAtom* const secondAtom = new TextAtom();
  42340. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42341. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42342. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42343. section2->atoms.add (secondAtom);
  42344. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42345. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42346. atom->numChars = (uint16) (indexToBreakAt - index);
  42347. int j;
  42348. for (j = i + 1; j < atoms.size(); ++j)
  42349. section2->atoms.add (getAtom (j));
  42350. for (j = atoms.size(); --j > i;)
  42351. atoms.remove (j);
  42352. break;
  42353. }
  42354. index = nextIndex;
  42355. }
  42356. return section2;
  42357. }
  42358. void appendAllText (String::Concatenator& concatenator) const
  42359. {
  42360. for (int i = 0; i < atoms.size(); ++i)
  42361. concatenator.append (getAtom(i)->atomText);
  42362. }
  42363. void appendSubstring (String::Concatenator& concatenator,
  42364. const Range<int>& range) const
  42365. {
  42366. int index = 0;
  42367. for (int i = 0; i < atoms.size(); ++i)
  42368. {
  42369. const TextAtom* const atom = getAtom (i);
  42370. const int nextIndex = index + atom->numChars;
  42371. if (range.getStart() < nextIndex)
  42372. {
  42373. if (range.getEnd() <= index)
  42374. break;
  42375. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42376. if (! r.isEmpty())
  42377. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42378. }
  42379. index = nextIndex;
  42380. }
  42381. }
  42382. int getTotalLength() const
  42383. {
  42384. int total = 0;
  42385. for (int i = atoms.size(); --i >= 0;)
  42386. total += getAtom(i)->numChars;
  42387. return total;
  42388. }
  42389. void setFont (const Font& newFont,
  42390. const juce_wchar passwordCharacter)
  42391. {
  42392. if (font != newFont)
  42393. {
  42394. font = newFont;
  42395. for (int i = atoms.size(); --i >= 0;)
  42396. {
  42397. TextAtom* const atom = atoms.getUnchecked(i);
  42398. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42399. }
  42400. }
  42401. }
  42402. juce_UseDebuggingNewOperator
  42403. Font font;
  42404. Colour colour;
  42405. private:
  42406. Array <TextAtom*> atoms;
  42407. void initialiseAtoms (const String& textToParse,
  42408. const juce_wchar passwordCharacter)
  42409. {
  42410. int i = 0;
  42411. const int len = textToParse.length();
  42412. const juce_wchar* const text = textToParse;
  42413. while (i < len)
  42414. {
  42415. int start = i;
  42416. // create a whitespace atom unless it starts with non-ws
  42417. if (CharacterFunctions::isWhitespace (text[i])
  42418. && text[i] != '\r'
  42419. && text[i] != '\n')
  42420. {
  42421. while (i < len
  42422. && CharacterFunctions::isWhitespace (text[i])
  42423. && text[i] != '\r'
  42424. && text[i] != '\n')
  42425. {
  42426. ++i;
  42427. }
  42428. }
  42429. else
  42430. {
  42431. if (text[i] == '\r')
  42432. {
  42433. ++i;
  42434. if ((i < len) && (text[i] == '\n'))
  42435. {
  42436. ++start;
  42437. ++i;
  42438. }
  42439. }
  42440. else if (text[i] == '\n')
  42441. {
  42442. ++i;
  42443. }
  42444. else
  42445. {
  42446. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42447. ++i;
  42448. }
  42449. }
  42450. TextAtom* const atom = new TextAtom();
  42451. atom->atomText = String (text + start, i - start);
  42452. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42453. atom->numChars = (uint16) (i - start);
  42454. atoms.add (atom);
  42455. }
  42456. }
  42457. UniformTextSection& operator= (const UniformTextSection& other);
  42458. };
  42459. class TextEditor::Iterator
  42460. {
  42461. public:
  42462. Iterator (const Array <UniformTextSection*>& sections_,
  42463. const float wordWrapWidth_,
  42464. const juce_wchar passwordCharacter_)
  42465. : indexInText (0),
  42466. lineY (0),
  42467. lineHeight (0),
  42468. maxDescent (0),
  42469. atomX (0),
  42470. atomRight (0),
  42471. atom (0),
  42472. currentSection (0),
  42473. sections (sections_),
  42474. sectionIndex (0),
  42475. atomIndex (0),
  42476. wordWrapWidth (wordWrapWidth_),
  42477. passwordCharacter (passwordCharacter_)
  42478. {
  42479. jassert (wordWrapWidth_ > 0);
  42480. if (sections.size() > 0)
  42481. {
  42482. currentSection = sections.getUnchecked (sectionIndex);
  42483. if (currentSection != 0)
  42484. beginNewLine();
  42485. }
  42486. }
  42487. Iterator (const Iterator& other)
  42488. : indexInText (other.indexInText),
  42489. lineY (other.lineY),
  42490. lineHeight (other.lineHeight),
  42491. maxDescent (other.maxDescent),
  42492. atomX (other.atomX),
  42493. atomRight (other.atomRight),
  42494. atom (other.atom),
  42495. currentSection (other.currentSection),
  42496. sections (other.sections),
  42497. sectionIndex (other.sectionIndex),
  42498. atomIndex (other.atomIndex),
  42499. wordWrapWidth (other.wordWrapWidth),
  42500. passwordCharacter (other.passwordCharacter),
  42501. tempAtom (other.tempAtom)
  42502. {
  42503. }
  42504. ~Iterator()
  42505. {
  42506. }
  42507. bool next()
  42508. {
  42509. if (atom == &tempAtom)
  42510. {
  42511. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42512. if (numRemaining > 0)
  42513. {
  42514. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42515. atomX = 0;
  42516. if (tempAtom.numChars > 0)
  42517. lineY += lineHeight;
  42518. indexInText += tempAtom.numChars;
  42519. GlyphArrangement g;
  42520. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42521. int split;
  42522. for (split = 0; split < g.getNumGlyphs(); ++split)
  42523. if (shouldWrap (g.getGlyph (split).getRight()))
  42524. break;
  42525. if (split > 0 && split <= numRemaining)
  42526. {
  42527. tempAtom.numChars = (uint16) split;
  42528. tempAtom.width = g.getGlyph (split - 1).getRight();
  42529. atomRight = atomX + tempAtom.width;
  42530. return true;
  42531. }
  42532. }
  42533. }
  42534. bool forceNewLine = false;
  42535. if (sectionIndex >= sections.size())
  42536. {
  42537. moveToEndOfLastAtom();
  42538. return false;
  42539. }
  42540. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42541. {
  42542. if (atomIndex >= currentSection->getNumAtoms())
  42543. {
  42544. if (++sectionIndex >= sections.size())
  42545. {
  42546. moveToEndOfLastAtom();
  42547. return false;
  42548. }
  42549. atomIndex = 0;
  42550. currentSection = sections.getUnchecked (sectionIndex);
  42551. }
  42552. else
  42553. {
  42554. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42555. if (! lastAtom->isWhitespace())
  42556. {
  42557. // handle the case where the last atom in a section is actually part of the same
  42558. // word as the first atom of the next section...
  42559. float right = atomRight + lastAtom->width;
  42560. float lineHeight2 = lineHeight;
  42561. float maxDescent2 = maxDescent;
  42562. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42563. {
  42564. const UniformTextSection* const s = sections.getUnchecked (section);
  42565. if (s->getNumAtoms() == 0)
  42566. break;
  42567. const TextAtom* const nextAtom = s->getAtom (0);
  42568. if (nextAtom->isWhitespace())
  42569. break;
  42570. right += nextAtom->width;
  42571. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42572. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42573. if (shouldWrap (right))
  42574. {
  42575. lineHeight = lineHeight2;
  42576. maxDescent = maxDescent2;
  42577. forceNewLine = true;
  42578. break;
  42579. }
  42580. if (s->getNumAtoms() > 1)
  42581. break;
  42582. }
  42583. }
  42584. }
  42585. }
  42586. if (atom != 0)
  42587. {
  42588. atomX = atomRight;
  42589. indexInText += atom->numChars;
  42590. if (atom->isNewLine())
  42591. beginNewLine();
  42592. }
  42593. atom = currentSection->getAtom (atomIndex);
  42594. atomRight = atomX + atom->width;
  42595. ++atomIndex;
  42596. if (shouldWrap (atomRight) || forceNewLine)
  42597. {
  42598. if (atom->isWhitespace())
  42599. {
  42600. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42601. atomRight = jmin (atomRight, wordWrapWidth);
  42602. }
  42603. else
  42604. {
  42605. atomRight = atom->width;
  42606. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42607. {
  42608. tempAtom = *atom;
  42609. tempAtom.width = 0;
  42610. tempAtom.numChars = 0;
  42611. atom = &tempAtom;
  42612. if (atomX > 0)
  42613. beginNewLine();
  42614. return next();
  42615. }
  42616. beginNewLine();
  42617. return true;
  42618. }
  42619. }
  42620. return true;
  42621. }
  42622. void beginNewLine()
  42623. {
  42624. atomX = 0;
  42625. lineY += lineHeight;
  42626. int tempSectionIndex = sectionIndex;
  42627. int tempAtomIndex = atomIndex;
  42628. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42629. lineHeight = section->font.getHeight();
  42630. maxDescent = section->font.getDescent();
  42631. float x = (atom != 0) ? atom->width : 0;
  42632. while (! shouldWrap (x))
  42633. {
  42634. if (tempSectionIndex >= sections.size())
  42635. break;
  42636. bool checkSize = false;
  42637. if (tempAtomIndex >= section->getNumAtoms())
  42638. {
  42639. if (++tempSectionIndex >= sections.size())
  42640. break;
  42641. tempAtomIndex = 0;
  42642. section = sections.getUnchecked (tempSectionIndex);
  42643. checkSize = true;
  42644. }
  42645. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42646. if (nextAtom == 0)
  42647. break;
  42648. x += nextAtom->width;
  42649. if (shouldWrap (x) || nextAtom->isNewLine())
  42650. break;
  42651. if (checkSize)
  42652. {
  42653. lineHeight = jmax (lineHeight, section->font.getHeight());
  42654. maxDescent = jmax (maxDescent, section->font.getDescent());
  42655. }
  42656. ++tempAtomIndex;
  42657. }
  42658. }
  42659. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42660. {
  42661. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42662. {
  42663. if (lastSection != currentSection)
  42664. {
  42665. lastSection = currentSection;
  42666. g.setColour (currentSection->colour);
  42667. g.setFont (currentSection->font);
  42668. }
  42669. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42670. GlyphArrangement ga;
  42671. ga.addLineOfText (currentSection->font,
  42672. atom->getTrimmedText (passwordCharacter),
  42673. atomX,
  42674. (float) roundToInt (lineY + lineHeight - maxDescent));
  42675. ga.draw (g);
  42676. }
  42677. }
  42678. void drawSelection (Graphics& g,
  42679. const Range<int>& selection) const
  42680. {
  42681. const int startX = roundToInt (indexToX (selection.getStart()));
  42682. const int endX = roundToInt (indexToX (selection.getEnd()));
  42683. const int y = roundToInt (lineY);
  42684. const int nextY = roundToInt (lineY + lineHeight);
  42685. g.fillRect (startX, y, endX - startX, nextY - y);
  42686. }
  42687. void drawSelectedText (Graphics& g,
  42688. const Range<int>& selection,
  42689. const Colour& selectedTextColour) const
  42690. {
  42691. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42692. {
  42693. GlyphArrangement ga;
  42694. ga.addLineOfText (currentSection->font,
  42695. atom->getTrimmedText (passwordCharacter),
  42696. atomX,
  42697. (float) roundToInt (lineY + lineHeight - maxDescent));
  42698. if (selection.getEnd() < indexInText + atom->numChars)
  42699. {
  42700. GlyphArrangement ga2 (ga);
  42701. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42702. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42703. g.setColour (currentSection->colour);
  42704. ga2.draw (g);
  42705. }
  42706. if (selection.getStart() > indexInText)
  42707. {
  42708. GlyphArrangement ga2 (ga);
  42709. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42710. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42711. g.setColour (currentSection->colour);
  42712. ga2.draw (g);
  42713. }
  42714. g.setColour (selectedTextColour);
  42715. ga.draw (g);
  42716. }
  42717. }
  42718. float indexToX (const int indexToFind) const
  42719. {
  42720. if (indexToFind <= indexInText)
  42721. return atomX;
  42722. if (indexToFind >= indexInText + atom->numChars)
  42723. return atomRight;
  42724. GlyphArrangement g;
  42725. g.addLineOfText (currentSection->font,
  42726. atom->getText (passwordCharacter),
  42727. atomX, 0.0f);
  42728. if (indexToFind - indexInText >= g.getNumGlyphs())
  42729. return atomRight;
  42730. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42731. }
  42732. int xToIndex (const float xToFind) const
  42733. {
  42734. if (xToFind <= atomX || atom->isNewLine())
  42735. return indexInText;
  42736. if (xToFind >= atomRight)
  42737. return indexInText + atom->numChars;
  42738. GlyphArrangement g;
  42739. g.addLineOfText (currentSection->font,
  42740. atom->getText (passwordCharacter),
  42741. atomX, 0.0f);
  42742. int j;
  42743. for (j = 0; j < g.getNumGlyphs(); ++j)
  42744. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42745. break;
  42746. return indexInText + j;
  42747. }
  42748. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42749. {
  42750. while (next())
  42751. {
  42752. if (indexInText + atom->numChars > index)
  42753. {
  42754. cx = indexToX (index);
  42755. cy = lineY;
  42756. lineHeight_ = lineHeight;
  42757. return true;
  42758. }
  42759. }
  42760. cx = atomX;
  42761. cy = lineY;
  42762. lineHeight_ = lineHeight;
  42763. return false;
  42764. }
  42765. juce_UseDebuggingNewOperator
  42766. int indexInText;
  42767. float lineY, lineHeight, maxDescent;
  42768. float atomX, atomRight;
  42769. const TextAtom* atom;
  42770. const UniformTextSection* currentSection;
  42771. private:
  42772. const Array <UniformTextSection*>& sections;
  42773. int sectionIndex, atomIndex;
  42774. const float wordWrapWidth;
  42775. const juce_wchar passwordCharacter;
  42776. TextAtom tempAtom;
  42777. Iterator& operator= (const Iterator&);
  42778. void moveToEndOfLastAtom()
  42779. {
  42780. if (atom != 0)
  42781. {
  42782. atomX = atomRight;
  42783. if (atom->isNewLine())
  42784. {
  42785. atomX = 0.0f;
  42786. lineY += lineHeight;
  42787. }
  42788. }
  42789. }
  42790. bool shouldWrap (const float x) const
  42791. {
  42792. return (x - 0.0001f) >= wordWrapWidth;
  42793. }
  42794. };
  42795. class TextEditor::InsertAction : public UndoableAction
  42796. {
  42797. TextEditor& owner;
  42798. const String text;
  42799. const int insertIndex, oldCaretPos, newCaretPos;
  42800. const Font font;
  42801. const Colour colour;
  42802. InsertAction (const InsertAction&);
  42803. InsertAction& operator= (const InsertAction&);
  42804. public:
  42805. InsertAction (TextEditor& owner_,
  42806. const String& text_,
  42807. const int insertIndex_,
  42808. const Font& font_,
  42809. const Colour& colour_,
  42810. const int oldCaretPos_,
  42811. const int newCaretPos_)
  42812. : owner (owner_),
  42813. text (text_),
  42814. insertIndex (insertIndex_),
  42815. oldCaretPos (oldCaretPos_),
  42816. newCaretPos (newCaretPos_),
  42817. font (font_),
  42818. colour (colour_)
  42819. {
  42820. }
  42821. ~InsertAction()
  42822. {
  42823. }
  42824. bool perform()
  42825. {
  42826. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42827. return true;
  42828. }
  42829. bool undo()
  42830. {
  42831. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42832. return true;
  42833. }
  42834. int getSizeInUnits()
  42835. {
  42836. return text.length() + 16;
  42837. }
  42838. };
  42839. class TextEditor::RemoveAction : public UndoableAction
  42840. {
  42841. TextEditor& owner;
  42842. const Range<int> range;
  42843. const int oldCaretPos, newCaretPos;
  42844. Array <UniformTextSection*> removedSections;
  42845. RemoveAction (const RemoveAction&);
  42846. RemoveAction& operator= (const RemoveAction&);
  42847. public:
  42848. RemoveAction (TextEditor& owner_,
  42849. const Range<int> range_,
  42850. const int oldCaretPos_,
  42851. const int newCaretPos_,
  42852. const Array <UniformTextSection*>& removedSections_)
  42853. : owner (owner_),
  42854. range (range_),
  42855. oldCaretPos (oldCaretPos_),
  42856. newCaretPos (newCaretPos_),
  42857. removedSections (removedSections_)
  42858. {
  42859. }
  42860. ~RemoveAction()
  42861. {
  42862. for (int i = removedSections.size(); --i >= 0;)
  42863. {
  42864. UniformTextSection* const section = removedSections.getUnchecked (i);
  42865. section->clear();
  42866. delete section;
  42867. }
  42868. }
  42869. bool perform()
  42870. {
  42871. owner.remove (range, 0, newCaretPos);
  42872. return true;
  42873. }
  42874. bool undo()
  42875. {
  42876. owner.reinsert (range.getStart(), removedSections);
  42877. owner.moveCursorTo (oldCaretPos, false);
  42878. return true;
  42879. }
  42880. int getSizeInUnits()
  42881. {
  42882. int n = 0;
  42883. for (int i = removedSections.size(); --i >= 0;)
  42884. n += removedSections.getUnchecked (i)->getTotalLength();
  42885. return n + 16;
  42886. }
  42887. };
  42888. class TextEditor::TextHolderComponent : public Component,
  42889. public Timer,
  42890. public Value::Listener
  42891. {
  42892. public:
  42893. TextHolderComponent (TextEditor& owner_)
  42894. : owner (owner_)
  42895. {
  42896. setWantsKeyboardFocus (false);
  42897. setInterceptsMouseClicks (false, true);
  42898. owner.getTextValue().addListener (this);
  42899. }
  42900. ~TextHolderComponent()
  42901. {
  42902. owner.getTextValue().removeListener (this);
  42903. }
  42904. void paint (Graphics& g)
  42905. {
  42906. owner.drawContent (g);
  42907. }
  42908. void timerCallback()
  42909. {
  42910. owner.timerCallbackInt();
  42911. }
  42912. const MouseCursor getMouseCursor()
  42913. {
  42914. return owner.getMouseCursor();
  42915. }
  42916. void valueChanged (Value&)
  42917. {
  42918. owner.textWasChangedByValue();
  42919. }
  42920. private:
  42921. TextEditor& owner;
  42922. TextHolderComponent (const TextHolderComponent&);
  42923. TextHolderComponent& operator= (const TextHolderComponent&);
  42924. };
  42925. class TextEditorViewport : public Viewport
  42926. {
  42927. public:
  42928. TextEditorViewport (TextEditor* const owner_)
  42929. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42930. {
  42931. }
  42932. ~TextEditorViewport()
  42933. {
  42934. }
  42935. void visibleAreaChanged (int, int, int, int)
  42936. {
  42937. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42938. // appear and disappear, causing the wrap width to change.
  42939. {
  42940. const float wordWrapWidth = owner->getWordWrapWidth();
  42941. if (wordWrapWidth != lastWordWrapWidth)
  42942. {
  42943. lastWordWrapWidth = wordWrapWidth;
  42944. rentrant = true;
  42945. owner->updateTextHolderSize();
  42946. rentrant = false;
  42947. }
  42948. }
  42949. }
  42950. private:
  42951. TextEditor* const owner;
  42952. float lastWordWrapWidth;
  42953. bool rentrant;
  42954. TextEditorViewport (const TextEditorViewport&);
  42955. TextEditorViewport& operator= (const TextEditorViewport&);
  42956. };
  42957. namespace TextEditorDefs
  42958. {
  42959. const int flashSpeedIntervalMs = 380;
  42960. const int textChangeMessageId = 0x10003001;
  42961. const int returnKeyMessageId = 0x10003002;
  42962. const int escapeKeyMessageId = 0x10003003;
  42963. const int focusLossMessageId = 0x10003004;
  42964. const int maxActionsPerTransaction = 100;
  42965. static int getCharacterCategory (const juce_wchar character)
  42966. {
  42967. return CharacterFunctions::isLetterOrDigit (character)
  42968. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42969. }
  42970. }
  42971. TextEditor::TextEditor (const String& name,
  42972. const juce_wchar passwordCharacter_)
  42973. : Component (name),
  42974. borderSize (1, 1, 1, 3),
  42975. readOnly (false),
  42976. multiline (false),
  42977. wordWrap (false),
  42978. returnKeyStartsNewLine (false),
  42979. caretVisible (true),
  42980. popupMenuEnabled (true),
  42981. selectAllTextWhenFocused (false),
  42982. scrollbarVisible (true),
  42983. wasFocused (false),
  42984. caretFlashState (true),
  42985. keepCursorOnScreen (true),
  42986. tabKeyUsed (false),
  42987. menuActive (false),
  42988. valueTextNeedsUpdating (false),
  42989. cursorX (0),
  42990. cursorY (0),
  42991. cursorHeight (0),
  42992. maxTextLength (0),
  42993. leftIndent (4),
  42994. topIndent (4),
  42995. lastTransactionTime (0),
  42996. currentFont (14.0f),
  42997. totalNumChars (0),
  42998. caretPosition (0),
  42999. passwordCharacter (passwordCharacter_),
  43000. dragType (notDragging)
  43001. {
  43002. setOpaque (true);
  43003. addAndMakeVisible (viewport = new TextEditorViewport (this));
  43004. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  43005. viewport->setWantsKeyboardFocus (false);
  43006. viewport->setScrollBarsShown (false, false);
  43007. setMouseCursor (MouseCursor::IBeamCursor);
  43008. setWantsKeyboardFocus (true);
  43009. }
  43010. TextEditor::~TextEditor()
  43011. {
  43012. textValue.referTo (Value());
  43013. clearInternal (0);
  43014. viewport = 0;
  43015. textHolder = 0;
  43016. }
  43017. void TextEditor::newTransaction()
  43018. {
  43019. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43020. undoManager.beginNewTransaction();
  43021. }
  43022. void TextEditor::doUndoRedo (const bool isRedo)
  43023. {
  43024. if (! isReadOnly())
  43025. {
  43026. if (isRedo ? undoManager.redo()
  43027. : undoManager.undo())
  43028. {
  43029. scrollToMakeSureCursorIsVisible();
  43030. repaint();
  43031. textChanged();
  43032. }
  43033. }
  43034. }
  43035. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  43036. const bool shouldWordWrap)
  43037. {
  43038. if (multiline != shouldBeMultiLine
  43039. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  43040. {
  43041. multiline = shouldBeMultiLine;
  43042. wordWrap = shouldWordWrap && shouldBeMultiLine;
  43043. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  43044. scrollbarVisible && multiline);
  43045. viewport->setViewPosition (0, 0);
  43046. resized();
  43047. scrollToMakeSureCursorIsVisible();
  43048. }
  43049. }
  43050. bool TextEditor::isMultiLine() const
  43051. {
  43052. return multiline;
  43053. }
  43054. void TextEditor::setScrollbarsShown (bool shown)
  43055. {
  43056. if (scrollbarVisible != shown)
  43057. {
  43058. scrollbarVisible = shown;
  43059. shown = shown && isMultiLine();
  43060. viewport->setScrollBarsShown (shown, shown);
  43061. }
  43062. }
  43063. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43064. {
  43065. if (readOnly != shouldBeReadOnly)
  43066. {
  43067. readOnly = shouldBeReadOnly;
  43068. enablementChanged();
  43069. }
  43070. }
  43071. bool TextEditor::isReadOnly() const
  43072. {
  43073. return readOnly || ! isEnabled();
  43074. }
  43075. bool TextEditor::isTextInputActive() const
  43076. {
  43077. return ! isReadOnly();
  43078. }
  43079. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43080. {
  43081. returnKeyStartsNewLine = shouldStartNewLine;
  43082. }
  43083. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43084. {
  43085. tabKeyUsed = shouldTabKeyBeUsed;
  43086. }
  43087. void TextEditor::setPopupMenuEnabled (const bool b)
  43088. {
  43089. popupMenuEnabled = b;
  43090. }
  43091. void TextEditor::setSelectAllWhenFocused (const bool b)
  43092. {
  43093. selectAllTextWhenFocused = b;
  43094. }
  43095. const Font TextEditor::getFont() const
  43096. {
  43097. return currentFont;
  43098. }
  43099. void TextEditor::setFont (const Font& newFont)
  43100. {
  43101. currentFont = newFont;
  43102. scrollToMakeSureCursorIsVisible();
  43103. }
  43104. void TextEditor::applyFontToAllText (const Font& newFont)
  43105. {
  43106. currentFont = newFont;
  43107. const Colour overallColour (findColour (textColourId));
  43108. for (int i = sections.size(); --i >= 0;)
  43109. {
  43110. UniformTextSection* const uts = sections.getUnchecked (i);
  43111. uts->setFont (newFont, passwordCharacter);
  43112. uts->colour = overallColour;
  43113. }
  43114. coalesceSimilarSections();
  43115. updateTextHolderSize();
  43116. scrollToMakeSureCursorIsVisible();
  43117. repaint();
  43118. }
  43119. void TextEditor::colourChanged()
  43120. {
  43121. setOpaque (findColour (backgroundColourId).isOpaque());
  43122. repaint();
  43123. }
  43124. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43125. {
  43126. caretVisible = shouldCaretBeVisible;
  43127. if (shouldCaretBeVisible)
  43128. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43129. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43130. : MouseCursor::NormalCursor);
  43131. }
  43132. void TextEditor::setInputRestrictions (const int maxLen,
  43133. const String& chars)
  43134. {
  43135. maxTextLength = jmax (0, maxLen);
  43136. allowedCharacters = chars;
  43137. }
  43138. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43139. {
  43140. textToShowWhenEmpty = text;
  43141. colourForTextWhenEmpty = colourToUse;
  43142. }
  43143. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43144. {
  43145. if (passwordCharacter != newPasswordCharacter)
  43146. {
  43147. passwordCharacter = newPasswordCharacter;
  43148. resized();
  43149. repaint();
  43150. }
  43151. }
  43152. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43153. {
  43154. viewport->setScrollBarThickness (newThicknessPixels);
  43155. }
  43156. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43157. {
  43158. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43159. }
  43160. void TextEditor::clear()
  43161. {
  43162. clearInternal (0);
  43163. updateTextHolderSize();
  43164. undoManager.clearUndoHistory();
  43165. }
  43166. void TextEditor::setText (const String& newText,
  43167. const bool sendTextChangeMessage)
  43168. {
  43169. const int newLength = newText.length();
  43170. if (newLength != getTotalNumChars() || getText() != newText)
  43171. {
  43172. const int oldCursorPos = caretPosition;
  43173. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43174. clearInternal (0);
  43175. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43176. // if you're adding text with line-feeds to a single-line text editor, it
  43177. // ain't gonna look right!
  43178. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43179. if (cursorWasAtEnd && ! isMultiLine())
  43180. moveCursorTo (getTotalNumChars(), false);
  43181. else
  43182. moveCursorTo (oldCursorPos, false);
  43183. if (sendTextChangeMessage)
  43184. textChanged();
  43185. updateTextHolderSize();
  43186. scrollToMakeSureCursorIsVisible();
  43187. undoManager.clearUndoHistory();
  43188. repaint();
  43189. }
  43190. }
  43191. Value& TextEditor::getTextValue()
  43192. {
  43193. if (valueTextNeedsUpdating)
  43194. {
  43195. valueTextNeedsUpdating = false;
  43196. textValue = getText();
  43197. }
  43198. return textValue;
  43199. }
  43200. void TextEditor::textWasChangedByValue()
  43201. {
  43202. if (textValue.getValueSource().getReferenceCount() > 1)
  43203. setText (textValue.getValue());
  43204. }
  43205. void TextEditor::textChanged()
  43206. {
  43207. updateTextHolderSize();
  43208. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43209. if (textValue.getValueSource().getReferenceCount() > 1)
  43210. {
  43211. valueTextNeedsUpdating = false;
  43212. textValue = getText();
  43213. }
  43214. }
  43215. void TextEditor::returnPressed()
  43216. {
  43217. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43218. }
  43219. void TextEditor::escapePressed()
  43220. {
  43221. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43222. }
  43223. void TextEditor::addListener (Listener* const newListener)
  43224. {
  43225. listeners.add (newListener);
  43226. }
  43227. void TextEditor::removeListener (Listener* const listenerToRemove)
  43228. {
  43229. listeners.remove (listenerToRemove);
  43230. }
  43231. void TextEditor::timerCallbackInt()
  43232. {
  43233. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43234. if (caretFlashState != newState)
  43235. {
  43236. caretFlashState = newState;
  43237. if (caretFlashState)
  43238. wasFocused = true;
  43239. if (caretVisible
  43240. && hasKeyboardFocus (false)
  43241. && ! isReadOnly())
  43242. {
  43243. repaintCaret();
  43244. }
  43245. }
  43246. const unsigned int now = Time::getApproximateMillisecondCounter();
  43247. if (now > lastTransactionTime + 200)
  43248. newTransaction();
  43249. }
  43250. void TextEditor::repaintCaret()
  43251. {
  43252. if (! findColour (caretColourId).isTransparent())
  43253. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43254. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43255. 4,
  43256. roundToInt (cursorHeight) + 2);
  43257. }
  43258. void TextEditor::repaintText (const Range<int>& range)
  43259. {
  43260. if (! range.isEmpty())
  43261. {
  43262. float x = 0, y = 0, lh = currentFont.getHeight();
  43263. const float wordWrapWidth = getWordWrapWidth();
  43264. if (wordWrapWidth > 0)
  43265. {
  43266. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43267. i.getCharPosition (range.getStart(), x, y, lh);
  43268. const int y1 = (int) y;
  43269. int y2;
  43270. if (range.getEnd() >= getTotalNumChars())
  43271. {
  43272. y2 = textHolder->getHeight();
  43273. }
  43274. else
  43275. {
  43276. i.getCharPosition (range.getEnd(), x, y, lh);
  43277. y2 = (int) (y + lh * 2.0f);
  43278. }
  43279. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43280. }
  43281. }
  43282. }
  43283. void TextEditor::moveCaret (int newCaretPos)
  43284. {
  43285. if (newCaretPos < 0)
  43286. newCaretPos = 0;
  43287. else if (newCaretPos > getTotalNumChars())
  43288. newCaretPos = getTotalNumChars();
  43289. if (newCaretPos != getCaretPosition())
  43290. {
  43291. repaintCaret();
  43292. caretFlashState = true;
  43293. caretPosition = newCaretPos;
  43294. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43295. scrollToMakeSureCursorIsVisible();
  43296. repaintCaret();
  43297. }
  43298. }
  43299. void TextEditor::setCaretPosition (const int newIndex)
  43300. {
  43301. moveCursorTo (newIndex, false);
  43302. }
  43303. int TextEditor::getCaretPosition() const
  43304. {
  43305. return caretPosition;
  43306. }
  43307. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43308. const int desiredCaretY)
  43309. {
  43310. updateCaretPosition();
  43311. int vx = roundToInt (cursorX) - desiredCaretX;
  43312. int vy = roundToInt (cursorY) - desiredCaretY;
  43313. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43314. {
  43315. vx += desiredCaretX - proportionOfWidth (0.2f);
  43316. }
  43317. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43318. {
  43319. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43320. }
  43321. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43322. if (! isMultiLine())
  43323. {
  43324. vy = viewport->getViewPositionY();
  43325. }
  43326. else
  43327. {
  43328. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43329. const int curH = roundToInt (cursorHeight);
  43330. if (desiredCaretY < 0)
  43331. {
  43332. vy = jmax (0, desiredCaretY + vy);
  43333. }
  43334. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43335. {
  43336. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43337. }
  43338. }
  43339. viewport->setViewPosition (vx, vy);
  43340. }
  43341. const Rectangle<int> TextEditor::getCaretRectangle()
  43342. {
  43343. updateCaretPosition();
  43344. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43345. roundToInt (cursorY) - viewport->getY(),
  43346. 1, roundToInt (cursorHeight));
  43347. }
  43348. float TextEditor::getWordWrapWidth() const
  43349. {
  43350. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43351. : 1.0e10f;
  43352. }
  43353. void TextEditor::updateTextHolderSize()
  43354. {
  43355. const float wordWrapWidth = getWordWrapWidth();
  43356. if (wordWrapWidth > 0)
  43357. {
  43358. float maxWidth = 0.0f;
  43359. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43360. while (i.next())
  43361. maxWidth = jmax (maxWidth, i.atomRight);
  43362. const int w = leftIndent + roundToInt (maxWidth);
  43363. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43364. currentFont.getHeight()));
  43365. textHolder->setSize (w + 1, h + 1);
  43366. }
  43367. }
  43368. int TextEditor::getTextWidth() const
  43369. {
  43370. return textHolder->getWidth();
  43371. }
  43372. int TextEditor::getTextHeight() const
  43373. {
  43374. return textHolder->getHeight();
  43375. }
  43376. void TextEditor::setIndents (const int newLeftIndent,
  43377. const int newTopIndent)
  43378. {
  43379. leftIndent = newLeftIndent;
  43380. topIndent = newTopIndent;
  43381. }
  43382. void TextEditor::setBorder (const BorderSize& border)
  43383. {
  43384. borderSize = border;
  43385. resized();
  43386. }
  43387. const BorderSize TextEditor::getBorder() const
  43388. {
  43389. return borderSize;
  43390. }
  43391. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43392. {
  43393. keepCursorOnScreen = shouldScrollToShowCursor;
  43394. }
  43395. void TextEditor::updateCaretPosition()
  43396. {
  43397. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43398. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43399. }
  43400. void TextEditor::scrollToMakeSureCursorIsVisible()
  43401. {
  43402. updateCaretPosition();
  43403. if (keepCursorOnScreen)
  43404. {
  43405. int x = viewport->getViewPositionX();
  43406. int y = viewport->getViewPositionY();
  43407. const int relativeCursorX = roundToInt (cursorX) - x;
  43408. const int relativeCursorY = roundToInt (cursorY) - y;
  43409. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43410. {
  43411. x += relativeCursorX - proportionOfWidth (0.2f);
  43412. }
  43413. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43414. {
  43415. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43416. }
  43417. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43418. if (! isMultiLine())
  43419. {
  43420. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43421. }
  43422. else
  43423. {
  43424. const int curH = roundToInt (cursorHeight);
  43425. if (relativeCursorY < 0)
  43426. {
  43427. y = jmax (0, relativeCursorY + y);
  43428. }
  43429. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43430. {
  43431. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43432. }
  43433. }
  43434. viewport->setViewPosition (x, y);
  43435. }
  43436. }
  43437. void TextEditor::moveCursorTo (const int newPosition,
  43438. const bool isSelecting)
  43439. {
  43440. if (isSelecting)
  43441. {
  43442. moveCaret (newPosition);
  43443. const Range<int> oldSelection (selection);
  43444. if (dragType == notDragging)
  43445. {
  43446. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43447. dragType = draggingSelectionStart;
  43448. else
  43449. dragType = draggingSelectionEnd;
  43450. }
  43451. if (dragType == draggingSelectionStart)
  43452. {
  43453. if (getCaretPosition() >= selection.getEnd())
  43454. dragType = draggingSelectionEnd;
  43455. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43456. }
  43457. else
  43458. {
  43459. if (getCaretPosition() < selection.getStart())
  43460. dragType = draggingSelectionStart;
  43461. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43462. }
  43463. repaintText (selection.getUnionWith (oldSelection));
  43464. }
  43465. else
  43466. {
  43467. dragType = notDragging;
  43468. repaintText (selection);
  43469. moveCaret (newPosition);
  43470. selection = Range<int>::emptyRange (getCaretPosition());
  43471. }
  43472. }
  43473. int TextEditor::getTextIndexAt (const int x,
  43474. const int y)
  43475. {
  43476. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43477. (float) (y + viewport->getViewPositionY() - topIndent));
  43478. }
  43479. void TextEditor::insertTextAtCaret (const String& newText_)
  43480. {
  43481. String newText (newText_);
  43482. if (allowedCharacters.isNotEmpty())
  43483. newText = newText.retainCharacters (allowedCharacters);
  43484. if ((! returnKeyStartsNewLine) && newText == "\n")
  43485. {
  43486. returnPressed();
  43487. return;
  43488. }
  43489. if (! isMultiLine())
  43490. newText = newText.replaceCharacters ("\r\n", " ");
  43491. else
  43492. newText = newText.replace ("\r\n", "\n");
  43493. const int newCaretPos = selection.getStart() + newText.length();
  43494. const int insertIndex = selection.getStart();
  43495. remove (selection, getUndoManager(),
  43496. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43497. if (maxTextLength > 0)
  43498. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43499. if (newText.isNotEmpty())
  43500. insert (newText,
  43501. insertIndex,
  43502. currentFont,
  43503. findColour (textColourId),
  43504. getUndoManager(),
  43505. newCaretPos);
  43506. textChanged();
  43507. }
  43508. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43509. {
  43510. moveCursorTo (newSelection.getStart(), false);
  43511. moveCursorTo (newSelection.getEnd(), true);
  43512. }
  43513. void TextEditor::copy()
  43514. {
  43515. if (passwordCharacter == 0)
  43516. {
  43517. const String selectedText (getHighlightedText());
  43518. if (selectedText.isNotEmpty())
  43519. SystemClipboard::copyTextToClipboard (selectedText);
  43520. }
  43521. }
  43522. void TextEditor::paste()
  43523. {
  43524. if (! isReadOnly())
  43525. {
  43526. const String clip (SystemClipboard::getTextFromClipboard());
  43527. if (clip.isNotEmpty())
  43528. insertTextAtCaret (clip);
  43529. }
  43530. }
  43531. void TextEditor::cut()
  43532. {
  43533. if (! isReadOnly())
  43534. {
  43535. moveCaret (selection.getEnd());
  43536. insertTextAtCaret (String::empty);
  43537. }
  43538. }
  43539. void TextEditor::drawContent (Graphics& g)
  43540. {
  43541. const float wordWrapWidth = getWordWrapWidth();
  43542. if (wordWrapWidth > 0)
  43543. {
  43544. g.setOrigin (leftIndent, topIndent);
  43545. const Rectangle<int> clip (g.getClipBounds());
  43546. Colour selectedTextColour;
  43547. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43548. while (i.lineY + 200.0 < clip.getY() && i.next())
  43549. {}
  43550. if (! selection.isEmpty())
  43551. {
  43552. g.setColour (findColour (highlightColourId)
  43553. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43554. selectedTextColour = findColour (highlightedTextColourId);
  43555. Iterator i2 (i);
  43556. while (i2.next() && i2.lineY < clip.getBottom())
  43557. {
  43558. if (i2.lineY + i2.lineHeight >= clip.getY()
  43559. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43560. {
  43561. i2.drawSelection (g, selection);
  43562. }
  43563. }
  43564. }
  43565. const UniformTextSection* lastSection = 0;
  43566. while (i.next() && i.lineY < clip.getBottom())
  43567. {
  43568. if (i.lineY + i.lineHeight >= clip.getY())
  43569. {
  43570. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43571. {
  43572. i.drawSelectedText (g, selection, selectedTextColour);
  43573. lastSection = 0;
  43574. }
  43575. else
  43576. {
  43577. i.draw (g, lastSection);
  43578. }
  43579. }
  43580. }
  43581. }
  43582. }
  43583. void TextEditor::paint (Graphics& g)
  43584. {
  43585. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43586. }
  43587. void TextEditor::paintOverChildren (Graphics& g)
  43588. {
  43589. if (caretFlashState
  43590. && hasKeyboardFocus (false)
  43591. && caretVisible
  43592. && ! isReadOnly())
  43593. {
  43594. g.setColour (findColour (caretColourId));
  43595. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43596. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43597. 2.0f, cursorHeight);
  43598. }
  43599. if (textToShowWhenEmpty.isNotEmpty()
  43600. && (! hasKeyboardFocus (false))
  43601. && getTotalNumChars() == 0)
  43602. {
  43603. g.setColour (colourForTextWhenEmpty);
  43604. g.setFont (getFont());
  43605. if (isMultiLine())
  43606. {
  43607. g.drawText (textToShowWhenEmpty,
  43608. 0, 0, getWidth(), getHeight(),
  43609. Justification::centred, true);
  43610. }
  43611. else
  43612. {
  43613. g.drawText (textToShowWhenEmpty,
  43614. leftIndent, topIndent,
  43615. viewport->getWidth() - leftIndent,
  43616. viewport->getHeight() - topIndent,
  43617. Justification::centredLeft, true);
  43618. }
  43619. }
  43620. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43621. }
  43622. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43623. {
  43624. public:
  43625. TextEditorMenuPerformer (TextEditor* const editor_)
  43626. : editor (editor_)
  43627. {
  43628. }
  43629. void modalStateFinished (int returnValue)
  43630. {
  43631. if (editor != 0 && returnValue != 0)
  43632. editor->performPopupMenuAction (returnValue);
  43633. }
  43634. private:
  43635. Component::SafePointer<TextEditor> editor;
  43636. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43637. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43638. };
  43639. void TextEditor::mouseDown (const MouseEvent& e)
  43640. {
  43641. beginDragAutoRepeat (100);
  43642. newTransaction();
  43643. if (wasFocused || ! selectAllTextWhenFocused)
  43644. {
  43645. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43646. {
  43647. moveCursorTo (getTextIndexAt (e.x, e.y),
  43648. e.mods.isShiftDown());
  43649. }
  43650. else
  43651. {
  43652. PopupMenu m;
  43653. m.setLookAndFeel (&getLookAndFeel());
  43654. addPopupMenuItems (m, &e);
  43655. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43656. }
  43657. }
  43658. }
  43659. void TextEditor::mouseDrag (const MouseEvent& e)
  43660. {
  43661. if (wasFocused || ! selectAllTextWhenFocused)
  43662. {
  43663. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43664. {
  43665. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43666. }
  43667. }
  43668. }
  43669. void TextEditor::mouseUp (const MouseEvent& e)
  43670. {
  43671. newTransaction();
  43672. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43673. if (wasFocused || ! selectAllTextWhenFocused)
  43674. {
  43675. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43676. {
  43677. moveCaret (getTextIndexAt (e.x, e.y));
  43678. }
  43679. }
  43680. wasFocused = true;
  43681. }
  43682. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43683. {
  43684. int tokenEnd = getTextIndexAt (e.x, e.y);
  43685. int tokenStart = tokenEnd;
  43686. if (e.getNumberOfClicks() > 3)
  43687. {
  43688. tokenStart = 0;
  43689. tokenEnd = getTotalNumChars();
  43690. }
  43691. else
  43692. {
  43693. const String t (getText());
  43694. const int totalLength = getTotalNumChars();
  43695. while (tokenEnd < totalLength)
  43696. {
  43697. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43698. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43699. ++tokenEnd;
  43700. else
  43701. break;
  43702. }
  43703. tokenStart = tokenEnd;
  43704. while (tokenStart > 0)
  43705. {
  43706. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43707. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43708. --tokenStart;
  43709. else
  43710. break;
  43711. }
  43712. if (e.getNumberOfClicks() > 2)
  43713. {
  43714. while (tokenEnd < totalLength)
  43715. {
  43716. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43717. ++tokenEnd;
  43718. else
  43719. break;
  43720. }
  43721. while (tokenStart > 0)
  43722. {
  43723. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43724. --tokenStart;
  43725. else
  43726. break;
  43727. }
  43728. }
  43729. }
  43730. moveCursorTo (tokenEnd, false);
  43731. moveCursorTo (tokenStart, true);
  43732. }
  43733. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43734. {
  43735. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43736. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43737. }
  43738. bool TextEditor::keyPressed (const KeyPress& key)
  43739. {
  43740. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43741. return false;
  43742. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43743. if (key.isKeyCode (KeyPress::leftKey)
  43744. || key.isKeyCode (KeyPress::upKey))
  43745. {
  43746. newTransaction();
  43747. int newPos;
  43748. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43749. newPos = indexAtPosition (cursorX, cursorY - 1);
  43750. else if (moveInWholeWordSteps)
  43751. newPos = findWordBreakBefore (getCaretPosition());
  43752. else
  43753. newPos = getCaretPosition() - 1;
  43754. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43755. }
  43756. else if (key.isKeyCode (KeyPress::rightKey)
  43757. || key.isKeyCode (KeyPress::downKey))
  43758. {
  43759. newTransaction();
  43760. int newPos;
  43761. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43762. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43763. else if (moveInWholeWordSteps)
  43764. newPos = findWordBreakAfter (getCaretPosition());
  43765. else
  43766. newPos = getCaretPosition() + 1;
  43767. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43768. }
  43769. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43770. {
  43771. newTransaction();
  43772. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43773. key.getModifiers().isShiftDown());
  43774. }
  43775. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43776. {
  43777. newTransaction();
  43778. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43779. key.getModifiers().isShiftDown());
  43780. }
  43781. else if (key.isKeyCode (KeyPress::homeKey))
  43782. {
  43783. newTransaction();
  43784. if (isMultiLine() && ! moveInWholeWordSteps)
  43785. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43786. key.getModifiers().isShiftDown());
  43787. else
  43788. moveCursorTo (0, key.getModifiers().isShiftDown());
  43789. }
  43790. else if (key.isKeyCode (KeyPress::endKey))
  43791. {
  43792. newTransaction();
  43793. if (isMultiLine() && ! moveInWholeWordSteps)
  43794. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43795. key.getModifiers().isShiftDown());
  43796. else
  43797. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43798. }
  43799. else if (key.isKeyCode (KeyPress::backspaceKey))
  43800. {
  43801. if (moveInWholeWordSteps)
  43802. {
  43803. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43804. }
  43805. else
  43806. {
  43807. if (selection.isEmpty() && selection.getStart() > 0)
  43808. selection.setStart (selection.getEnd() - 1);
  43809. }
  43810. cut();
  43811. }
  43812. else if (key.isKeyCode (KeyPress::deleteKey))
  43813. {
  43814. if (key.getModifiers().isShiftDown())
  43815. copy();
  43816. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43817. selection.setEnd (selection.getStart() + 1);
  43818. cut();
  43819. }
  43820. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43821. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43822. {
  43823. newTransaction();
  43824. copy();
  43825. }
  43826. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43827. {
  43828. newTransaction();
  43829. copy();
  43830. cut();
  43831. }
  43832. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43833. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43834. {
  43835. newTransaction();
  43836. paste();
  43837. }
  43838. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43839. {
  43840. newTransaction();
  43841. doUndoRedo (false);
  43842. }
  43843. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43844. {
  43845. newTransaction();
  43846. doUndoRedo (true);
  43847. }
  43848. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43849. {
  43850. newTransaction();
  43851. moveCursorTo (getTotalNumChars(), false);
  43852. moveCursorTo (0, true);
  43853. }
  43854. else if (key == KeyPress::returnKey)
  43855. {
  43856. newTransaction();
  43857. insertTextAtCaret ("\n");
  43858. }
  43859. else if (key.isKeyCode (KeyPress::escapeKey))
  43860. {
  43861. newTransaction();
  43862. moveCursorTo (getCaretPosition(), false);
  43863. escapePressed();
  43864. }
  43865. else if (key.getTextCharacter() >= ' '
  43866. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43867. {
  43868. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43869. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43870. }
  43871. else
  43872. {
  43873. return false;
  43874. }
  43875. return true;
  43876. }
  43877. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43878. {
  43879. if (! isKeyDown)
  43880. return false;
  43881. #if JUCE_WINDOWS
  43882. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43883. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43884. #endif
  43885. // (overridden to avoid forwarding key events to the parent)
  43886. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43887. }
  43888. const int baseMenuItemID = 0x7fff0000;
  43889. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43890. {
  43891. const bool writable = ! isReadOnly();
  43892. if (passwordCharacter == 0)
  43893. {
  43894. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43895. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43896. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43897. }
  43898. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43899. m.addSeparator();
  43900. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43901. m.addSeparator();
  43902. if (getUndoManager() != 0)
  43903. {
  43904. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43905. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43906. }
  43907. }
  43908. void TextEditor::performPopupMenuAction (const int menuItemID)
  43909. {
  43910. switch (menuItemID)
  43911. {
  43912. case baseMenuItemID + 1:
  43913. copy();
  43914. cut();
  43915. break;
  43916. case baseMenuItemID + 2:
  43917. copy();
  43918. break;
  43919. case baseMenuItemID + 3:
  43920. paste();
  43921. break;
  43922. case baseMenuItemID + 4:
  43923. cut();
  43924. break;
  43925. case baseMenuItemID + 5:
  43926. moveCursorTo (getTotalNumChars(), false);
  43927. moveCursorTo (0, true);
  43928. break;
  43929. case baseMenuItemID + 6:
  43930. doUndoRedo (false);
  43931. break;
  43932. case baseMenuItemID + 7:
  43933. doUndoRedo (true);
  43934. break;
  43935. default:
  43936. break;
  43937. }
  43938. }
  43939. void TextEditor::focusGained (FocusChangeType)
  43940. {
  43941. newTransaction();
  43942. caretFlashState = true;
  43943. if (selectAllTextWhenFocused)
  43944. {
  43945. moveCursorTo (0, false);
  43946. moveCursorTo (getTotalNumChars(), true);
  43947. }
  43948. repaint();
  43949. if (caretVisible)
  43950. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43951. ComponentPeer* const peer = getPeer();
  43952. if (peer != 0 && ! isReadOnly())
  43953. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43954. }
  43955. void TextEditor::focusLost (FocusChangeType)
  43956. {
  43957. newTransaction();
  43958. wasFocused = false;
  43959. textHolder->stopTimer();
  43960. caretFlashState = false;
  43961. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43962. repaint();
  43963. }
  43964. void TextEditor::resized()
  43965. {
  43966. viewport->setBoundsInset (borderSize);
  43967. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43968. updateTextHolderSize();
  43969. if (! isMultiLine())
  43970. {
  43971. scrollToMakeSureCursorIsVisible();
  43972. }
  43973. else
  43974. {
  43975. updateCaretPosition();
  43976. }
  43977. }
  43978. void TextEditor::handleCommandMessage (const int commandId)
  43979. {
  43980. Component::BailOutChecker checker (this);
  43981. switch (commandId)
  43982. {
  43983. case TextEditorDefs::textChangeMessageId:
  43984. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43985. break;
  43986. case TextEditorDefs::returnKeyMessageId:
  43987. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43988. break;
  43989. case TextEditorDefs::escapeKeyMessageId:
  43990. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43991. break;
  43992. case TextEditorDefs::focusLossMessageId:
  43993. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43994. break;
  43995. default:
  43996. jassertfalse;
  43997. break;
  43998. }
  43999. }
  44000. void TextEditor::enablementChanged()
  44001. {
  44002. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  44003. : MouseCursor::IBeamCursor);
  44004. repaint();
  44005. }
  44006. UndoManager* TextEditor::getUndoManager() throw()
  44007. {
  44008. return isReadOnly() ? 0 : &undoManager;
  44009. }
  44010. void TextEditor::clearInternal (UndoManager* const um)
  44011. {
  44012. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  44013. }
  44014. void TextEditor::insert (const String& text,
  44015. const int insertIndex,
  44016. const Font& font,
  44017. const Colour& colour,
  44018. UndoManager* const um,
  44019. const int caretPositionToMoveTo)
  44020. {
  44021. if (text.isNotEmpty())
  44022. {
  44023. if (um != 0)
  44024. {
  44025. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44026. newTransaction();
  44027. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  44028. caretPosition, caretPositionToMoveTo));
  44029. }
  44030. else
  44031. {
  44032. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  44033. // a line gets moved due to word wrap
  44034. int index = 0;
  44035. int nextIndex = 0;
  44036. for (int i = 0; i < sections.size(); ++i)
  44037. {
  44038. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44039. if (insertIndex == index)
  44040. {
  44041. sections.insert (i, new UniformTextSection (text,
  44042. font, colour,
  44043. passwordCharacter));
  44044. break;
  44045. }
  44046. else if (insertIndex > index && insertIndex < nextIndex)
  44047. {
  44048. splitSection (i, insertIndex - index);
  44049. sections.insert (i + 1, new UniformTextSection (text,
  44050. font, colour,
  44051. passwordCharacter));
  44052. break;
  44053. }
  44054. index = nextIndex;
  44055. }
  44056. if (nextIndex == insertIndex)
  44057. sections.add (new UniformTextSection (text,
  44058. font, colour,
  44059. passwordCharacter));
  44060. coalesceSimilarSections();
  44061. totalNumChars = -1;
  44062. valueTextNeedsUpdating = true;
  44063. moveCursorTo (caretPositionToMoveTo, false);
  44064. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44065. }
  44066. }
  44067. }
  44068. void TextEditor::reinsert (const int insertIndex,
  44069. const Array <UniformTextSection*>& sectionsToInsert)
  44070. {
  44071. int index = 0;
  44072. int nextIndex = 0;
  44073. for (int i = 0; i < sections.size(); ++i)
  44074. {
  44075. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44076. if (insertIndex == index)
  44077. {
  44078. for (int j = sectionsToInsert.size(); --j >= 0;)
  44079. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44080. break;
  44081. }
  44082. else if (insertIndex > index && insertIndex < nextIndex)
  44083. {
  44084. splitSection (i, insertIndex - index);
  44085. for (int j = sectionsToInsert.size(); --j >= 0;)
  44086. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44087. break;
  44088. }
  44089. index = nextIndex;
  44090. }
  44091. if (nextIndex == insertIndex)
  44092. {
  44093. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44094. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44095. }
  44096. coalesceSimilarSections();
  44097. totalNumChars = -1;
  44098. valueTextNeedsUpdating = true;
  44099. }
  44100. void TextEditor::remove (const Range<int>& range,
  44101. UndoManager* const um,
  44102. const int caretPositionToMoveTo)
  44103. {
  44104. if (! range.isEmpty())
  44105. {
  44106. int index = 0;
  44107. for (int i = 0; i < sections.size(); ++i)
  44108. {
  44109. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44110. if (range.getStart() > index && range.getStart() < nextIndex)
  44111. {
  44112. splitSection (i, range.getStart() - index);
  44113. --i;
  44114. }
  44115. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44116. {
  44117. splitSection (i, range.getEnd() - index);
  44118. --i;
  44119. }
  44120. else
  44121. {
  44122. index = nextIndex;
  44123. if (index > range.getEnd())
  44124. break;
  44125. }
  44126. }
  44127. index = 0;
  44128. if (um != 0)
  44129. {
  44130. Array <UniformTextSection*> removedSections;
  44131. for (int i = 0; i < sections.size(); ++i)
  44132. {
  44133. if (range.getEnd() <= range.getStart())
  44134. break;
  44135. UniformTextSection* const section = sections.getUnchecked (i);
  44136. const int nextIndex = index + section->getTotalLength();
  44137. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44138. removedSections.add (new UniformTextSection (*section));
  44139. index = nextIndex;
  44140. }
  44141. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44142. newTransaction();
  44143. um->perform (new RemoveAction (*this, range, caretPosition,
  44144. caretPositionToMoveTo, removedSections));
  44145. }
  44146. else
  44147. {
  44148. Range<int> remainingRange (range);
  44149. for (int i = 0; i < sections.size(); ++i)
  44150. {
  44151. UniformTextSection* const section = sections.getUnchecked (i);
  44152. const int nextIndex = index + section->getTotalLength();
  44153. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44154. {
  44155. sections.remove(i);
  44156. section->clear();
  44157. delete section;
  44158. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44159. if (remainingRange.isEmpty())
  44160. break;
  44161. --i;
  44162. }
  44163. else
  44164. {
  44165. index = nextIndex;
  44166. }
  44167. }
  44168. coalesceSimilarSections();
  44169. totalNumChars = -1;
  44170. valueTextNeedsUpdating = true;
  44171. moveCursorTo (caretPositionToMoveTo, false);
  44172. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44173. }
  44174. }
  44175. }
  44176. const String TextEditor::getText() const
  44177. {
  44178. String t;
  44179. t.preallocateStorage (getTotalNumChars());
  44180. String::Concatenator concatenator (t);
  44181. for (int i = 0; i < sections.size(); ++i)
  44182. sections.getUnchecked (i)->appendAllText (concatenator);
  44183. return t;
  44184. }
  44185. const String TextEditor::getTextInRange (const Range<int>& range) const
  44186. {
  44187. String t;
  44188. if (! range.isEmpty())
  44189. {
  44190. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44191. String::Concatenator concatenator (t);
  44192. int index = 0;
  44193. for (int i = 0; i < sections.size(); ++i)
  44194. {
  44195. const UniformTextSection* const s = sections.getUnchecked (i);
  44196. const int nextIndex = index + s->getTotalLength();
  44197. if (range.getStart() < nextIndex)
  44198. {
  44199. if (range.getEnd() <= index)
  44200. break;
  44201. s->appendSubstring (concatenator, range - index);
  44202. }
  44203. index = nextIndex;
  44204. }
  44205. }
  44206. return t;
  44207. }
  44208. const String TextEditor::getHighlightedText() const
  44209. {
  44210. return getTextInRange (selection);
  44211. }
  44212. int TextEditor::getTotalNumChars() const
  44213. {
  44214. if (totalNumChars < 0)
  44215. {
  44216. totalNumChars = 0;
  44217. for (int i = sections.size(); --i >= 0;)
  44218. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44219. }
  44220. return totalNumChars;
  44221. }
  44222. bool TextEditor::isEmpty() const
  44223. {
  44224. return getTotalNumChars() == 0;
  44225. }
  44226. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44227. {
  44228. const float wordWrapWidth = getWordWrapWidth();
  44229. if (wordWrapWidth > 0 && sections.size() > 0)
  44230. {
  44231. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44232. i.getCharPosition (index, cx, cy, lineHeight);
  44233. }
  44234. else
  44235. {
  44236. cx = cy = 0;
  44237. lineHeight = currentFont.getHeight();
  44238. }
  44239. }
  44240. int TextEditor::indexAtPosition (const float x, const float y)
  44241. {
  44242. const float wordWrapWidth = getWordWrapWidth();
  44243. if (wordWrapWidth > 0)
  44244. {
  44245. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44246. while (i.next())
  44247. {
  44248. if (i.lineY + i.lineHeight > y)
  44249. {
  44250. if (i.lineY > y)
  44251. return jmax (0, i.indexInText - 1);
  44252. if (i.atomX >= x)
  44253. return i.indexInText;
  44254. if (x < i.atomRight)
  44255. return i.xToIndex (x);
  44256. }
  44257. }
  44258. }
  44259. return getTotalNumChars();
  44260. }
  44261. int TextEditor::findWordBreakAfter (const int position) const
  44262. {
  44263. const String t (getTextInRange (Range<int> (position, position + 512)));
  44264. const int totalLength = t.length();
  44265. int i = 0;
  44266. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44267. ++i;
  44268. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44269. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44270. ++i;
  44271. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44272. ++i;
  44273. return position + i;
  44274. }
  44275. int TextEditor::findWordBreakBefore (const int position) const
  44276. {
  44277. if (position <= 0)
  44278. return 0;
  44279. const int startOfBuffer = jmax (0, position - 512);
  44280. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44281. int i = position - startOfBuffer;
  44282. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44283. --i;
  44284. if (i > 0)
  44285. {
  44286. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44287. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44288. --i;
  44289. }
  44290. jassert (startOfBuffer + i >= 0);
  44291. return startOfBuffer + i;
  44292. }
  44293. void TextEditor::splitSection (const int sectionIndex,
  44294. const int charToSplitAt)
  44295. {
  44296. jassert (sections[sectionIndex] != 0);
  44297. sections.insert (sectionIndex + 1,
  44298. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44299. }
  44300. void TextEditor::coalesceSimilarSections()
  44301. {
  44302. for (int i = 0; i < sections.size() - 1; ++i)
  44303. {
  44304. UniformTextSection* const s1 = sections.getUnchecked (i);
  44305. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44306. if (s1->font == s2->font
  44307. && s1->colour == s2->colour)
  44308. {
  44309. s1->append (*s2, passwordCharacter);
  44310. sections.remove (i + 1);
  44311. delete s2;
  44312. --i;
  44313. }
  44314. }
  44315. }
  44316. END_JUCE_NAMESPACE
  44317. /*** End of inlined file: juce_TextEditor.cpp ***/
  44318. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44319. BEGIN_JUCE_NAMESPACE
  44320. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44321. class ToolbarSpacerComp : public ToolbarItemComponent
  44322. {
  44323. public:
  44324. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44325. : ToolbarItemComponent (itemId_, String::empty, false),
  44326. fixedSize (fixedSize_),
  44327. drawBar (drawBar_)
  44328. {
  44329. }
  44330. ~ToolbarSpacerComp()
  44331. {
  44332. }
  44333. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44334. int& preferredSize, int& minSize, int& maxSize)
  44335. {
  44336. if (fixedSize <= 0)
  44337. {
  44338. preferredSize = toolbarThickness * 2;
  44339. minSize = 4;
  44340. maxSize = 32768;
  44341. }
  44342. else
  44343. {
  44344. maxSize = roundToInt (toolbarThickness * fixedSize);
  44345. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44346. preferredSize = maxSize;
  44347. if (getEditingMode() == editableOnPalette)
  44348. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44349. }
  44350. return true;
  44351. }
  44352. void paintButtonArea (Graphics&, int, int, bool, bool)
  44353. {
  44354. }
  44355. void contentAreaChanged (const Rectangle<int>&)
  44356. {
  44357. }
  44358. int getResizeOrder() const throw()
  44359. {
  44360. return fixedSize <= 0 ? 0 : 1;
  44361. }
  44362. void paint (Graphics& g)
  44363. {
  44364. const int w = getWidth();
  44365. const int h = getHeight();
  44366. if (drawBar)
  44367. {
  44368. g.setColour (findColour (Toolbar::separatorColourId, true));
  44369. const float thickness = 0.2f;
  44370. if (isToolbarVertical())
  44371. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44372. else
  44373. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44374. }
  44375. if (getEditingMode() != normalMode && ! drawBar)
  44376. {
  44377. g.setColour (findColour (Toolbar::separatorColourId, true));
  44378. const int indentX = jmin (2, (w - 3) / 2);
  44379. const int indentY = jmin (2, (h - 3) / 2);
  44380. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44381. if (fixedSize <= 0)
  44382. {
  44383. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44384. if (isToolbarVertical())
  44385. {
  44386. x1 = w * 0.5f;
  44387. y1 = h * 0.4f;
  44388. x2 = x1;
  44389. y2 = indentX * 2.0f;
  44390. x3 = x1;
  44391. y3 = h * 0.6f;
  44392. x4 = x1;
  44393. y4 = h - y2;
  44394. hw = w * 0.15f;
  44395. hl = w * 0.2f;
  44396. }
  44397. else
  44398. {
  44399. x1 = w * 0.4f;
  44400. y1 = h * 0.5f;
  44401. x2 = indentX * 2.0f;
  44402. y2 = y1;
  44403. x3 = w * 0.6f;
  44404. y3 = y1;
  44405. x4 = w - x2;
  44406. y4 = y1;
  44407. hw = h * 0.15f;
  44408. hl = h * 0.2f;
  44409. }
  44410. Path p;
  44411. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44412. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44413. g.fillPath (p);
  44414. }
  44415. }
  44416. }
  44417. juce_UseDebuggingNewOperator
  44418. private:
  44419. const float fixedSize;
  44420. const bool drawBar;
  44421. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44422. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44423. };
  44424. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44425. {
  44426. public:
  44427. MissingItemsComponent (Toolbar& owner_, const int height_)
  44428. : PopupMenuCustomComponent (true),
  44429. owner (owner_),
  44430. height (height_)
  44431. {
  44432. for (int i = owner_.items.size(); --i >= 0;)
  44433. {
  44434. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44435. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44436. {
  44437. oldIndexes.insert (0, i);
  44438. addAndMakeVisible (tc, 0);
  44439. }
  44440. }
  44441. layout (400);
  44442. }
  44443. ~MissingItemsComponent()
  44444. {
  44445. // deleting the toolbar while its menu it open??
  44446. jassert (owner.isValidComponent());
  44447. for (int i = 0; i < getNumChildComponents(); ++i)
  44448. {
  44449. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44450. if (tc != 0)
  44451. {
  44452. tc->setVisible (false);
  44453. const int index = oldIndexes.remove (i);
  44454. owner.addChildComponent (tc, index);
  44455. --i;
  44456. }
  44457. }
  44458. owner.resized();
  44459. }
  44460. void layout (const int preferredWidth)
  44461. {
  44462. const int indent = 8;
  44463. int x = indent;
  44464. int y = indent;
  44465. int maxX = 0;
  44466. for (int i = 0; i < getNumChildComponents(); ++i)
  44467. {
  44468. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44469. if (tc != 0)
  44470. {
  44471. int preferredSize = 1, minSize = 1, maxSize = 1;
  44472. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44473. {
  44474. if (x + preferredSize > preferredWidth && x > indent)
  44475. {
  44476. x = indent;
  44477. y += height;
  44478. }
  44479. tc->setBounds (x, y, preferredSize, height);
  44480. x += preferredSize;
  44481. maxX = jmax (maxX, x);
  44482. }
  44483. }
  44484. }
  44485. setSize (maxX + 8, y + height + 8);
  44486. }
  44487. void getIdealSize (int& idealWidth, int& idealHeight)
  44488. {
  44489. idealWidth = getWidth();
  44490. idealHeight = getHeight();
  44491. }
  44492. juce_UseDebuggingNewOperator
  44493. private:
  44494. Toolbar& owner;
  44495. const int height;
  44496. Array <int> oldIndexes;
  44497. MissingItemsComponent (const MissingItemsComponent&);
  44498. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44499. };
  44500. Toolbar::Toolbar()
  44501. : vertical (false),
  44502. isEditingActive (false),
  44503. toolbarStyle (Toolbar::iconsOnly)
  44504. {
  44505. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44506. missingItemsButton->setAlwaysOnTop (true);
  44507. missingItemsButton->addButtonListener (this);
  44508. }
  44509. Toolbar::~Toolbar()
  44510. {
  44511. animator.cancelAllAnimations (true);
  44512. deleteAllChildren();
  44513. }
  44514. void Toolbar::setVertical (const bool shouldBeVertical)
  44515. {
  44516. if (vertical != shouldBeVertical)
  44517. {
  44518. vertical = shouldBeVertical;
  44519. resized();
  44520. }
  44521. }
  44522. void Toolbar::clear()
  44523. {
  44524. for (int i = items.size(); --i >= 0;)
  44525. {
  44526. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44527. items.remove (i);
  44528. delete tc;
  44529. }
  44530. resized();
  44531. }
  44532. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44533. {
  44534. if (itemId == ToolbarItemFactory::separatorBarId)
  44535. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44536. else if (itemId == ToolbarItemFactory::spacerId)
  44537. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44538. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44539. return new ToolbarSpacerComp (itemId, 0, false);
  44540. return factory.createItem (itemId);
  44541. }
  44542. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44543. const int itemId,
  44544. const int insertIndex)
  44545. {
  44546. // An ID can't be zero - this might indicate a mistake somewhere?
  44547. jassert (itemId != 0);
  44548. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44549. if (tc != 0)
  44550. {
  44551. #if JUCE_DEBUG
  44552. Array <int> allowedIds;
  44553. factory.getAllToolbarItemIds (allowedIds);
  44554. // If your factory can create an item for a given ID, it must also return
  44555. // that ID from its getAllToolbarItemIds() method!
  44556. jassert (allowedIds.contains (itemId));
  44557. #endif
  44558. items.insert (insertIndex, tc);
  44559. addAndMakeVisible (tc, insertIndex);
  44560. }
  44561. }
  44562. void Toolbar::addItem (ToolbarItemFactory& factory,
  44563. const int itemId,
  44564. const int insertIndex)
  44565. {
  44566. addItemInternal (factory, itemId, insertIndex);
  44567. resized();
  44568. }
  44569. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44570. {
  44571. Array <int> ids;
  44572. factoryToUse.getDefaultItemSet (ids);
  44573. clear();
  44574. for (int i = 0; i < ids.size(); ++i)
  44575. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44576. resized();
  44577. }
  44578. void Toolbar::removeToolbarItem (const int itemIndex)
  44579. {
  44580. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44581. if (tc != 0)
  44582. {
  44583. items.removeValue (tc);
  44584. delete tc;
  44585. resized();
  44586. }
  44587. }
  44588. int Toolbar::getNumItems() const throw()
  44589. {
  44590. return items.size();
  44591. }
  44592. int Toolbar::getItemId (const int itemIndex) const throw()
  44593. {
  44594. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44595. return tc != 0 ? tc->getItemId() : 0;
  44596. }
  44597. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44598. {
  44599. return items [itemIndex];
  44600. }
  44601. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44602. {
  44603. for (;;)
  44604. {
  44605. index += delta;
  44606. ToolbarItemComponent* const tc = getItemComponent (index);
  44607. if (tc == 0)
  44608. break;
  44609. if (tc->isActive)
  44610. return tc;
  44611. }
  44612. return 0;
  44613. }
  44614. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44615. {
  44616. if (toolbarStyle != newStyle)
  44617. {
  44618. toolbarStyle = newStyle;
  44619. updateAllItemPositions (false);
  44620. }
  44621. }
  44622. const String Toolbar::toString() const
  44623. {
  44624. String s ("TB:");
  44625. for (int i = 0; i < getNumItems(); ++i)
  44626. s << getItemId(i) << ' ';
  44627. return s.trimEnd();
  44628. }
  44629. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44630. const String& savedVersion)
  44631. {
  44632. if (! savedVersion.startsWith ("TB:"))
  44633. return false;
  44634. StringArray tokens;
  44635. tokens.addTokens (savedVersion.substring (3), false);
  44636. clear();
  44637. for (int i = 0; i < tokens.size(); ++i)
  44638. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44639. resized();
  44640. return true;
  44641. }
  44642. void Toolbar::paint (Graphics& g)
  44643. {
  44644. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44645. }
  44646. int Toolbar::getThickness() const throw()
  44647. {
  44648. return vertical ? getWidth() : getHeight();
  44649. }
  44650. int Toolbar::getLength() const throw()
  44651. {
  44652. return vertical ? getHeight() : getWidth();
  44653. }
  44654. void Toolbar::setEditingActive (const bool active)
  44655. {
  44656. if (isEditingActive != active)
  44657. {
  44658. isEditingActive = active;
  44659. updateAllItemPositions (false);
  44660. }
  44661. }
  44662. void Toolbar::resized()
  44663. {
  44664. updateAllItemPositions (false);
  44665. }
  44666. void Toolbar::updateAllItemPositions (const bool animate)
  44667. {
  44668. if (getWidth() > 0 && getHeight() > 0)
  44669. {
  44670. StretchableObjectResizer resizer;
  44671. int i;
  44672. for (i = 0; i < items.size(); ++i)
  44673. {
  44674. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44675. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44676. : ToolbarItemComponent::normalMode);
  44677. tc->setStyle (toolbarStyle);
  44678. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44679. int preferredSize = 1, minSize = 1, maxSize = 1;
  44680. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44681. preferredSize, minSize, maxSize))
  44682. {
  44683. tc->isActive = true;
  44684. resizer.addItem (preferredSize, minSize, maxSize,
  44685. spacer != 0 ? spacer->getResizeOrder() : 2);
  44686. }
  44687. else
  44688. {
  44689. tc->isActive = false;
  44690. tc->setVisible (false);
  44691. }
  44692. }
  44693. resizer.resizeToFit (getLength());
  44694. int totalLength = 0;
  44695. for (i = 0; i < resizer.getNumItems(); ++i)
  44696. totalLength += (int) resizer.getItemSize (i);
  44697. const bool itemsOffTheEnd = totalLength > getLength();
  44698. const int extrasButtonSize = getThickness() / 2;
  44699. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44700. missingItemsButton->setVisible (itemsOffTheEnd);
  44701. missingItemsButton->setEnabled (! isEditingActive);
  44702. if (vertical)
  44703. missingItemsButton->setCentrePosition (getWidth() / 2,
  44704. getHeight() - 4 - extrasButtonSize / 2);
  44705. else
  44706. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44707. getHeight() / 2);
  44708. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44709. : missingItemsButton->getX()) - 4
  44710. : getLength();
  44711. int pos = 0, activeIndex = 0;
  44712. for (i = 0; i < items.size(); ++i)
  44713. {
  44714. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44715. if (tc->isActive)
  44716. {
  44717. const int size = (int) resizer.getItemSize (activeIndex++);
  44718. Rectangle<int> newBounds;
  44719. if (vertical)
  44720. newBounds.setBounds (0, pos, getWidth(), size);
  44721. else
  44722. newBounds.setBounds (pos, 0, size, getHeight());
  44723. if (animate)
  44724. {
  44725. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44726. }
  44727. else
  44728. {
  44729. animator.cancelAnimation (tc, false);
  44730. tc->setBounds (newBounds);
  44731. }
  44732. pos += size;
  44733. tc->setVisible (pos <= maxLength
  44734. && ((! tc->isBeingDragged)
  44735. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44736. }
  44737. }
  44738. }
  44739. }
  44740. void Toolbar::buttonClicked (Button*)
  44741. {
  44742. jassert (missingItemsButton->isShowing());
  44743. if (missingItemsButton->isShowing())
  44744. {
  44745. PopupMenu m;
  44746. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44747. m.showAt (missingItemsButton);
  44748. }
  44749. }
  44750. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44751. Component* /*sourceComponent*/)
  44752. {
  44753. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44754. }
  44755. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44756. {
  44757. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44758. if (tc != 0)
  44759. {
  44760. if (getNumItems() == 0)
  44761. {
  44762. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44763. {
  44764. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44765. if (palette != 0)
  44766. palette->replaceComponent (tc);
  44767. }
  44768. else
  44769. {
  44770. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44771. }
  44772. items.add (tc);
  44773. addChildComponent (tc);
  44774. updateAllItemPositions (false);
  44775. }
  44776. else
  44777. {
  44778. for (int i = getNumItems(); --i >= 0;)
  44779. {
  44780. int currentIndex = getIndexOfChildComponent (tc);
  44781. if (currentIndex < 0)
  44782. {
  44783. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44784. {
  44785. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44786. if (palette != 0)
  44787. palette->replaceComponent (tc);
  44788. }
  44789. else
  44790. {
  44791. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44792. }
  44793. items.add (tc);
  44794. addChildComponent (tc);
  44795. currentIndex = getIndexOfChildComponent (tc);
  44796. updateAllItemPositions (true);
  44797. }
  44798. int newIndex = currentIndex;
  44799. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44800. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44801. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44802. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44803. if (prev != 0)
  44804. {
  44805. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44806. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44807. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44808. {
  44809. newIndex = getIndexOfChildComponent (prev);
  44810. }
  44811. }
  44812. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44813. if (next != 0)
  44814. {
  44815. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44816. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44817. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44818. {
  44819. newIndex = getIndexOfChildComponent (next) + 1;
  44820. }
  44821. }
  44822. if (newIndex != currentIndex)
  44823. {
  44824. items.removeValue (tc);
  44825. removeChildComponent (tc);
  44826. addChildComponent (tc, newIndex);
  44827. items.insert (newIndex, tc);
  44828. updateAllItemPositions (true);
  44829. }
  44830. else
  44831. {
  44832. break;
  44833. }
  44834. }
  44835. }
  44836. }
  44837. }
  44838. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44839. {
  44840. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44841. if (tc != 0)
  44842. {
  44843. if (isParentOf (tc))
  44844. {
  44845. items.removeValue (tc);
  44846. removeChildComponent (tc);
  44847. updateAllItemPositions (true);
  44848. }
  44849. }
  44850. }
  44851. void Toolbar::itemDropped (const String&, Component*, int, int)
  44852. {
  44853. }
  44854. void Toolbar::mouseDown (const MouseEvent& e)
  44855. {
  44856. if (e.mods.isPopupMenu())
  44857. {
  44858. }
  44859. }
  44860. class ToolbarCustomisationDialog : public DialogWindow
  44861. {
  44862. public:
  44863. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44864. Toolbar* const toolbar_,
  44865. const int optionFlags)
  44866. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44867. toolbar (toolbar_)
  44868. {
  44869. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44870. setResizable (true, true);
  44871. setResizeLimits (400, 300, 1500, 1000);
  44872. positionNearBar();
  44873. }
  44874. ~ToolbarCustomisationDialog()
  44875. {
  44876. setContentComponent (0, true);
  44877. }
  44878. void closeButtonPressed()
  44879. {
  44880. setVisible (false);
  44881. }
  44882. bool canModalEventBeSentToComponent (const Component* comp)
  44883. {
  44884. return toolbar->isParentOf (comp);
  44885. }
  44886. void positionNearBar()
  44887. {
  44888. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44889. const int tbx = toolbar->getScreenX();
  44890. const int tby = toolbar->getScreenY();
  44891. const int gap = 8;
  44892. int x, y;
  44893. if (toolbar->isVertical())
  44894. {
  44895. y = tby;
  44896. if (tbx > screenSize.getCentreX())
  44897. x = tbx - getWidth() - gap;
  44898. else
  44899. x = tbx + toolbar->getWidth() + gap;
  44900. }
  44901. else
  44902. {
  44903. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44904. if (tby > screenSize.getCentreY())
  44905. y = tby - getHeight() - gap;
  44906. else
  44907. y = tby + toolbar->getHeight() + gap;
  44908. }
  44909. setTopLeftPosition (x, y);
  44910. }
  44911. private:
  44912. Toolbar* const toolbar;
  44913. class CustomiserPanel : public Component,
  44914. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44915. private ButtonListener
  44916. {
  44917. public:
  44918. CustomiserPanel (ToolbarItemFactory& factory_,
  44919. Toolbar* const toolbar_,
  44920. const int optionFlags)
  44921. : factory (factory_),
  44922. toolbar (toolbar_),
  44923. styleBox (0),
  44924. defaultButton (0)
  44925. {
  44926. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44927. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44928. | Toolbar::allowIconsWithTextChoice
  44929. | Toolbar::allowTextOnlyChoice)) != 0)
  44930. {
  44931. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44932. styleBox->setEditableText (false);
  44933. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44934. styleBox->addItem (TRANS("Show icons only"), 1);
  44935. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44936. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44937. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44938. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44939. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44940. styleBox->setSelectedId (1);
  44941. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44942. styleBox->setSelectedId (2);
  44943. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44944. styleBox->setSelectedId (3);
  44945. styleBox->addListener (this);
  44946. }
  44947. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44948. {
  44949. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44950. defaultButton->addButtonListener (this);
  44951. }
  44952. addAndMakeVisible (instructions = new Label (String::empty,
  44953. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  44954. instructions->setFont (Font (13.0f));
  44955. setSize (500, 300);
  44956. }
  44957. ~CustomiserPanel()
  44958. {
  44959. deleteAllChildren();
  44960. }
  44961. void comboBoxChanged (ComboBox*)
  44962. {
  44963. if (styleBox->getSelectedId() == 1)
  44964. toolbar->setStyle (Toolbar::iconsOnly);
  44965. else if (styleBox->getSelectedId() == 2)
  44966. toolbar->setStyle (Toolbar::iconsWithText);
  44967. else if (styleBox->getSelectedId() == 3)
  44968. toolbar->setStyle (Toolbar::textOnly);
  44969. palette->resized(); // to make it update the styles
  44970. }
  44971. void buttonClicked (Button*)
  44972. {
  44973. toolbar->addDefaultItems (factory);
  44974. }
  44975. void paint (Graphics& g)
  44976. {
  44977. Colour background;
  44978. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44979. if (dw != 0)
  44980. background = dw->getBackgroundColour();
  44981. g.setColour (background.contrasting().withAlpha (0.3f));
  44982. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44983. }
  44984. void resized()
  44985. {
  44986. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44987. if (styleBox != 0)
  44988. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44989. if (defaultButton != 0)
  44990. {
  44991. defaultButton->changeWidthToFitText (22);
  44992. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44993. }
  44994. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44995. }
  44996. private:
  44997. ToolbarItemFactory& factory;
  44998. Toolbar* const toolbar;
  44999. Label* instructions;
  45000. ToolbarItemPalette* palette;
  45001. ComboBox* styleBox;
  45002. TextButton* defaultButton;
  45003. };
  45004. };
  45005. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  45006. {
  45007. setEditingActive (true);
  45008. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  45009. dw.runModalLoop();
  45010. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  45011. setEditingActive (false);
  45012. }
  45013. END_JUCE_NAMESPACE
  45014. /*** End of inlined file: juce_Toolbar.cpp ***/
  45015. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  45016. BEGIN_JUCE_NAMESPACE
  45017. ToolbarItemFactory::ToolbarItemFactory()
  45018. {
  45019. }
  45020. ToolbarItemFactory::~ToolbarItemFactory()
  45021. {
  45022. }
  45023. class ItemDragAndDropOverlayComponent : public Component
  45024. {
  45025. public:
  45026. ItemDragAndDropOverlayComponent()
  45027. : isDragging (false)
  45028. {
  45029. setAlwaysOnTop (true);
  45030. setRepaintsOnMouseActivity (true);
  45031. setMouseCursor (MouseCursor::DraggingHandCursor);
  45032. }
  45033. ~ItemDragAndDropOverlayComponent()
  45034. {
  45035. }
  45036. void paint (Graphics& g)
  45037. {
  45038. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45039. if (isMouseOverOrDragging()
  45040. && tc != 0
  45041. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45042. {
  45043. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  45044. g.drawRect (0, 0, getWidth(), getHeight(),
  45045. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  45046. }
  45047. }
  45048. void mouseDown (const MouseEvent& e)
  45049. {
  45050. isDragging = false;
  45051. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45052. if (tc != 0)
  45053. {
  45054. tc->dragOffsetX = e.x;
  45055. tc->dragOffsetY = e.y;
  45056. }
  45057. }
  45058. void mouseDrag (const MouseEvent& e)
  45059. {
  45060. if (! (isDragging || e.mouseWasClicked()))
  45061. {
  45062. isDragging = true;
  45063. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45064. if (dnd != 0)
  45065. {
  45066. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45067. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45068. if (tc != 0)
  45069. {
  45070. tc->isBeingDragged = true;
  45071. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45072. tc->setVisible (false);
  45073. }
  45074. }
  45075. }
  45076. }
  45077. void mouseUp (const MouseEvent&)
  45078. {
  45079. isDragging = false;
  45080. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45081. if (tc != 0)
  45082. {
  45083. tc->isBeingDragged = false;
  45084. Toolbar* const tb = tc->getToolbar();
  45085. if (tb != 0)
  45086. tb->updateAllItemPositions (true);
  45087. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45088. delete tc;
  45089. }
  45090. }
  45091. void parentSizeChanged()
  45092. {
  45093. setBounds (0, 0, getParentWidth(), getParentHeight());
  45094. }
  45095. juce_UseDebuggingNewOperator
  45096. private:
  45097. bool isDragging;
  45098. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45099. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45100. };
  45101. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45102. const String& labelText,
  45103. const bool isBeingUsedAsAButton_)
  45104. : Button (labelText),
  45105. itemId (itemId_),
  45106. mode (normalMode),
  45107. toolbarStyle (Toolbar::iconsOnly),
  45108. dragOffsetX (0),
  45109. dragOffsetY (0),
  45110. isActive (true),
  45111. isBeingDragged (false),
  45112. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45113. {
  45114. // Your item ID can't be 0!
  45115. jassert (itemId_ != 0);
  45116. }
  45117. ToolbarItemComponent::~ToolbarItemComponent()
  45118. {
  45119. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45120. overlayComp = 0;
  45121. }
  45122. Toolbar* ToolbarItemComponent::getToolbar() const
  45123. {
  45124. return dynamic_cast <Toolbar*> (getParentComponent());
  45125. }
  45126. bool ToolbarItemComponent::isToolbarVertical() const
  45127. {
  45128. const Toolbar* const t = getToolbar();
  45129. return t != 0 && t->isVertical();
  45130. }
  45131. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45132. {
  45133. if (toolbarStyle != newStyle)
  45134. {
  45135. toolbarStyle = newStyle;
  45136. repaint();
  45137. resized();
  45138. }
  45139. }
  45140. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45141. {
  45142. if (isBeingUsedAsAButton)
  45143. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45144. over, down, *this);
  45145. if (toolbarStyle != Toolbar::iconsOnly)
  45146. {
  45147. const int indent = contentArea.getX();
  45148. int y = indent;
  45149. int h = getHeight() - indent * 2;
  45150. if (toolbarStyle == Toolbar::iconsWithText)
  45151. {
  45152. y = contentArea.getBottom() + indent / 2;
  45153. h -= contentArea.getHeight();
  45154. }
  45155. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45156. getButtonText(), *this);
  45157. }
  45158. if (! contentArea.isEmpty())
  45159. {
  45160. g.saveState();
  45161. g.setOrigin (contentArea.getX(), contentArea.getY());
  45162. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45163. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45164. g.restoreState();
  45165. }
  45166. }
  45167. void ToolbarItemComponent::resized()
  45168. {
  45169. if (toolbarStyle != Toolbar::textOnly)
  45170. {
  45171. const int indent = jmin (proportionOfWidth (0.08f),
  45172. proportionOfHeight (0.08f));
  45173. contentArea = Rectangle<int> (indent, indent,
  45174. getWidth() - indent * 2,
  45175. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45176. : (getHeight() - indent * 2));
  45177. }
  45178. else
  45179. {
  45180. contentArea = Rectangle<int>();
  45181. }
  45182. contentAreaChanged (contentArea);
  45183. }
  45184. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45185. {
  45186. if (mode != newMode)
  45187. {
  45188. mode = newMode;
  45189. repaint();
  45190. if (mode == normalMode)
  45191. {
  45192. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45193. overlayComp = 0;
  45194. }
  45195. else if (overlayComp == 0)
  45196. {
  45197. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45198. overlayComp->parentSizeChanged();
  45199. }
  45200. resized();
  45201. }
  45202. }
  45203. END_JUCE_NAMESPACE
  45204. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45205. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45206. BEGIN_JUCE_NAMESPACE
  45207. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45208. Toolbar* const toolbar_)
  45209. : factory (factory_),
  45210. toolbar (toolbar_)
  45211. {
  45212. Component* const itemHolder = new Component();
  45213. Array <int> allIds;
  45214. factory_.getAllToolbarItemIds (allIds);
  45215. for (int i = 0; i < allIds.size(); ++i)
  45216. {
  45217. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45218. jassert (tc != 0);
  45219. if (tc != 0)
  45220. {
  45221. itemHolder->addAndMakeVisible (tc);
  45222. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45223. }
  45224. }
  45225. viewport = new Viewport();
  45226. viewport->setViewedComponent (itemHolder);
  45227. addAndMakeVisible (viewport);
  45228. }
  45229. ToolbarItemPalette::~ToolbarItemPalette()
  45230. {
  45231. viewport->getViewedComponent()->deleteAllChildren();
  45232. deleteAllChildren();
  45233. }
  45234. void ToolbarItemPalette::resized()
  45235. {
  45236. viewport->setBoundsInset (BorderSize (1));
  45237. Component* const itemHolder = viewport->getViewedComponent();
  45238. const int indent = 8;
  45239. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45240. const int height = toolbar->getThickness();
  45241. int x = indent;
  45242. int y = indent;
  45243. int maxX = 0;
  45244. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45245. {
  45246. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45247. if (tc != 0)
  45248. {
  45249. tc->setStyle (toolbar->getStyle());
  45250. int preferredSize = 1, minSize = 1, maxSize = 1;
  45251. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45252. {
  45253. if (x + preferredSize > preferredWidth && x > indent)
  45254. {
  45255. x = indent;
  45256. y += height;
  45257. }
  45258. tc->setBounds (x, y, preferredSize, height);
  45259. x += preferredSize + 8;
  45260. maxX = jmax (maxX, x);
  45261. }
  45262. }
  45263. }
  45264. itemHolder->setSize (maxX, y + height + 8);
  45265. }
  45266. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45267. {
  45268. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45269. jassert (tc != 0);
  45270. if (tc != 0)
  45271. {
  45272. tc->setBounds (comp->getBounds());
  45273. tc->setStyle (toolbar->getStyle());
  45274. tc->setEditingMode (comp->getEditingMode());
  45275. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45276. }
  45277. }
  45278. END_JUCE_NAMESPACE
  45279. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45280. /*** Start of inlined file: juce_TreeView.cpp ***/
  45281. BEGIN_JUCE_NAMESPACE
  45282. class TreeViewContentComponent : public Component,
  45283. public TooltipClient
  45284. {
  45285. public:
  45286. TreeViewContentComponent (TreeView& owner_)
  45287. : owner (owner_),
  45288. buttonUnderMouse (0),
  45289. isDragging (false)
  45290. {
  45291. }
  45292. ~TreeViewContentComponent()
  45293. {
  45294. deleteAllChildren();
  45295. }
  45296. void mouseDown (const MouseEvent& e)
  45297. {
  45298. updateButtonUnderMouse (e);
  45299. isDragging = false;
  45300. needSelectionOnMouseUp = false;
  45301. Rectangle<int> pos;
  45302. TreeViewItem* const item = findItemAt (e.y, pos);
  45303. if (item == 0)
  45304. return;
  45305. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45306. // as selection clicks)
  45307. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45308. {
  45309. if (e.x >= pos.getX() - owner.getIndentSize())
  45310. item->setOpen (! item->isOpen());
  45311. // (clicks to the left of an open/close button are ignored)
  45312. }
  45313. else
  45314. {
  45315. // mouse-down inside the body of the item..
  45316. if (! owner.isMultiSelectEnabled())
  45317. item->setSelected (true, true);
  45318. else if (item->isSelected())
  45319. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45320. else
  45321. selectBasedOnModifiers (item, e.mods);
  45322. if (e.x >= pos.getX())
  45323. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45324. }
  45325. }
  45326. void mouseUp (const MouseEvent& e)
  45327. {
  45328. updateButtonUnderMouse (e);
  45329. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45330. {
  45331. Rectangle<int> pos;
  45332. TreeViewItem* const item = findItemAt (e.y, pos);
  45333. if (item != 0)
  45334. selectBasedOnModifiers (item, e.mods);
  45335. }
  45336. }
  45337. void mouseDoubleClick (const MouseEvent& e)
  45338. {
  45339. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45340. {
  45341. Rectangle<int> pos;
  45342. TreeViewItem* const item = findItemAt (e.y, pos);
  45343. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45344. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45345. }
  45346. }
  45347. void mouseDrag (const MouseEvent& e)
  45348. {
  45349. if (isEnabled()
  45350. && ! (isDragging || e.mouseWasClicked()
  45351. || e.getDistanceFromDragStart() < 5
  45352. || e.mods.isPopupMenu()))
  45353. {
  45354. isDragging = true;
  45355. Rectangle<int> pos;
  45356. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45357. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45358. {
  45359. const String dragDescription (item->getDragSourceDescription());
  45360. if (dragDescription.isNotEmpty())
  45361. {
  45362. DragAndDropContainer* const dragContainer
  45363. = DragAndDropContainer::findParentDragContainerFor (this);
  45364. if (dragContainer != 0)
  45365. {
  45366. pos.setSize (pos.getWidth(), item->itemHeight);
  45367. Image dragImage (Component::createComponentSnapshot (pos, true));
  45368. dragImage.multiplyAllAlphas (0.6f);
  45369. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45370. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45371. }
  45372. else
  45373. {
  45374. // to be able to do a drag-and-drop operation, the treeview needs to
  45375. // be inside a component which is also a DragAndDropContainer.
  45376. jassertfalse;
  45377. }
  45378. }
  45379. }
  45380. }
  45381. }
  45382. void mouseMove (const MouseEvent& e)
  45383. {
  45384. updateButtonUnderMouse (e);
  45385. }
  45386. void mouseExit (const MouseEvent& e)
  45387. {
  45388. updateButtonUnderMouse (e);
  45389. }
  45390. void paint (Graphics& g)
  45391. {
  45392. if (owner.rootItem != 0)
  45393. {
  45394. owner.handleAsyncUpdate();
  45395. if (! owner.rootItemVisible)
  45396. g.setOrigin (0, -owner.rootItem->itemHeight);
  45397. owner.rootItem->paintRecursively (g, getWidth());
  45398. }
  45399. }
  45400. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45401. {
  45402. if (owner.rootItem != 0)
  45403. {
  45404. owner.handleAsyncUpdate();
  45405. if (! owner.rootItemVisible)
  45406. y += owner.rootItem->itemHeight;
  45407. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45408. if (ti != 0)
  45409. itemPosition = ti->getItemPosition (false);
  45410. return ti;
  45411. }
  45412. return 0;
  45413. }
  45414. void updateComponents()
  45415. {
  45416. const int visibleTop = -getY();
  45417. const int visibleBottom = visibleTop + getParentHeight();
  45418. BigInteger itemsToKeep;
  45419. {
  45420. TreeViewItem* item = owner.rootItem;
  45421. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45422. while (item != 0 && y < visibleBottom)
  45423. {
  45424. y += item->itemHeight;
  45425. if (y >= visibleTop)
  45426. {
  45427. const int index = rowComponentIds.indexOf (item->uid);
  45428. if (index < 0)
  45429. {
  45430. Component* const comp = item->createItemComponent();
  45431. if (comp != 0)
  45432. {
  45433. addAndMakeVisible (comp);
  45434. itemsToKeep.setBit (rowComponentItems.size());
  45435. rowComponentItems.add (item);
  45436. rowComponentIds.add (item->uid);
  45437. rowComponents.add (comp);
  45438. }
  45439. }
  45440. else
  45441. {
  45442. itemsToKeep.setBit (index);
  45443. }
  45444. }
  45445. item = item->getNextVisibleItem (true);
  45446. }
  45447. }
  45448. for (int i = rowComponentItems.size(); --i >= 0;)
  45449. {
  45450. Component* const comp = rowComponents.getUnchecked(i);
  45451. bool keep = false;
  45452. if (isParentOf (comp))
  45453. {
  45454. if (itemsToKeep[i])
  45455. {
  45456. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45457. Rectangle<int> pos (item->getItemPosition (false));
  45458. pos.setSize (pos.getWidth(), item->itemHeight);
  45459. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45460. {
  45461. keep = true;
  45462. comp->setBounds (pos);
  45463. }
  45464. }
  45465. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45466. {
  45467. keep = true;
  45468. comp->setSize (0, 0);
  45469. }
  45470. }
  45471. if (! keep)
  45472. {
  45473. delete comp;
  45474. rowComponents.remove (i);
  45475. rowComponentIds.remove (i);
  45476. rowComponentItems.remove (i);
  45477. }
  45478. }
  45479. }
  45480. void updateButtonUnderMouse (const MouseEvent& e)
  45481. {
  45482. TreeViewItem* newItem = 0;
  45483. if (owner.openCloseButtonsVisible)
  45484. {
  45485. Rectangle<int> pos;
  45486. TreeViewItem* item = findItemAt (e.y, pos);
  45487. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45488. {
  45489. newItem = item;
  45490. if (! newItem->mightContainSubItems())
  45491. newItem = 0;
  45492. }
  45493. }
  45494. if (buttonUnderMouse != newItem)
  45495. {
  45496. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45497. {
  45498. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45499. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45500. }
  45501. buttonUnderMouse = newItem;
  45502. if (buttonUnderMouse != 0)
  45503. {
  45504. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45505. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45506. }
  45507. }
  45508. }
  45509. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45510. {
  45511. return item == buttonUnderMouse;
  45512. }
  45513. void resized()
  45514. {
  45515. owner.itemsChanged();
  45516. }
  45517. const String getTooltip()
  45518. {
  45519. Rectangle<int> pos;
  45520. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45521. if (item != 0)
  45522. return item->getTooltip();
  45523. return owner.getTooltip();
  45524. }
  45525. juce_UseDebuggingNewOperator
  45526. private:
  45527. TreeView& owner;
  45528. Array <TreeViewItem*> rowComponentItems;
  45529. Array <int> rowComponentIds;
  45530. Array <Component*> rowComponents;
  45531. TreeViewItem* buttonUnderMouse;
  45532. bool isDragging, needSelectionOnMouseUp;
  45533. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45534. {
  45535. TreeViewItem* firstSelected = 0;
  45536. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45537. {
  45538. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45539. jassert (lastSelected != 0);
  45540. int rowStart = firstSelected->getRowNumberInTree();
  45541. int rowEnd = lastSelected->getRowNumberInTree();
  45542. if (rowStart > rowEnd)
  45543. swapVariables (rowStart, rowEnd);
  45544. int ourRow = item->getRowNumberInTree();
  45545. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45546. if (ourRow > otherEnd)
  45547. swapVariables (ourRow, otherEnd);
  45548. for (int i = ourRow; i <= otherEnd; ++i)
  45549. owner.getItemOnRow (i)->setSelected (true, false);
  45550. }
  45551. else
  45552. {
  45553. const bool cmd = modifiers.isCommandDown();
  45554. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45555. }
  45556. }
  45557. bool containsItem (TreeViewItem* const item) const
  45558. {
  45559. for (int i = rowComponentItems.size(); --i >= 0;)
  45560. if (rowComponentItems.getUnchecked(i) == item)
  45561. return true;
  45562. return false;
  45563. }
  45564. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45565. {
  45566. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45567. {
  45568. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45569. if (source->isDragging())
  45570. {
  45571. Component* const underMouse = source->getComponentUnderMouse();
  45572. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45573. return true;
  45574. }
  45575. }
  45576. return false;
  45577. }
  45578. TreeViewContentComponent (const TreeViewContentComponent&);
  45579. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45580. };
  45581. class TreeView::TreeViewport : public Viewport
  45582. {
  45583. public:
  45584. TreeViewport() throw() : lastX (-1) {}
  45585. ~TreeViewport() throw() {}
  45586. void updateComponents (const bool triggerResize = false)
  45587. {
  45588. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45589. if (tvc != 0)
  45590. {
  45591. if (triggerResize)
  45592. tvc->resized();
  45593. else
  45594. tvc->updateComponents();
  45595. }
  45596. repaint();
  45597. }
  45598. void visibleAreaChanged (int x, int, int, int)
  45599. {
  45600. const bool hasScrolledSideways = (x != lastX);
  45601. lastX = x;
  45602. updateComponents (hasScrolledSideways);
  45603. }
  45604. juce_UseDebuggingNewOperator
  45605. private:
  45606. int lastX;
  45607. TreeViewport (const TreeViewport&);
  45608. TreeViewport& operator= (const TreeViewport&);
  45609. };
  45610. TreeView::TreeView (const String& componentName)
  45611. : Component (componentName),
  45612. rootItem (0),
  45613. indentSize (24),
  45614. defaultOpenness (false),
  45615. needsRecalculating (true),
  45616. rootItemVisible (true),
  45617. multiSelectEnabled (false),
  45618. openCloseButtonsVisible (true)
  45619. {
  45620. addAndMakeVisible (viewport = new TreeViewport());
  45621. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45622. viewport->setWantsKeyboardFocus (false);
  45623. setWantsKeyboardFocus (true);
  45624. }
  45625. TreeView::~TreeView()
  45626. {
  45627. if (rootItem != 0)
  45628. rootItem->setOwnerView (0);
  45629. }
  45630. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45631. {
  45632. if (rootItem != newRootItem)
  45633. {
  45634. if (newRootItem != 0)
  45635. {
  45636. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45637. if (newRootItem->ownerView != 0)
  45638. newRootItem->ownerView->setRootItem (0);
  45639. }
  45640. if (rootItem != 0)
  45641. rootItem->setOwnerView (0);
  45642. rootItem = newRootItem;
  45643. if (newRootItem != 0)
  45644. newRootItem->setOwnerView (this);
  45645. needsRecalculating = true;
  45646. handleAsyncUpdate();
  45647. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45648. {
  45649. rootItem->setOpen (false); // force a re-open
  45650. rootItem->setOpen (true);
  45651. }
  45652. }
  45653. }
  45654. void TreeView::deleteRootItem()
  45655. {
  45656. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45657. setRootItem (0);
  45658. }
  45659. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45660. {
  45661. rootItemVisible = shouldBeVisible;
  45662. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45663. {
  45664. rootItem->setOpen (false); // force a re-open
  45665. rootItem->setOpen (true);
  45666. }
  45667. itemsChanged();
  45668. }
  45669. void TreeView::colourChanged()
  45670. {
  45671. setOpaque (findColour (backgroundColourId).isOpaque());
  45672. repaint();
  45673. }
  45674. void TreeView::setIndentSize (const int newIndentSize)
  45675. {
  45676. if (indentSize != newIndentSize)
  45677. {
  45678. indentSize = newIndentSize;
  45679. resized();
  45680. }
  45681. }
  45682. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45683. {
  45684. if (defaultOpenness != isOpenByDefault)
  45685. {
  45686. defaultOpenness = isOpenByDefault;
  45687. itemsChanged();
  45688. }
  45689. }
  45690. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45691. {
  45692. multiSelectEnabled = canMultiSelect;
  45693. }
  45694. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45695. {
  45696. if (openCloseButtonsVisible != shouldBeVisible)
  45697. {
  45698. openCloseButtonsVisible = shouldBeVisible;
  45699. itemsChanged();
  45700. }
  45701. }
  45702. Viewport* TreeView::getViewport() const throw()
  45703. {
  45704. return viewport;
  45705. }
  45706. void TreeView::clearSelectedItems()
  45707. {
  45708. if (rootItem != 0)
  45709. rootItem->deselectAllRecursively();
  45710. }
  45711. int TreeView::getNumSelectedItems() const throw()
  45712. {
  45713. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45714. }
  45715. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45716. {
  45717. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45718. }
  45719. int TreeView::getNumRowsInTree() const
  45720. {
  45721. if (rootItem != 0)
  45722. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45723. return 0;
  45724. }
  45725. TreeViewItem* TreeView::getItemOnRow (int index) const
  45726. {
  45727. if (! rootItemVisible)
  45728. ++index;
  45729. if (rootItem != 0 && index >= 0)
  45730. return rootItem->getItemOnRow (index);
  45731. return 0;
  45732. }
  45733. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45734. {
  45735. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45736. Rectangle<int> pos;
  45737. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45738. }
  45739. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45740. {
  45741. if (rootItem == 0)
  45742. return 0;
  45743. return rootItem->findItemFromIdentifierString (identifierString);
  45744. }
  45745. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45746. {
  45747. XmlElement* e = 0;
  45748. if (rootItem != 0)
  45749. {
  45750. e = rootItem->getOpennessState();
  45751. if (e != 0 && alsoIncludeScrollPosition)
  45752. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45753. }
  45754. return e;
  45755. }
  45756. void TreeView::restoreOpennessState (const XmlElement& newState)
  45757. {
  45758. if (rootItem != 0)
  45759. {
  45760. rootItem->restoreOpennessState (newState);
  45761. if (newState.hasAttribute ("scrollPos"))
  45762. viewport->setViewPosition (viewport->getViewPositionX(),
  45763. newState.getIntAttribute ("scrollPos"));
  45764. }
  45765. }
  45766. void TreeView::paint (Graphics& g)
  45767. {
  45768. g.fillAll (findColour (backgroundColourId));
  45769. }
  45770. void TreeView::resized()
  45771. {
  45772. viewport->setBounds (getLocalBounds());
  45773. itemsChanged();
  45774. handleAsyncUpdate();
  45775. }
  45776. void TreeView::enablementChanged()
  45777. {
  45778. repaint();
  45779. }
  45780. void TreeView::moveSelectedRow (int delta)
  45781. {
  45782. if (delta == 0)
  45783. return;
  45784. int rowSelected = 0;
  45785. TreeViewItem* const firstSelected = getSelectedItem (0);
  45786. if (firstSelected != 0)
  45787. rowSelected = firstSelected->getRowNumberInTree();
  45788. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45789. for (;;)
  45790. {
  45791. TreeViewItem* item = getItemOnRow (rowSelected);
  45792. if (item != 0)
  45793. {
  45794. if (! item->canBeSelected())
  45795. {
  45796. // if the row we want to highlight doesn't allow it, try skipping
  45797. // to the next item..
  45798. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45799. rowSelected + (delta < 0 ? -1 : 1));
  45800. if (rowSelected != nextRowToTry)
  45801. {
  45802. rowSelected = nextRowToTry;
  45803. continue;
  45804. }
  45805. else
  45806. {
  45807. break;
  45808. }
  45809. }
  45810. item->setSelected (true, true);
  45811. scrollToKeepItemVisible (item);
  45812. }
  45813. break;
  45814. }
  45815. }
  45816. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45817. {
  45818. if (item != 0 && item->ownerView == this)
  45819. {
  45820. handleAsyncUpdate();
  45821. item = item->getDeepestOpenParentItem();
  45822. int y = item->y;
  45823. int viewTop = viewport->getViewPositionY();
  45824. if (y < viewTop)
  45825. {
  45826. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45827. }
  45828. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45829. {
  45830. viewport->setViewPosition (viewport->getViewPositionX(),
  45831. (y + item->itemHeight) - viewport->getViewHeight());
  45832. }
  45833. }
  45834. }
  45835. bool TreeView::keyPressed (const KeyPress& key)
  45836. {
  45837. if (key.isKeyCode (KeyPress::upKey))
  45838. {
  45839. moveSelectedRow (-1);
  45840. }
  45841. else if (key.isKeyCode (KeyPress::downKey))
  45842. {
  45843. moveSelectedRow (1);
  45844. }
  45845. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45846. {
  45847. if (rootItem != 0)
  45848. {
  45849. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45850. if (key.isKeyCode (KeyPress::pageUpKey))
  45851. rowsOnScreen = -rowsOnScreen;
  45852. moveSelectedRow (rowsOnScreen);
  45853. }
  45854. }
  45855. else if (key.isKeyCode (KeyPress::homeKey))
  45856. {
  45857. moveSelectedRow (-0x3fffffff);
  45858. }
  45859. else if (key.isKeyCode (KeyPress::endKey))
  45860. {
  45861. moveSelectedRow (0x3fffffff);
  45862. }
  45863. else if (key.isKeyCode (KeyPress::returnKey))
  45864. {
  45865. TreeViewItem* const firstSelected = getSelectedItem (0);
  45866. if (firstSelected != 0)
  45867. firstSelected->setOpen (! firstSelected->isOpen());
  45868. }
  45869. else if (key.isKeyCode (KeyPress::leftKey))
  45870. {
  45871. TreeViewItem* const firstSelected = getSelectedItem (0);
  45872. if (firstSelected != 0)
  45873. {
  45874. if (firstSelected->isOpen())
  45875. {
  45876. firstSelected->setOpen (false);
  45877. }
  45878. else
  45879. {
  45880. TreeViewItem* parent = firstSelected->parentItem;
  45881. if ((! rootItemVisible) && parent == rootItem)
  45882. parent = 0;
  45883. if (parent != 0)
  45884. {
  45885. parent->setSelected (true, true);
  45886. scrollToKeepItemVisible (parent);
  45887. }
  45888. }
  45889. }
  45890. }
  45891. else if (key.isKeyCode (KeyPress::rightKey))
  45892. {
  45893. TreeViewItem* const firstSelected = getSelectedItem (0);
  45894. if (firstSelected != 0)
  45895. {
  45896. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45897. moveSelectedRow (1);
  45898. else
  45899. firstSelected->setOpen (true);
  45900. }
  45901. }
  45902. else
  45903. {
  45904. return false;
  45905. }
  45906. return true;
  45907. }
  45908. void TreeView::itemsChanged() throw()
  45909. {
  45910. needsRecalculating = true;
  45911. repaint();
  45912. triggerAsyncUpdate();
  45913. }
  45914. void TreeView::handleAsyncUpdate()
  45915. {
  45916. if (needsRecalculating)
  45917. {
  45918. needsRecalculating = false;
  45919. const ScopedLock sl (nodeAlterationLock);
  45920. if (rootItem != 0)
  45921. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45922. viewport->updateComponents();
  45923. if (rootItem != 0)
  45924. {
  45925. viewport->getViewedComponent()
  45926. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45927. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45928. }
  45929. else
  45930. {
  45931. viewport->getViewedComponent()->setSize (0, 0);
  45932. }
  45933. }
  45934. }
  45935. class TreeView::InsertPointHighlight : public Component
  45936. {
  45937. public:
  45938. InsertPointHighlight()
  45939. : lastItem (0)
  45940. {
  45941. setSize (100, 12);
  45942. setAlwaysOnTop (true);
  45943. setInterceptsMouseClicks (false, false);
  45944. }
  45945. ~InsertPointHighlight() {}
  45946. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45947. {
  45948. lastItem = item;
  45949. lastIndex = insertIndex;
  45950. const int offset = getHeight() / 2;
  45951. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45952. }
  45953. void paint (Graphics& g)
  45954. {
  45955. Path p;
  45956. const float h = (float) getHeight();
  45957. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45958. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45959. p.lineTo ((float) getWidth(), h / 2.0f);
  45960. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45961. g.strokePath (p, PathStrokeType (2.0f));
  45962. }
  45963. TreeViewItem* lastItem;
  45964. int lastIndex;
  45965. private:
  45966. InsertPointHighlight (const InsertPointHighlight&);
  45967. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45968. };
  45969. class TreeView::TargetGroupHighlight : public Component
  45970. {
  45971. public:
  45972. TargetGroupHighlight()
  45973. {
  45974. setAlwaysOnTop (true);
  45975. setInterceptsMouseClicks (false, false);
  45976. }
  45977. ~TargetGroupHighlight() {}
  45978. void setTargetPosition (TreeViewItem* const item) throw()
  45979. {
  45980. Rectangle<int> r (item->getItemPosition (true));
  45981. r.setHeight (item->getItemHeight());
  45982. setBounds (r);
  45983. }
  45984. void paint (Graphics& g)
  45985. {
  45986. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45987. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45988. }
  45989. private:
  45990. TargetGroupHighlight (const TargetGroupHighlight&);
  45991. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45992. };
  45993. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45994. {
  45995. beginDragAutoRepeat (100);
  45996. if (dragInsertPointHighlight == 0)
  45997. {
  45998. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45999. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  46000. }
  46001. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  46002. dragTargetGroupHighlight->setTargetPosition (item);
  46003. }
  46004. void TreeView::hideDragHighlight() throw()
  46005. {
  46006. dragInsertPointHighlight = 0;
  46007. dragTargetGroupHighlight = 0;
  46008. }
  46009. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  46010. const StringArray& files, const String& sourceDescription,
  46011. Component* sourceComponent) const throw()
  46012. {
  46013. insertIndex = 0;
  46014. TreeViewItem* item = getItemAt (y);
  46015. if (item == 0)
  46016. return 0;
  46017. Rectangle<int> itemPos (item->getItemPosition (true));
  46018. insertIndex = item->getIndexInParent();
  46019. const int oldY = y;
  46020. y = itemPos.getY();
  46021. if (item->getNumSubItems() == 0 || ! item->isOpen())
  46022. {
  46023. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46024. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46025. {
  46026. // Check if we're trying to drag into an empty group item..
  46027. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  46028. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  46029. {
  46030. insertIndex = 0;
  46031. x = itemPos.getX() + getIndentSize();
  46032. y = itemPos.getBottom();
  46033. return item;
  46034. }
  46035. }
  46036. }
  46037. if (oldY > itemPos.getCentreY())
  46038. {
  46039. y += item->getItemHeight();
  46040. while (item->isLastOfSiblings() && item->parentItem != 0
  46041. && item->parentItem->parentItem != 0)
  46042. {
  46043. if (x > itemPos.getX())
  46044. break;
  46045. item = item->parentItem;
  46046. itemPos = item->getItemPosition (true);
  46047. insertIndex = item->getIndexInParent();
  46048. }
  46049. ++insertIndex;
  46050. }
  46051. x = itemPos.getX();
  46052. return item->parentItem;
  46053. }
  46054. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46055. {
  46056. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  46057. int insertIndex;
  46058. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46059. if (item != 0)
  46060. {
  46061. if (scrolled || dragInsertPointHighlight == 0
  46062. || dragInsertPointHighlight->lastItem != item
  46063. || dragInsertPointHighlight->lastIndex != insertIndex)
  46064. {
  46065. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46066. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46067. showDragHighlight (item, insertIndex, x, y);
  46068. else
  46069. hideDragHighlight();
  46070. }
  46071. }
  46072. else
  46073. {
  46074. hideDragHighlight();
  46075. }
  46076. }
  46077. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46078. {
  46079. hideDragHighlight();
  46080. int insertIndex;
  46081. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46082. if (item != 0)
  46083. {
  46084. if (files.size() > 0)
  46085. {
  46086. if (item->isInterestedInFileDrag (files))
  46087. item->filesDropped (files, insertIndex);
  46088. }
  46089. else
  46090. {
  46091. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46092. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46093. }
  46094. }
  46095. }
  46096. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46097. {
  46098. return true;
  46099. }
  46100. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46101. {
  46102. fileDragMove (files, x, y);
  46103. }
  46104. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46105. {
  46106. handleDrag (files, String::empty, 0, x, y);
  46107. }
  46108. void TreeView::fileDragExit (const StringArray&)
  46109. {
  46110. hideDragHighlight();
  46111. }
  46112. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46113. {
  46114. handleDrop (files, String::empty, 0, x, y);
  46115. }
  46116. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46117. {
  46118. return true;
  46119. }
  46120. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46121. {
  46122. itemDragMove (sourceDescription, sourceComponent, x, y);
  46123. }
  46124. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46125. {
  46126. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46127. }
  46128. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46129. {
  46130. hideDragHighlight();
  46131. }
  46132. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46133. {
  46134. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46135. }
  46136. enum TreeViewOpenness
  46137. {
  46138. opennessDefault = 0,
  46139. opennessClosed = 1,
  46140. opennessOpen = 2
  46141. };
  46142. TreeViewItem::TreeViewItem()
  46143. : ownerView (0),
  46144. parentItem (0),
  46145. y (0),
  46146. itemHeight (0),
  46147. totalHeight (0),
  46148. selected (false),
  46149. redrawNeeded (true),
  46150. drawLinesInside (true),
  46151. drawsInLeftMargin (false),
  46152. openness (opennessDefault)
  46153. {
  46154. static int nextUID = 0;
  46155. uid = nextUID++;
  46156. }
  46157. TreeViewItem::~TreeViewItem()
  46158. {
  46159. }
  46160. const String TreeViewItem::getUniqueName() const
  46161. {
  46162. return String::empty;
  46163. }
  46164. void TreeViewItem::itemOpennessChanged (bool)
  46165. {
  46166. }
  46167. int TreeViewItem::getNumSubItems() const throw()
  46168. {
  46169. return subItems.size();
  46170. }
  46171. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46172. {
  46173. return subItems [index];
  46174. }
  46175. void TreeViewItem::clearSubItems()
  46176. {
  46177. if (subItems.size() > 0)
  46178. {
  46179. if (ownerView != 0)
  46180. {
  46181. const ScopedLock sl (ownerView->nodeAlterationLock);
  46182. subItems.clear();
  46183. treeHasChanged();
  46184. }
  46185. else
  46186. {
  46187. subItems.clear();
  46188. }
  46189. }
  46190. }
  46191. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46192. {
  46193. if (newItem != 0)
  46194. {
  46195. newItem->parentItem = this;
  46196. newItem->setOwnerView (ownerView);
  46197. newItem->y = 0;
  46198. newItem->itemHeight = newItem->getItemHeight();
  46199. newItem->totalHeight = 0;
  46200. newItem->itemWidth = newItem->getItemWidth();
  46201. newItem->totalWidth = 0;
  46202. if (ownerView != 0)
  46203. {
  46204. const ScopedLock sl (ownerView->nodeAlterationLock);
  46205. subItems.insert (insertPosition, newItem);
  46206. treeHasChanged();
  46207. if (newItem->isOpen())
  46208. newItem->itemOpennessChanged (true);
  46209. }
  46210. else
  46211. {
  46212. subItems.insert (insertPosition, newItem);
  46213. if (newItem->isOpen())
  46214. newItem->itemOpennessChanged (true);
  46215. }
  46216. }
  46217. }
  46218. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46219. {
  46220. if (ownerView != 0)
  46221. {
  46222. const ScopedLock sl (ownerView->nodeAlterationLock);
  46223. if (((unsigned int) index) < (unsigned int) subItems.size())
  46224. {
  46225. subItems.remove (index, deleteItem);
  46226. treeHasChanged();
  46227. }
  46228. }
  46229. else
  46230. {
  46231. subItems.remove (index, deleteItem);
  46232. }
  46233. }
  46234. bool TreeViewItem::isOpen() const throw()
  46235. {
  46236. if (openness == opennessDefault)
  46237. return ownerView != 0 && ownerView->defaultOpenness;
  46238. else
  46239. return openness == opennessOpen;
  46240. }
  46241. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46242. {
  46243. if (isOpen() != shouldBeOpen)
  46244. {
  46245. openness = shouldBeOpen ? opennessOpen
  46246. : opennessClosed;
  46247. treeHasChanged();
  46248. itemOpennessChanged (isOpen());
  46249. }
  46250. }
  46251. bool TreeViewItem::isSelected() const throw()
  46252. {
  46253. return selected;
  46254. }
  46255. void TreeViewItem::deselectAllRecursively()
  46256. {
  46257. setSelected (false, false);
  46258. for (int i = 0; i < subItems.size(); ++i)
  46259. subItems.getUnchecked(i)->deselectAllRecursively();
  46260. }
  46261. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46262. const bool deselectOtherItemsFirst)
  46263. {
  46264. if (shouldBeSelected && ! canBeSelected())
  46265. return;
  46266. if (deselectOtherItemsFirst)
  46267. getTopLevelItem()->deselectAllRecursively();
  46268. if (shouldBeSelected != selected)
  46269. {
  46270. selected = shouldBeSelected;
  46271. if (ownerView != 0)
  46272. ownerView->repaint();
  46273. itemSelectionChanged (shouldBeSelected);
  46274. }
  46275. }
  46276. void TreeViewItem::paintItem (Graphics&, int, int)
  46277. {
  46278. }
  46279. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46280. {
  46281. ownerView->getLookAndFeel()
  46282. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46283. }
  46284. void TreeViewItem::itemClicked (const MouseEvent&)
  46285. {
  46286. }
  46287. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46288. {
  46289. if (mightContainSubItems())
  46290. setOpen (! isOpen());
  46291. }
  46292. void TreeViewItem::itemSelectionChanged (bool)
  46293. {
  46294. }
  46295. const String TreeViewItem::getTooltip()
  46296. {
  46297. return String::empty;
  46298. }
  46299. const String TreeViewItem::getDragSourceDescription()
  46300. {
  46301. return String::empty;
  46302. }
  46303. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46304. {
  46305. return false;
  46306. }
  46307. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46308. {
  46309. }
  46310. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46311. {
  46312. return false;
  46313. }
  46314. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46315. {
  46316. }
  46317. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46318. {
  46319. const int indentX = getIndentX();
  46320. int width = itemWidth;
  46321. if (ownerView != 0 && width < 0)
  46322. width = ownerView->viewport->getViewWidth() - indentX;
  46323. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46324. if (relativeToTreeViewTopLeft)
  46325. r -= ownerView->viewport->getViewPosition();
  46326. return r;
  46327. }
  46328. void TreeViewItem::treeHasChanged() const throw()
  46329. {
  46330. if (ownerView != 0)
  46331. ownerView->itemsChanged();
  46332. }
  46333. void TreeViewItem::repaintItem() const
  46334. {
  46335. if (ownerView != 0 && areAllParentsOpen())
  46336. {
  46337. Rectangle<int> r (getItemPosition (true));
  46338. r.setLeft (0);
  46339. ownerView->viewport->repaint (r);
  46340. }
  46341. }
  46342. bool TreeViewItem::areAllParentsOpen() const throw()
  46343. {
  46344. return parentItem == 0
  46345. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46346. }
  46347. void TreeViewItem::updatePositions (int newY)
  46348. {
  46349. y = newY;
  46350. itemHeight = getItemHeight();
  46351. totalHeight = itemHeight;
  46352. itemWidth = getItemWidth();
  46353. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46354. if (isOpen())
  46355. {
  46356. newY += totalHeight;
  46357. for (int i = 0; i < subItems.size(); ++i)
  46358. {
  46359. TreeViewItem* const ti = subItems.getUnchecked(i);
  46360. ti->updatePositions (newY);
  46361. newY += ti->totalHeight;
  46362. totalHeight += ti->totalHeight;
  46363. totalWidth = jmax (totalWidth, ti->totalWidth);
  46364. }
  46365. }
  46366. }
  46367. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46368. {
  46369. TreeViewItem* result = this;
  46370. TreeViewItem* item = this;
  46371. while (item->parentItem != 0)
  46372. {
  46373. item = item->parentItem;
  46374. if (! item->isOpen())
  46375. result = item;
  46376. }
  46377. return result;
  46378. }
  46379. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46380. {
  46381. ownerView = newOwner;
  46382. for (int i = subItems.size(); --i >= 0;)
  46383. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46384. }
  46385. int TreeViewItem::getIndentX() const throw()
  46386. {
  46387. const int indentWidth = ownerView->getIndentSize();
  46388. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46389. if (! ownerView->openCloseButtonsVisible)
  46390. x -= indentWidth;
  46391. TreeViewItem* p = parentItem;
  46392. while (p != 0)
  46393. {
  46394. x += indentWidth;
  46395. p = p->parentItem;
  46396. }
  46397. return x;
  46398. }
  46399. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46400. {
  46401. drawsInLeftMargin = canDrawInLeftMargin;
  46402. }
  46403. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46404. {
  46405. jassert (ownerView != 0);
  46406. if (ownerView == 0)
  46407. return;
  46408. const int indent = getIndentX();
  46409. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46410. {
  46411. g.saveState();
  46412. g.setOrigin (indent, 0);
  46413. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46414. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46415. paintItem (g, itemW, itemHeight);
  46416. g.restoreState();
  46417. }
  46418. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46419. const float halfH = itemHeight * 0.5f;
  46420. int depth = 0;
  46421. TreeViewItem* p = parentItem;
  46422. while (p != 0)
  46423. {
  46424. ++depth;
  46425. p = p->parentItem;
  46426. }
  46427. if (! ownerView->rootItemVisible)
  46428. --depth;
  46429. const int indentWidth = ownerView->getIndentSize();
  46430. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46431. {
  46432. float x = (depth + 0.5f) * indentWidth;
  46433. if (depth >= 0)
  46434. {
  46435. if (parentItem != 0 && parentItem->drawLinesInside)
  46436. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46437. if ((parentItem != 0 && parentItem->drawLinesInside)
  46438. || (parentItem == 0 && drawLinesInside))
  46439. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46440. }
  46441. p = parentItem;
  46442. int d = depth;
  46443. while (p != 0 && --d >= 0)
  46444. {
  46445. x -= (float) indentWidth;
  46446. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46447. && ! p->isLastOfSiblings())
  46448. {
  46449. g.drawLine (x, 0, x, (float) itemHeight);
  46450. }
  46451. p = p->parentItem;
  46452. }
  46453. if (mightContainSubItems())
  46454. {
  46455. g.saveState();
  46456. g.setOrigin (depth * indentWidth, 0);
  46457. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46458. paintOpenCloseButton (g, indentWidth, itemHeight,
  46459. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46460. ->isMouseOverButton (this));
  46461. g.restoreState();
  46462. }
  46463. }
  46464. if (isOpen())
  46465. {
  46466. const Rectangle<int> clip (g.getClipBounds());
  46467. for (int i = 0; i < subItems.size(); ++i)
  46468. {
  46469. TreeViewItem* const ti = subItems.getUnchecked(i);
  46470. const int relY = ti->y - y;
  46471. if (relY >= clip.getBottom())
  46472. break;
  46473. if (relY + ti->totalHeight >= clip.getY())
  46474. {
  46475. g.saveState();
  46476. g.setOrigin (0, relY);
  46477. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46478. ti->paintRecursively (g, width);
  46479. g.restoreState();
  46480. }
  46481. }
  46482. }
  46483. }
  46484. bool TreeViewItem::isLastOfSiblings() const throw()
  46485. {
  46486. return parentItem == 0
  46487. || parentItem->subItems.getLast() == this;
  46488. }
  46489. int TreeViewItem::getIndexInParent() const throw()
  46490. {
  46491. if (parentItem == 0)
  46492. return 0;
  46493. return parentItem->subItems.indexOf (this);
  46494. }
  46495. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46496. {
  46497. return (parentItem == 0) ? this
  46498. : parentItem->getTopLevelItem();
  46499. }
  46500. int TreeViewItem::getNumRows() const throw()
  46501. {
  46502. int num = 1;
  46503. if (isOpen())
  46504. {
  46505. for (int i = subItems.size(); --i >= 0;)
  46506. num += subItems.getUnchecked(i)->getNumRows();
  46507. }
  46508. return num;
  46509. }
  46510. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46511. {
  46512. if (index == 0)
  46513. return this;
  46514. if (index > 0 && isOpen())
  46515. {
  46516. --index;
  46517. for (int i = 0; i < subItems.size(); ++i)
  46518. {
  46519. TreeViewItem* const item = subItems.getUnchecked(i);
  46520. if (index == 0)
  46521. return item;
  46522. const int numRows = item->getNumRows();
  46523. if (numRows > index)
  46524. return item->getItemOnRow (index);
  46525. index -= numRows;
  46526. }
  46527. }
  46528. return 0;
  46529. }
  46530. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46531. {
  46532. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46533. {
  46534. const int h = itemHeight;
  46535. if (targetY < h)
  46536. return this;
  46537. if (isOpen())
  46538. {
  46539. targetY -= h;
  46540. for (int i = 0; i < subItems.size(); ++i)
  46541. {
  46542. TreeViewItem* const ti = subItems.getUnchecked(i);
  46543. if (targetY < ti->totalHeight)
  46544. return ti->findItemRecursively (targetY);
  46545. targetY -= ti->totalHeight;
  46546. }
  46547. }
  46548. }
  46549. return 0;
  46550. }
  46551. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46552. {
  46553. int total = 0;
  46554. if (isSelected())
  46555. ++total;
  46556. for (int i = subItems.size(); --i >= 0;)
  46557. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46558. return total;
  46559. }
  46560. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46561. {
  46562. if (isSelected())
  46563. {
  46564. if (index == 0)
  46565. return this;
  46566. --index;
  46567. }
  46568. if (index >= 0)
  46569. {
  46570. for (int i = 0; i < subItems.size(); ++i)
  46571. {
  46572. TreeViewItem* const item = subItems.getUnchecked(i);
  46573. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46574. if (found != 0)
  46575. return found;
  46576. index -= item->countSelectedItemsRecursively();
  46577. }
  46578. }
  46579. return 0;
  46580. }
  46581. int TreeViewItem::getRowNumberInTree() const throw()
  46582. {
  46583. if (parentItem != 0 && ownerView != 0)
  46584. {
  46585. int n = 1 + parentItem->getRowNumberInTree();
  46586. int ourIndex = parentItem->subItems.indexOf (this);
  46587. jassert (ourIndex >= 0);
  46588. while (--ourIndex >= 0)
  46589. n += parentItem->subItems [ourIndex]->getNumRows();
  46590. if (parentItem->parentItem == 0
  46591. && ! ownerView->rootItemVisible)
  46592. --n;
  46593. return n;
  46594. }
  46595. else
  46596. {
  46597. return 0;
  46598. }
  46599. }
  46600. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46601. {
  46602. drawLinesInside = drawLines;
  46603. }
  46604. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46605. {
  46606. if (recurse && isOpen() && subItems.size() > 0)
  46607. return subItems [0];
  46608. if (parentItem != 0)
  46609. {
  46610. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46611. if (nextIndex >= parentItem->subItems.size())
  46612. return parentItem->getNextVisibleItem (false);
  46613. return parentItem->subItems [nextIndex];
  46614. }
  46615. return 0;
  46616. }
  46617. const String TreeViewItem::getItemIdentifierString() const
  46618. {
  46619. String s;
  46620. if (parentItem != 0)
  46621. s = parentItem->getItemIdentifierString();
  46622. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46623. }
  46624. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46625. {
  46626. const String thisId (getUniqueName());
  46627. if (thisId == identifierString)
  46628. return this;
  46629. if (identifierString.startsWith (thisId + "/"))
  46630. {
  46631. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46632. bool wasOpen = isOpen();
  46633. setOpen (true);
  46634. for (int i = subItems.size(); --i >= 0;)
  46635. {
  46636. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46637. if (item != 0)
  46638. return item;
  46639. }
  46640. setOpen (wasOpen);
  46641. }
  46642. return 0;
  46643. }
  46644. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46645. {
  46646. if (e.hasTagName ("CLOSED"))
  46647. {
  46648. setOpen (false);
  46649. }
  46650. else if (e.hasTagName ("OPEN"))
  46651. {
  46652. setOpen (true);
  46653. forEachXmlChildElement (e, n)
  46654. {
  46655. const String id (n->getStringAttribute ("id"));
  46656. for (int i = 0; i < subItems.size(); ++i)
  46657. {
  46658. TreeViewItem* const ti = subItems.getUnchecked(i);
  46659. if (ti->getUniqueName() == id)
  46660. {
  46661. ti->restoreOpennessState (*n);
  46662. break;
  46663. }
  46664. }
  46665. }
  46666. }
  46667. }
  46668. XmlElement* TreeViewItem::getOpennessState() const throw()
  46669. {
  46670. const String name (getUniqueName());
  46671. if (name.isNotEmpty())
  46672. {
  46673. XmlElement* e;
  46674. if (isOpen())
  46675. {
  46676. e = new XmlElement ("OPEN");
  46677. for (int i = 0; i < subItems.size(); ++i)
  46678. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46679. }
  46680. else
  46681. {
  46682. e = new XmlElement ("CLOSED");
  46683. }
  46684. e->setAttribute ("id", name);
  46685. return e;
  46686. }
  46687. else
  46688. {
  46689. // trying to save the openness for an element that has no name - this won't
  46690. // work because it needs the names to identify what to open.
  46691. jassertfalse;
  46692. }
  46693. return 0;
  46694. }
  46695. END_JUCE_NAMESPACE
  46696. /*** End of inlined file: juce_TreeView.cpp ***/
  46697. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46698. BEGIN_JUCE_NAMESPACE
  46699. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46700. : fileList (listToShow)
  46701. {
  46702. }
  46703. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46704. {
  46705. }
  46706. FileBrowserListener::~FileBrowserListener()
  46707. {
  46708. }
  46709. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46710. {
  46711. listeners.add (listener);
  46712. }
  46713. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46714. {
  46715. listeners.remove (listener);
  46716. }
  46717. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46718. {
  46719. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46720. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46721. }
  46722. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46723. {
  46724. if (fileList.getDirectory().exists())
  46725. {
  46726. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46727. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46728. }
  46729. }
  46730. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46731. {
  46732. if (fileList.getDirectory().exists())
  46733. {
  46734. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46735. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46736. }
  46737. }
  46738. END_JUCE_NAMESPACE
  46739. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46740. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46741. BEGIN_JUCE_NAMESPACE
  46742. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46743. TimeSliceThread& thread_)
  46744. : fileFilter (fileFilter_),
  46745. thread (thread_),
  46746. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46747. fileFindHandle (0),
  46748. shouldStop (true)
  46749. {
  46750. }
  46751. DirectoryContentsList::~DirectoryContentsList()
  46752. {
  46753. clear();
  46754. }
  46755. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46756. {
  46757. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46758. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46759. }
  46760. bool DirectoryContentsList::ignoresHiddenFiles() const
  46761. {
  46762. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46763. }
  46764. const File& DirectoryContentsList::getDirectory() const
  46765. {
  46766. return root;
  46767. }
  46768. void DirectoryContentsList::setDirectory (const File& directory,
  46769. const bool includeDirectories,
  46770. const bool includeFiles)
  46771. {
  46772. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46773. if (directory != root)
  46774. {
  46775. clear();
  46776. root = directory;
  46777. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46778. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46779. }
  46780. int newFlags = fileTypeFlags;
  46781. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46782. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46783. setTypeFlags (newFlags);
  46784. }
  46785. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46786. {
  46787. if (fileTypeFlags != newFlags)
  46788. {
  46789. fileTypeFlags = newFlags;
  46790. refresh();
  46791. }
  46792. }
  46793. void DirectoryContentsList::clear()
  46794. {
  46795. shouldStop = true;
  46796. thread.removeTimeSliceClient (this);
  46797. fileFindHandle = 0;
  46798. if (files.size() > 0)
  46799. {
  46800. files.clear();
  46801. changed();
  46802. }
  46803. }
  46804. void DirectoryContentsList::refresh()
  46805. {
  46806. clear();
  46807. if (root.isDirectory())
  46808. {
  46809. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46810. shouldStop = false;
  46811. thread.addTimeSliceClient (this);
  46812. }
  46813. }
  46814. int DirectoryContentsList::getNumFiles() const
  46815. {
  46816. return files.size();
  46817. }
  46818. bool DirectoryContentsList::getFileInfo (const int index,
  46819. FileInfo& result) const
  46820. {
  46821. const ScopedLock sl (fileListLock);
  46822. const FileInfo* const info = files [index];
  46823. if (info != 0)
  46824. {
  46825. result = *info;
  46826. return true;
  46827. }
  46828. return false;
  46829. }
  46830. const File DirectoryContentsList::getFile (const int index) const
  46831. {
  46832. const ScopedLock sl (fileListLock);
  46833. const FileInfo* const info = files [index];
  46834. if (info != 0)
  46835. return root.getChildFile (info->filename);
  46836. return File::nonexistent;
  46837. }
  46838. bool DirectoryContentsList::isStillLoading() const
  46839. {
  46840. return fileFindHandle != 0;
  46841. }
  46842. void DirectoryContentsList::changed()
  46843. {
  46844. sendChangeMessage (this);
  46845. }
  46846. bool DirectoryContentsList::useTimeSlice()
  46847. {
  46848. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46849. bool hasChanged = false;
  46850. for (int i = 100; --i >= 0;)
  46851. {
  46852. if (! checkNextFile (hasChanged))
  46853. {
  46854. if (hasChanged)
  46855. changed();
  46856. return false;
  46857. }
  46858. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46859. break;
  46860. }
  46861. if (hasChanged)
  46862. changed();
  46863. return true;
  46864. }
  46865. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46866. {
  46867. if (fileFindHandle != 0)
  46868. {
  46869. bool fileFoundIsDir, isHidden, isReadOnly;
  46870. int64 fileSize;
  46871. Time modTime, creationTime;
  46872. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46873. &modTime, &creationTime, &isReadOnly))
  46874. {
  46875. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46876. fileSize, modTime, creationTime, isReadOnly))
  46877. {
  46878. hasChanged = true;
  46879. }
  46880. return true;
  46881. }
  46882. else
  46883. {
  46884. fileFindHandle = 0;
  46885. }
  46886. }
  46887. return false;
  46888. }
  46889. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46890. const DirectoryContentsList::FileInfo* const second)
  46891. {
  46892. #if JUCE_WINDOWS
  46893. if (first->isDirectory != second->isDirectory)
  46894. return first->isDirectory ? -1 : 1;
  46895. #endif
  46896. return first->filename.compareIgnoreCase (second->filename);
  46897. }
  46898. bool DirectoryContentsList::addFile (const File& file,
  46899. const bool isDir,
  46900. const int64 fileSize,
  46901. const Time& modTime,
  46902. const Time& creationTime,
  46903. const bool isReadOnly)
  46904. {
  46905. if (fileFilter == 0
  46906. || ((! isDir) && fileFilter->isFileSuitable (file))
  46907. || (isDir && fileFilter->isDirectorySuitable (file)))
  46908. {
  46909. ScopedPointer <FileInfo> info (new FileInfo());
  46910. info->filename = file.getFileName();
  46911. info->fileSize = fileSize;
  46912. info->modificationTime = modTime;
  46913. info->creationTime = creationTime;
  46914. info->isDirectory = isDir;
  46915. info->isReadOnly = isReadOnly;
  46916. const ScopedLock sl (fileListLock);
  46917. for (int i = files.size(); --i >= 0;)
  46918. if (files.getUnchecked(i)->filename == info->filename)
  46919. return false;
  46920. files.addSorted (*this, info.release());
  46921. return true;
  46922. }
  46923. return false;
  46924. }
  46925. END_JUCE_NAMESPACE
  46926. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46927. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46928. BEGIN_JUCE_NAMESPACE
  46929. FileBrowserComponent::FileBrowserComponent (int flags_,
  46930. const File& initialFileOrDirectory,
  46931. const FileFilter* fileFilter_,
  46932. FilePreviewComponent* previewComp_)
  46933. : FileFilter (String::empty),
  46934. fileFilter (fileFilter_),
  46935. flags (flags_),
  46936. previewComp (previewComp_),
  46937. thread ("Juce FileBrowser")
  46938. {
  46939. // You need to specify one or other of the open/save flags..
  46940. jassert ((flags & (saveMode | openMode)) != 0);
  46941. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46942. // You need to specify at least one of these flags..
  46943. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46944. String filename;
  46945. if (initialFileOrDirectory == File::nonexistent)
  46946. {
  46947. currentRoot = File::getCurrentWorkingDirectory();
  46948. }
  46949. else if (initialFileOrDirectory.isDirectory())
  46950. {
  46951. currentRoot = initialFileOrDirectory;
  46952. }
  46953. else
  46954. {
  46955. chosenFiles.add (initialFileOrDirectory);
  46956. currentRoot = initialFileOrDirectory.getParentDirectory();
  46957. filename = initialFileOrDirectory.getFileName();
  46958. }
  46959. fileList = new DirectoryContentsList (this, thread);
  46960. if ((flags & useTreeView) != 0)
  46961. {
  46962. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46963. if ((flags & canSelectMultipleItems) != 0)
  46964. tree->setMultiSelectEnabled (true);
  46965. addAndMakeVisible (tree);
  46966. fileListComponent = tree;
  46967. }
  46968. else
  46969. {
  46970. FileListComponent* const list = new FileListComponent (*fileList);
  46971. list->setOutlineThickness (1);
  46972. if ((flags & canSelectMultipleItems) != 0)
  46973. list->setMultipleSelectionEnabled (true);
  46974. addAndMakeVisible (list);
  46975. fileListComponent = list;
  46976. }
  46977. fileListComponent->addListener (this);
  46978. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46979. currentPathBox->setEditableText (true);
  46980. StringArray rootNames, rootPaths;
  46981. const BigInteger separators (getRoots (rootNames, rootPaths));
  46982. for (int i = 0; i < rootNames.size(); ++i)
  46983. {
  46984. if (separators [i])
  46985. currentPathBox->addSeparator();
  46986. currentPathBox->addItem (rootNames[i], i + 1);
  46987. }
  46988. currentPathBox->addSeparator();
  46989. currentPathBox->addListener (this);
  46990. addAndMakeVisible (filenameBox = new TextEditor());
  46991. filenameBox->setMultiLine (false);
  46992. filenameBox->setSelectAllWhenFocused (true);
  46993. filenameBox->setText (filename, false);
  46994. filenameBox->addListener (this);
  46995. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46996. Label* label = new Label ("f", TRANS("file:"));
  46997. addAndMakeVisible (label);
  46998. label->attachToComponent (filenameBox, true);
  46999. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  47000. goUpButton->addButtonListener (this);
  47001. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  47002. if (previewComp != 0)
  47003. addAndMakeVisible (previewComp);
  47004. setRoot (currentRoot);
  47005. thread.startThread (4);
  47006. }
  47007. FileBrowserComponent::~FileBrowserComponent()
  47008. {
  47009. if (previewComp != 0)
  47010. removeChildComponent (previewComp);
  47011. deleteAllChildren();
  47012. fileList = 0;
  47013. thread.stopThread (10000);
  47014. }
  47015. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  47016. {
  47017. listeners.add (newListener);
  47018. }
  47019. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  47020. {
  47021. listeners.remove (listener);
  47022. }
  47023. bool FileBrowserComponent::isSaveMode() const throw()
  47024. {
  47025. return (flags & saveMode) != 0;
  47026. }
  47027. int FileBrowserComponent::getNumSelectedFiles() const throw()
  47028. {
  47029. if (chosenFiles.size() == 0 && currentFileIsValid())
  47030. return 1;
  47031. return chosenFiles.size();
  47032. }
  47033. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  47034. {
  47035. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  47036. return currentRoot;
  47037. if (! filenameBox->isReadOnly())
  47038. return currentRoot.getChildFile (filenameBox->getText());
  47039. return chosenFiles[index];
  47040. }
  47041. bool FileBrowserComponent::currentFileIsValid() const
  47042. {
  47043. if (isSaveMode())
  47044. return ! getSelectedFile (0).isDirectory();
  47045. else
  47046. return getSelectedFile (0).exists();
  47047. }
  47048. const File FileBrowserComponent::getHighlightedFile() const throw()
  47049. {
  47050. return fileListComponent->getSelectedFile (0);
  47051. }
  47052. void FileBrowserComponent::deselectAllFiles()
  47053. {
  47054. fileListComponent->deselectAllFiles();
  47055. }
  47056. bool FileBrowserComponent::isFileSuitable (const File& file) const
  47057. {
  47058. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  47059. : false;
  47060. }
  47061. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  47062. {
  47063. return true;
  47064. }
  47065. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47066. {
  47067. if (f.isDirectory())
  47068. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47069. return (flags & canSelectFiles) != 0 && f.exists()
  47070. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47071. }
  47072. const File FileBrowserComponent::getRoot() const
  47073. {
  47074. return currentRoot;
  47075. }
  47076. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47077. {
  47078. if (currentRoot != newRootDirectory)
  47079. {
  47080. fileListComponent->scrollToTop();
  47081. String path (newRootDirectory.getFullPathName());
  47082. if (path.isEmpty())
  47083. path = File::separatorString;
  47084. StringArray rootNames, rootPaths;
  47085. getRoots (rootNames, rootPaths);
  47086. if (! rootPaths.contains (path, true))
  47087. {
  47088. bool alreadyListed = false;
  47089. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  47090. {
  47091. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  47092. {
  47093. alreadyListed = true;
  47094. break;
  47095. }
  47096. }
  47097. if (! alreadyListed)
  47098. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  47099. }
  47100. }
  47101. currentRoot = newRootDirectory;
  47102. fileList->setDirectory (currentRoot, true, true);
  47103. String currentRootName (currentRoot.getFullPathName());
  47104. if (currentRootName.isEmpty())
  47105. currentRootName = File::separatorString;
  47106. currentPathBox->setText (currentRootName, true);
  47107. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47108. && currentRoot.getParentDirectory() != currentRoot);
  47109. }
  47110. void FileBrowserComponent::goUp()
  47111. {
  47112. setRoot (getRoot().getParentDirectory());
  47113. }
  47114. void FileBrowserComponent::refresh()
  47115. {
  47116. fileList->refresh();
  47117. }
  47118. const String FileBrowserComponent::getActionVerb() const
  47119. {
  47120. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47121. }
  47122. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47123. {
  47124. return previewComp;
  47125. }
  47126. void FileBrowserComponent::resized()
  47127. {
  47128. getLookAndFeel()
  47129. .layoutFileBrowserComponent (*this, fileListComponent,
  47130. previewComp, currentPathBox,
  47131. filenameBox, goUpButton);
  47132. }
  47133. void FileBrowserComponent::sendListenerChangeMessage()
  47134. {
  47135. Component::BailOutChecker checker (this);
  47136. if (previewComp != 0)
  47137. previewComp->selectedFileChanged (getSelectedFile (0));
  47138. // You shouldn't delete the browser when the file gets changed!
  47139. jassert (! checker.shouldBailOut());
  47140. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47141. }
  47142. void FileBrowserComponent::selectionChanged()
  47143. {
  47144. StringArray newFilenames;
  47145. bool resetChosenFiles = true;
  47146. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47147. {
  47148. const File f (fileListComponent->getSelectedFile (i));
  47149. if (isFileOrDirSuitable (f))
  47150. {
  47151. if (resetChosenFiles)
  47152. {
  47153. chosenFiles.clear();
  47154. resetChosenFiles = false;
  47155. }
  47156. chosenFiles.add (f);
  47157. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47158. }
  47159. }
  47160. if (newFilenames.size() > 0)
  47161. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47162. sendListenerChangeMessage();
  47163. }
  47164. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47165. {
  47166. Component::BailOutChecker checker (this);
  47167. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47168. }
  47169. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47170. {
  47171. if (f.isDirectory())
  47172. {
  47173. setRoot (f);
  47174. if ((flags & canSelectDirectories) != 0)
  47175. filenameBox->setText (String::empty);
  47176. }
  47177. else
  47178. {
  47179. Component::BailOutChecker checker (this);
  47180. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47181. }
  47182. }
  47183. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47184. {
  47185. (void) key;
  47186. #if JUCE_LINUX || JUCE_WINDOWS
  47187. if (key.getModifiers().isCommandDown()
  47188. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47189. {
  47190. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47191. fileList->refresh();
  47192. return true;
  47193. }
  47194. #endif
  47195. return false;
  47196. }
  47197. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47198. {
  47199. sendListenerChangeMessage();
  47200. }
  47201. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47202. {
  47203. if (filenameBox->getText().containsChar (File::separator))
  47204. {
  47205. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47206. if (f.isDirectory())
  47207. {
  47208. setRoot (f);
  47209. chosenFiles.clear();
  47210. filenameBox->setText (String::empty);
  47211. }
  47212. else
  47213. {
  47214. setRoot (f.getParentDirectory());
  47215. chosenFiles.clear();
  47216. chosenFiles.add (f);
  47217. filenameBox->setText (f.getFileName());
  47218. }
  47219. }
  47220. else
  47221. {
  47222. fileDoubleClicked (getSelectedFile (0));
  47223. }
  47224. }
  47225. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47226. {
  47227. }
  47228. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47229. {
  47230. if (! isSaveMode())
  47231. selectionChanged();
  47232. }
  47233. void FileBrowserComponent::buttonClicked (Button*)
  47234. {
  47235. goUp();
  47236. }
  47237. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47238. {
  47239. const String newText (currentPathBox->getText().trim().unquoted());
  47240. if (newText.isNotEmpty())
  47241. {
  47242. const int index = currentPathBox->getSelectedId() - 1;
  47243. StringArray rootNames, rootPaths;
  47244. getRoots (rootNames, rootPaths);
  47245. if (rootPaths [index].isNotEmpty())
  47246. {
  47247. setRoot (File (rootPaths [index]));
  47248. }
  47249. else
  47250. {
  47251. File f (newText);
  47252. for (;;)
  47253. {
  47254. if (f.isDirectory())
  47255. {
  47256. setRoot (f);
  47257. break;
  47258. }
  47259. if (f.getParentDirectory() == f)
  47260. break;
  47261. f = f.getParentDirectory();
  47262. }
  47263. }
  47264. }
  47265. }
  47266. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47267. {
  47268. BigInteger separators;
  47269. #if JUCE_WINDOWS
  47270. Array<File> roots;
  47271. File::findFileSystemRoots (roots);
  47272. rootPaths.clear();
  47273. for (int i = 0; i < roots.size(); ++i)
  47274. {
  47275. const File& drive = roots.getReference(i);
  47276. String name (drive.getFullPathName());
  47277. rootPaths.add (name);
  47278. if (drive.isOnHardDisk())
  47279. {
  47280. String volume (drive.getVolumeLabel());
  47281. if (volume.isEmpty())
  47282. volume = TRANS("Hard Drive");
  47283. name << " [" << drive.getVolumeLabel() << ']';
  47284. }
  47285. else if (drive.isOnCDRomDrive())
  47286. {
  47287. name << TRANS(" [CD/DVD drive]");
  47288. }
  47289. rootNames.add (name);
  47290. }
  47291. separators.setBit (rootPaths.size());
  47292. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47293. rootNames.add ("Documents");
  47294. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47295. rootNames.add ("Desktop");
  47296. #endif
  47297. #if JUCE_MAC
  47298. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47299. rootNames.add ("Home folder");
  47300. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47301. rootNames.add ("Documents");
  47302. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47303. rootNames.add ("Desktop");
  47304. separators.setBit (rootPaths.size());
  47305. Array <File> volumes;
  47306. File vol ("/Volumes");
  47307. vol.findChildFiles (volumes, File::findDirectories, false);
  47308. for (int i = 0; i < volumes.size(); ++i)
  47309. {
  47310. const File& volume = volumes.getReference(i);
  47311. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47312. {
  47313. rootPaths.add (volume.getFullPathName());
  47314. rootNames.add (volume.getFileName());
  47315. }
  47316. }
  47317. #endif
  47318. #if JUCE_LINUX
  47319. rootPaths.add ("/");
  47320. rootNames.add ("/");
  47321. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47322. rootNames.add ("Home folder");
  47323. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47324. rootNames.add ("Desktop");
  47325. #endif
  47326. return separators;
  47327. }
  47328. END_JUCE_NAMESPACE
  47329. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47330. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47331. BEGIN_JUCE_NAMESPACE
  47332. FileChooser::FileChooser (const String& chooserBoxTitle,
  47333. const File& currentFileOrDirectory,
  47334. const String& fileFilters,
  47335. const bool useNativeDialogBox_)
  47336. : title (chooserBoxTitle),
  47337. filters (fileFilters),
  47338. startingFile (currentFileOrDirectory),
  47339. useNativeDialogBox (useNativeDialogBox_)
  47340. {
  47341. #if JUCE_LINUX
  47342. useNativeDialogBox = false;
  47343. #endif
  47344. if (! fileFilters.containsNonWhitespaceChars())
  47345. filters = "*";
  47346. }
  47347. FileChooser::~FileChooser()
  47348. {
  47349. }
  47350. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47351. {
  47352. return showDialog (false, true, false, false, false, previewComponent);
  47353. }
  47354. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47355. {
  47356. return showDialog (false, true, false, false, true, previewComponent);
  47357. }
  47358. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47359. {
  47360. return showDialog (true, true, false, false, true, previewComponent);
  47361. }
  47362. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47363. {
  47364. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47365. }
  47366. bool FileChooser::browseForDirectory()
  47367. {
  47368. return showDialog (true, false, false, false, false, 0);
  47369. }
  47370. const File FileChooser::getResult() const
  47371. {
  47372. // if you've used a multiple-file select, you should use the getResults() method
  47373. // to retrieve all the files that were chosen.
  47374. jassert (results.size() <= 1);
  47375. return results.getFirst();
  47376. }
  47377. const Array<File>& FileChooser::getResults() const
  47378. {
  47379. return results;
  47380. }
  47381. bool FileChooser::showDialog (const bool selectsDirectories,
  47382. const bool selectsFiles,
  47383. const bool isSave,
  47384. const bool warnAboutOverwritingExistingFiles,
  47385. const bool selectMultipleFiles,
  47386. FilePreviewComponent* const previewComponent)
  47387. {
  47388. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47389. results.clear();
  47390. // the preview component needs to be the right size before you pass it in here..
  47391. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47392. && previewComponent->getHeight() > 10));
  47393. #if JUCE_WINDOWS
  47394. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47395. #elif JUCE_MAC
  47396. if (useNativeDialogBox && (previewComponent == 0))
  47397. #else
  47398. if (false)
  47399. #endif
  47400. {
  47401. showPlatformDialog (results, title, startingFile, filters,
  47402. selectsDirectories, selectsFiles, isSave,
  47403. warnAboutOverwritingExistingFiles,
  47404. selectMultipleFiles,
  47405. previewComponent);
  47406. }
  47407. else
  47408. {
  47409. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47410. selectsDirectories ? "*" : String::empty,
  47411. String::empty);
  47412. int flags = isSave ? FileBrowserComponent::saveMode
  47413. : FileBrowserComponent::openMode;
  47414. if (selectsFiles)
  47415. flags |= FileBrowserComponent::canSelectFiles;
  47416. if (selectsDirectories)
  47417. {
  47418. flags |= FileBrowserComponent::canSelectDirectories;
  47419. if (! isSave)
  47420. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47421. }
  47422. if (selectMultipleFiles)
  47423. flags |= FileBrowserComponent::canSelectMultipleItems;
  47424. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47425. FileChooserDialogBox box (title, String::empty,
  47426. browserComponent,
  47427. warnAboutOverwritingExistingFiles,
  47428. browserComponent.findColour (AlertWindow::backgroundColourId));
  47429. if (box.show())
  47430. {
  47431. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47432. results.add (browserComponent.getSelectedFile (i));
  47433. }
  47434. }
  47435. if (previouslyFocused != 0)
  47436. previouslyFocused->grabKeyboardFocus();
  47437. return results.size() > 0;
  47438. }
  47439. FilePreviewComponent::FilePreviewComponent()
  47440. {
  47441. }
  47442. FilePreviewComponent::~FilePreviewComponent()
  47443. {
  47444. }
  47445. END_JUCE_NAMESPACE
  47446. /*** End of inlined file: juce_FileChooser.cpp ***/
  47447. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47448. BEGIN_JUCE_NAMESPACE
  47449. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47450. const String& instructions,
  47451. FileBrowserComponent& chooserComponent,
  47452. const bool warnAboutOverwritingExistingFiles_,
  47453. const Colour& backgroundColour)
  47454. : ResizableWindow (name, backgroundColour, true),
  47455. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47456. {
  47457. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47458. setResizable (true, true);
  47459. setResizeLimits (300, 300, 1200, 1000);
  47460. content->okButton.addButtonListener (this);
  47461. content->cancelButton.addButtonListener (this);
  47462. content->chooserComponent.addListener (this);
  47463. }
  47464. FileChooserDialogBox::~FileChooserDialogBox()
  47465. {
  47466. content->chooserComponent.removeListener (this);
  47467. }
  47468. bool FileChooserDialogBox::show (int w, int h)
  47469. {
  47470. return showAt (-1, -1, w, h);
  47471. }
  47472. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47473. {
  47474. if (w <= 0)
  47475. {
  47476. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47477. if (previewComp != 0)
  47478. w = 400 + previewComp->getWidth();
  47479. else
  47480. w = 600;
  47481. }
  47482. if (h <= 0)
  47483. h = 500;
  47484. if (x < 0 || y < 0)
  47485. centreWithSize (w, h);
  47486. else
  47487. setBounds (x, y, w, h);
  47488. const bool ok = (runModalLoop() != 0);
  47489. setVisible (false);
  47490. return ok;
  47491. }
  47492. void FileChooserDialogBox::buttonClicked (Button* button)
  47493. {
  47494. if (button == &(content->okButton))
  47495. {
  47496. if (warnAboutOverwritingExistingFiles
  47497. && content->chooserComponent.isSaveMode()
  47498. && content->chooserComponent.getSelectedFile(0).exists())
  47499. {
  47500. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47501. TRANS("File already exists"),
  47502. TRANS("There's already a file called:")
  47503. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47504. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47505. TRANS("overwrite"),
  47506. TRANS("cancel")))
  47507. {
  47508. return;
  47509. }
  47510. }
  47511. exitModalState (1);
  47512. }
  47513. else if (button == &(content->cancelButton))
  47514. {
  47515. closeButtonPressed();
  47516. }
  47517. }
  47518. void FileChooserDialogBox::closeButtonPressed()
  47519. {
  47520. setVisible (false);
  47521. }
  47522. void FileChooserDialogBox::selectionChanged()
  47523. {
  47524. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47525. }
  47526. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47527. {
  47528. }
  47529. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47530. {
  47531. selectionChanged();
  47532. content->okButton.triggerClick();
  47533. }
  47534. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47535. : Component (name), instructions (instructions_),
  47536. chooserComponent (chooserComponent_),
  47537. okButton (chooserComponent_.getActionVerb()),
  47538. cancelButton (TRANS ("Cancel"))
  47539. {
  47540. addAndMakeVisible (&chooserComponent);
  47541. addAndMakeVisible (&okButton);
  47542. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47543. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47544. addAndMakeVisible (&cancelButton);
  47545. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47546. setInterceptsMouseClicks (false, true);
  47547. }
  47548. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47549. {
  47550. }
  47551. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47552. {
  47553. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47554. text.draw (g);
  47555. }
  47556. void FileChooserDialogBox::ContentComponent::resized()
  47557. {
  47558. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47559. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47560. const int y = roundToInt (bb.getBottom()) + 10;
  47561. const int buttonHeight = 26;
  47562. const int buttonY = getHeight() - buttonHeight - 8;
  47563. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47564. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47565. proportionOfWidth (0.2f), buttonHeight);
  47566. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47567. proportionOfWidth (0.2f), buttonHeight);
  47568. }
  47569. END_JUCE_NAMESPACE
  47570. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47571. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47572. BEGIN_JUCE_NAMESPACE
  47573. FileFilter::FileFilter (const String& filterDescription)
  47574. : description (filterDescription)
  47575. {
  47576. }
  47577. FileFilter::~FileFilter()
  47578. {
  47579. }
  47580. const String& FileFilter::getDescription() const throw()
  47581. {
  47582. return description;
  47583. }
  47584. END_JUCE_NAMESPACE
  47585. /*** End of inlined file: juce_FileFilter.cpp ***/
  47586. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47587. BEGIN_JUCE_NAMESPACE
  47588. const Image juce_createIconForFile (const File& file);
  47589. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47590. : ListBox (String::empty, 0),
  47591. DirectoryContentsDisplayComponent (listToShow)
  47592. {
  47593. setModel (this);
  47594. fileList.addChangeListener (this);
  47595. }
  47596. FileListComponent::~FileListComponent()
  47597. {
  47598. fileList.removeChangeListener (this);
  47599. }
  47600. int FileListComponent::getNumSelectedFiles() const
  47601. {
  47602. return getNumSelectedRows();
  47603. }
  47604. const File FileListComponent::getSelectedFile (int index) const
  47605. {
  47606. return fileList.getFile (getSelectedRow (index));
  47607. }
  47608. void FileListComponent::deselectAllFiles()
  47609. {
  47610. deselectAllRows();
  47611. }
  47612. void FileListComponent::scrollToTop()
  47613. {
  47614. getVerticalScrollBar()->setCurrentRangeStart (0);
  47615. }
  47616. void FileListComponent::changeListenerCallback (void*)
  47617. {
  47618. updateContent();
  47619. if (lastDirectory != fileList.getDirectory())
  47620. {
  47621. lastDirectory = fileList.getDirectory();
  47622. deselectAllRows();
  47623. }
  47624. }
  47625. class FileListItemComponent : public Component,
  47626. public TimeSliceClient,
  47627. public AsyncUpdater
  47628. {
  47629. public:
  47630. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47631. : owner (owner_), thread (thread_),
  47632. highlighted (false), index (0), icon (0)
  47633. {
  47634. }
  47635. ~FileListItemComponent()
  47636. {
  47637. thread.removeTimeSliceClient (this);
  47638. clearIcon();
  47639. }
  47640. void paint (Graphics& g)
  47641. {
  47642. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47643. file.getFileName(),
  47644. &icon,
  47645. fileSize, modTime,
  47646. isDirectory, highlighted,
  47647. index, owner);
  47648. }
  47649. void mouseDown (const MouseEvent& e)
  47650. {
  47651. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47652. owner.sendMouseClickMessage (file, e);
  47653. }
  47654. void mouseDoubleClick (const MouseEvent&)
  47655. {
  47656. owner.sendDoubleClickMessage (file);
  47657. }
  47658. void update (const File& root,
  47659. const DirectoryContentsList::FileInfo* const fileInfo,
  47660. const int index_,
  47661. const bool highlighted_)
  47662. {
  47663. thread.removeTimeSliceClient (this);
  47664. if (highlighted_ != highlighted
  47665. || index_ != index)
  47666. {
  47667. index = index_;
  47668. highlighted = highlighted_;
  47669. repaint();
  47670. }
  47671. File newFile;
  47672. String newFileSize;
  47673. String newModTime;
  47674. if (fileInfo != 0)
  47675. {
  47676. newFile = root.getChildFile (fileInfo->filename);
  47677. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47678. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47679. }
  47680. if (newFile != file
  47681. || fileSize != newFileSize
  47682. || modTime != newModTime)
  47683. {
  47684. file = newFile;
  47685. fileSize = newFileSize;
  47686. modTime = newModTime;
  47687. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47688. repaint();
  47689. clearIcon();
  47690. }
  47691. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47692. {
  47693. updateIcon (true);
  47694. if (! icon.isValid())
  47695. thread.addTimeSliceClient (this);
  47696. }
  47697. }
  47698. bool useTimeSlice()
  47699. {
  47700. updateIcon (false);
  47701. return false;
  47702. }
  47703. void handleAsyncUpdate()
  47704. {
  47705. repaint();
  47706. }
  47707. juce_UseDebuggingNewOperator
  47708. private:
  47709. FileListComponent& owner;
  47710. TimeSliceThread& thread;
  47711. bool highlighted;
  47712. int index;
  47713. File file;
  47714. String fileSize;
  47715. String modTime;
  47716. Image icon;
  47717. bool isDirectory;
  47718. void clearIcon()
  47719. {
  47720. icon = Image::null;
  47721. }
  47722. void updateIcon (const bool onlyUpdateIfCached)
  47723. {
  47724. if (icon.isNull())
  47725. {
  47726. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47727. Image im (ImageCache::getFromHashCode (hashCode));
  47728. if (im.isNull() && ! onlyUpdateIfCached)
  47729. {
  47730. im = juce_createIconForFile (file);
  47731. if (im.isValid())
  47732. ImageCache::addImageToCache (im, hashCode);
  47733. }
  47734. if (im.isValid())
  47735. {
  47736. icon = im;
  47737. triggerAsyncUpdate();
  47738. }
  47739. }
  47740. }
  47741. };
  47742. int FileListComponent::getNumRows()
  47743. {
  47744. return fileList.getNumFiles();
  47745. }
  47746. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47747. {
  47748. }
  47749. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47750. {
  47751. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47752. if (comp == 0)
  47753. {
  47754. delete existingComponentToUpdate;
  47755. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47756. }
  47757. DirectoryContentsList::FileInfo fileInfo;
  47758. if (fileList.getFileInfo (row, fileInfo))
  47759. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47760. else
  47761. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47762. return comp;
  47763. }
  47764. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47765. {
  47766. sendSelectionChangeMessage();
  47767. }
  47768. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47769. {
  47770. }
  47771. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47772. {
  47773. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47774. }
  47775. END_JUCE_NAMESPACE
  47776. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47777. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47778. BEGIN_JUCE_NAMESPACE
  47779. FilenameComponent::FilenameComponent (const String& name,
  47780. const File& currentFile,
  47781. const bool canEditFilename,
  47782. const bool isDirectory,
  47783. const bool isForSaving,
  47784. const String& fileBrowserWildcard,
  47785. const String& enforcedSuffix_,
  47786. const String& textWhenNothingSelected)
  47787. : Component (name),
  47788. maxRecentFiles (30),
  47789. isDir (isDirectory),
  47790. isSaving (isForSaving),
  47791. isFileDragOver (false),
  47792. wildcard (fileBrowserWildcard),
  47793. enforcedSuffix (enforcedSuffix_)
  47794. {
  47795. addAndMakeVisible (&filenameBox);
  47796. filenameBox.setEditableText (canEditFilename);
  47797. filenameBox.addListener (this);
  47798. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47799. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47800. setBrowseButtonText ("...");
  47801. setCurrentFile (currentFile, true);
  47802. }
  47803. FilenameComponent::~FilenameComponent()
  47804. {
  47805. }
  47806. void FilenameComponent::paintOverChildren (Graphics& g)
  47807. {
  47808. if (isFileDragOver)
  47809. {
  47810. g.setColour (Colours::red.withAlpha (0.2f));
  47811. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47812. }
  47813. }
  47814. void FilenameComponent::resized()
  47815. {
  47816. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47817. }
  47818. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47819. {
  47820. browseButtonText = newBrowseButtonText;
  47821. lookAndFeelChanged();
  47822. }
  47823. void FilenameComponent::lookAndFeelChanged()
  47824. {
  47825. browseButton = 0;
  47826. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47827. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47828. resized();
  47829. browseButton->addButtonListener (this);
  47830. }
  47831. void FilenameComponent::setTooltip (const String& newTooltip)
  47832. {
  47833. SettableTooltipClient::setTooltip (newTooltip);
  47834. filenameBox.setTooltip (newTooltip);
  47835. }
  47836. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47837. {
  47838. defaultBrowseFile = newDefaultDirectory;
  47839. }
  47840. void FilenameComponent::buttonClicked (Button*)
  47841. {
  47842. FileChooser fc (TRANS("Choose a new file"),
  47843. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47844. : getCurrentFile(),
  47845. wildcard);
  47846. if (isDir ? fc.browseForDirectory()
  47847. : (isSaving ? fc.browseForFileToSave (false)
  47848. : fc.browseForFileToOpen()))
  47849. {
  47850. setCurrentFile (fc.getResult(), true);
  47851. }
  47852. }
  47853. void FilenameComponent::comboBoxChanged (ComboBox*)
  47854. {
  47855. setCurrentFile (getCurrentFile(), true);
  47856. }
  47857. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47858. {
  47859. return true;
  47860. }
  47861. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47862. {
  47863. isFileDragOver = false;
  47864. repaint();
  47865. const File f (filenames[0]);
  47866. if (f.exists() && (f.isDirectory() == isDir))
  47867. setCurrentFile (f, true);
  47868. }
  47869. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47870. {
  47871. isFileDragOver = true;
  47872. repaint();
  47873. }
  47874. void FilenameComponent::fileDragExit (const StringArray&)
  47875. {
  47876. isFileDragOver = false;
  47877. repaint();
  47878. }
  47879. const File FilenameComponent::getCurrentFile() const
  47880. {
  47881. File f (filenameBox.getText());
  47882. if (enforcedSuffix.isNotEmpty())
  47883. f = f.withFileExtension (enforcedSuffix);
  47884. return f;
  47885. }
  47886. void FilenameComponent::setCurrentFile (File newFile,
  47887. const bool addToRecentlyUsedList,
  47888. const bool sendChangeNotification)
  47889. {
  47890. if (enforcedSuffix.isNotEmpty())
  47891. newFile = newFile.withFileExtension (enforcedSuffix);
  47892. if (newFile.getFullPathName() != lastFilename)
  47893. {
  47894. lastFilename = newFile.getFullPathName();
  47895. if (addToRecentlyUsedList)
  47896. addRecentlyUsedFile (newFile);
  47897. filenameBox.setText (lastFilename, true);
  47898. if (sendChangeNotification)
  47899. triggerAsyncUpdate();
  47900. }
  47901. }
  47902. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47903. {
  47904. filenameBox.setEditableText (shouldBeEditable);
  47905. }
  47906. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47907. {
  47908. StringArray names;
  47909. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47910. names.add (filenameBox.getItemText (i));
  47911. return names;
  47912. }
  47913. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47914. {
  47915. if (filenames != getRecentlyUsedFilenames())
  47916. {
  47917. filenameBox.clear();
  47918. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47919. filenameBox.addItem (filenames[i], i + 1);
  47920. }
  47921. }
  47922. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47923. {
  47924. maxRecentFiles = jmax (1, newMaximum);
  47925. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47926. }
  47927. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47928. {
  47929. StringArray files (getRecentlyUsedFilenames());
  47930. if (file.getFullPathName().isNotEmpty())
  47931. {
  47932. files.removeString (file.getFullPathName(), true);
  47933. files.insert (0, file.getFullPathName());
  47934. setRecentlyUsedFilenames (files);
  47935. }
  47936. }
  47937. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47938. {
  47939. listeners.add (listener);
  47940. }
  47941. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47942. {
  47943. listeners.remove (listener);
  47944. }
  47945. void FilenameComponent::handleAsyncUpdate()
  47946. {
  47947. Component::BailOutChecker checker (this);
  47948. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47949. }
  47950. END_JUCE_NAMESPACE
  47951. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47952. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47953. BEGIN_JUCE_NAMESPACE
  47954. FileSearchPathListComponent::FileSearchPathListComponent()
  47955. {
  47956. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47957. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47958. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47959. listBox->setOutlineThickness (1);
  47960. addAndMakeVisible (addButton = new TextButton ("+"));
  47961. addButton->addButtonListener (this);
  47962. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47963. addAndMakeVisible (removeButton = new TextButton ("-"));
  47964. removeButton->addButtonListener (this);
  47965. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47966. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47967. changeButton->addButtonListener (this);
  47968. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47969. upButton->addButtonListener (this);
  47970. {
  47971. Path arrowPath;
  47972. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47973. DrawablePath arrowImage;
  47974. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47975. arrowImage.setPath (arrowPath);
  47976. upButton->setImages (&arrowImage);
  47977. }
  47978. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47979. downButton->addButtonListener (this);
  47980. {
  47981. Path arrowPath;
  47982. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47983. DrawablePath arrowImage;
  47984. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47985. arrowImage.setPath (arrowPath);
  47986. downButton->setImages (&arrowImage);
  47987. }
  47988. updateButtons();
  47989. }
  47990. FileSearchPathListComponent::~FileSearchPathListComponent()
  47991. {
  47992. deleteAllChildren();
  47993. }
  47994. void FileSearchPathListComponent::updateButtons()
  47995. {
  47996. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47997. removeButton->setEnabled (anythingSelected);
  47998. changeButton->setEnabled (anythingSelected);
  47999. upButton->setEnabled (anythingSelected);
  48000. downButton->setEnabled (anythingSelected);
  48001. }
  48002. void FileSearchPathListComponent::changed()
  48003. {
  48004. listBox->updateContent();
  48005. listBox->repaint();
  48006. updateButtons();
  48007. }
  48008. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  48009. {
  48010. if (newPath.toString() != path.toString())
  48011. {
  48012. path = newPath;
  48013. changed();
  48014. }
  48015. }
  48016. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  48017. {
  48018. defaultBrowseTarget = newDefaultDirectory;
  48019. }
  48020. int FileSearchPathListComponent::getNumRows()
  48021. {
  48022. return path.getNumPaths();
  48023. }
  48024. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  48025. {
  48026. if (rowIsSelected)
  48027. g.fillAll (findColour (TextEditor::highlightColourId));
  48028. g.setColour (findColour (ListBox::textColourId));
  48029. Font f (height * 0.7f);
  48030. f.setHorizontalScale (0.9f);
  48031. g.setFont (f);
  48032. g.drawText (path [rowNumber].getFullPathName(),
  48033. 4, 0, width - 6, height,
  48034. Justification::centredLeft, true);
  48035. }
  48036. void FileSearchPathListComponent::deleteKeyPressed (int row)
  48037. {
  48038. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  48039. {
  48040. path.remove (row);
  48041. changed();
  48042. }
  48043. }
  48044. void FileSearchPathListComponent::returnKeyPressed (int row)
  48045. {
  48046. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  48047. if (chooser.browseForDirectory())
  48048. {
  48049. path.remove (row);
  48050. path.add (chooser.getResult(), row);
  48051. changed();
  48052. }
  48053. }
  48054. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  48055. {
  48056. returnKeyPressed (row);
  48057. }
  48058. void FileSearchPathListComponent::selectedRowsChanged (int)
  48059. {
  48060. updateButtons();
  48061. }
  48062. void FileSearchPathListComponent::paint (Graphics& g)
  48063. {
  48064. g.fillAll (findColour (backgroundColourId));
  48065. }
  48066. void FileSearchPathListComponent::resized()
  48067. {
  48068. const int buttonH = 22;
  48069. const int buttonY = getHeight() - buttonH - 4;
  48070. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48071. addButton->setBounds (2, buttonY, buttonH, buttonH);
  48072. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  48073. changeButton->changeWidthToFitText (buttonH);
  48074. downButton->setSize (buttonH * 2, buttonH);
  48075. upButton->setSize (buttonH * 2, buttonH);
  48076. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  48077. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  48078. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  48079. }
  48080. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48081. {
  48082. return true;
  48083. }
  48084. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48085. {
  48086. for (int i = filenames.size(); --i >= 0;)
  48087. {
  48088. const File f (filenames[i]);
  48089. if (f.isDirectory())
  48090. {
  48091. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  48092. path.add (f, row);
  48093. changed();
  48094. }
  48095. }
  48096. }
  48097. void FileSearchPathListComponent::buttonClicked (Button* button)
  48098. {
  48099. const int currentRow = listBox->getSelectedRow();
  48100. if (button == removeButton)
  48101. {
  48102. deleteKeyPressed (currentRow);
  48103. }
  48104. else if (button == addButton)
  48105. {
  48106. File start (defaultBrowseTarget);
  48107. if (start == File::nonexistent)
  48108. start = path [0];
  48109. if (start == File::nonexistent)
  48110. start = File::getCurrentWorkingDirectory();
  48111. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48112. if (chooser.browseForDirectory())
  48113. {
  48114. path.add (chooser.getResult(), currentRow);
  48115. }
  48116. }
  48117. else if (button == changeButton)
  48118. {
  48119. returnKeyPressed (currentRow);
  48120. }
  48121. else if (button == upButton)
  48122. {
  48123. if (currentRow > 0 && currentRow < path.getNumPaths())
  48124. {
  48125. const File f (path[currentRow]);
  48126. path.remove (currentRow);
  48127. path.add (f, currentRow - 1);
  48128. listBox->selectRow (currentRow - 1);
  48129. }
  48130. }
  48131. else if (button == downButton)
  48132. {
  48133. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48134. {
  48135. const File f (path[currentRow]);
  48136. path.remove (currentRow);
  48137. path.add (f, currentRow + 1);
  48138. listBox->selectRow (currentRow + 1);
  48139. }
  48140. }
  48141. changed();
  48142. }
  48143. END_JUCE_NAMESPACE
  48144. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48145. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48146. BEGIN_JUCE_NAMESPACE
  48147. const Image juce_createIconForFile (const File& file);
  48148. class FileListTreeItem : public TreeViewItem,
  48149. public TimeSliceClient,
  48150. public AsyncUpdater,
  48151. public ChangeListener
  48152. {
  48153. public:
  48154. FileListTreeItem (FileTreeComponent& owner_,
  48155. DirectoryContentsList* const parentContentsList_,
  48156. const int indexInContentsList_,
  48157. const File& file_,
  48158. TimeSliceThread& thread_)
  48159. : file (file_),
  48160. owner (owner_),
  48161. parentContentsList (parentContentsList_),
  48162. indexInContentsList (indexInContentsList_),
  48163. subContentsList (0),
  48164. canDeleteSubContentsList (false),
  48165. thread (thread_),
  48166. icon (0)
  48167. {
  48168. DirectoryContentsList::FileInfo fileInfo;
  48169. if (parentContentsList_ != 0
  48170. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48171. {
  48172. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48173. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48174. isDirectory = fileInfo.isDirectory;
  48175. }
  48176. else
  48177. {
  48178. isDirectory = true;
  48179. }
  48180. }
  48181. ~FileListTreeItem()
  48182. {
  48183. thread.removeTimeSliceClient (this);
  48184. clearSubItems();
  48185. if (canDeleteSubContentsList)
  48186. delete subContentsList;
  48187. }
  48188. bool mightContainSubItems() { return isDirectory; }
  48189. const String getUniqueName() const { return file.getFullPathName(); }
  48190. int getItemHeight() const { return 22; }
  48191. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48192. void itemOpennessChanged (bool isNowOpen)
  48193. {
  48194. if (isNowOpen)
  48195. {
  48196. clearSubItems();
  48197. isDirectory = file.isDirectory();
  48198. if (isDirectory)
  48199. {
  48200. if (subContentsList == 0)
  48201. {
  48202. jassert (parentContentsList != 0);
  48203. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48204. l->setDirectory (file, true, true);
  48205. setSubContentsList (l);
  48206. canDeleteSubContentsList = true;
  48207. }
  48208. changeListenerCallback (0);
  48209. }
  48210. }
  48211. }
  48212. void setSubContentsList (DirectoryContentsList* newList)
  48213. {
  48214. jassert (subContentsList == 0);
  48215. subContentsList = newList;
  48216. newList->addChangeListener (this);
  48217. }
  48218. void changeListenerCallback (void*)
  48219. {
  48220. clearSubItems();
  48221. if (isOpen() && subContentsList != 0)
  48222. {
  48223. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48224. {
  48225. FileListTreeItem* const item
  48226. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48227. addSubItem (item);
  48228. }
  48229. }
  48230. }
  48231. void paintItem (Graphics& g, int width, int height)
  48232. {
  48233. if (file != File::nonexistent)
  48234. {
  48235. updateIcon (true);
  48236. if (icon.isNull())
  48237. thread.addTimeSliceClient (this);
  48238. }
  48239. owner.getLookAndFeel()
  48240. .drawFileBrowserRow (g, width, height,
  48241. file.getFileName(),
  48242. &icon, fileSize, modTime,
  48243. isDirectory, isSelected(),
  48244. indexInContentsList, owner);
  48245. }
  48246. void itemClicked (const MouseEvent& e)
  48247. {
  48248. owner.sendMouseClickMessage (file, e);
  48249. }
  48250. void itemDoubleClicked (const MouseEvent& e)
  48251. {
  48252. TreeViewItem::itemDoubleClicked (e);
  48253. owner.sendDoubleClickMessage (file);
  48254. }
  48255. void itemSelectionChanged (bool)
  48256. {
  48257. owner.sendSelectionChangeMessage();
  48258. }
  48259. bool useTimeSlice()
  48260. {
  48261. updateIcon (false);
  48262. thread.removeTimeSliceClient (this);
  48263. return false;
  48264. }
  48265. void handleAsyncUpdate()
  48266. {
  48267. owner.repaint();
  48268. }
  48269. const File file;
  48270. juce_UseDebuggingNewOperator
  48271. private:
  48272. FileTreeComponent& owner;
  48273. DirectoryContentsList* parentContentsList;
  48274. int indexInContentsList;
  48275. DirectoryContentsList* subContentsList;
  48276. bool isDirectory, canDeleteSubContentsList;
  48277. TimeSliceThread& thread;
  48278. Image icon;
  48279. String fileSize;
  48280. String modTime;
  48281. void updateIcon (const bool onlyUpdateIfCached)
  48282. {
  48283. if (icon.isNull())
  48284. {
  48285. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48286. Image im (ImageCache::getFromHashCode (hashCode));
  48287. if (im.isNull() && ! onlyUpdateIfCached)
  48288. {
  48289. im = juce_createIconForFile (file);
  48290. if (im.isValid())
  48291. ImageCache::addImageToCache (im, hashCode);
  48292. }
  48293. if (im.isValid())
  48294. {
  48295. icon = im;
  48296. triggerAsyncUpdate();
  48297. }
  48298. }
  48299. }
  48300. };
  48301. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48302. : DirectoryContentsDisplayComponent (listToShow)
  48303. {
  48304. FileListTreeItem* const root
  48305. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48306. listToShow.getTimeSliceThread());
  48307. root->setSubContentsList (&listToShow);
  48308. setRootItemVisible (false);
  48309. setRootItem (root);
  48310. }
  48311. FileTreeComponent::~FileTreeComponent()
  48312. {
  48313. deleteRootItem();
  48314. }
  48315. const File FileTreeComponent::getSelectedFile (const int index) const
  48316. {
  48317. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48318. return item != 0 ? item->file
  48319. : File::nonexistent;
  48320. }
  48321. void FileTreeComponent::deselectAllFiles()
  48322. {
  48323. clearSelectedItems();
  48324. }
  48325. void FileTreeComponent::scrollToTop()
  48326. {
  48327. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48328. }
  48329. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48330. {
  48331. dragAndDropDescription = description;
  48332. }
  48333. END_JUCE_NAMESPACE
  48334. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48335. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48336. BEGIN_JUCE_NAMESPACE
  48337. ImagePreviewComponent::ImagePreviewComponent()
  48338. {
  48339. }
  48340. ImagePreviewComponent::~ImagePreviewComponent()
  48341. {
  48342. }
  48343. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48344. {
  48345. const int availableW = proportionOfWidth (0.97f);
  48346. const int availableH = getHeight() - 13 * 4;
  48347. const double scale = jmin (1.0,
  48348. availableW / (double) w,
  48349. availableH / (double) h);
  48350. w = roundToInt (scale * w);
  48351. h = roundToInt (scale * h);
  48352. }
  48353. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48354. {
  48355. if (fileToLoad != file)
  48356. {
  48357. fileToLoad = file;
  48358. startTimer (100);
  48359. }
  48360. }
  48361. void ImagePreviewComponent::timerCallback()
  48362. {
  48363. stopTimer();
  48364. currentThumbnail = Image::null;
  48365. currentDetails = String::empty;
  48366. repaint();
  48367. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48368. if (in != 0)
  48369. {
  48370. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48371. if (format != 0)
  48372. {
  48373. currentThumbnail = format->decodeImage (*in);
  48374. if (currentThumbnail.isValid())
  48375. {
  48376. int w = currentThumbnail.getWidth();
  48377. int h = currentThumbnail.getHeight();
  48378. currentDetails
  48379. << fileToLoad.getFileName() << "\n"
  48380. << format->getFormatName() << "\n"
  48381. << w << " x " << h << " pixels\n"
  48382. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48383. getThumbSize (w, h);
  48384. currentThumbnail = currentThumbnail.rescaled (w, h);
  48385. }
  48386. }
  48387. }
  48388. }
  48389. void ImagePreviewComponent::paint (Graphics& g)
  48390. {
  48391. if (currentThumbnail.isValid())
  48392. {
  48393. g.setFont (13.0f);
  48394. int w = currentThumbnail.getWidth();
  48395. int h = currentThumbnail.getHeight();
  48396. getThumbSize (w, h);
  48397. const int numLines = 4;
  48398. const int totalH = 13 * numLines + h + 4;
  48399. const int y = (getHeight() - totalH) / 2;
  48400. g.drawImageWithin (currentThumbnail,
  48401. (getWidth() - w) / 2, y, w, h,
  48402. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48403. false);
  48404. g.drawFittedText (currentDetails,
  48405. 0, y + h + 4, getWidth(), 100,
  48406. Justification::centredTop, numLines);
  48407. }
  48408. }
  48409. END_JUCE_NAMESPACE
  48410. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48411. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48412. BEGIN_JUCE_NAMESPACE
  48413. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48414. const String& directoryWildcardPatterns,
  48415. const String& description_)
  48416. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48417. : (description_ + " (" + fileWildcardPatterns + ")"))
  48418. {
  48419. parse (fileWildcardPatterns, fileWildcards);
  48420. parse (directoryWildcardPatterns, directoryWildcards);
  48421. }
  48422. WildcardFileFilter::~WildcardFileFilter()
  48423. {
  48424. }
  48425. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48426. {
  48427. return match (file, fileWildcards);
  48428. }
  48429. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48430. {
  48431. return match (file, directoryWildcards);
  48432. }
  48433. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48434. {
  48435. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48436. result.trim();
  48437. result.removeEmptyStrings();
  48438. // special case for *.*, because people use it to mean "any file", but it
  48439. // would actually ignore files with no extension.
  48440. for (int i = result.size(); --i >= 0;)
  48441. if (result[i] == "*.*")
  48442. result.set (i, "*");
  48443. }
  48444. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48445. {
  48446. const String filename (file.getFileName());
  48447. for (int i = wildcards.size(); --i >= 0;)
  48448. if (filename.matchesWildcard (wildcards[i], true))
  48449. return true;
  48450. return false;
  48451. }
  48452. END_JUCE_NAMESPACE
  48453. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48454. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48455. BEGIN_JUCE_NAMESPACE
  48456. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48457. {
  48458. }
  48459. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48460. {
  48461. }
  48462. namespace KeyboardFocusHelpers
  48463. {
  48464. // This will sort a set of components, so that they are ordered in terms of
  48465. // left-to-right and then top-to-bottom.
  48466. class ScreenPositionComparator
  48467. {
  48468. public:
  48469. ScreenPositionComparator() {}
  48470. static int compareElements (const Component* const first, const Component* const second)
  48471. {
  48472. int explicitOrder1 = first->getExplicitFocusOrder();
  48473. if (explicitOrder1 <= 0)
  48474. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48475. int explicitOrder2 = second->getExplicitFocusOrder();
  48476. if (explicitOrder2 <= 0)
  48477. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48478. if (explicitOrder1 != explicitOrder2)
  48479. return explicitOrder1 - explicitOrder2;
  48480. const int diff = first->getY() - second->getY();
  48481. return (diff == 0) ? first->getX() - second->getX()
  48482. : diff;
  48483. }
  48484. };
  48485. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48486. {
  48487. if (parent->getNumChildComponents() > 0)
  48488. {
  48489. Array <Component*> localComps;
  48490. ScreenPositionComparator comparator;
  48491. int i;
  48492. for (i = parent->getNumChildComponents(); --i >= 0;)
  48493. {
  48494. Component* const c = parent->getChildComponent (i);
  48495. if (c->isVisible() && c->isEnabled())
  48496. localComps.addSorted (comparator, c);
  48497. }
  48498. for (i = 0; i < localComps.size(); ++i)
  48499. {
  48500. Component* const c = localComps.getUnchecked (i);
  48501. if (c->getWantsKeyboardFocus())
  48502. comps.add (c);
  48503. if (! c->isFocusContainer())
  48504. findAllFocusableComponents (c, comps);
  48505. }
  48506. }
  48507. }
  48508. }
  48509. static Component* getIncrementedComponent (Component* const current, const int delta)
  48510. {
  48511. Component* focusContainer = current->getParentComponent();
  48512. if (focusContainer != 0)
  48513. {
  48514. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48515. focusContainer = focusContainer->getParentComponent();
  48516. if (focusContainer != 0)
  48517. {
  48518. Array <Component*> comps;
  48519. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48520. if (comps.size() > 0)
  48521. {
  48522. const int index = comps.indexOf (current);
  48523. return comps [(index + comps.size() + delta) % comps.size()];
  48524. }
  48525. }
  48526. }
  48527. return 0;
  48528. }
  48529. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48530. {
  48531. return getIncrementedComponent (current, 1);
  48532. }
  48533. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48534. {
  48535. return getIncrementedComponent (current, -1);
  48536. }
  48537. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48538. {
  48539. Array <Component*> comps;
  48540. if (parentComponent != 0)
  48541. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48542. return comps.getFirst();
  48543. }
  48544. END_JUCE_NAMESPACE
  48545. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48546. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48547. BEGIN_JUCE_NAMESPACE
  48548. bool KeyListener::keyStateChanged (const bool, Component*)
  48549. {
  48550. return false;
  48551. }
  48552. END_JUCE_NAMESPACE
  48553. /*** End of inlined file: juce_KeyListener.cpp ***/
  48554. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48555. BEGIN_JUCE_NAMESPACE
  48556. // N.B. these two includes are put here deliberately to avoid problems with
  48557. // old GCCs failing on long include paths
  48558. const int maxKeys = 3;
  48559. class KeyMappingChangeButton : public Button
  48560. {
  48561. public:
  48562. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48563. const CommandID commandID_,
  48564. const String& keyName,
  48565. const int keyNum_)
  48566. : Button (keyName),
  48567. owner (owner_),
  48568. commandID (commandID_),
  48569. keyNum (keyNum_)
  48570. {
  48571. setWantsKeyboardFocus (false);
  48572. setTriggeredOnMouseDown (keyNum >= 0);
  48573. if (keyNum_ < 0)
  48574. setTooltip (TRANS("adds a new key-mapping"));
  48575. else
  48576. setTooltip (TRANS("click to change this key-mapping"));
  48577. }
  48578. ~KeyMappingChangeButton()
  48579. {
  48580. }
  48581. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48582. {
  48583. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48584. keyNum >= 0 ? getName() : String::empty);
  48585. }
  48586. void clicked()
  48587. {
  48588. if (keyNum >= 0)
  48589. {
  48590. // existing key clicked..
  48591. PopupMenu m;
  48592. m.addItem (1, TRANS("change this key-mapping"));
  48593. m.addSeparator();
  48594. m.addItem (2, TRANS("remove this key-mapping"));
  48595. const int res = m.show();
  48596. if (res == 1)
  48597. {
  48598. owner->assignNewKey (commandID, keyNum);
  48599. }
  48600. else if (res == 2)
  48601. {
  48602. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48603. }
  48604. }
  48605. else
  48606. {
  48607. // + button pressed..
  48608. owner->assignNewKey (commandID, -1);
  48609. }
  48610. }
  48611. void fitToContent (const int h) throw()
  48612. {
  48613. if (keyNum < 0)
  48614. {
  48615. setSize (h, h);
  48616. }
  48617. else
  48618. {
  48619. Font f (h * 0.6f);
  48620. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48621. }
  48622. }
  48623. juce_UseDebuggingNewOperator
  48624. private:
  48625. KeyMappingEditorComponent* const owner;
  48626. const CommandID commandID;
  48627. const int keyNum;
  48628. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48629. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48630. };
  48631. class KeyMappingItemComponent : public Component
  48632. {
  48633. public:
  48634. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48635. const CommandID commandID_)
  48636. : owner (owner_),
  48637. commandID (commandID_)
  48638. {
  48639. setInterceptsMouseClicks (false, true);
  48640. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48641. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48642. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48643. {
  48644. KeyMappingChangeButton* const kb
  48645. = new KeyMappingChangeButton (owner_, commandID,
  48646. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48647. kb->setEnabled (! isReadOnly);
  48648. addAndMakeVisible (kb);
  48649. }
  48650. KeyMappingChangeButton* const kb
  48651. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48652. addChildComponent (kb);
  48653. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48654. }
  48655. ~KeyMappingItemComponent()
  48656. {
  48657. deleteAllChildren();
  48658. }
  48659. void paint (Graphics& g)
  48660. {
  48661. g.setFont (getHeight() * 0.7f);
  48662. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48663. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48664. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48665. Justification::centredLeft, true);
  48666. }
  48667. void resized()
  48668. {
  48669. int x = getWidth() - 4;
  48670. for (int i = getNumChildComponents(); --i >= 0;)
  48671. {
  48672. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48673. kb->fitToContent (getHeight() - 2);
  48674. kb->setTopRightPosition (x, 1);
  48675. x -= kb->getWidth() + 5;
  48676. }
  48677. }
  48678. juce_UseDebuggingNewOperator
  48679. private:
  48680. KeyMappingEditorComponent* const owner;
  48681. const CommandID commandID;
  48682. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48683. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48684. };
  48685. class KeyMappingTreeViewItem : public TreeViewItem
  48686. {
  48687. public:
  48688. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48689. const CommandID commandID_)
  48690. : owner (owner_),
  48691. commandID (commandID_)
  48692. {
  48693. }
  48694. ~KeyMappingTreeViewItem()
  48695. {
  48696. }
  48697. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48698. bool mightContainSubItems() { return false; }
  48699. int getItemHeight() const { return 20; }
  48700. Component* createItemComponent()
  48701. {
  48702. return new KeyMappingItemComponent (owner, commandID);
  48703. }
  48704. juce_UseDebuggingNewOperator
  48705. private:
  48706. KeyMappingEditorComponent* const owner;
  48707. const CommandID commandID;
  48708. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48709. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48710. };
  48711. class KeyCategoryTreeViewItem : public TreeViewItem
  48712. {
  48713. public:
  48714. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48715. const String& name)
  48716. : owner (owner_),
  48717. categoryName (name)
  48718. {
  48719. }
  48720. ~KeyCategoryTreeViewItem()
  48721. {
  48722. }
  48723. const String getUniqueName() const { return categoryName + "_cat"; }
  48724. bool mightContainSubItems() { return true; }
  48725. int getItemHeight() const { return 28; }
  48726. void paintItem (Graphics& g, int width, int height)
  48727. {
  48728. g.setFont (height * 0.6f, Font::bold);
  48729. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48730. g.drawText (categoryName,
  48731. 2, 0, width - 2, height,
  48732. Justification::centredLeft, true);
  48733. }
  48734. void itemOpennessChanged (bool isNowOpen)
  48735. {
  48736. if (isNowOpen)
  48737. {
  48738. if (getNumSubItems() == 0)
  48739. {
  48740. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48741. for (int i = 0; i < commands.size(); ++i)
  48742. {
  48743. if (owner->shouldCommandBeIncluded (commands[i]))
  48744. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48745. }
  48746. }
  48747. }
  48748. else
  48749. {
  48750. clearSubItems();
  48751. }
  48752. }
  48753. juce_UseDebuggingNewOperator
  48754. private:
  48755. KeyMappingEditorComponent* owner;
  48756. String categoryName;
  48757. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48758. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48759. };
  48760. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48761. const bool showResetToDefaultButton)
  48762. : mappings (mappingManager)
  48763. {
  48764. jassert (mappingManager != 0); // can't be null!
  48765. mappingManager->addChangeListener (this);
  48766. setLinesDrawnForSubItems (false);
  48767. resetButton = 0;
  48768. if (showResetToDefaultButton)
  48769. {
  48770. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48771. resetButton->addButtonListener (this);
  48772. }
  48773. addAndMakeVisible (tree = new TreeView());
  48774. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48775. tree->setRootItemVisible (false);
  48776. tree->setDefaultOpenness (true);
  48777. tree->setRootItem (this);
  48778. }
  48779. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48780. {
  48781. mappings->removeChangeListener (this);
  48782. deleteAllChildren();
  48783. }
  48784. bool KeyMappingEditorComponent::mightContainSubItems()
  48785. {
  48786. return true;
  48787. }
  48788. const String KeyMappingEditorComponent::getUniqueName() const
  48789. {
  48790. return "keys";
  48791. }
  48792. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48793. const Colour& textColour)
  48794. {
  48795. setColour (backgroundColourId, mainBackground);
  48796. setColour (textColourId, textColour);
  48797. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48798. }
  48799. void KeyMappingEditorComponent::parentHierarchyChanged()
  48800. {
  48801. changeListenerCallback (0);
  48802. }
  48803. void KeyMappingEditorComponent::resized()
  48804. {
  48805. int h = getHeight();
  48806. if (resetButton != 0)
  48807. {
  48808. const int buttonHeight = 20;
  48809. h -= buttonHeight + 8;
  48810. int x = getWidth() - 8;
  48811. resetButton->changeWidthToFitText (buttonHeight);
  48812. resetButton->setTopRightPosition (x, h + 6);
  48813. }
  48814. tree->setBounds (0, 0, getWidth(), h);
  48815. }
  48816. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48817. {
  48818. if (button == resetButton)
  48819. {
  48820. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48821. TRANS("Reset to defaults"),
  48822. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48823. TRANS("Reset")))
  48824. {
  48825. mappings->resetToDefaultMappings();
  48826. }
  48827. }
  48828. }
  48829. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48830. {
  48831. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48832. clearSubItems();
  48833. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48834. for (int i = 0; i < categories.size(); ++i)
  48835. {
  48836. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48837. int count = 0;
  48838. for (int j = 0; j < commands.size(); ++j)
  48839. if (shouldCommandBeIncluded (commands[j]))
  48840. ++count;
  48841. if (count > 0)
  48842. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48843. }
  48844. if (oldOpenness != 0)
  48845. tree->restoreOpennessState (*oldOpenness);
  48846. }
  48847. class KeyEntryWindow : public AlertWindow
  48848. {
  48849. public:
  48850. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48851. : AlertWindow (TRANS("New key-mapping"),
  48852. TRANS("Please press a key combination now..."),
  48853. AlertWindow::NoIcon),
  48854. owner (owner_)
  48855. {
  48856. addButton (TRANS("ok"), 1);
  48857. addButton (TRANS("cancel"), 0);
  48858. // (avoid return + escape keys getting processed by the buttons..)
  48859. for (int i = getNumChildComponents(); --i >= 0;)
  48860. getChildComponent (i)->setWantsKeyboardFocus (false);
  48861. setWantsKeyboardFocus (true);
  48862. grabKeyboardFocus();
  48863. }
  48864. ~KeyEntryWindow()
  48865. {
  48866. }
  48867. bool keyPressed (const KeyPress& key)
  48868. {
  48869. lastPress = key;
  48870. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48871. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48872. if (previousCommand != 0)
  48873. {
  48874. message << "\n\n"
  48875. << TRANS("(Currently assigned to \"")
  48876. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48877. << "\")";
  48878. }
  48879. setMessage (message);
  48880. return true;
  48881. }
  48882. bool keyStateChanged (bool)
  48883. {
  48884. return true;
  48885. }
  48886. KeyPress lastPress;
  48887. juce_UseDebuggingNewOperator
  48888. private:
  48889. KeyMappingEditorComponent* owner;
  48890. KeyEntryWindow (const KeyEntryWindow&);
  48891. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48892. };
  48893. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48894. {
  48895. KeyEntryWindow entryWindow (this);
  48896. if (entryWindow.runModalLoop() != 0)
  48897. {
  48898. entryWindow.setVisible (false);
  48899. if (entryWindow.lastPress.isValid())
  48900. {
  48901. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48902. if (previousCommand != 0)
  48903. {
  48904. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48905. TRANS("Change key-mapping"),
  48906. TRANS("This key is already assigned to the command \"")
  48907. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48908. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48909. TRANS("re-assign"),
  48910. TRANS("cancel")))
  48911. {
  48912. return;
  48913. }
  48914. }
  48915. mappings->removeKeyPress (entryWindow.lastPress);
  48916. if (index >= 0)
  48917. mappings->removeKeyPress (commandID, index);
  48918. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48919. }
  48920. }
  48921. }
  48922. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48923. {
  48924. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48925. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48926. }
  48927. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48928. {
  48929. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48930. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48931. }
  48932. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48933. {
  48934. return key.getTextDescription();
  48935. }
  48936. END_JUCE_NAMESPACE
  48937. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48938. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48939. BEGIN_JUCE_NAMESPACE
  48940. KeyPress::KeyPress() throw()
  48941. : keyCode (0),
  48942. mods (0),
  48943. textCharacter (0)
  48944. {
  48945. }
  48946. KeyPress::KeyPress (const int keyCode_,
  48947. const ModifierKeys& mods_,
  48948. const juce_wchar textCharacter_) throw()
  48949. : keyCode (keyCode_),
  48950. mods (mods_),
  48951. textCharacter (textCharacter_)
  48952. {
  48953. }
  48954. KeyPress::KeyPress (const int keyCode_) throw()
  48955. : keyCode (keyCode_),
  48956. textCharacter (0)
  48957. {
  48958. }
  48959. KeyPress::KeyPress (const KeyPress& other) throw()
  48960. : keyCode (other.keyCode),
  48961. mods (other.mods),
  48962. textCharacter (other.textCharacter)
  48963. {
  48964. }
  48965. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48966. {
  48967. keyCode = other.keyCode;
  48968. mods = other.mods;
  48969. textCharacter = other.textCharacter;
  48970. return *this;
  48971. }
  48972. bool KeyPress::operator== (const KeyPress& other) const throw()
  48973. {
  48974. return mods.getRawFlags() == other.mods.getRawFlags()
  48975. && (textCharacter == other.textCharacter
  48976. || textCharacter == 0
  48977. || other.textCharacter == 0)
  48978. && (keyCode == other.keyCode
  48979. || (keyCode < 256
  48980. && other.keyCode < 256
  48981. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48982. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48983. }
  48984. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48985. {
  48986. return ! operator== (other);
  48987. }
  48988. bool KeyPress::isCurrentlyDown() const
  48989. {
  48990. return isKeyCurrentlyDown (keyCode)
  48991. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48992. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48993. }
  48994. namespace KeyPressHelpers
  48995. {
  48996. struct KeyNameAndCode
  48997. {
  48998. const char* name;
  48999. int code;
  49000. };
  49001. static const KeyNameAndCode translations[] =
  49002. {
  49003. { "spacebar", KeyPress::spaceKey },
  49004. { "return", KeyPress::returnKey },
  49005. { "escape", KeyPress::escapeKey },
  49006. { "backspace", KeyPress::backspaceKey },
  49007. { "cursor left", KeyPress::leftKey },
  49008. { "cursor right", KeyPress::rightKey },
  49009. { "cursor up", KeyPress::upKey },
  49010. { "cursor down", KeyPress::downKey },
  49011. { "page up", KeyPress::pageUpKey },
  49012. { "page down", KeyPress::pageDownKey },
  49013. { "home", KeyPress::homeKey },
  49014. { "end", KeyPress::endKey },
  49015. { "delete", KeyPress::deleteKey },
  49016. { "insert", KeyPress::insertKey },
  49017. { "tab", KeyPress::tabKey },
  49018. { "play", KeyPress::playKey },
  49019. { "stop", KeyPress::stopKey },
  49020. { "fast forward", KeyPress::fastForwardKey },
  49021. { "rewind", KeyPress::rewindKey }
  49022. };
  49023. static const String numberPadPrefix() { return "numpad "; }
  49024. }
  49025. const KeyPress KeyPress::createFromDescription (const String& desc)
  49026. {
  49027. int modifiers = 0;
  49028. if (desc.containsWholeWordIgnoreCase ("ctrl")
  49029. || desc.containsWholeWordIgnoreCase ("control")
  49030. || desc.containsWholeWordIgnoreCase ("ctl"))
  49031. modifiers |= ModifierKeys::ctrlModifier;
  49032. if (desc.containsWholeWordIgnoreCase ("shift")
  49033. || desc.containsWholeWordIgnoreCase ("shft"))
  49034. modifiers |= ModifierKeys::shiftModifier;
  49035. if (desc.containsWholeWordIgnoreCase ("alt")
  49036. || desc.containsWholeWordIgnoreCase ("option"))
  49037. modifiers |= ModifierKeys::altModifier;
  49038. if (desc.containsWholeWordIgnoreCase ("command")
  49039. || desc.containsWholeWordIgnoreCase ("cmd"))
  49040. modifiers |= ModifierKeys::commandModifier;
  49041. int key = 0;
  49042. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49043. {
  49044. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  49045. {
  49046. key = KeyPressHelpers::translations[i].code;
  49047. break;
  49048. }
  49049. }
  49050. if (key == 0)
  49051. {
  49052. // see if it's a numpad key..
  49053. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  49054. {
  49055. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  49056. if (lastChar >= '0' && lastChar <= '9')
  49057. key = numberPad0 + lastChar - '0';
  49058. else if (lastChar == '+')
  49059. key = numberPadAdd;
  49060. else if (lastChar == '-')
  49061. key = numberPadSubtract;
  49062. else if (lastChar == '*')
  49063. key = numberPadMultiply;
  49064. else if (lastChar == '/')
  49065. key = numberPadDivide;
  49066. else if (lastChar == '.')
  49067. key = numberPadDecimalPoint;
  49068. else if (lastChar == '=')
  49069. key = numberPadEquals;
  49070. else if (desc.endsWith ("separator"))
  49071. key = numberPadSeparator;
  49072. else if (desc.endsWith ("delete"))
  49073. key = numberPadDelete;
  49074. }
  49075. if (key == 0)
  49076. {
  49077. // see if it's a function key..
  49078. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49079. for (int i = 1; i <= 12; ++i)
  49080. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49081. key = F1Key + i - 1;
  49082. if (key == 0)
  49083. {
  49084. // give up and use the hex code..
  49085. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49086. .toLowerCase()
  49087. .retainCharacters ("0123456789abcdef")
  49088. .getHexValue32();
  49089. if (hexCode > 0)
  49090. key = hexCode;
  49091. else
  49092. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49093. }
  49094. }
  49095. }
  49096. return KeyPress (key, ModifierKeys (modifiers), 0);
  49097. }
  49098. const String KeyPress::getTextDescription() const
  49099. {
  49100. String desc;
  49101. if (keyCode > 0)
  49102. {
  49103. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49104. // want to store it as being a slash, not shift+whatever.
  49105. if (textCharacter == '/')
  49106. return "/";
  49107. if (mods.isCtrlDown())
  49108. desc << "ctrl + ";
  49109. if (mods.isShiftDown())
  49110. desc << "shift + ";
  49111. #if JUCE_MAC
  49112. // only do this on the mac, because on Windows ctrl and command are the same,
  49113. // and this would get confusing
  49114. if (mods.isCommandDown())
  49115. desc << "command + ";
  49116. if (mods.isAltDown())
  49117. desc << "option + ";
  49118. #else
  49119. if (mods.isAltDown())
  49120. desc << "alt + ";
  49121. #endif
  49122. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49123. if (keyCode == KeyPressHelpers::translations[i].code)
  49124. return desc + KeyPressHelpers::translations[i].name;
  49125. if (keyCode >= F1Key && keyCode <= F16Key)
  49126. desc << 'F' << (1 + keyCode - F1Key);
  49127. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49128. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49129. else if (keyCode >= 33 && keyCode < 176)
  49130. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49131. else if (keyCode == numberPadAdd)
  49132. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49133. else if (keyCode == numberPadSubtract)
  49134. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49135. else if (keyCode == numberPadMultiply)
  49136. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49137. else if (keyCode == numberPadDivide)
  49138. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49139. else if (keyCode == numberPadSeparator)
  49140. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49141. else if (keyCode == numberPadDecimalPoint)
  49142. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49143. else if (keyCode == numberPadDelete)
  49144. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49145. else
  49146. desc << '#' << String::toHexString (keyCode);
  49147. }
  49148. return desc;
  49149. }
  49150. END_JUCE_NAMESPACE
  49151. /*** End of inlined file: juce_KeyPress.cpp ***/
  49152. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49153. BEGIN_JUCE_NAMESPACE
  49154. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49155. : commandManager (commandManager_)
  49156. {
  49157. // A manager is needed to get the descriptions of commands, and will be called when
  49158. // a command is invoked. So you can't leave this null..
  49159. jassert (commandManager_ != 0);
  49160. Desktop::getInstance().addFocusChangeListener (this);
  49161. }
  49162. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49163. : commandManager (other.commandManager)
  49164. {
  49165. Desktop::getInstance().addFocusChangeListener (this);
  49166. }
  49167. KeyPressMappingSet::~KeyPressMappingSet()
  49168. {
  49169. Desktop::getInstance().removeFocusChangeListener (this);
  49170. }
  49171. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49172. {
  49173. for (int i = 0; i < mappings.size(); ++i)
  49174. if (mappings.getUnchecked(i)->commandID == commandID)
  49175. return mappings.getUnchecked (i)->keypresses;
  49176. return Array <KeyPress> ();
  49177. }
  49178. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49179. const KeyPress& newKeyPress,
  49180. int insertIndex)
  49181. {
  49182. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49183. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49184. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49185. && ! newKeyPress.getModifiers().isShiftDown()));
  49186. if (findCommandForKeyPress (newKeyPress) != commandID)
  49187. {
  49188. removeKeyPress (newKeyPress);
  49189. if (newKeyPress.isValid())
  49190. {
  49191. for (int i = mappings.size(); --i >= 0;)
  49192. {
  49193. if (mappings.getUnchecked(i)->commandID == commandID)
  49194. {
  49195. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49196. sendChangeMessage (this);
  49197. return;
  49198. }
  49199. }
  49200. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49201. if (ci != 0)
  49202. {
  49203. CommandMapping* const cm = new CommandMapping();
  49204. cm->commandID = commandID;
  49205. cm->keypresses.add (newKeyPress);
  49206. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49207. mappings.add (cm);
  49208. sendChangeMessage (this);
  49209. }
  49210. }
  49211. }
  49212. }
  49213. void KeyPressMappingSet::resetToDefaultMappings()
  49214. {
  49215. mappings.clear();
  49216. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49217. {
  49218. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49219. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49220. {
  49221. addKeyPress (ci->commandID,
  49222. ci->defaultKeypresses.getReference (j));
  49223. }
  49224. }
  49225. sendChangeMessage (this);
  49226. }
  49227. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49228. {
  49229. clearAllKeyPresses (commandID);
  49230. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49231. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49232. {
  49233. addKeyPress (ci->commandID,
  49234. ci->defaultKeypresses.getReference (j));
  49235. }
  49236. }
  49237. void KeyPressMappingSet::clearAllKeyPresses()
  49238. {
  49239. if (mappings.size() > 0)
  49240. {
  49241. sendChangeMessage (this);
  49242. mappings.clear();
  49243. }
  49244. }
  49245. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49246. {
  49247. for (int i = mappings.size(); --i >= 0;)
  49248. {
  49249. if (mappings.getUnchecked(i)->commandID == commandID)
  49250. {
  49251. mappings.remove (i);
  49252. sendChangeMessage (this);
  49253. }
  49254. }
  49255. }
  49256. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49257. {
  49258. if (keypress.isValid())
  49259. {
  49260. for (int i = mappings.size(); --i >= 0;)
  49261. {
  49262. CommandMapping* const cm = mappings.getUnchecked(i);
  49263. for (int j = cm->keypresses.size(); --j >= 0;)
  49264. {
  49265. if (keypress == cm->keypresses [j])
  49266. {
  49267. cm->keypresses.remove (j);
  49268. sendChangeMessage (this);
  49269. }
  49270. }
  49271. }
  49272. }
  49273. }
  49274. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49275. {
  49276. for (int i = mappings.size(); --i >= 0;)
  49277. {
  49278. if (mappings.getUnchecked(i)->commandID == commandID)
  49279. {
  49280. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49281. sendChangeMessage (this);
  49282. break;
  49283. }
  49284. }
  49285. }
  49286. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49287. {
  49288. for (int i = 0; i < mappings.size(); ++i)
  49289. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49290. return mappings.getUnchecked(i)->commandID;
  49291. return 0;
  49292. }
  49293. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49294. {
  49295. for (int i = mappings.size(); --i >= 0;)
  49296. if (mappings.getUnchecked(i)->commandID == commandID)
  49297. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49298. return false;
  49299. }
  49300. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49301. const KeyPress& key,
  49302. const bool isKeyDown,
  49303. const int millisecsSinceKeyPressed,
  49304. Component* const originatingComponent) const
  49305. {
  49306. ApplicationCommandTarget::InvocationInfo info (commandID);
  49307. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49308. info.isKeyDown = isKeyDown;
  49309. info.keyPress = key;
  49310. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49311. info.originatingComponent = originatingComponent;
  49312. commandManager->invoke (info, false);
  49313. }
  49314. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49315. {
  49316. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49317. {
  49318. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49319. {
  49320. // if the XML was created as a set of differences from the default mappings,
  49321. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49322. resetToDefaultMappings();
  49323. }
  49324. else
  49325. {
  49326. // if the XML was created calling createXml (false), then we need to clear all
  49327. // the keys and treat the xml as describing the entire set of mappings.
  49328. clearAllKeyPresses();
  49329. }
  49330. forEachXmlChildElement (xmlVersion, map)
  49331. {
  49332. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49333. if (commandId != 0)
  49334. {
  49335. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49336. if (map->hasTagName ("MAPPING"))
  49337. {
  49338. addKeyPress (commandId, key);
  49339. }
  49340. else if (map->hasTagName ("UNMAPPING"))
  49341. {
  49342. if (containsMapping (commandId, key))
  49343. removeKeyPress (key);
  49344. }
  49345. }
  49346. }
  49347. return true;
  49348. }
  49349. return false;
  49350. }
  49351. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49352. {
  49353. ScopedPointer <KeyPressMappingSet> defaultSet;
  49354. if (saveDifferencesFromDefaultSet)
  49355. {
  49356. defaultSet = new KeyPressMappingSet (commandManager);
  49357. defaultSet->resetToDefaultMappings();
  49358. }
  49359. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49360. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49361. int i;
  49362. for (i = 0; i < mappings.size(); ++i)
  49363. {
  49364. const CommandMapping* const cm = mappings.getUnchecked(i);
  49365. for (int j = 0; j < cm->keypresses.size(); ++j)
  49366. {
  49367. if (defaultSet == 0
  49368. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49369. {
  49370. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49371. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49372. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49373. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49374. }
  49375. }
  49376. }
  49377. if (defaultSet != 0)
  49378. {
  49379. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49380. {
  49381. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49382. for (int j = 0; j < cm->keypresses.size(); ++j)
  49383. {
  49384. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49385. {
  49386. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49387. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49388. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49389. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49390. }
  49391. }
  49392. }
  49393. }
  49394. return doc;
  49395. }
  49396. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49397. Component* originatingComponent)
  49398. {
  49399. bool used = false;
  49400. const CommandID commandID = findCommandForKeyPress (key);
  49401. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49402. if (ci != 0
  49403. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49404. {
  49405. ApplicationCommandInfo info (0);
  49406. if (commandManager->getTargetForCommand (commandID, info) != 0
  49407. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49408. {
  49409. invokeCommand (commandID, key, true, 0, originatingComponent);
  49410. used = true;
  49411. }
  49412. else
  49413. {
  49414. if (originatingComponent != 0)
  49415. originatingComponent->getLookAndFeel().playAlertSound();
  49416. }
  49417. }
  49418. return used;
  49419. }
  49420. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49421. {
  49422. bool used = false;
  49423. const uint32 now = Time::getMillisecondCounter();
  49424. for (int i = mappings.size(); --i >= 0;)
  49425. {
  49426. CommandMapping* const cm = mappings.getUnchecked(i);
  49427. if (cm->wantsKeyUpDownCallbacks)
  49428. {
  49429. for (int j = cm->keypresses.size(); --j >= 0;)
  49430. {
  49431. const KeyPress key (cm->keypresses.getReference (j));
  49432. const bool isDown = key.isCurrentlyDown();
  49433. int keyPressEntryIndex = 0;
  49434. bool wasDown = false;
  49435. for (int k = keysDown.size(); --k >= 0;)
  49436. {
  49437. if (key == keysDown.getUnchecked(k)->key)
  49438. {
  49439. keyPressEntryIndex = k;
  49440. wasDown = true;
  49441. used = true;
  49442. break;
  49443. }
  49444. }
  49445. if (isDown != wasDown)
  49446. {
  49447. int millisecs = 0;
  49448. if (isDown)
  49449. {
  49450. KeyPressTime* const k = new KeyPressTime();
  49451. k->key = key;
  49452. k->timeWhenPressed = now;
  49453. keysDown.add (k);
  49454. }
  49455. else
  49456. {
  49457. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49458. if (now > pressTime)
  49459. millisecs = now - pressTime;
  49460. keysDown.remove (keyPressEntryIndex);
  49461. }
  49462. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49463. used = true;
  49464. }
  49465. }
  49466. }
  49467. }
  49468. return used;
  49469. }
  49470. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49471. {
  49472. if (focusedComponent != 0)
  49473. focusedComponent->keyStateChanged (false);
  49474. }
  49475. END_JUCE_NAMESPACE
  49476. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49477. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49478. BEGIN_JUCE_NAMESPACE
  49479. ModifierKeys::ModifierKeys (const int flags_) throw()
  49480. : flags (flags_)
  49481. {
  49482. }
  49483. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49484. : flags (other.flags)
  49485. {
  49486. }
  49487. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49488. {
  49489. flags = other.flags;
  49490. return *this;
  49491. }
  49492. ModifierKeys ModifierKeys::currentModifiers;
  49493. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49494. {
  49495. return currentModifiers;
  49496. }
  49497. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49498. {
  49499. int num = 0;
  49500. if (isLeftButtonDown()) ++num;
  49501. if (isRightButtonDown()) ++num;
  49502. if (isMiddleButtonDown()) ++num;
  49503. return num;
  49504. }
  49505. END_JUCE_NAMESPACE
  49506. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49507. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49508. BEGIN_JUCE_NAMESPACE
  49509. class ComponentAnimator::AnimationTask
  49510. {
  49511. public:
  49512. AnimationTask (Component* const comp)
  49513. : component (comp)
  49514. {
  49515. }
  49516. bool useTimeslice (const int elapsed)
  49517. {
  49518. if (component == 0)
  49519. return false;
  49520. msElapsed += elapsed;
  49521. double newProgress = msElapsed / (double) msTotal;
  49522. if (newProgress >= 0 && newProgress < 1.0)
  49523. {
  49524. newProgress = timeToDistance (newProgress);
  49525. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49526. jassert (newProgress >= lastProgress);
  49527. lastProgress = newProgress;
  49528. left += (destination.getX() - left) * delta;
  49529. top += (destination.getY() - top) * delta;
  49530. right += (destination.getRight() - right) * delta;
  49531. bottom += (destination.getBottom() - bottom) * delta;
  49532. if (delta < 1.0)
  49533. {
  49534. const Rectangle<int> newBounds (roundToInt (left),
  49535. roundToInt (top),
  49536. roundToInt (right - left),
  49537. roundToInt (bottom - top));
  49538. if (newBounds != destination)
  49539. {
  49540. component->setBounds (newBounds);
  49541. return true;
  49542. }
  49543. }
  49544. }
  49545. component->setBounds (destination);
  49546. return false;
  49547. }
  49548. void moveToFinalDestination()
  49549. {
  49550. if (component != 0)
  49551. component->setBounds (destination);
  49552. }
  49553. Component::SafePointer<Component> component;
  49554. Rectangle<int> destination;
  49555. int msElapsed, msTotal;
  49556. double startSpeed, midSpeed, endSpeed, lastProgress;
  49557. double left, top, right, bottom;
  49558. private:
  49559. inline double timeToDistance (const double time) const
  49560. {
  49561. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49562. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49563. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49564. }
  49565. };
  49566. ComponentAnimator::ComponentAnimator()
  49567. : lastTime (0)
  49568. {
  49569. }
  49570. ComponentAnimator::~ComponentAnimator()
  49571. {
  49572. }
  49573. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49574. {
  49575. for (int i = tasks.size(); --i >= 0;)
  49576. if (component == tasks.getUnchecked(i)->component.getComponent())
  49577. return tasks.getUnchecked(i);
  49578. return 0;
  49579. }
  49580. void ComponentAnimator::animateComponent (Component* const component,
  49581. const Rectangle<int>& finalPosition,
  49582. const int millisecondsToSpendMoving,
  49583. const double startSpeed,
  49584. const double endSpeed)
  49585. {
  49586. if (component != 0)
  49587. {
  49588. AnimationTask* at = findTaskFor (component);
  49589. if (at == 0)
  49590. {
  49591. at = new AnimationTask (component);
  49592. tasks.add (at);
  49593. sendChangeMessage (this);
  49594. }
  49595. at->msElapsed = 0;
  49596. at->lastProgress = 0;
  49597. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49598. at->destination = finalPosition;
  49599. // the speeds must be 0 or greater!
  49600. jassert (startSpeed >= 0 && endSpeed >= 0)
  49601. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49602. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49603. at->midSpeed = invTotalDistance;
  49604. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49605. at->left = component->getX();
  49606. at->top = component->getY();
  49607. at->right = component->getRight();
  49608. at->bottom = component->getBottom();
  49609. if (! isTimerRunning())
  49610. {
  49611. lastTime = Time::getMillisecondCounter();
  49612. startTimer (1000 / 50);
  49613. }
  49614. }
  49615. }
  49616. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49617. {
  49618. if (tasks.size() > 0)
  49619. {
  49620. if (moveComponentsToTheirFinalPositions)
  49621. for (int i = tasks.size(); --i >= 0;)
  49622. tasks.getUnchecked(i)->moveToFinalDestination();
  49623. tasks.clear();
  49624. sendChangeMessage (this);
  49625. }
  49626. }
  49627. void ComponentAnimator::cancelAnimation (Component* const component,
  49628. const bool moveComponentToItsFinalPosition)
  49629. {
  49630. AnimationTask* const at = findTaskFor (component);
  49631. if (at != 0)
  49632. {
  49633. if (moveComponentToItsFinalPosition)
  49634. at->moveToFinalDestination();
  49635. tasks.removeObject (at);
  49636. sendChangeMessage (this);
  49637. }
  49638. }
  49639. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49640. {
  49641. AnimationTask* const at = findTaskFor (component);
  49642. if (at != 0)
  49643. return at->destination;
  49644. else if (component != 0)
  49645. return component->getBounds();
  49646. return Rectangle<int>();
  49647. }
  49648. bool ComponentAnimator::isAnimating (Component* component) const
  49649. {
  49650. return findTaskFor (component) != 0;
  49651. }
  49652. void ComponentAnimator::timerCallback()
  49653. {
  49654. const uint32 timeNow = Time::getMillisecondCounter();
  49655. if (lastTime == 0 || lastTime == timeNow)
  49656. lastTime = timeNow;
  49657. const int elapsed = timeNow - lastTime;
  49658. for (int i = tasks.size(); --i >= 0;)
  49659. {
  49660. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49661. {
  49662. tasks.remove (i);
  49663. sendChangeMessage (this);
  49664. }
  49665. }
  49666. lastTime = timeNow;
  49667. if (tasks.size() == 0)
  49668. stopTimer();
  49669. }
  49670. END_JUCE_NAMESPACE
  49671. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49672. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49673. BEGIN_JUCE_NAMESPACE
  49674. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49675. : minW (0),
  49676. maxW (0x3fffffff),
  49677. minH (0),
  49678. maxH (0x3fffffff),
  49679. minOffTop (0),
  49680. minOffLeft (0),
  49681. minOffBottom (0),
  49682. minOffRight (0),
  49683. aspectRatio (0.0)
  49684. {
  49685. }
  49686. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49687. {
  49688. }
  49689. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49690. {
  49691. minW = minimumWidth;
  49692. }
  49693. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49694. {
  49695. maxW = maximumWidth;
  49696. }
  49697. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49698. {
  49699. minH = minimumHeight;
  49700. }
  49701. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49702. {
  49703. maxH = maximumHeight;
  49704. }
  49705. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49706. {
  49707. jassert (maxW >= minimumWidth);
  49708. jassert (maxH >= minimumHeight);
  49709. jassert (minimumWidth > 0 && minimumHeight > 0);
  49710. minW = minimumWidth;
  49711. minH = minimumHeight;
  49712. if (minW > maxW)
  49713. maxW = minW;
  49714. if (minH > maxH)
  49715. maxH = minH;
  49716. }
  49717. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49718. {
  49719. jassert (maximumWidth >= minW);
  49720. jassert (maximumHeight >= minH);
  49721. jassert (maximumWidth > 0 && maximumHeight > 0);
  49722. maxW = jmax (minW, maximumWidth);
  49723. maxH = jmax (minH, maximumHeight);
  49724. }
  49725. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49726. const int minimumHeight,
  49727. const int maximumWidth,
  49728. const int maximumHeight) throw()
  49729. {
  49730. jassert (maximumWidth >= minimumWidth);
  49731. jassert (maximumHeight >= minimumHeight);
  49732. jassert (maximumWidth > 0 && maximumHeight > 0);
  49733. jassert (minimumWidth > 0 && minimumHeight > 0);
  49734. minW = jmax (0, minimumWidth);
  49735. minH = jmax (0, minimumHeight);
  49736. maxW = jmax (minW, maximumWidth);
  49737. maxH = jmax (minH, maximumHeight);
  49738. }
  49739. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49740. const int minimumWhenOffTheLeft,
  49741. const int minimumWhenOffTheBottom,
  49742. const int minimumWhenOffTheRight) throw()
  49743. {
  49744. minOffTop = minimumWhenOffTheTop;
  49745. minOffLeft = minimumWhenOffTheLeft;
  49746. minOffBottom = minimumWhenOffTheBottom;
  49747. minOffRight = minimumWhenOffTheRight;
  49748. }
  49749. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49750. {
  49751. aspectRatio = jmax (0.0, widthOverHeight);
  49752. }
  49753. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49754. {
  49755. return aspectRatio;
  49756. }
  49757. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49758. const Rectangle<int>& targetBounds,
  49759. const bool isStretchingTop,
  49760. const bool isStretchingLeft,
  49761. const bool isStretchingBottom,
  49762. const bool isStretchingRight)
  49763. {
  49764. jassert (component != 0);
  49765. Rectangle<int> limits, bounds (targetBounds);
  49766. BorderSize border;
  49767. Component* const parent = component->getParentComponent();
  49768. if (parent == 0)
  49769. {
  49770. ComponentPeer* peer = component->getPeer();
  49771. if (peer != 0)
  49772. border = peer->getFrameSize();
  49773. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49774. }
  49775. else
  49776. {
  49777. limits.setSize (parent->getWidth(), parent->getHeight());
  49778. }
  49779. border.addTo (bounds);
  49780. checkBounds (bounds,
  49781. border.addedTo (component->getBounds()), limits,
  49782. isStretchingTop, isStretchingLeft,
  49783. isStretchingBottom, isStretchingRight);
  49784. border.subtractFrom (bounds);
  49785. applyBoundsToComponent (component, bounds);
  49786. }
  49787. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49788. {
  49789. setBoundsForComponent (component, component->getBounds(),
  49790. false, false, false, false);
  49791. }
  49792. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49793. const Rectangle<int>& bounds)
  49794. {
  49795. component->setBounds (bounds);
  49796. }
  49797. void ComponentBoundsConstrainer::resizeStart()
  49798. {
  49799. }
  49800. void ComponentBoundsConstrainer::resizeEnd()
  49801. {
  49802. }
  49803. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49804. const Rectangle<int>& old,
  49805. const Rectangle<int>& limits,
  49806. const bool isStretchingTop,
  49807. const bool isStretchingLeft,
  49808. const bool isStretchingBottom,
  49809. const bool isStretchingRight)
  49810. {
  49811. int x = bounds.getX();
  49812. int y = bounds.getY();
  49813. int w = bounds.getWidth();
  49814. int h = bounds.getHeight();
  49815. // constrain the size if it's being stretched..
  49816. if (isStretchingLeft)
  49817. {
  49818. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49819. w = old.getRight() - x;
  49820. }
  49821. if (isStretchingRight)
  49822. {
  49823. w = jlimit (minW, maxW, w);
  49824. }
  49825. if (isStretchingTop)
  49826. {
  49827. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49828. h = old.getBottom() - y;
  49829. }
  49830. if (isStretchingBottom)
  49831. {
  49832. h = jlimit (minH, maxH, h);
  49833. }
  49834. // constrain the aspect ratio if one has been specified..
  49835. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49836. {
  49837. bool adjustWidth;
  49838. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49839. {
  49840. adjustWidth = true;
  49841. }
  49842. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49843. {
  49844. adjustWidth = false;
  49845. }
  49846. else
  49847. {
  49848. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49849. const double newRatio = std::abs (w / (double) h);
  49850. adjustWidth = (oldRatio > newRatio);
  49851. }
  49852. if (adjustWidth)
  49853. {
  49854. w = roundToInt (h * aspectRatio);
  49855. if (w > maxW || w < minW)
  49856. {
  49857. w = jlimit (minW, maxW, w);
  49858. h = roundToInt (w / aspectRatio);
  49859. }
  49860. }
  49861. else
  49862. {
  49863. h = roundToInt (w / aspectRatio);
  49864. if (h > maxH || h < minH)
  49865. {
  49866. h = jlimit (minH, maxH, h);
  49867. w = roundToInt (h * aspectRatio);
  49868. }
  49869. }
  49870. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49871. {
  49872. x = old.getX() + (old.getWidth() - w) / 2;
  49873. }
  49874. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49875. {
  49876. y = old.getY() + (old.getHeight() - h) / 2;
  49877. }
  49878. else
  49879. {
  49880. if (isStretchingLeft)
  49881. x = old.getRight() - w;
  49882. if (isStretchingTop)
  49883. y = old.getBottom() - h;
  49884. }
  49885. }
  49886. // ...and constrain the position if limits have been set for that.
  49887. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49888. {
  49889. if (minOffTop > 0)
  49890. {
  49891. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49892. if (y < limit)
  49893. {
  49894. if (isStretchingTop)
  49895. h -= (limit - y);
  49896. y = limit;
  49897. }
  49898. }
  49899. if (minOffLeft > 0)
  49900. {
  49901. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49902. if (x < limit)
  49903. {
  49904. if (isStretchingLeft)
  49905. w -= (limit - x);
  49906. x = limit;
  49907. }
  49908. }
  49909. if (minOffBottom > 0)
  49910. {
  49911. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49912. if (y > limit)
  49913. {
  49914. if (isStretchingBottom)
  49915. h += (limit - y);
  49916. else
  49917. y = limit;
  49918. }
  49919. }
  49920. if (minOffRight > 0)
  49921. {
  49922. const int limit = limits.getRight() - jmin (minOffRight, w);
  49923. if (x > limit)
  49924. {
  49925. if (isStretchingRight)
  49926. w += (limit - x);
  49927. else
  49928. x = limit;
  49929. }
  49930. }
  49931. }
  49932. jassert (w >= 0 && h >= 0);
  49933. bounds = Rectangle<int> (x, y, w, h);
  49934. }
  49935. END_JUCE_NAMESPACE
  49936. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49937. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49938. BEGIN_JUCE_NAMESPACE
  49939. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49940. : component (component_),
  49941. lastPeer (0),
  49942. reentrant (false)
  49943. {
  49944. jassert (component != 0); // can't use this with a null pointer..
  49945. component->addComponentListener (this);
  49946. registerWithParentComps();
  49947. }
  49948. ComponentMovementWatcher::~ComponentMovementWatcher()
  49949. {
  49950. component->removeComponentListener (this);
  49951. unregister();
  49952. }
  49953. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49954. {
  49955. // agh! don't delete the target component without deleting this object first!
  49956. jassert (component != 0);
  49957. if (! reentrant)
  49958. {
  49959. reentrant = true;
  49960. ComponentPeer* const peer = component->getPeer();
  49961. if (peer != lastPeer)
  49962. {
  49963. componentPeerChanged();
  49964. if (component == 0)
  49965. return;
  49966. lastPeer = peer;
  49967. }
  49968. unregister();
  49969. registerWithParentComps();
  49970. reentrant = false;
  49971. componentMovedOrResized (*component, true, true);
  49972. }
  49973. }
  49974. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49975. {
  49976. // agh! don't delete the target component without deleting this object first!
  49977. jassert (component != 0);
  49978. if (wasMoved)
  49979. {
  49980. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49981. wasMoved = lastBounds.getPosition() != pos;
  49982. lastBounds.setPosition (pos);
  49983. }
  49984. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49985. lastBounds.setSize (component->getWidth(), component->getHeight());
  49986. if (wasMoved || wasResized)
  49987. componentMovedOrResized (wasMoved, wasResized);
  49988. }
  49989. void ComponentMovementWatcher::registerWithParentComps()
  49990. {
  49991. Component* p = component->getParentComponent();
  49992. while (p != 0)
  49993. {
  49994. p->addComponentListener (this);
  49995. registeredParentComps.add (p);
  49996. p = p->getParentComponent();
  49997. }
  49998. }
  49999. void ComponentMovementWatcher::unregister()
  50000. {
  50001. for (int i = registeredParentComps.size(); --i >= 0;)
  50002. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  50003. registeredParentComps.clear();
  50004. }
  50005. END_JUCE_NAMESPACE
  50006. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50007. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  50008. BEGIN_JUCE_NAMESPACE
  50009. GroupComponent::GroupComponent (const String& componentName,
  50010. const String& labelText)
  50011. : Component (componentName),
  50012. text (labelText),
  50013. justification (Justification::left)
  50014. {
  50015. setInterceptsMouseClicks (false, true);
  50016. }
  50017. GroupComponent::~GroupComponent()
  50018. {
  50019. }
  50020. void GroupComponent::setText (const String& newText)
  50021. {
  50022. if (text != newText)
  50023. {
  50024. text = newText;
  50025. repaint();
  50026. }
  50027. }
  50028. const String GroupComponent::getText() const
  50029. {
  50030. return text;
  50031. }
  50032. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  50033. {
  50034. if (justification != newJustification)
  50035. {
  50036. justification = newJustification;
  50037. repaint();
  50038. }
  50039. }
  50040. void GroupComponent::paint (Graphics& g)
  50041. {
  50042. getLookAndFeel()
  50043. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  50044. text, justification,
  50045. *this);
  50046. }
  50047. void GroupComponent::enablementChanged()
  50048. {
  50049. repaint();
  50050. }
  50051. void GroupComponent::colourChanged()
  50052. {
  50053. repaint();
  50054. }
  50055. END_JUCE_NAMESPACE
  50056. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50057. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50058. BEGIN_JUCE_NAMESPACE
  50059. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50060. : DocumentWindow (String::empty, backgroundColour,
  50061. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50062. {
  50063. }
  50064. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50065. {
  50066. }
  50067. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50068. {
  50069. MultiDocumentPanel* const owner = getOwner();
  50070. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50071. if (owner != 0)
  50072. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50073. }
  50074. void MultiDocumentPanelWindow::closeButtonPressed()
  50075. {
  50076. MultiDocumentPanel* const owner = getOwner();
  50077. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50078. if (owner != 0)
  50079. owner->closeDocument (getContentComponent(), true);
  50080. }
  50081. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50082. {
  50083. DocumentWindow::activeWindowStatusChanged();
  50084. updateOrder();
  50085. }
  50086. void MultiDocumentPanelWindow::broughtToFront()
  50087. {
  50088. DocumentWindow::broughtToFront();
  50089. updateOrder();
  50090. }
  50091. void MultiDocumentPanelWindow::updateOrder()
  50092. {
  50093. MultiDocumentPanel* const owner = getOwner();
  50094. if (owner != 0)
  50095. owner->updateOrder();
  50096. }
  50097. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50098. {
  50099. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50100. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50101. }
  50102. class MDITabbedComponentInternal : public TabbedComponent
  50103. {
  50104. public:
  50105. MDITabbedComponentInternal()
  50106. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50107. {
  50108. }
  50109. ~MDITabbedComponentInternal()
  50110. {
  50111. }
  50112. void currentTabChanged (int, const String&)
  50113. {
  50114. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50115. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50116. if (owner != 0)
  50117. owner->updateOrder();
  50118. }
  50119. };
  50120. MultiDocumentPanel::MultiDocumentPanel()
  50121. : mode (MaximisedWindowsWithTabs),
  50122. backgroundColour (Colours::lightblue),
  50123. maximumNumDocuments (0),
  50124. numDocsBeforeTabsUsed (0)
  50125. {
  50126. setOpaque (true);
  50127. }
  50128. MultiDocumentPanel::~MultiDocumentPanel()
  50129. {
  50130. closeAllDocuments (false);
  50131. }
  50132. static bool shouldDeleteComp (Component* const c)
  50133. {
  50134. return c->getProperties() ["mdiDocumentDelete_"];
  50135. }
  50136. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50137. {
  50138. while (components.size() > 0)
  50139. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50140. return false;
  50141. return true;
  50142. }
  50143. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50144. {
  50145. return new MultiDocumentPanelWindow (backgroundColour);
  50146. }
  50147. void MultiDocumentPanel::addWindow (Component* component)
  50148. {
  50149. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50150. dw->setResizable (true, false);
  50151. dw->setContentComponent (component, false, true);
  50152. dw->setName (component->getName());
  50153. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50154. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50155. int x = 4;
  50156. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50157. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50158. x += 16;
  50159. dw->setTopLeftPosition (x, x);
  50160. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50161. if (pos.toString().isNotEmpty())
  50162. dw->restoreWindowStateFromString (pos.toString());
  50163. addAndMakeVisible (dw);
  50164. dw->toFront (true);
  50165. }
  50166. bool MultiDocumentPanel::addDocument (Component* const component,
  50167. const Colour& docColour,
  50168. const bool deleteWhenRemoved)
  50169. {
  50170. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50171. // with a frame-within-a-frame! Just pass in the bare content component.
  50172. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50173. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50174. return false;
  50175. components.add (component);
  50176. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50177. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50178. component->addComponentListener (this);
  50179. if (mode == FloatingWindows)
  50180. {
  50181. if (isFullscreenWhenOneDocument())
  50182. {
  50183. if (components.size() == 1)
  50184. {
  50185. addAndMakeVisible (component);
  50186. }
  50187. else
  50188. {
  50189. if (components.size() == 2)
  50190. addWindow (components.getFirst());
  50191. addWindow (component);
  50192. }
  50193. }
  50194. else
  50195. {
  50196. addWindow (component);
  50197. }
  50198. }
  50199. else
  50200. {
  50201. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50202. {
  50203. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50204. Array <Component*> temp (components);
  50205. for (int i = 0; i < temp.size(); ++i)
  50206. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50207. resized();
  50208. }
  50209. else
  50210. {
  50211. if (tabComponent != 0)
  50212. tabComponent->addTab (component->getName(), docColour, component, false);
  50213. else
  50214. addAndMakeVisible (component);
  50215. }
  50216. setActiveDocument (component);
  50217. }
  50218. resized();
  50219. activeDocumentChanged();
  50220. return true;
  50221. }
  50222. bool MultiDocumentPanel::closeDocument (Component* component,
  50223. const bool checkItsOkToCloseFirst)
  50224. {
  50225. if (components.contains (component))
  50226. {
  50227. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50228. return false;
  50229. component->removeComponentListener (this);
  50230. const bool shouldDelete = shouldDeleteComp (component);
  50231. component->getProperties().remove ("mdiDocumentDelete_");
  50232. component->getProperties().remove ("mdiDocumentBkg_");
  50233. if (mode == FloatingWindows)
  50234. {
  50235. for (int i = getNumChildComponents(); --i >= 0;)
  50236. {
  50237. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50238. if (dw != 0 && dw->getContentComponent() == component)
  50239. {
  50240. dw->setContentComponent (0, false);
  50241. delete dw;
  50242. break;
  50243. }
  50244. }
  50245. if (shouldDelete)
  50246. delete component;
  50247. components.removeValue (component);
  50248. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50249. {
  50250. for (int i = getNumChildComponents(); --i >= 0;)
  50251. {
  50252. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50253. if (dw != 0)
  50254. {
  50255. dw->setContentComponent (0, false);
  50256. delete dw;
  50257. }
  50258. }
  50259. addAndMakeVisible (components.getFirst());
  50260. }
  50261. }
  50262. else
  50263. {
  50264. jassert (components.indexOf (component) >= 0);
  50265. if (tabComponent != 0)
  50266. {
  50267. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50268. if (tabComponent->getTabContentComponent (i) == component)
  50269. tabComponent->removeTab (i);
  50270. }
  50271. else
  50272. {
  50273. removeChildComponent (component);
  50274. }
  50275. if (shouldDelete)
  50276. delete component;
  50277. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50278. tabComponent = 0;
  50279. components.removeValue (component);
  50280. if (components.size() > 0 && tabComponent == 0)
  50281. addAndMakeVisible (components.getFirst());
  50282. }
  50283. resized();
  50284. activeDocumentChanged();
  50285. }
  50286. else
  50287. {
  50288. jassertfalse;
  50289. }
  50290. return true;
  50291. }
  50292. int MultiDocumentPanel::getNumDocuments() const throw()
  50293. {
  50294. return components.size();
  50295. }
  50296. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50297. {
  50298. return components [index];
  50299. }
  50300. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50301. {
  50302. if (mode == FloatingWindows)
  50303. {
  50304. for (int i = getNumChildComponents(); --i >= 0;)
  50305. {
  50306. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50307. if (dw != 0 && dw->isActiveWindow())
  50308. return dw->getContentComponent();
  50309. }
  50310. }
  50311. return components.getLast();
  50312. }
  50313. void MultiDocumentPanel::setActiveDocument (Component* component)
  50314. {
  50315. if (mode == FloatingWindows)
  50316. {
  50317. component = getContainerComp (component);
  50318. if (component != 0)
  50319. component->toFront (true);
  50320. }
  50321. else if (tabComponent != 0)
  50322. {
  50323. jassert (components.indexOf (component) >= 0);
  50324. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50325. {
  50326. if (tabComponent->getTabContentComponent (i) == component)
  50327. {
  50328. tabComponent->setCurrentTabIndex (i);
  50329. break;
  50330. }
  50331. }
  50332. }
  50333. else
  50334. {
  50335. component->grabKeyboardFocus();
  50336. }
  50337. }
  50338. void MultiDocumentPanel::activeDocumentChanged()
  50339. {
  50340. }
  50341. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50342. {
  50343. maximumNumDocuments = newNumber;
  50344. }
  50345. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50346. {
  50347. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50348. }
  50349. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50350. {
  50351. return numDocsBeforeTabsUsed != 0;
  50352. }
  50353. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50354. {
  50355. if (mode != newLayoutMode)
  50356. {
  50357. mode = newLayoutMode;
  50358. if (mode == FloatingWindows)
  50359. {
  50360. tabComponent = 0;
  50361. }
  50362. else
  50363. {
  50364. for (int i = getNumChildComponents(); --i >= 0;)
  50365. {
  50366. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50367. if (dw != 0)
  50368. {
  50369. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50370. dw->setContentComponent (0, false);
  50371. delete dw;
  50372. }
  50373. }
  50374. }
  50375. resized();
  50376. const Array <Component*> tempComps (components);
  50377. components.clear();
  50378. for (int i = 0; i < tempComps.size(); ++i)
  50379. {
  50380. Component* const c = tempComps.getUnchecked(i);
  50381. addDocument (c,
  50382. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50383. shouldDeleteComp (c));
  50384. }
  50385. }
  50386. }
  50387. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50388. {
  50389. if (backgroundColour != newBackgroundColour)
  50390. {
  50391. backgroundColour = newBackgroundColour;
  50392. setOpaque (newBackgroundColour.isOpaque());
  50393. repaint();
  50394. }
  50395. }
  50396. void MultiDocumentPanel::paint (Graphics& g)
  50397. {
  50398. g.fillAll (backgroundColour);
  50399. }
  50400. void MultiDocumentPanel::resized()
  50401. {
  50402. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50403. {
  50404. for (int i = getNumChildComponents(); --i >= 0;)
  50405. getChildComponent (i)->setBounds (getLocalBounds());
  50406. }
  50407. setWantsKeyboardFocus (components.size() == 0);
  50408. }
  50409. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50410. {
  50411. if (mode == FloatingWindows)
  50412. {
  50413. for (int i = 0; i < getNumChildComponents(); ++i)
  50414. {
  50415. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50416. if (dw != 0 && dw->getContentComponent() == c)
  50417. {
  50418. c = dw;
  50419. break;
  50420. }
  50421. }
  50422. }
  50423. return c;
  50424. }
  50425. void MultiDocumentPanel::componentNameChanged (Component&)
  50426. {
  50427. if (mode == FloatingWindows)
  50428. {
  50429. for (int i = 0; i < getNumChildComponents(); ++i)
  50430. {
  50431. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50432. if (dw != 0)
  50433. dw->setName (dw->getContentComponent()->getName());
  50434. }
  50435. }
  50436. else if (tabComponent != 0)
  50437. {
  50438. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50439. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50440. }
  50441. }
  50442. void MultiDocumentPanel::updateOrder()
  50443. {
  50444. const Array <Component*> oldList (components);
  50445. if (mode == FloatingWindows)
  50446. {
  50447. components.clear();
  50448. for (int i = 0; i < getNumChildComponents(); ++i)
  50449. {
  50450. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50451. if (dw != 0)
  50452. components.add (dw->getContentComponent());
  50453. }
  50454. }
  50455. else
  50456. {
  50457. if (tabComponent != 0)
  50458. {
  50459. Component* const current = tabComponent->getCurrentContentComponent();
  50460. if (current != 0)
  50461. {
  50462. components.removeValue (current);
  50463. components.add (current);
  50464. }
  50465. }
  50466. }
  50467. if (components != oldList)
  50468. activeDocumentChanged();
  50469. }
  50470. END_JUCE_NAMESPACE
  50471. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50472. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50473. BEGIN_JUCE_NAMESPACE
  50474. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50475. : zone (zoneFlags)
  50476. {
  50477. }
  50478. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50479. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50480. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50481. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50482. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50483. const BorderSize& border,
  50484. const Point<int>& position)
  50485. {
  50486. int z = 0;
  50487. if (totalSize.contains (position)
  50488. && ! border.subtractedFrom (totalSize).contains (position))
  50489. {
  50490. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50491. if (position.getX() < jmax (border.getLeft(), minW))
  50492. z |= left;
  50493. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50494. z |= right;
  50495. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50496. if (position.getY() < jmax (border.getTop(), minH))
  50497. z |= top;
  50498. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50499. z |= bottom;
  50500. }
  50501. return Zone (z);
  50502. }
  50503. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50504. {
  50505. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50506. switch (zone)
  50507. {
  50508. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50509. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50510. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50511. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50512. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50513. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50514. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50515. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50516. default: break;
  50517. }
  50518. return mc;
  50519. }
  50520. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50521. {
  50522. if (isDraggingWholeObject())
  50523. return b + offset;
  50524. if (isDraggingLeftEdge())
  50525. b.setLeft (b.getX() + offset.getX());
  50526. if (isDraggingRightEdge())
  50527. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50528. if (isDraggingTopEdge())
  50529. b.setTop (b.getY() + offset.getY());
  50530. if (isDraggingBottomEdge())
  50531. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50532. return b;
  50533. }
  50534. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50535. {
  50536. if (isDraggingWholeObject())
  50537. return b + offset;
  50538. if (isDraggingLeftEdge())
  50539. b.setLeft (b.getX() + offset.getX());
  50540. if (isDraggingRightEdge())
  50541. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50542. if (isDraggingTopEdge())
  50543. b.setTop (b.getY() + offset.getY());
  50544. if (isDraggingBottomEdge())
  50545. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50546. return b;
  50547. }
  50548. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50549. ComponentBoundsConstrainer* const constrainer_)
  50550. : component (componentToResize),
  50551. constrainer (constrainer_),
  50552. borderSize (5),
  50553. mouseZone (0)
  50554. {
  50555. }
  50556. ResizableBorderComponent::~ResizableBorderComponent()
  50557. {
  50558. }
  50559. void ResizableBorderComponent::paint (Graphics& g)
  50560. {
  50561. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50562. }
  50563. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50564. {
  50565. updateMouseZone (e);
  50566. }
  50567. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50568. {
  50569. updateMouseZone (e);
  50570. }
  50571. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50572. {
  50573. if (component == 0)
  50574. {
  50575. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50576. return;
  50577. }
  50578. updateMouseZone (e);
  50579. originalBounds = component->getBounds();
  50580. if (constrainer != 0)
  50581. constrainer->resizeStart();
  50582. }
  50583. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50584. {
  50585. if (component == 0)
  50586. {
  50587. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50588. return;
  50589. }
  50590. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50591. if (constrainer != 0)
  50592. constrainer->setBoundsForComponent (component, bounds,
  50593. mouseZone.isDraggingTopEdge(),
  50594. mouseZone.isDraggingLeftEdge(),
  50595. mouseZone.isDraggingBottomEdge(),
  50596. mouseZone.isDraggingRightEdge());
  50597. else
  50598. component->setBounds (bounds);
  50599. }
  50600. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50601. {
  50602. if (constrainer != 0)
  50603. constrainer->resizeEnd();
  50604. }
  50605. bool ResizableBorderComponent::hitTest (int x, int y)
  50606. {
  50607. return x < borderSize.getLeft()
  50608. || x >= getWidth() - borderSize.getRight()
  50609. || y < borderSize.getTop()
  50610. || y >= getHeight() - borderSize.getBottom();
  50611. }
  50612. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50613. {
  50614. if (borderSize != newBorderSize)
  50615. {
  50616. borderSize = newBorderSize;
  50617. repaint();
  50618. }
  50619. }
  50620. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50621. {
  50622. return borderSize;
  50623. }
  50624. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50625. {
  50626. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50627. if (mouseZone != newZone)
  50628. {
  50629. mouseZone = newZone;
  50630. setMouseCursor (newZone.getMouseCursor());
  50631. }
  50632. }
  50633. END_JUCE_NAMESPACE
  50634. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50635. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50636. BEGIN_JUCE_NAMESPACE
  50637. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50638. ComponentBoundsConstrainer* const constrainer_)
  50639. : component (componentToResize),
  50640. constrainer (constrainer_)
  50641. {
  50642. setRepaintsOnMouseActivity (true);
  50643. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50644. }
  50645. ResizableCornerComponent::~ResizableCornerComponent()
  50646. {
  50647. }
  50648. void ResizableCornerComponent::paint (Graphics& g)
  50649. {
  50650. getLookAndFeel()
  50651. .drawCornerResizer (g, getWidth(), getHeight(),
  50652. isMouseOverOrDragging(),
  50653. isMouseButtonDown());
  50654. }
  50655. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50656. {
  50657. if (component == 0)
  50658. {
  50659. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50660. return;
  50661. }
  50662. originalBounds = component->getBounds();
  50663. if (constrainer != 0)
  50664. constrainer->resizeStart();
  50665. }
  50666. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50667. {
  50668. if (component == 0)
  50669. {
  50670. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50671. return;
  50672. }
  50673. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50674. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50675. if (constrainer != 0)
  50676. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50677. else
  50678. component->setBounds (r);
  50679. }
  50680. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50681. {
  50682. if (constrainer != 0)
  50683. constrainer->resizeStart();
  50684. }
  50685. bool ResizableCornerComponent::hitTest (int x, int y)
  50686. {
  50687. if (getWidth() <= 0)
  50688. return false;
  50689. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50690. return y >= yAtX - getHeight() / 4;
  50691. }
  50692. END_JUCE_NAMESPACE
  50693. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50694. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50695. BEGIN_JUCE_NAMESPACE
  50696. class ScrollBar::ScrollbarButton : public Button
  50697. {
  50698. public:
  50699. int direction;
  50700. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50701. : Button (String::empty),
  50702. direction (direction_),
  50703. owner (owner_)
  50704. {
  50705. setWantsKeyboardFocus (false);
  50706. }
  50707. ~ScrollbarButton()
  50708. {
  50709. }
  50710. void paintButton (Graphics& g, bool over, bool down)
  50711. {
  50712. getLookAndFeel()
  50713. .drawScrollbarButton (g, owner,
  50714. getWidth(), getHeight(),
  50715. direction,
  50716. owner.isVertical(),
  50717. over, down);
  50718. }
  50719. void clicked()
  50720. {
  50721. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50722. }
  50723. juce_UseDebuggingNewOperator
  50724. private:
  50725. ScrollBar& owner;
  50726. ScrollbarButton (const ScrollbarButton&);
  50727. ScrollbarButton& operator= (const ScrollbarButton&);
  50728. };
  50729. ScrollBar::ScrollBar (const bool vertical_,
  50730. const bool buttonsAreVisible)
  50731. : totalRange (0.0, 1.0),
  50732. visibleRange (0.0, 0.1),
  50733. singleStepSize (0.1),
  50734. thumbAreaStart (0),
  50735. thumbAreaSize (0),
  50736. thumbStart (0),
  50737. thumbSize (0),
  50738. initialDelayInMillisecs (100),
  50739. repeatDelayInMillisecs (50),
  50740. minimumDelayInMillisecs (10),
  50741. vertical (vertical_),
  50742. isDraggingThumb (false),
  50743. autohides (true)
  50744. {
  50745. setButtonVisibility (buttonsAreVisible);
  50746. setRepaintsOnMouseActivity (true);
  50747. setFocusContainer (true);
  50748. }
  50749. ScrollBar::~ScrollBar()
  50750. {
  50751. upButton = 0;
  50752. downButton = 0;
  50753. }
  50754. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50755. {
  50756. if (totalRange != newRangeLimit)
  50757. {
  50758. totalRange = newRangeLimit;
  50759. setCurrentRange (visibleRange);
  50760. updateThumbPosition();
  50761. }
  50762. }
  50763. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50764. {
  50765. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50766. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50767. }
  50768. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50769. {
  50770. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50771. if (visibleRange != constrainedRange)
  50772. {
  50773. visibleRange = constrainedRange;
  50774. updateThumbPosition();
  50775. triggerAsyncUpdate();
  50776. }
  50777. }
  50778. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50779. {
  50780. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50781. }
  50782. void ScrollBar::setCurrentRangeStart (const double newStart)
  50783. {
  50784. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50785. }
  50786. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50787. {
  50788. singleStepSize = newSingleStepSize;
  50789. }
  50790. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50791. {
  50792. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50793. }
  50794. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50795. {
  50796. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50797. }
  50798. void ScrollBar::scrollToTop()
  50799. {
  50800. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50801. }
  50802. void ScrollBar::scrollToBottom()
  50803. {
  50804. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50805. }
  50806. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50807. const int repeatDelayInMillisecs_,
  50808. const int minimumDelayInMillisecs_)
  50809. {
  50810. initialDelayInMillisecs = initialDelayInMillisecs_;
  50811. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50812. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50813. if (upButton != 0)
  50814. {
  50815. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50816. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50817. }
  50818. }
  50819. void ScrollBar::addListener (Listener* const listener)
  50820. {
  50821. listeners.add (listener);
  50822. }
  50823. void ScrollBar::removeListener (Listener* const listener)
  50824. {
  50825. listeners.remove (listener);
  50826. }
  50827. void ScrollBar::handleAsyncUpdate()
  50828. {
  50829. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50830. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50831. }
  50832. void ScrollBar::updateThumbPosition()
  50833. {
  50834. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50835. : thumbAreaSize);
  50836. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50837. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50838. if (newThumbSize > thumbAreaSize)
  50839. newThumbSize = thumbAreaSize;
  50840. int newThumbStart = thumbAreaStart;
  50841. if (totalRange.getLength() > visibleRange.getLength())
  50842. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50843. / (totalRange.getLength() - visibleRange.getLength()));
  50844. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50845. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50846. {
  50847. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50848. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50849. if (vertical)
  50850. repaint (0, repaintStart, getWidth(), repaintSize);
  50851. else
  50852. repaint (repaintStart, 0, repaintSize, getHeight());
  50853. thumbStart = newThumbStart;
  50854. thumbSize = newThumbSize;
  50855. }
  50856. }
  50857. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50858. {
  50859. if (vertical != shouldBeVertical)
  50860. {
  50861. vertical = shouldBeVertical;
  50862. if (upButton != 0)
  50863. {
  50864. upButton->direction = vertical ? 0 : 3;
  50865. downButton->direction = vertical ? 2 : 1;
  50866. }
  50867. updateThumbPosition();
  50868. }
  50869. }
  50870. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50871. {
  50872. upButton = 0;
  50873. downButton = 0;
  50874. if (buttonsAreVisible)
  50875. {
  50876. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50877. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50878. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50879. }
  50880. updateThumbPosition();
  50881. }
  50882. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50883. {
  50884. autohides = shouldHideWhenFullRange;
  50885. updateThumbPosition();
  50886. }
  50887. bool ScrollBar::autoHides() const throw()
  50888. {
  50889. return autohides;
  50890. }
  50891. void ScrollBar::paint (Graphics& g)
  50892. {
  50893. if (thumbAreaSize > 0)
  50894. {
  50895. LookAndFeel& lf = getLookAndFeel();
  50896. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50897. ? thumbSize : 0;
  50898. if (vertical)
  50899. {
  50900. lf.drawScrollbar (g, *this,
  50901. 0, thumbAreaStart,
  50902. getWidth(), thumbAreaSize,
  50903. vertical,
  50904. thumbStart, thumb,
  50905. isMouseOver(), isMouseButtonDown());
  50906. }
  50907. else
  50908. {
  50909. lf.drawScrollbar (g, *this,
  50910. thumbAreaStart, 0,
  50911. thumbAreaSize, getHeight(),
  50912. vertical,
  50913. thumbStart, thumb,
  50914. isMouseOver(), isMouseButtonDown());
  50915. }
  50916. }
  50917. }
  50918. void ScrollBar::lookAndFeelChanged()
  50919. {
  50920. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50921. }
  50922. void ScrollBar::resized()
  50923. {
  50924. const int length = ((vertical) ? getHeight() : getWidth());
  50925. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50926. : 0;
  50927. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50928. {
  50929. thumbAreaStart = length >> 1;
  50930. thumbAreaSize = 0;
  50931. }
  50932. else
  50933. {
  50934. thumbAreaStart = buttonSize;
  50935. thumbAreaSize = length - (buttonSize << 1);
  50936. }
  50937. if (upButton != 0)
  50938. {
  50939. if (vertical)
  50940. {
  50941. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50942. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50943. }
  50944. else
  50945. {
  50946. upButton->setBounds (0, 0, buttonSize, getHeight());
  50947. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50948. }
  50949. }
  50950. updateThumbPosition();
  50951. }
  50952. void ScrollBar::mouseDown (const MouseEvent& e)
  50953. {
  50954. isDraggingThumb = false;
  50955. lastMousePos = vertical ? e.y : e.x;
  50956. dragStartMousePos = lastMousePos;
  50957. dragStartRange = visibleRange.getStart();
  50958. if (dragStartMousePos < thumbStart)
  50959. {
  50960. moveScrollbarInPages (-1);
  50961. startTimer (400);
  50962. }
  50963. else if (dragStartMousePos >= thumbStart + thumbSize)
  50964. {
  50965. moveScrollbarInPages (1);
  50966. startTimer (400);
  50967. }
  50968. else
  50969. {
  50970. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50971. && (thumbAreaSize > thumbSize);
  50972. }
  50973. }
  50974. void ScrollBar::mouseDrag (const MouseEvent& e)
  50975. {
  50976. if (isDraggingThumb)
  50977. {
  50978. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50979. setCurrentRangeStart (dragStartRange
  50980. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50981. / (thumbAreaSize - thumbSize));
  50982. }
  50983. else
  50984. {
  50985. lastMousePos = (vertical) ? e.y : e.x;
  50986. }
  50987. }
  50988. void ScrollBar::mouseUp (const MouseEvent&)
  50989. {
  50990. isDraggingThumb = false;
  50991. stopTimer();
  50992. repaint();
  50993. }
  50994. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50995. float wheelIncrementX,
  50996. float wheelIncrementY)
  50997. {
  50998. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50999. if (increment < 0)
  51000. increment = jmin (increment * 10.0f, -1.0f);
  51001. else if (increment > 0)
  51002. increment = jmax (increment * 10.0f, 1.0f);
  51003. setCurrentRange (visibleRange - singleStepSize * increment);
  51004. }
  51005. void ScrollBar::timerCallback()
  51006. {
  51007. if (isMouseButtonDown())
  51008. {
  51009. startTimer (40);
  51010. if (lastMousePos < thumbStart)
  51011. setCurrentRange (visibleRange - visibleRange.getLength());
  51012. else if (lastMousePos > thumbStart + thumbSize)
  51013. setCurrentRangeStart (visibleRange.getEnd());
  51014. }
  51015. else
  51016. {
  51017. stopTimer();
  51018. }
  51019. }
  51020. bool ScrollBar::keyPressed (const KeyPress& key)
  51021. {
  51022. if (! isVisible())
  51023. return false;
  51024. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  51025. moveScrollbarInSteps (-1);
  51026. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  51027. moveScrollbarInSteps (1);
  51028. else if (key.isKeyCode (KeyPress::pageUpKey))
  51029. moveScrollbarInPages (-1);
  51030. else if (key.isKeyCode (KeyPress::pageDownKey))
  51031. moveScrollbarInPages (1);
  51032. else if (key.isKeyCode (KeyPress::homeKey))
  51033. scrollToTop();
  51034. else if (key.isKeyCode (KeyPress::endKey))
  51035. scrollToBottom();
  51036. else
  51037. return false;
  51038. return true;
  51039. }
  51040. END_JUCE_NAMESPACE
  51041. /*** End of inlined file: juce_ScrollBar.cpp ***/
  51042. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  51043. BEGIN_JUCE_NAMESPACE
  51044. StretchableLayoutManager::StretchableLayoutManager()
  51045. : totalSize (0)
  51046. {
  51047. }
  51048. StretchableLayoutManager::~StretchableLayoutManager()
  51049. {
  51050. }
  51051. void StretchableLayoutManager::clearAllItems()
  51052. {
  51053. items.clear();
  51054. totalSize = 0;
  51055. }
  51056. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51057. const double minimumSize,
  51058. const double maximumSize,
  51059. const double preferredSize)
  51060. {
  51061. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51062. if (layout == 0)
  51063. {
  51064. layout = new ItemLayoutProperties();
  51065. layout->itemIndex = itemIndex;
  51066. int i;
  51067. for (i = 0; i < items.size(); ++i)
  51068. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51069. break;
  51070. items.insert (i, layout);
  51071. }
  51072. layout->minSize = minimumSize;
  51073. layout->maxSize = maximumSize;
  51074. layout->preferredSize = preferredSize;
  51075. layout->currentSize = 0;
  51076. }
  51077. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51078. double& minimumSize,
  51079. double& maximumSize,
  51080. double& preferredSize) const
  51081. {
  51082. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51083. if (layout != 0)
  51084. {
  51085. minimumSize = layout->minSize;
  51086. maximumSize = layout->maxSize;
  51087. preferredSize = layout->preferredSize;
  51088. return true;
  51089. }
  51090. return false;
  51091. }
  51092. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51093. {
  51094. totalSize = newTotalSize;
  51095. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51096. }
  51097. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51098. {
  51099. int pos = 0;
  51100. for (int i = 0; i < itemIndex; ++i)
  51101. {
  51102. const ItemLayoutProperties* const layout = getInfoFor (i);
  51103. if (layout != 0)
  51104. pos += layout->currentSize;
  51105. }
  51106. return pos;
  51107. }
  51108. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51109. {
  51110. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51111. if (layout != 0)
  51112. return layout->currentSize;
  51113. return 0;
  51114. }
  51115. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51116. {
  51117. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51118. if (layout != 0)
  51119. return -layout->currentSize / (double) totalSize;
  51120. return 0;
  51121. }
  51122. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51123. int newPosition)
  51124. {
  51125. for (int i = items.size(); --i >= 0;)
  51126. {
  51127. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51128. if (layout->itemIndex == itemIndex)
  51129. {
  51130. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51131. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51132. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51133. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51134. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51135. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51136. endPos += layout->currentSize;
  51137. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51138. updatePrefSizesToMatchCurrentPositions();
  51139. break;
  51140. }
  51141. }
  51142. }
  51143. void StretchableLayoutManager::layOutComponents (Component** const components,
  51144. int numComponents,
  51145. int x, int y, int w, int h,
  51146. const bool vertically,
  51147. const bool resizeOtherDimension)
  51148. {
  51149. setTotalSize (vertically ? h : w);
  51150. int pos = vertically ? y : x;
  51151. for (int i = 0; i < numComponents; ++i)
  51152. {
  51153. const ItemLayoutProperties* const layout = getInfoFor (i);
  51154. if (layout != 0)
  51155. {
  51156. Component* const c = components[i];
  51157. if (c != 0)
  51158. {
  51159. if (i == numComponents - 1)
  51160. {
  51161. // if it's the last item, crop it to exactly fit the available space..
  51162. if (resizeOtherDimension)
  51163. {
  51164. if (vertically)
  51165. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51166. else
  51167. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51168. }
  51169. else
  51170. {
  51171. if (vertically)
  51172. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51173. else
  51174. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51175. }
  51176. }
  51177. else
  51178. {
  51179. if (resizeOtherDimension)
  51180. {
  51181. if (vertically)
  51182. c->setBounds (x, pos, w, layout->currentSize);
  51183. else
  51184. c->setBounds (pos, y, layout->currentSize, h);
  51185. }
  51186. else
  51187. {
  51188. if (vertically)
  51189. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51190. else
  51191. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51192. }
  51193. }
  51194. }
  51195. pos += layout->currentSize;
  51196. }
  51197. }
  51198. }
  51199. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51200. {
  51201. for (int i = items.size(); --i >= 0;)
  51202. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51203. return items.getUnchecked(i);
  51204. return 0;
  51205. }
  51206. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51207. const int endIndex,
  51208. const int availableSpace,
  51209. int startPos)
  51210. {
  51211. // calculate the total sizes
  51212. int i;
  51213. double totalIdealSize = 0.0;
  51214. int totalMinimums = 0;
  51215. for (i = startIndex; i < endIndex; ++i)
  51216. {
  51217. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51218. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51219. totalMinimums += layout->currentSize;
  51220. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51221. }
  51222. if (totalIdealSize <= 0)
  51223. totalIdealSize = 1.0;
  51224. // now calc the best sizes..
  51225. int extraSpace = availableSpace - totalMinimums;
  51226. while (extraSpace > 0)
  51227. {
  51228. int numWantingMoreSpace = 0;
  51229. int numHavingTakenExtraSpace = 0;
  51230. // first figure out how many comps want a slice of the extra space..
  51231. for (i = startIndex; i < endIndex; ++i)
  51232. {
  51233. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51234. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51235. const int bestSize = jlimit (layout->currentSize,
  51236. jmax (layout->currentSize,
  51237. sizeToRealSize (layout->maxSize, totalSize)),
  51238. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51239. if (bestSize > layout->currentSize)
  51240. ++numWantingMoreSpace;
  51241. }
  51242. // ..share out the extra space..
  51243. for (i = startIndex; i < endIndex; ++i)
  51244. {
  51245. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51246. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51247. int bestSize = jlimit (layout->currentSize,
  51248. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51249. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51250. const int extraWanted = bestSize - layout->currentSize;
  51251. if (extraWanted > 0)
  51252. {
  51253. const int extraAllowed = jmin (extraWanted,
  51254. extraSpace / jmax (1, numWantingMoreSpace));
  51255. if (extraAllowed > 0)
  51256. {
  51257. ++numHavingTakenExtraSpace;
  51258. --numWantingMoreSpace;
  51259. layout->currentSize += extraAllowed;
  51260. extraSpace -= extraAllowed;
  51261. }
  51262. }
  51263. }
  51264. if (numHavingTakenExtraSpace <= 0)
  51265. break;
  51266. }
  51267. // ..and calculate the end position
  51268. for (i = startIndex; i < endIndex; ++i)
  51269. {
  51270. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51271. startPos += layout->currentSize;
  51272. }
  51273. return startPos;
  51274. }
  51275. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51276. const int endIndex) const
  51277. {
  51278. int totalMinimums = 0;
  51279. for (int i = startIndex; i < endIndex; ++i)
  51280. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51281. return totalMinimums;
  51282. }
  51283. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51284. {
  51285. int totalMaximums = 0;
  51286. for (int i = startIndex; i < endIndex; ++i)
  51287. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51288. return totalMaximums;
  51289. }
  51290. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51291. {
  51292. for (int i = 0; i < items.size(); ++i)
  51293. {
  51294. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51295. layout->preferredSize
  51296. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51297. : getItemCurrentAbsoluteSize (i);
  51298. }
  51299. }
  51300. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51301. {
  51302. if (size < 0)
  51303. size *= -totalSpace;
  51304. return roundToInt (size);
  51305. }
  51306. END_JUCE_NAMESPACE
  51307. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51308. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51309. BEGIN_JUCE_NAMESPACE
  51310. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51311. const int itemIndex_,
  51312. const bool isVertical_)
  51313. : layout (layout_),
  51314. itemIndex (itemIndex_),
  51315. isVertical (isVertical_)
  51316. {
  51317. setRepaintsOnMouseActivity (true);
  51318. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51319. : MouseCursor::UpDownResizeCursor));
  51320. }
  51321. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51322. {
  51323. }
  51324. void StretchableLayoutResizerBar::paint (Graphics& g)
  51325. {
  51326. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51327. getWidth(), getHeight(),
  51328. isVertical,
  51329. isMouseOver(),
  51330. isMouseButtonDown());
  51331. }
  51332. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51333. {
  51334. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51335. }
  51336. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51337. {
  51338. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51339. : e.getDistanceFromDragStartY());
  51340. layout->setItemPosition (itemIndex, desiredPos);
  51341. hasBeenMoved();
  51342. }
  51343. void StretchableLayoutResizerBar::hasBeenMoved()
  51344. {
  51345. if (getParentComponent() != 0)
  51346. getParentComponent()->resized();
  51347. }
  51348. END_JUCE_NAMESPACE
  51349. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51350. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51351. BEGIN_JUCE_NAMESPACE
  51352. StretchableObjectResizer::StretchableObjectResizer()
  51353. {
  51354. }
  51355. StretchableObjectResizer::~StretchableObjectResizer()
  51356. {
  51357. }
  51358. void StretchableObjectResizer::addItem (const double size,
  51359. const double minSize, const double maxSize,
  51360. const int order)
  51361. {
  51362. // the order must be >= 0 but less than the maximum integer value.
  51363. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51364. Item* const item = new Item();
  51365. item->size = size;
  51366. item->minSize = minSize;
  51367. item->maxSize = maxSize;
  51368. item->order = order;
  51369. items.add (item);
  51370. }
  51371. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51372. {
  51373. const Item* const it = items [index];
  51374. return it != 0 ? it->size : 0;
  51375. }
  51376. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51377. {
  51378. int order = 0;
  51379. for (;;)
  51380. {
  51381. double currentSize = 0;
  51382. double minSize = 0;
  51383. double maxSize = 0;
  51384. int nextHighestOrder = std::numeric_limits<int>::max();
  51385. for (int i = 0; i < items.size(); ++i)
  51386. {
  51387. const Item* const it = items.getUnchecked(i);
  51388. currentSize += it->size;
  51389. if (it->order <= order)
  51390. {
  51391. minSize += it->minSize;
  51392. maxSize += it->maxSize;
  51393. }
  51394. else
  51395. {
  51396. minSize += it->size;
  51397. maxSize += it->size;
  51398. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51399. }
  51400. }
  51401. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51402. if (thisIterationTarget >= currentSize)
  51403. {
  51404. const double availableExtraSpace = maxSize - currentSize;
  51405. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51406. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51407. for (int i = 0; i < items.size(); ++i)
  51408. {
  51409. Item* const it = items.getUnchecked(i);
  51410. if (it->order <= order)
  51411. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51412. }
  51413. }
  51414. else
  51415. {
  51416. const double amountOfSlack = currentSize - minSize;
  51417. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51418. const double scale = targetAmountOfSlack / amountOfSlack;
  51419. for (int i = 0; i < items.size(); ++i)
  51420. {
  51421. Item* const it = items.getUnchecked(i);
  51422. if (it->order <= order)
  51423. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51424. }
  51425. }
  51426. if (nextHighestOrder < std::numeric_limits<int>::max())
  51427. order = nextHighestOrder;
  51428. else
  51429. break;
  51430. }
  51431. }
  51432. END_JUCE_NAMESPACE
  51433. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51434. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51435. BEGIN_JUCE_NAMESPACE
  51436. TabBarButton::TabBarButton (const String& name,
  51437. TabbedButtonBar* const owner_,
  51438. const int index)
  51439. : Button (name),
  51440. owner (owner_),
  51441. tabIndex (index),
  51442. overlapPixels (0)
  51443. {
  51444. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51445. setComponentEffect (&shadow);
  51446. setWantsKeyboardFocus (false);
  51447. }
  51448. TabBarButton::~TabBarButton()
  51449. {
  51450. }
  51451. void TabBarButton::paintButton (Graphics& g,
  51452. bool isMouseOverButton,
  51453. bool isButtonDown)
  51454. {
  51455. int x, y, w, h;
  51456. getActiveArea (x, y, w, h);
  51457. g.setOrigin (x, y);
  51458. getLookAndFeel()
  51459. .drawTabButton (g, w, h,
  51460. owner->getTabBackgroundColour (tabIndex),
  51461. tabIndex, getButtonText(), *this,
  51462. owner->getOrientation(),
  51463. isMouseOverButton, isButtonDown,
  51464. getToggleState());
  51465. }
  51466. void TabBarButton::clicked (const ModifierKeys& mods)
  51467. {
  51468. if (mods.isPopupMenu())
  51469. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51470. else
  51471. owner->setCurrentTabIndex (tabIndex);
  51472. }
  51473. bool TabBarButton::hitTest (int mx, int my)
  51474. {
  51475. int x, y, w, h;
  51476. getActiveArea (x, y, w, h);
  51477. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51478. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51479. {
  51480. if (((unsigned int) mx) < (unsigned int) getWidth()
  51481. && my >= y + overlapPixels
  51482. && my < y + h - overlapPixels)
  51483. return true;
  51484. }
  51485. else
  51486. {
  51487. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51488. && ((unsigned int) my) < (unsigned int) getHeight())
  51489. return true;
  51490. }
  51491. Path p;
  51492. getLookAndFeel()
  51493. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51494. owner->getOrientation(),
  51495. false, false, getToggleState());
  51496. return p.contains ((float) (mx - x),
  51497. (float) (my - y));
  51498. }
  51499. int TabBarButton::getBestTabLength (const int depth)
  51500. {
  51501. return jlimit (depth * 2,
  51502. depth * 7,
  51503. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51504. }
  51505. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51506. {
  51507. x = 0;
  51508. y = 0;
  51509. int r = getWidth();
  51510. int b = getHeight();
  51511. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51512. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51513. r -= spaceAroundImage;
  51514. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51515. x += spaceAroundImage;
  51516. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51517. y += spaceAroundImage;
  51518. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51519. b -= spaceAroundImage;
  51520. w = r - x;
  51521. h = b - y;
  51522. }
  51523. class TabAreaBehindFrontButtonComponent : public Component
  51524. {
  51525. public:
  51526. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51527. : owner (owner_)
  51528. {
  51529. setInterceptsMouseClicks (false, false);
  51530. }
  51531. ~TabAreaBehindFrontButtonComponent()
  51532. {
  51533. }
  51534. void paint (Graphics& g)
  51535. {
  51536. getLookAndFeel()
  51537. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51538. *owner, owner->getOrientation());
  51539. }
  51540. void enablementChanged()
  51541. {
  51542. repaint();
  51543. }
  51544. private:
  51545. TabbedButtonBar* const owner;
  51546. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51547. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51548. };
  51549. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51550. : orientation (orientation_),
  51551. currentTabIndex (-1)
  51552. {
  51553. setInterceptsMouseClicks (false, true);
  51554. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51555. setFocusContainer (true);
  51556. }
  51557. TabbedButtonBar::~TabbedButtonBar()
  51558. {
  51559. extraTabsButton = 0;
  51560. deleteAllChildren();
  51561. }
  51562. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51563. {
  51564. orientation = newOrientation;
  51565. for (int i = getNumChildComponents(); --i >= 0;)
  51566. getChildComponent (i)->resized();
  51567. resized();
  51568. }
  51569. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51570. {
  51571. return new TabBarButton (name, this, index);
  51572. }
  51573. void TabbedButtonBar::clearTabs()
  51574. {
  51575. tabs.clear();
  51576. tabColours.clear();
  51577. currentTabIndex = -1;
  51578. extraTabsButton = 0;
  51579. removeChildComponent (behindFrontTab);
  51580. deleteAllChildren();
  51581. addChildComponent (behindFrontTab);
  51582. setCurrentTabIndex (-1);
  51583. }
  51584. void TabbedButtonBar::addTab (const String& tabName,
  51585. const Colour& tabBackgroundColour,
  51586. int insertIndex)
  51587. {
  51588. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51589. if (tabName.isNotEmpty())
  51590. {
  51591. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51592. insertIndex = tabs.size();
  51593. for (int i = tabs.size(); --i >= insertIndex;)
  51594. {
  51595. TabBarButton* const tb = getTabButton (i);
  51596. if (tb != 0)
  51597. tb->tabIndex++;
  51598. }
  51599. tabs.insert (insertIndex, tabName);
  51600. tabColours.insert (insertIndex, tabBackgroundColour);
  51601. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51602. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51603. addAndMakeVisible (tb, insertIndex);
  51604. resized();
  51605. if (currentTabIndex < 0)
  51606. setCurrentTabIndex (0);
  51607. }
  51608. }
  51609. void TabbedButtonBar::setTabName (const int tabIndex,
  51610. const String& newName)
  51611. {
  51612. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51613. && tabs[tabIndex] != newName)
  51614. {
  51615. tabs.set (tabIndex, newName);
  51616. TabBarButton* const tb = getTabButton (tabIndex);
  51617. if (tb != 0)
  51618. tb->setButtonText (newName);
  51619. resized();
  51620. }
  51621. }
  51622. void TabbedButtonBar::removeTab (const int tabIndex)
  51623. {
  51624. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51625. {
  51626. const int oldTabIndex = currentTabIndex;
  51627. if (currentTabIndex == tabIndex)
  51628. currentTabIndex = -1;
  51629. tabs.remove (tabIndex);
  51630. tabColours.remove (tabIndex);
  51631. delete getTabButton (tabIndex);
  51632. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51633. {
  51634. TabBarButton* const tb = getTabButton (i);
  51635. if (tb != 0)
  51636. tb->tabIndex--;
  51637. }
  51638. resized();
  51639. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51640. }
  51641. }
  51642. void TabbedButtonBar::moveTab (const int currentIndex,
  51643. const int newIndex)
  51644. {
  51645. tabs.move (currentIndex, newIndex);
  51646. tabColours.move (currentIndex, newIndex);
  51647. resized();
  51648. }
  51649. int TabbedButtonBar::getNumTabs() const
  51650. {
  51651. return tabs.size();
  51652. }
  51653. const StringArray TabbedButtonBar::getTabNames() const
  51654. {
  51655. return tabs;
  51656. }
  51657. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51658. {
  51659. if (currentTabIndex != newIndex)
  51660. {
  51661. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51662. newIndex = -1;
  51663. currentTabIndex = newIndex;
  51664. for (int i = 0; i < getNumChildComponents(); ++i)
  51665. {
  51666. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51667. if (tb != 0)
  51668. tb->setToggleState (tb->tabIndex == newIndex, false);
  51669. }
  51670. resized();
  51671. if (sendChangeMessage_)
  51672. sendChangeMessage (this);
  51673. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51674. }
  51675. }
  51676. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51677. {
  51678. for (int i = getNumChildComponents(); --i >= 0;)
  51679. {
  51680. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51681. if (tb != 0 && tb->tabIndex == index)
  51682. return tb;
  51683. }
  51684. return 0;
  51685. }
  51686. void TabbedButtonBar::lookAndFeelChanged()
  51687. {
  51688. extraTabsButton = 0;
  51689. resized();
  51690. }
  51691. void TabbedButtonBar::resized()
  51692. {
  51693. const double minimumScale = 0.7;
  51694. int depth = getWidth();
  51695. int length = getHeight();
  51696. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51697. swapVariables (depth, length);
  51698. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51699. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51700. int i, totalLength = overlap;
  51701. int numVisibleButtons = tabs.size();
  51702. for (i = 0; i < getNumChildComponents(); ++i)
  51703. {
  51704. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51705. if (tb != 0)
  51706. {
  51707. totalLength += tb->getBestTabLength (depth) - overlap;
  51708. tb->overlapPixels = overlap / 2;
  51709. }
  51710. }
  51711. double scale = 1.0;
  51712. if (totalLength > length)
  51713. scale = jmax (minimumScale, length / (double) totalLength);
  51714. const bool isTooBig = totalLength * scale > length;
  51715. int tabsButtonPos = 0;
  51716. if (isTooBig)
  51717. {
  51718. if (extraTabsButton == 0)
  51719. {
  51720. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51721. extraTabsButton->addButtonListener (this);
  51722. extraTabsButton->setAlwaysOnTop (true);
  51723. extraTabsButton->setTriggeredOnMouseDown (true);
  51724. }
  51725. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51726. extraTabsButton->setSize (buttonSize, buttonSize);
  51727. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51728. {
  51729. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51730. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51731. }
  51732. else
  51733. {
  51734. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51735. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51736. }
  51737. totalLength = 0;
  51738. for (i = 0; i < tabs.size(); ++i)
  51739. {
  51740. TabBarButton* const tb = getTabButton (i);
  51741. if (tb != 0)
  51742. {
  51743. const int newLength = totalLength + tb->getBestTabLength (depth);
  51744. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51745. {
  51746. totalLength += overlap;
  51747. break;
  51748. }
  51749. numVisibleButtons = i + 1;
  51750. totalLength = newLength - overlap;
  51751. }
  51752. }
  51753. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51754. }
  51755. else
  51756. {
  51757. extraTabsButton = 0;
  51758. }
  51759. int pos = 0;
  51760. TabBarButton* frontTab = 0;
  51761. for (i = 0; i < tabs.size(); ++i)
  51762. {
  51763. TabBarButton* const tb = getTabButton (i);
  51764. if (tb != 0)
  51765. {
  51766. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51767. if (i < numVisibleButtons)
  51768. {
  51769. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51770. tb->setBounds (pos, 0, bestLength, getHeight());
  51771. else
  51772. tb->setBounds (0, pos, getWidth(), bestLength);
  51773. tb->toBack();
  51774. if (tb->tabIndex == currentTabIndex)
  51775. frontTab = tb;
  51776. tb->setVisible (true);
  51777. }
  51778. else
  51779. {
  51780. tb->setVisible (false);
  51781. }
  51782. pos += bestLength - overlap;
  51783. }
  51784. }
  51785. behindFrontTab->setBounds (getLocalBounds());
  51786. if (frontTab != 0)
  51787. {
  51788. frontTab->toFront (false);
  51789. behindFrontTab->toBehind (frontTab);
  51790. }
  51791. }
  51792. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51793. {
  51794. return tabColours [tabIndex];
  51795. }
  51796. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51797. {
  51798. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51799. && tabColours [tabIndex] != newColour)
  51800. {
  51801. tabColours.set (tabIndex, newColour);
  51802. repaint();
  51803. }
  51804. }
  51805. void TabbedButtonBar::buttonClicked (Button* button)
  51806. {
  51807. if (button == extraTabsButton)
  51808. {
  51809. PopupMenu m;
  51810. for (int i = 0; i < tabs.size(); ++i)
  51811. {
  51812. TabBarButton* const tb = getTabButton (i);
  51813. if (tb != 0 && ! tb->isVisible())
  51814. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51815. }
  51816. const int res = m.showAt (extraTabsButton);
  51817. if (res != 0)
  51818. setCurrentTabIndex (res - 1);
  51819. }
  51820. }
  51821. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51822. {
  51823. }
  51824. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51825. {
  51826. }
  51827. END_JUCE_NAMESPACE
  51828. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51829. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51830. BEGIN_JUCE_NAMESPACE
  51831. class TabCompButtonBar : public TabbedButtonBar
  51832. {
  51833. public:
  51834. TabCompButtonBar (TabbedComponent* const owner_,
  51835. const TabbedButtonBar::Orientation orientation_)
  51836. : TabbedButtonBar (orientation_),
  51837. owner (owner_)
  51838. {
  51839. }
  51840. ~TabCompButtonBar()
  51841. {
  51842. }
  51843. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51844. {
  51845. owner->changeCallback (newCurrentTabIndex, newTabName);
  51846. }
  51847. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51848. {
  51849. owner->popupMenuClickOnTab (tabIndex, tabName);
  51850. }
  51851. const Colour getTabBackgroundColour (const int tabIndex)
  51852. {
  51853. return owner->tabs->getTabBackgroundColour (tabIndex);
  51854. }
  51855. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51856. {
  51857. return owner->createTabButton (tabName, tabIndex);
  51858. }
  51859. juce_UseDebuggingNewOperator
  51860. private:
  51861. TabbedComponent* const owner;
  51862. TabCompButtonBar (const TabCompButtonBar&);
  51863. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51864. };
  51865. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51866. : panelComponent (0),
  51867. tabDepth (30),
  51868. outlineThickness (1),
  51869. edgeIndent (0)
  51870. {
  51871. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51872. }
  51873. TabbedComponent::~TabbedComponent()
  51874. {
  51875. clearTabs();
  51876. delete tabs;
  51877. }
  51878. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51879. {
  51880. tabs->setOrientation (orientation);
  51881. resized();
  51882. }
  51883. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51884. {
  51885. return tabs->getOrientation();
  51886. }
  51887. void TabbedComponent::setTabBarDepth (const int newDepth)
  51888. {
  51889. if (tabDepth != newDepth)
  51890. {
  51891. tabDepth = newDepth;
  51892. resized();
  51893. }
  51894. }
  51895. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51896. {
  51897. return new TabBarButton (tabName, tabs, tabIndex);
  51898. }
  51899. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51900. void TabbedComponent::clearTabs()
  51901. {
  51902. if (panelComponent != 0)
  51903. {
  51904. panelComponent->setVisible (false);
  51905. removeChildComponent (panelComponent);
  51906. panelComponent = 0;
  51907. }
  51908. tabs->clearTabs();
  51909. for (int i = contentComponents.size(); --i >= 0;)
  51910. {
  51911. Component* const c = contentComponents.getUnchecked(i);
  51912. // be careful not to delete these components until they've been removed from the tab component
  51913. jassert (c == 0 || c->isValidComponent());
  51914. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51915. delete c;
  51916. }
  51917. contentComponents.clear();
  51918. }
  51919. void TabbedComponent::addTab (const String& tabName,
  51920. const Colour& tabBackgroundColour,
  51921. Component* const contentComponent,
  51922. const bool deleteComponentWhenNotNeeded,
  51923. const int insertIndex)
  51924. {
  51925. contentComponents.insert (insertIndex, contentComponent);
  51926. if (contentComponent != 0)
  51927. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51928. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51929. }
  51930. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51931. {
  51932. tabs->setTabName (tabIndex, newName);
  51933. }
  51934. void TabbedComponent::removeTab (const int tabIndex)
  51935. {
  51936. Component* const c = contentComponents [tabIndex];
  51937. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51938. {
  51939. if (c == panelComponent)
  51940. panelComponent = 0;
  51941. delete c;
  51942. }
  51943. contentComponents.remove (tabIndex);
  51944. tabs->removeTab (tabIndex);
  51945. }
  51946. int TabbedComponent::getNumTabs() const
  51947. {
  51948. return tabs->getNumTabs();
  51949. }
  51950. const StringArray TabbedComponent::getTabNames() const
  51951. {
  51952. return tabs->getTabNames();
  51953. }
  51954. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51955. {
  51956. return contentComponents [tabIndex];
  51957. }
  51958. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51959. {
  51960. return tabs->getTabBackgroundColour (tabIndex);
  51961. }
  51962. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51963. {
  51964. tabs->setTabBackgroundColour (tabIndex, newColour);
  51965. if (getCurrentTabIndex() == tabIndex)
  51966. repaint();
  51967. }
  51968. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51969. {
  51970. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51971. }
  51972. int TabbedComponent::getCurrentTabIndex() const
  51973. {
  51974. return tabs->getCurrentTabIndex();
  51975. }
  51976. const String& TabbedComponent::getCurrentTabName() const
  51977. {
  51978. return tabs->getCurrentTabName();
  51979. }
  51980. void TabbedComponent::setOutline (int thickness)
  51981. {
  51982. outlineThickness = thickness;
  51983. repaint();
  51984. }
  51985. void TabbedComponent::setIndent (const int indentThickness)
  51986. {
  51987. edgeIndent = indentThickness;
  51988. }
  51989. void TabbedComponent::paint (Graphics& g)
  51990. {
  51991. g.fillAll (findColour (backgroundColourId));
  51992. const TabbedButtonBar::Orientation o = getOrientation();
  51993. int x = 0;
  51994. int y = 0;
  51995. int r = getWidth();
  51996. int b = getHeight();
  51997. if (o == TabbedButtonBar::TabsAtTop)
  51998. y += tabDepth;
  51999. else if (o == TabbedButtonBar::TabsAtBottom)
  52000. b -= tabDepth;
  52001. else if (o == TabbedButtonBar::TabsAtLeft)
  52002. x += tabDepth;
  52003. else if (o == TabbedButtonBar::TabsAtRight)
  52004. r -= tabDepth;
  52005. g.reduceClipRegion (x, y, r - x, b - y);
  52006. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  52007. if (outlineThickness > 0)
  52008. {
  52009. if (o == TabbedButtonBar::TabsAtTop)
  52010. --y;
  52011. else if (o == TabbedButtonBar::TabsAtBottom)
  52012. ++b;
  52013. else if (o == TabbedButtonBar::TabsAtLeft)
  52014. --x;
  52015. else if (o == TabbedButtonBar::TabsAtRight)
  52016. ++r;
  52017. g.setColour (findColour (outlineColourId));
  52018. g.drawRect (x, y, r - x, b - y, outlineThickness);
  52019. }
  52020. }
  52021. void TabbedComponent::resized()
  52022. {
  52023. const TabbedButtonBar::Orientation o = getOrientation();
  52024. const int indent = edgeIndent + outlineThickness;
  52025. BorderSize indents (indent);
  52026. if (o == TabbedButtonBar::TabsAtTop)
  52027. {
  52028. tabs->setBounds (0, 0, getWidth(), tabDepth);
  52029. indents.setTop (tabDepth + edgeIndent);
  52030. }
  52031. else if (o == TabbedButtonBar::TabsAtBottom)
  52032. {
  52033. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  52034. indents.setBottom (tabDepth + edgeIndent);
  52035. }
  52036. else if (o == TabbedButtonBar::TabsAtLeft)
  52037. {
  52038. tabs->setBounds (0, 0, tabDepth, getHeight());
  52039. indents.setLeft (tabDepth + edgeIndent);
  52040. }
  52041. else if (o == TabbedButtonBar::TabsAtRight)
  52042. {
  52043. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  52044. indents.setRight (tabDepth + edgeIndent);
  52045. }
  52046. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  52047. for (int i = contentComponents.size(); --i >= 0;)
  52048. if (contentComponents.getUnchecked (i) != 0)
  52049. contentComponents.getUnchecked (i)->setBounds (bounds);
  52050. }
  52051. void TabbedComponent::lookAndFeelChanged()
  52052. {
  52053. for (int i = contentComponents.size(); --i >= 0;)
  52054. if (contentComponents.getUnchecked (i) != 0)
  52055. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  52056. }
  52057. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52058. const String& newTabName)
  52059. {
  52060. if (panelComponent != 0)
  52061. {
  52062. panelComponent->setVisible (false);
  52063. removeChildComponent (panelComponent);
  52064. panelComponent = 0;
  52065. }
  52066. if (getCurrentTabIndex() >= 0)
  52067. {
  52068. panelComponent = contentComponents [getCurrentTabIndex()];
  52069. if (panelComponent != 0)
  52070. {
  52071. // do these ops as two stages instead of addAndMakeVisible() so that the
  52072. // component has always got a parent when it gets the visibilityChanged() callback
  52073. addChildComponent (panelComponent);
  52074. panelComponent->setVisible (true);
  52075. panelComponent->toFront (true);
  52076. }
  52077. repaint();
  52078. }
  52079. resized();
  52080. currentTabChanged (newCurrentTabIndex, newTabName);
  52081. }
  52082. void TabbedComponent::currentTabChanged (const int, const String&)
  52083. {
  52084. }
  52085. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52086. {
  52087. }
  52088. END_JUCE_NAMESPACE
  52089. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52090. /*** Start of inlined file: juce_Viewport.cpp ***/
  52091. BEGIN_JUCE_NAMESPACE
  52092. Viewport::Viewport (const String& componentName)
  52093. : Component (componentName),
  52094. scrollBarThickness (0),
  52095. singleStepX (16),
  52096. singleStepY (16),
  52097. showHScrollbar (true),
  52098. showVScrollbar (true),
  52099. verticalScrollBar (true),
  52100. horizontalScrollBar (false)
  52101. {
  52102. // content holder is used to clip the contents so they don't overlap the scrollbars
  52103. addAndMakeVisible (&contentHolder);
  52104. contentHolder.setInterceptsMouseClicks (false, true);
  52105. addChildComponent (&verticalScrollBar);
  52106. addChildComponent (&horizontalScrollBar);
  52107. verticalScrollBar.addListener (this);
  52108. horizontalScrollBar.addListener (this);
  52109. setInterceptsMouseClicks (false, true);
  52110. setWantsKeyboardFocus (true);
  52111. }
  52112. Viewport::~Viewport()
  52113. {
  52114. contentHolder.deleteAllChildren();
  52115. }
  52116. void Viewport::visibleAreaChanged (int, int, int, int)
  52117. {
  52118. }
  52119. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52120. {
  52121. if (contentComp.getComponent() != newViewedComponent)
  52122. {
  52123. {
  52124. ScopedPointer<Component> oldCompDeleter (contentComp);
  52125. contentComp = 0;
  52126. }
  52127. contentComp = newViewedComponent;
  52128. if (contentComp != 0)
  52129. {
  52130. contentComp->setTopLeftPosition (0, 0);
  52131. contentHolder.addAndMakeVisible (contentComp);
  52132. contentComp->addComponentListener (this);
  52133. }
  52134. updateVisibleArea();
  52135. }
  52136. }
  52137. int Viewport::getMaximumVisibleWidth() const
  52138. {
  52139. return contentHolder.getWidth();
  52140. }
  52141. int Viewport::getMaximumVisibleHeight() const
  52142. {
  52143. return contentHolder.getHeight();
  52144. }
  52145. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52146. {
  52147. if (contentComp != 0)
  52148. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52149. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52150. }
  52151. void Viewport::setViewPosition (const Point<int>& newPosition)
  52152. {
  52153. setViewPosition (newPosition.getX(), newPosition.getY());
  52154. }
  52155. void Viewport::setViewPositionProportionately (const double x, const double y)
  52156. {
  52157. if (contentComp != 0)
  52158. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52159. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52160. }
  52161. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52162. {
  52163. if (contentComp != 0)
  52164. {
  52165. int dx = 0, dy = 0;
  52166. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52167. {
  52168. if (mouseX < activeBorderThickness)
  52169. dx = activeBorderThickness - mouseX;
  52170. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52171. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52172. if (dx < 0)
  52173. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52174. else
  52175. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52176. }
  52177. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52178. {
  52179. if (mouseY < activeBorderThickness)
  52180. dy = activeBorderThickness - mouseY;
  52181. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52182. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52183. if (dy < 0)
  52184. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52185. else
  52186. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52187. }
  52188. if (dx != 0 || dy != 0)
  52189. {
  52190. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52191. contentComp->getY() + dy);
  52192. return true;
  52193. }
  52194. }
  52195. return false;
  52196. }
  52197. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52198. {
  52199. updateVisibleArea();
  52200. }
  52201. void Viewport::resized()
  52202. {
  52203. updateVisibleArea();
  52204. }
  52205. void Viewport::updateVisibleArea()
  52206. {
  52207. const int scrollbarWidth = getScrollBarThickness();
  52208. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52209. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52210. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52211. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52212. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52213. Rectangle<int> contentArea (getLocalBounds());
  52214. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52215. {
  52216. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52217. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52218. if (vBarVisible)
  52219. contentArea.setWidth (getWidth() - scrollbarWidth);
  52220. if (hBarVisible)
  52221. contentArea.setHeight (getHeight() - scrollbarWidth);
  52222. if (! contentArea.contains (contentComp->getBounds()))
  52223. {
  52224. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52225. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52226. }
  52227. }
  52228. if (vBarVisible)
  52229. contentArea.setWidth (getWidth() - scrollbarWidth);
  52230. if (hBarVisible)
  52231. contentArea.setHeight (getHeight() - scrollbarWidth);
  52232. contentHolder.setBounds (contentArea);
  52233. Rectangle<int> contentBounds;
  52234. if (contentComp != 0)
  52235. contentBounds = contentComp->getBounds();
  52236. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52237. if (hBarVisible)
  52238. {
  52239. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52240. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52241. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52242. horizontalScrollBar.setSingleStepSize (singleStepX);
  52243. horizontalScrollBar.cancelPendingUpdate();
  52244. }
  52245. if (vBarVisible)
  52246. {
  52247. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52248. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52249. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52250. verticalScrollBar.setSingleStepSize (singleStepY);
  52251. verticalScrollBar.cancelPendingUpdate();
  52252. }
  52253. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52254. horizontalScrollBar.setVisible (hBarVisible);
  52255. verticalScrollBar.setVisible (vBarVisible);
  52256. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52257. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52258. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52259. if (lastVisibleArea != visibleArea)
  52260. {
  52261. lastVisibleArea = visibleArea;
  52262. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52263. }
  52264. horizontalScrollBar.handleUpdateNowIfNeeded();
  52265. verticalScrollBar.handleUpdateNowIfNeeded();
  52266. }
  52267. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52268. {
  52269. if (singleStepX != stepX || singleStepY != stepY)
  52270. {
  52271. singleStepX = stepX;
  52272. singleStepY = stepY;
  52273. updateVisibleArea();
  52274. }
  52275. }
  52276. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52277. const bool showHorizontalScrollbarIfNeeded)
  52278. {
  52279. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52280. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52281. {
  52282. showVScrollbar = showVerticalScrollbarIfNeeded;
  52283. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52284. updateVisibleArea();
  52285. }
  52286. }
  52287. void Viewport::setScrollBarThickness (const int thickness)
  52288. {
  52289. if (scrollBarThickness != thickness)
  52290. {
  52291. scrollBarThickness = thickness;
  52292. updateVisibleArea();
  52293. }
  52294. }
  52295. int Viewport::getScrollBarThickness() const
  52296. {
  52297. return scrollBarThickness > 0 ? scrollBarThickness
  52298. : getLookAndFeel().getDefaultScrollbarWidth();
  52299. }
  52300. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52301. {
  52302. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52303. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52304. }
  52305. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52306. {
  52307. const int newRangeStartInt = roundToInt (newRangeStart);
  52308. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52309. {
  52310. setViewPosition (newRangeStartInt, getViewPositionY());
  52311. }
  52312. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52313. {
  52314. setViewPosition (getViewPositionX(), newRangeStartInt);
  52315. }
  52316. }
  52317. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52318. {
  52319. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52320. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52321. }
  52322. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52323. {
  52324. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52325. {
  52326. const bool hasVertBar = verticalScrollBar.isVisible();
  52327. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52328. if (hasHorzBar || hasVertBar)
  52329. {
  52330. if (wheelIncrementX != 0)
  52331. {
  52332. wheelIncrementX *= 14.0f * singleStepX;
  52333. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52334. : jmax (wheelIncrementX, 1.0f);
  52335. }
  52336. if (wheelIncrementY != 0)
  52337. {
  52338. wheelIncrementY *= 14.0f * singleStepY;
  52339. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52340. : jmax (wheelIncrementY, 1.0f);
  52341. }
  52342. Point<int> pos (getViewPosition());
  52343. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52344. {
  52345. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52346. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52347. }
  52348. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52349. {
  52350. if (wheelIncrementX == 0 && ! hasVertBar)
  52351. wheelIncrementX = wheelIncrementY;
  52352. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52353. }
  52354. else if (hasVertBar && wheelIncrementY != 0)
  52355. {
  52356. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52357. }
  52358. if (pos != getViewPosition())
  52359. {
  52360. setViewPosition (pos);
  52361. return true;
  52362. }
  52363. }
  52364. }
  52365. return false;
  52366. }
  52367. bool Viewport::keyPressed (const KeyPress& key)
  52368. {
  52369. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52370. || key.isKeyCode (KeyPress::downKey)
  52371. || key.isKeyCode (KeyPress::pageUpKey)
  52372. || key.isKeyCode (KeyPress::pageDownKey)
  52373. || key.isKeyCode (KeyPress::homeKey)
  52374. || key.isKeyCode (KeyPress::endKey);
  52375. if (verticalScrollBar.isVisible() && isUpDownKey)
  52376. return verticalScrollBar.keyPressed (key);
  52377. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52378. || key.isKeyCode (KeyPress::rightKey);
  52379. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52380. return horizontalScrollBar.keyPressed (key);
  52381. return false;
  52382. }
  52383. END_JUCE_NAMESPACE
  52384. /*** End of inlined file: juce_Viewport.cpp ***/
  52385. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52386. BEGIN_JUCE_NAMESPACE
  52387. static const Colour createBaseColour (const Colour& buttonColour,
  52388. const bool hasKeyboardFocus,
  52389. const bool isMouseOverButton,
  52390. const bool isButtonDown) throw()
  52391. {
  52392. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52393. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52394. if (isButtonDown)
  52395. return baseColour.contrasting (0.2f);
  52396. else if (isMouseOverButton)
  52397. return baseColour.contrasting (0.1f);
  52398. return baseColour;
  52399. }
  52400. LookAndFeel::LookAndFeel()
  52401. {
  52402. /* if this fails it means you're trying to create a LookAndFeel object before
  52403. the static Colours have been initialised. That ain't gonna work. It probably
  52404. means that you're using a static LookAndFeel object and that your compiler has
  52405. decided to intialise it before the Colours class.
  52406. */
  52407. jassert (Colours::white == Colour (0xffffffff));
  52408. // set up the standard set of colours..
  52409. const int textButtonColour = 0xffbbbbff;
  52410. const int textHighlightColour = 0x401111ee;
  52411. const int standardOutlineColour = 0xb2808080;
  52412. static const int standardColours[] =
  52413. {
  52414. TextButton::buttonColourId, textButtonColour,
  52415. TextButton::buttonOnColourId, 0xff4444ff,
  52416. TextButton::textColourOnId, 0xff000000,
  52417. TextButton::textColourOffId, 0xff000000,
  52418. ComboBox::buttonColourId, 0xffbbbbff,
  52419. ComboBox::outlineColourId, standardOutlineColour,
  52420. ToggleButton::textColourId, 0xff000000,
  52421. TextEditor::backgroundColourId, 0xffffffff,
  52422. TextEditor::textColourId, 0xff000000,
  52423. TextEditor::highlightColourId, textHighlightColour,
  52424. TextEditor::highlightedTextColourId, 0xff000000,
  52425. TextEditor::caretColourId, 0xff000000,
  52426. TextEditor::outlineColourId, 0x00000000,
  52427. TextEditor::focusedOutlineColourId, textButtonColour,
  52428. TextEditor::shadowColourId, 0x38000000,
  52429. Label::backgroundColourId, 0x00000000,
  52430. Label::textColourId, 0xff000000,
  52431. Label::outlineColourId, 0x00000000,
  52432. ScrollBar::backgroundColourId, 0x00000000,
  52433. ScrollBar::thumbColourId, 0xffffffff,
  52434. ScrollBar::trackColourId, 0xffffffff,
  52435. TreeView::linesColourId, 0x4c000000,
  52436. TreeView::backgroundColourId, 0x00000000,
  52437. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52438. PopupMenu::backgroundColourId, 0xffffffff,
  52439. PopupMenu::textColourId, 0xff000000,
  52440. PopupMenu::headerTextColourId, 0xff000000,
  52441. PopupMenu::highlightedTextColourId, 0xffffffff,
  52442. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52443. ComboBox::textColourId, 0xff000000,
  52444. ComboBox::backgroundColourId, 0xffffffff,
  52445. ComboBox::arrowColourId, 0x99000000,
  52446. ListBox::backgroundColourId, 0xffffffff,
  52447. ListBox::outlineColourId, standardOutlineColour,
  52448. ListBox::textColourId, 0xff000000,
  52449. Slider::backgroundColourId, 0x00000000,
  52450. Slider::thumbColourId, textButtonColour,
  52451. Slider::trackColourId, 0x7fffffff,
  52452. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52453. Slider::rotarySliderOutlineColourId, 0x66000000,
  52454. Slider::textBoxTextColourId, 0xff000000,
  52455. Slider::textBoxBackgroundColourId, 0xffffffff,
  52456. Slider::textBoxHighlightColourId, textHighlightColour,
  52457. Slider::textBoxOutlineColourId, standardOutlineColour,
  52458. ResizableWindow::backgroundColourId, 0xff777777,
  52459. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52460. AlertWindow::backgroundColourId, 0xffededed,
  52461. AlertWindow::textColourId, 0xff000000,
  52462. AlertWindow::outlineColourId, 0xff666666,
  52463. ProgressBar::backgroundColourId, 0xffeeeeee,
  52464. ProgressBar::foregroundColourId, 0xffaaaaee,
  52465. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52466. TooltipWindow::textColourId, 0xff000000,
  52467. TooltipWindow::outlineColourId, 0x4c000000,
  52468. TabbedComponent::backgroundColourId, 0x00000000,
  52469. TabbedComponent::outlineColourId, 0xff777777,
  52470. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52471. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52472. Toolbar::backgroundColourId, 0xfff6f8f9,
  52473. Toolbar::separatorColourId, 0x4c000000,
  52474. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52475. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52476. Toolbar::labelTextColourId, 0xff000000,
  52477. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52478. HyperlinkButton::textColourId, 0xcc1111ee,
  52479. GroupComponent::outlineColourId, 0x66000000,
  52480. GroupComponent::textColourId, 0xff000000,
  52481. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52482. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52483. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52484. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52485. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52486. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52487. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52488. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52489. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52490. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52491. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52492. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52493. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52494. CodeEditorComponent::caretColourId, 0xff000000,
  52495. CodeEditorComponent::highlightColourId, textHighlightColour,
  52496. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52497. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52498. ColourSelector::labelTextColourId, 0xff000000,
  52499. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52500. KeyMappingEditorComponent::textColourId, 0xff000000,
  52501. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52502. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52503. DrawableButton::textColourId, 0xff000000,
  52504. };
  52505. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52506. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52507. static String defaultSansName, defaultSerifName, defaultFixedName;
  52508. if (defaultSansName.isEmpty())
  52509. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52510. defaultSans = defaultSansName;
  52511. defaultSerif = defaultSerifName;
  52512. defaultFixed = defaultFixedName;
  52513. }
  52514. LookAndFeel::~LookAndFeel()
  52515. {
  52516. }
  52517. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52518. {
  52519. const int index = colourIds.indexOf (colourId);
  52520. if (index >= 0)
  52521. return colours [index];
  52522. jassertfalse;
  52523. return Colours::black;
  52524. }
  52525. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52526. {
  52527. const int index = colourIds.indexOf (colourId);
  52528. if (index >= 0)
  52529. {
  52530. colours.set (index, colour);
  52531. }
  52532. else
  52533. {
  52534. colourIds.add (colourId);
  52535. colours.add (colour);
  52536. }
  52537. }
  52538. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52539. {
  52540. return colourIds.contains (colourId);
  52541. }
  52542. static LookAndFeel* defaultLF = 0;
  52543. static LookAndFeel* currentDefaultLF = 0;
  52544. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52545. {
  52546. // if this happens, your app hasn't initialised itself properly.. if you're
  52547. // trying to hack your own main() function, have a look at
  52548. // JUCEApplication::initialiseForGUI()
  52549. jassert (currentDefaultLF != 0);
  52550. return *currentDefaultLF;
  52551. }
  52552. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52553. {
  52554. if (newDefaultLookAndFeel == 0)
  52555. {
  52556. if (defaultLF == 0)
  52557. defaultLF = new LookAndFeel();
  52558. newDefaultLookAndFeel = defaultLF;
  52559. }
  52560. currentDefaultLF = newDefaultLookAndFeel;
  52561. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52562. {
  52563. Component* const c = Desktop::getInstance().getComponent (i);
  52564. if (c != 0)
  52565. c->sendLookAndFeelChange();
  52566. }
  52567. }
  52568. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52569. {
  52570. if (currentDefaultLF == defaultLF)
  52571. currentDefaultLF = 0;
  52572. deleteAndZero (defaultLF);
  52573. }
  52574. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52575. {
  52576. String faceName (font.getTypefaceName());
  52577. if (faceName == Font::getDefaultSansSerifFontName())
  52578. faceName = defaultSans;
  52579. else if (faceName == Font::getDefaultSerifFontName())
  52580. faceName = defaultSerif;
  52581. else if (faceName == Font::getDefaultMonospacedFontName())
  52582. faceName = defaultFixed;
  52583. Font f (font);
  52584. f.setTypefaceName (faceName);
  52585. return Typeface::createSystemTypefaceFor (f);
  52586. }
  52587. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52588. {
  52589. defaultSans = newName;
  52590. }
  52591. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52592. {
  52593. return component.getMouseCursor();
  52594. }
  52595. void LookAndFeel::drawButtonBackground (Graphics& g,
  52596. Button& button,
  52597. const Colour& backgroundColour,
  52598. bool isMouseOverButton,
  52599. bool isButtonDown)
  52600. {
  52601. const int width = button.getWidth();
  52602. const int height = button.getHeight();
  52603. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52604. const float halfThickness = outlineThickness * 0.5f;
  52605. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52606. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52607. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52608. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52609. const Colour baseColour (createBaseColour (backgroundColour,
  52610. button.hasKeyboardFocus (true),
  52611. isMouseOverButton, isButtonDown)
  52612. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52613. drawGlassLozenge (g,
  52614. indentL,
  52615. indentT,
  52616. width - indentL - indentR,
  52617. height - indentT - indentB,
  52618. baseColour, outlineThickness, -1.0f,
  52619. button.isConnectedOnLeft(),
  52620. button.isConnectedOnRight(),
  52621. button.isConnectedOnTop(),
  52622. button.isConnectedOnBottom());
  52623. }
  52624. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52625. {
  52626. return button.getFont();
  52627. }
  52628. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52629. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52630. {
  52631. Font font (getFontForTextButton (button));
  52632. g.setFont (font);
  52633. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52634. : TextButton::textColourOffId)
  52635. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52636. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52637. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52638. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52639. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52640. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52641. g.drawFittedText (button.getButtonText(),
  52642. leftIndent,
  52643. yIndent,
  52644. button.getWidth() - leftIndent - rightIndent,
  52645. button.getHeight() - yIndent * 2,
  52646. Justification::centred, 2);
  52647. }
  52648. void LookAndFeel::drawTickBox (Graphics& g,
  52649. Component& component,
  52650. float x, float y, float w, float h,
  52651. const bool ticked,
  52652. const bool isEnabled,
  52653. const bool isMouseOverButton,
  52654. const bool isButtonDown)
  52655. {
  52656. const float boxSize = w * 0.7f;
  52657. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52658. createBaseColour (component.findColour (TextButton::buttonColourId)
  52659. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52660. true,
  52661. isMouseOverButton,
  52662. isButtonDown),
  52663. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52664. if (ticked)
  52665. {
  52666. Path tick;
  52667. tick.startNewSubPath (1.5f, 3.0f);
  52668. tick.lineTo (3.0f, 6.0f);
  52669. tick.lineTo (6.0f, 0.0f);
  52670. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52671. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52672. .translated (x, y));
  52673. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52674. }
  52675. }
  52676. void LookAndFeel::drawToggleButton (Graphics& g,
  52677. ToggleButton& button,
  52678. bool isMouseOverButton,
  52679. bool isButtonDown)
  52680. {
  52681. if (button.hasKeyboardFocus (true))
  52682. {
  52683. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52684. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52685. }
  52686. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52687. const float tickWidth = fontSize * 1.1f;
  52688. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52689. tickWidth, tickWidth,
  52690. button.getToggleState(),
  52691. button.isEnabled(),
  52692. isMouseOverButton,
  52693. isButtonDown);
  52694. g.setColour (button.findColour (ToggleButton::textColourId));
  52695. g.setFont (fontSize);
  52696. if (! button.isEnabled())
  52697. g.setOpacity (0.5f);
  52698. const int textX = (int) tickWidth + 5;
  52699. g.drawFittedText (button.getButtonText(),
  52700. textX, 0,
  52701. button.getWidth() - textX - 2, button.getHeight(),
  52702. Justification::centredLeft, 10);
  52703. }
  52704. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52705. {
  52706. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52707. const int tickWidth = jmin (24, button.getHeight());
  52708. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52709. button.getHeight());
  52710. }
  52711. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52712. const String& message,
  52713. const String& button1,
  52714. const String& button2,
  52715. const String& button3,
  52716. AlertWindow::AlertIconType iconType,
  52717. int numButtons,
  52718. Component* associatedComponent)
  52719. {
  52720. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52721. if (numButtons == 1)
  52722. {
  52723. aw->addButton (button1, 0,
  52724. KeyPress (KeyPress::escapeKey, 0, 0),
  52725. KeyPress (KeyPress::returnKey, 0, 0));
  52726. }
  52727. else
  52728. {
  52729. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52730. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52731. if (button1ShortCut == button2ShortCut)
  52732. button2ShortCut = KeyPress();
  52733. if (numButtons == 2)
  52734. {
  52735. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52736. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52737. }
  52738. else if (numButtons == 3)
  52739. {
  52740. aw->addButton (button1, 1, button1ShortCut);
  52741. aw->addButton (button2, 2, button2ShortCut);
  52742. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52743. }
  52744. }
  52745. return aw;
  52746. }
  52747. void LookAndFeel::drawAlertBox (Graphics& g,
  52748. AlertWindow& alert,
  52749. const Rectangle<int>& textArea,
  52750. TextLayout& textLayout)
  52751. {
  52752. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52753. int iconSpaceUsed = 0;
  52754. Justification alignment (Justification::horizontallyCentred);
  52755. const int iconWidth = 80;
  52756. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52757. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52758. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52759. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52760. iconSize, iconSize);
  52761. if (alert.getAlertType() != AlertWindow::NoIcon)
  52762. {
  52763. Path icon;
  52764. uint32 colour;
  52765. char character;
  52766. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52767. {
  52768. colour = 0x55ff5555;
  52769. character = '!';
  52770. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52771. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52772. (float) iconRect.getX(), (float) iconRect.getBottom());
  52773. icon = icon.createPathWithRoundedCorners (5.0f);
  52774. }
  52775. else
  52776. {
  52777. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52778. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52779. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52780. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52781. }
  52782. GlyphArrangement ga;
  52783. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52784. String::charToString (character),
  52785. (float) iconRect.getX(), (float) iconRect.getY(),
  52786. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52787. Justification::centred, false);
  52788. ga.createPath (icon);
  52789. icon.setUsingNonZeroWinding (false);
  52790. g.setColour (Colour (colour));
  52791. g.fillPath (icon);
  52792. iconSpaceUsed = iconWidth;
  52793. alignment = Justification::left;
  52794. }
  52795. g.setColour (alert.findColour (AlertWindow::textColourId));
  52796. textLayout.drawWithin (g,
  52797. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52798. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52799. alignment.getFlags() | Justification::top);
  52800. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52801. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52802. }
  52803. int LookAndFeel::getAlertBoxWindowFlags()
  52804. {
  52805. return ComponentPeer::windowAppearsOnTaskbar
  52806. | ComponentPeer::windowHasDropShadow;
  52807. }
  52808. int LookAndFeel::getAlertWindowButtonHeight()
  52809. {
  52810. return 28;
  52811. }
  52812. const Font LookAndFeel::getAlertWindowFont()
  52813. {
  52814. return Font (12.0f);
  52815. }
  52816. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52817. int width, int height,
  52818. double progress, const String& textToShow)
  52819. {
  52820. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52821. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52822. g.fillAll (background);
  52823. if (progress >= 0.0f && progress < 1.0f)
  52824. {
  52825. drawGlassLozenge (g, 1.0f, 1.0f,
  52826. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52827. (float) (height - 2),
  52828. foreground,
  52829. 0.5f, 0.0f,
  52830. true, true, true, true);
  52831. }
  52832. else
  52833. {
  52834. // spinning bar..
  52835. g.setColour (foreground);
  52836. const int stripeWidth = height * 2;
  52837. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52838. Path p;
  52839. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52840. p.addQuadrilateral (x, 0.0f,
  52841. x + stripeWidth * 0.5f, 0.0f,
  52842. x, (float) height,
  52843. x - stripeWidth * 0.5f, (float) height);
  52844. Image im (Image::ARGB, width, height, true);
  52845. {
  52846. Graphics g2 (im);
  52847. drawGlassLozenge (g2, 1.0f, 1.0f,
  52848. (float) (width - 2),
  52849. (float) (height - 2),
  52850. foreground,
  52851. 0.5f, 0.0f,
  52852. true, true, true, true);
  52853. }
  52854. g.setTiledImageFill (im, 0, 0, 0.85f);
  52855. g.fillPath (p);
  52856. }
  52857. if (textToShow.isNotEmpty())
  52858. {
  52859. g.setColour (Colour::contrasting (background, foreground));
  52860. g.setFont (height * 0.6f);
  52861. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52862. }
  52863. }
  52864. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52865. {
  52866. const float radius = jmin (w, h) * 0.4f;
  52867. const float thickness = radius * 0.15f;
  52868. Path p;
  52869. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52870. radius * 0.6f, thickness,
  52871. thickness * 0.5f);
  52872. const float cx = x + w * 0.5f;
  52873. const float cy = y + h * 0.5f;
  52874. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52875. for (int i = 0; i < 12; ++i)
  52876. {
  52877. const int n = (i + 12 - animationIndex) % 12;
  52878. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52879. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52880. .translated (cx, cy));
  52881. }
  52882. }
  52883. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52884. ScrollBar& scrollbar,
  52885. int width, int height,
  52886. int buttonDirection,
  52887. bool /*isScrollbarVertical*/,
  52888. bool /*isMouseOverButton*/,
  52889. bool isButtonDown)
  52890. {
  52891. Path p;
  52892. if (buttonDirection == 0)
  52893. p.addTriangle (width * 0.5f, height * 0.2f,
  52894. width * 0.1f, height * 0.7f,
  52895. width * 0.9f, height * 0.7f);
  52896. else if (buttonDirection == 1)
  52897. p.addTriangle (width * 0.8f, height * 0.5f,
  52898. width * 0.3f, height * 0.1f,
  52899. width * 0.3f, height * 0.9f);
  52900. else if (buttonDirection == 2)
  52901. p.addTriangle (width * 0.5f, height * 0.8f,
  52902. width * 0.1f, height * 0.3f,
  52903. width * 0.9f, height * 0.3f);
  52904. else if (buttonDirection == 3)
  52905. p.addTriangle (width * 0.2f, height * 0.5f,
  52906. width * 0.7f, height * 0.1f,
  52907. width * 0.7f, height * 0.9f);
  52908. if (isButtonDown)
  52909. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52910. else
  52911. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52912. g.fillPath (p);
  52913. g.setColour (Colour (0x80000000));
  52914. g.strokePath (p, PathStrokeType (0.5f));
  52915. }
  52916. void LookAndFeel::drawScrollbar (Graphics& g,
  52917. ScrollBar& scrollbar,
  52918. int x, int y,
  52919. int width, int height,
  52920. bool isScrollbarVertical,
  52921. int thumbStartPosition,
  52922. int thumbSize,
  52923. bool /*isMouseOver*/,
  52924. bool /*isMouseDown*/)
  52925. {
  52926. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52927. Path slotPath, thumbPath;
  52928. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52929. const float slotIndentx2 = slotIndent * 2.0f;
  52930. const float thumbIndent = slotIndent + 1.0f;
  52931. const float thumbIndentx2 = thumbIndent * 2.0f;
  52932. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52933. if (isScrollbarVertical)
  52934. {
  52935. slotPath.addRoundedRectangle (x + slotIndent,
  52936. y + slotIndent,
  52937. width - slotIndentx2,
  52938. height - slotIndentx2,
  52939. (width - slotIndentx2) * 0.5f);
  52940. if (thumbSize > 0)
  52941. thumbPath.addRoundedRectangle (x + thumbIndent,
  52942. thumbStartPosition + thumbIndent,
  52943. width - thumbIndentx2,
  52944. thumbSize - thumbIndentx2,
  52945. (width - thumbIndentx2) * 0.5f);
  52946. gx1 = (float) x;
  52947. gx2 = x + width * 0.7f;
  52948. }
  52949. else
  52950. {
  52951. slotPath.addRoundedRectangle (x + slotIndent,
  52952. y + slotIndent,
  52953. width - slotIndentx2,
  52954. height - slotIndentx2,
  52955. (height - slotIndentx2) * 0.5f);
  52956. if (thumbSize > 0)
  52957. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52958. y + thumbIndent,
  52959. thumbSize - thumbIndentx2,
  52960. height - thumbIndentx2,
  52961. (height - thumbIndentx2) * 0.5f);
  52962. gy1 = (float) y;
  52963. gy2 = y + height * 0.7f;
  52964. }
  52965. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52966. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52967. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52968. g.fillPath (slotPath);
  52969. if (isScrollbarVertical)
  52970. {
  52971. gx1 = x + width * 0.6f;
  52972. gx2 = (float) x + width;
  52973. }
  52974. else
  52975. {
  52976. gy1 = y + height * 0.6f;
  52977. gy2 = (float) y + height;
  52978. }
  52979. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52980. Colour (0x19000000), gx2, gy2, false));
  52981. g.fillPath (slotPath);
  52982. g.setColour (thumbColour);
  52983. g.fillPath (thumbPath);
  52984. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52985. Colours::transparentBlack, gx2, gy2, false));
  52986. g.saveState();
  52987. if (isScrollbarVertical)
  52988. g.reduceClipRegion (x + width / 2, y, width, height);
  52989. else
  52990. g.reduceClipRegion (x, y + height / 2, width, height);
  52991. g.fillPath (thumbPath);
  52992. g.restoreState();
  52993. g.setColour (Colour (0x4c000000));
  52994. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52995. }
  52996. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52997. {
  52998. return 0;
  52999. }
  53000. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  53001. {
  53002. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  53003. }
  53004. int LookAndFeel::getDefaultScrollbarWidth()
  53005. {
  53006. return 18;
  53007. }
  53008. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  53009. {
  53010. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  53011. : scrollbar.getHeight());
  53012. }
  53013. const Path LookAndFeel::getTickShape (const float height)
  53014. {
  53015. static const unsigned char tickShapeData[] =
  53016. {
  53017. 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,
  53018. 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,
  53019. 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,
  53020. 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,
  53021. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53022. };
  53023. Path p;
  53024. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53025. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53026. return p;
  53027. }
  53028. const Path LookAndFeel::getCrossShape (const float height)
  53029. {
  53030. static const unsigned char crossShapeData[] =
  53031. {
  53032. 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,
  53033. 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,
  53034. 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,
  53035. 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,
  53036. 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,
  53037. 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,
  53038. 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
  53039. };
  53040. Path p;
  53041. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53042. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53043. return p;
  53044. }
  53045. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53046. {
  53047. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53048. x += (w - boxSize) >> 1;
  53049. y += (h - boxSize) >> 1;
  53050. w = boxSize;
  53051. h = boxSize;
  53052. g.setColour (Colour (0xe5ffffff));
  53053. g.fillRect (x, y, w, h);
  53054. g.setColour (Colour (0x80000000));
  53055. g.drawRect (x, y, w, h);
  53056. const float size = boxSize / 2 + 1.0f;
  53057. const float centre = (float) (boxSize / 2);
  53058. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53059. if (isPlus)
  53060. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53061. }
  53062. void LookAndFeel::drawBubble (Graphics& g,
  53063. float tipX, float tipY,
  53064. float boxX, float boxY,
  53065. float boxW, float boxH)
  53066. {
  53067. int side = 0;
  53068. if (tipX < boxX)
  53069. side = 1;
  53070. else if (tipX > boxX + boxW)
  53071. side = 3;
  53072. else if (tipY > boxY + boxH)
  53073. side = 2;
  53074. const float indent = 2.0f;
  53075. Path p;
  53076. p.addBubble (boxX + indent,
  53077. boxY + indent,
  53078. boxW - indent * 2.0f,
  53079. boxH - indent * 2.0f,
  53080. 5.0f,
  53081. tipX, tipY,
  53082. side,
  53083. 0.5f,
  53084. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53085. //xxx need to take comp as param for colour
  53086. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53087. g.fillPath (p);
  53088. //xxx as above
  53089. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53090. g.strokePath (p, PathStrokeType (1.33f));
  53091. }
  53092. const Font LookAndFeel::getPopupMenuFont()
  53093. {
  53094. return Font (17.0f);
  53095. }
  53096. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53097. const bool isSeparator,
  53098. int standardMenuItemHeight,
  53099. int& idealWidth,
  53100. int& idealHeight)
  53101. {
  53102. if (isSeparator)
  53103. {
  53104. idealWidth = 50;
  53105. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53106. }
  53107. else
  53108. {
  53109. Font font (getPopupMenuFont());
  53110. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53111. font.setHeight (standardMenuItemHeight / 1.3f);
  53112. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53113. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53114. }
  53115. }
  53116. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53117. {
  53118. const Colour background (findColour (PopupMenu::backgroundColourId));
  53119. g.fillAll (background);
  53120. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53121. for (int i = 0; i < height; i += 3)
  53122. g.fillRect (0, i, width, 1);
  53123. #if ! JUCE_MAC
  53124. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53125. g.drawRect (0, 0, width, height);
  53126. #endif
  53127. }
  53128. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53129. int width, int height,
  53130. bool isScrollUpArrow)
  53131. {
  53132. const Colour background (findColour (PopupMenu::backgroundColourId));
  53133. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53134. background.withAlpha (0.0f),
  53135. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53136. false));
  53137. g.fillRect (1, 1, width - 2, height - 2);
  53138. const float hw = width * 0.5f;
  53139. const float arrowW = height * 0.3f;
  53140. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53141. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53142. Path p;
  53143. p.addTriangle (hw - arrowW, y1,
  53144. hw + arrowW, y1,
  53145. hw, y2);
  53146. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53147. g.fillPath (p);
  53148. }
  53149. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53150. int width, int height,
  53151. const bool isSeparator,
  53152. const bool isActive,
  53153. const bool isHighlighted,
  53154. const bool isTicked,
  53155. const bool hasSubMenu,
  53156. const String& text,
  53157. const String& shortcutKeyText,
  53158. Image* image,
  53159. const Colour* const textColourToUse)
  53160. {
  53161. const float halfH = height * 0.5f;
  53162. if (isSeparator)
  53163. {
  53164. const float separatorIndent = 5.5f;
  53165. g.setColour (Colour (0x33000000));
  53166. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53167. g.setColour (Colour (0x66ffffff));
  53168. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53169. }
  53170. else
  53171. {
  53172. Colour textColour (findColour (PopupMenu::textColourId));
  53173. if (textColourToUse != 0)
  53174. textColour = *textColourToUse;
  53175. if (isHighlighted)
  53176. {
  53177. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53178. g.fillRect (1, 1, width - 2, height - 2);
  53179. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53180. }
  53181. else
  53182. {
  53183. g.setColour (textColour);
  53184. }
  53185. if (! isActive)
  53186. g.setOpacity (0.3f);
  53187. Font font (getPopupMenuFont());
  53188. if (font.getHeight() > height / 1.3f)
  53189. font.setHeight (height / 1.3f);
  53190. g.setFont (font);
  53191. const int leftBorder = (height * 5) / 4;
  53192. const int rightBorder = 4;
  53193. if (image != 0)
  53194. {
  53195. g.drawImageWithin (*image,
  53196. 2, 1, leftBorder - 4, height - 2,
  53197. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53198. }
  53199. else if (isTicked)
  53200. {
  53201. const Path tick (getTickShape (1.0f));
  53202. const float th = font.getAscent();
  53203. const float ty = halfH - th * 0.5f;
  53204. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53205. th, true));
  53206. }
  53207. g.drawFittedText (text,
  53208. leftBorder, 0,
  53209. width - (leftBorder + rightBorder), height,
  53210. Justification::centredLeft, 1);
  53211. if (shortcutKeyText.isNotEmpty())
  53212. {
  53213. Font f2 (font);
  53214. f2.setHeight (f2.getHeight() * 0.75f);
  53215. f2.setHorizontalScale (0.95f);
  53216. g.setFont (f2);
  53217. g.drawText (shortcutKeyText,
  53218. leftBorder,
  53219. 0,
  53220. width - (leftBorder + rightBorder + 4),
  53221. height,
  53222. Justification::centredRight,
  53223. true);
  53224. }
  53225. if (hasSubMenu)
  53226. {
  53227. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53228. const float x = width - height * 0.6f;
  53229. Path p;
  53230. p.addTriangle (x, halfH - arrowH * 0.5f,
  53231. x, halfH + arrowH * 0.5f,
  53232. x + arrowH * 0.6f, halfH);
  53233. g.fillPath (p);
  53234. }
  53235. }
  53236. }
  53237. int LookAndFeel::getMenuWindowFlags()
  53238. {
  53239. return ComponentPeer::windowHasDropShadow;
  53240. }
  53241. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53242. bool, MenuBarComponent& menuBar)
  53243. {
  53244. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53245. if (menuBar.isEnabled())
  53246. {
  53247. drawShinyButtonShape (g,
  53248. -4.0f, 0.0f,
  53249. width + 8.0f, (float) height,
  53250. 0.0f,
  53251. baseColour,
  53252. 0.4f,
  53253. true, true, true, true);
  53254. }
  53255. else
  53256. {
  53257. g.fillAll (baseColour);
  53258. }
  53259. }
  53260. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53261. {
  53262. return Font (menuBar.getHeight() * 0.7f);
  53263. }
  53264. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53265. {
  53266. return getMenuBarFont (menuBar, itemIndex, itemText)
  53267. .getStringWidth (itemText) + menuBar.getHeight();
  53268. }
  53269. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53270. int width, int height,
  53271. int itemIndex,
  53272. const String& itemText,
  53273. bool isMouseOverItem,
  53274. bool isMenuOpen,
  53275. bool /*isMouseOverBar*/,
  53276. MenuBarComponent& menuBar)
  53277. {
  53278. if (! menuBar.isEnabled())
  53279. {
  53280. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53281. .withMultipliedAlpha (0.5f));
  53282. }
  53283. else if (isMenuOpen || isMouseOverItem)
  53284. {
  53285. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53286. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53287. }
  53288. else
  53289. {
  53290. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53291. }
  53292. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53293. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53294. }
  53295. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53296. TextEditor& textEditor)
  53297. {
  53298. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53299. }
  53300. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53301. {
  53302. if (textEditor.isEnabled())
  53303. {
  53304. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53305. {
  53306. const int border = 2;
  53307. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53308. g.drawRect (0, 0, width, height, border);
  53309. g.setOpacity (1.0f);
  53310. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53311. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53312. }
  53313. else
  53314. {
  53315. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53316. g.drawRect (0, 0, width, height);
  53317. g.setOpacity (1.0f);
  53318. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53319. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53320. }
  53321. }
  53322. }
  53323. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53324. const bool isButtonDown,
  53325. int buttonX, int buttonY,
  53326. int buttonW, int buttonH,
  53327. ComboBox& box)
  53328. {
  53329. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53330. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53331. {
  53332. g.setColour (box.findColour (TextButton::buttonColourId));
  53333. g.drawRect (0, 0, width, height, 2);
  53334. }
  53335. else
  53336. {
  53337. g.setColour (box.findColour (ComboBox::outlineColourId));
  53338. g.drawRect (0, 0, width, height);
  53339. }
  53340. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53341. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53342. box.hasKeyboardFocus (true),
  53343. false, isButtonDown)
  53344. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53345. drawGlassLozenge (g,
  53346. buttonX + outlineThickness, buttonY + outlineThickness,
  53347. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53348. baseColour, outlineThickness, -1.0f,
  53349. true, true, true, true);
  53350. if (box.isEnabled())
  53351. {
  53352. const float arrowX = 0.3f;
  53353. const float arrowH = 0.2f;
  53354. Path p;
  53355. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53356. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53357. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53358. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53359. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53360. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53361. g.setColour (box.findColour (ComboBox::arrowColourId));
  53362. g.fillPath (p);
  53363. }
  53364. }
  53365. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53366. {
  53367. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53368. }
  53369. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53370. {
  53371. return new Label (String::empty, String::empty);
  53372. }
  53373. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53374. {
  53375. label.setBounds (1, 1,
  53376. box.getWidth() + 3 - box.getHeight(),
  53377. box.getHeight() - 2);
  53378. label.setFont (getComboBoxFont (box));
  53379. }
  53380. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53381. {
  53382. g.fillAll (label.findColour (Label::backgroundColourId));
  53383. if (! label.isBeingEdited())
  53384. {
  53385. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53386. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53387. g.setFont (label.getFont());
  53388. g.drawFittedText (label.getText(),
  53389. label.getHorizontalBorderSize(),
  53390. label.getVerticalBorderSize(),
  53391. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53392. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53393. label.getJustificationType(),
  53394. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53395. label.getMinimumHorizontalScale());
  53396. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53397. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53398. }
  53399. else if (label.isEnabled())
  53400. {
  53401. g.setColour (label.findColour (Label::outlineColourId));
  53402. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53403. }
  53404. }
  53405. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53406. int x, int y,
  53407. int width, int height,
  53408. float /*sliderPos*/,
  53409. float /*minSliderPos*/,
  53410. float /*maxSliderPos*/,
  53411. const Slider::SliderStyle /*style*/,
  53412. Slider& slider)
  53413. {
  53414. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53415. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53416. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53417. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53418. Path indent;
  53419. if (slider.isHorizontal())
  53420. {
  53421. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53422. const float ih = sliderRadius;
  53423. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53424. gradCol2, 0.0f, iy + ih, false));
  53425. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53426. width + sliderRadius, ih,
  53427. 5.0f);
  53428. g.fillPath (indent);
  53429. }
  53430. else
  53431. {
  53432. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53433. const float iw = sliderRadius;
  53434. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53435. gradCol2, ix + iw, 0.0f, false));
  53436. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53437. iw, height + sliderRadius,
  53438. 5.0f);
  53439. g.fillPath (indent);
  53440. }
  53441. g.setColour (Colour (0x4c000000));
  53442. g.strokePath (indent, PathStrokeType (0.5f));
  53443. }
  53444. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53445. int x, int y,
  53446. int width, int height,
  53447. float sliderPos,
  53448. float minSliderPos,
  53449. float maxSliderPos,
  53450. const Slider::SliderStyle style,
  53451. Slider& slider)
  53452. {
  53453. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53454. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53455. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53456. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53457. slider.isMouseButtonDown() && slider.isEnabled()));
  53458. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53459. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53460. {
  53461. float kx, ky;
  53462. if (style == Slider::LinearVertical)
  53463. {
  53464. kx = x + width * 0.5f;
  53465. ky = sliderPos;
  53466. }
  53467. else
  53468. {
  53469. kx = sliderPos;
  53470. ky = y + height * 0.5f;
  53471. }
  53472. drawGlassSphere (g,
  53473. kx - sliderRadius,
  53474. ky - sliderRadius,
  53475. sliderRadius * 2.0f,
  53476. knobColour, outlineThickness);
  53477. }
  53478. else
  53479. {
  53480. if (style == Slider::ThreeValueVertical)
  53481. {
  53482. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53483. sliderPos - sliderRadius,
  53484. sliderRadius * 2.0f,
  53485. knobColour, outlineThickness);
  53486. }
  53487. else if (style == Slider::ThreeValueHorizontal)
  53488. {
  53489. drawGlassSphere (g,sliderPos - sliderRadius,
  53490. y + height * 0.5f - sliderRadius,
  53491. sliderRadius * 2.0f,
  53492. knobColour, outlineThickness);
  53493. }
  53494. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53495. {
  53496. const float sr = jmin (sliderRadius, width * 0.4f);
  53497. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53498. minSliderPos - sliderRadius,
  53499. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53500. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53501. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53502. }
  53503. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53504. {
  53505. const float sr = jmin (sliderRadius, height * 0.4f);
  53506. drawGlassPointer (g, minSliderPos - sr,
  53507. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53508. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53509. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53510. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53511. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53512. }
  53513. }
  53514. }
  53515. void LookAndFeel::drawLinearSlider (Graphics& g,
  53516. int x, int y,
  53517. int width, int height,
  53518. float sliderPos,
  53519. float minSliderPos,
  53520. float maxSliderPos,
  53521. const Slider::SliderStyle style,
  53522. Slider& slider)
  53523. {
  53524. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53525. if (style == Slider::LinearBar)
  53526. {
  53527. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53528. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53529. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53530. false,
  53531. isMouseOver,
  53532. isMouseOver || slider.isMouseButtonDown()));
  53533. drawShinyButtonShape (g,
  53534. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53535. baseColour,
  53536. slider.isEnabled() ? 0.9f : 0.3f,
  53537. true, true, true, true);
  53538. }
  53539. else
  53540. {
  53541. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53542. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53543. }
  53544. }
  53545. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53546. {
  53547. return jmin (7,
  53548. slider.getHeight() / 2,
  53549. slider.getWidth() / 2) + 2;
  53550. }
  53551. void LookAndFeel::drawRotarySlider (Graphics& g,
  53552. int x, int y,
  53553. int width, int height,
  53554. float sliderPos,
  53555. const float rotaryStartAngle,
  53556. const float rotaryEndAngle,
  53557. Slider& slider)
  53558. {
  53559. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53560. const float centreX = x + width * 0.5f;
  53561. const float centreY = y + height * 0.5f;
  53562. const float rx = centreX - radius;
  53563. const float ry = centreY - radius;
  53564. const float rw = radius * 2.0f;
  53565. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53566. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53567. if (radius > 12.0f)
  53568. {
  53569. if (slider.isEnabled())
  53570. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53571. else
  53572. g.setColour (Colour (0x80808080));
  53573. const float thickness = 0.7f;
  53574. {
  53575. Path filledArc;
  53576. filledArc.addPieSegment (rx, ry, rw, rw,
  53577. rotaryStartAngle,
  53578. angle,
  53579. thickness);
  53580. g.fillPath (filledArc);
  53581. }
  53582. if (thickness > 0)
  53583. {
  53584. const float innerRadius = radius * 0.2f;
  53585. Path p;
  53586. p.addTriangle (-innerRadius, 0.0f,
  53587. 0.0f, -radius * thickness * 1.1f,
  53588. innerRadius, 0.0f);
  53589. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53590. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53591. }
  53592. if (slider.isEnabled())
  53593. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53594. else
  53595. g.setColour (Colour (0x80808080));
  53596. Path outlineArc;
  53597. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53598. outlineArc.closeSubPath();
  53599. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53600. }
  53601. else
  53602. {
  53603. if (slider.isEnabled())
  53604. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53605. else
  53606. g.setColour (Colour (0x80808080));
  53607. Path p;
  53608. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53609. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53610. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53611. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53612. }
  53613. }
  53614. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53615. {
  53616. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53617. }
  53618. class SliderLabelComp : public Label
  53619. {
  53620. public:
  53621. SliderLabelComp() : Label (String::empty, String::empty) {}
  53622. ~SliderLabelComp() {}
  53623. void mouseWheelMove (const MouseEvent&, float, float) {}
  53624. };
  53625. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53626. {
  53627. Label* const l = new SliderLabelComp();
  53628. l->setJustificationType (Justification::centred);
  53629. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53630. l->setColour (Label::backgroundColourId,
  53631. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53632. : slider.findColour (Slider::textBoxBackgroundColourId));
  53633. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53634. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53635. l->setColour (TextEditor::backgroundColourId,
  53636. slider.findColour (Slider::textBoxBackgroundColourId)
  53637. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53638. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53639. return l;
  53640. }
  53641. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53642. {
  53643. return 0;
  53644. }
  53645. static const TextLayout layoutTooltipText (const String& text) throw()
  53646. {
  53647. const float tooltipFontSize = 12.0f;
  53648. const int maxToolTipWidth = 400;
  53649. const Font f (tooltipFontSize, Font::bold);
  53650. TextLayout tl (text, f);
  53651. tl.layout (maxToolTipWidth, Justification::left, true);
  53652. return tl;
  53653. }
  53654. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53655. {
  53656. const TextLayout tl (layoutTooltipText (tipText));
  53657. width = tl.getWidth() + 14;
  53658. height = tl.getHeight() + 6;
  53659. }
  53660. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53661. {
  53662. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53663. const Colour textCol (findColour (TooltipWindow::textColourId));
  53664. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53665. g.setColour (findColour (TooltipWindow::outlineColourId));
  53666. g.drawRect (0, 0, width, height, 1);
  53667. #endif
  53668. const TextLayout tl (layoutTooltipText (text));
  53669. g.setColour (findColour (TooltipWindow::textColourId));
  53670. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53671. }
  53672. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53673. {
  53674. return new TextButton (text, TRANS("click to browse for a different file"));
  53675. }
  53676. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53677. ComboBox* filenameBox,
  53678. Button* browseButton)
  53679. {
  53680. browseButton->setSize (80, filenameComp.getHeight());
  53681. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53682. if (tb != 0)
  53683. tb->changeWidthToFitText();
  53684. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53685. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53686. }
  53687. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53688. int imageX, int imageY, int imageW, int imageH,
  53689. const Colour& overlayColour,
  53690. float imageOpacity,
  53691. ImageButton& button)
  53692. {
  53693. if (! button.isEnabled())
  53694. imageOpacity *= 0.3f;
  53695. if (! overlayColour.isOpaque())
  53696. {
  53697. g.setOpacity (imageOpacity);
  53698. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53699. 0, 0, image->getWidth(), image->getHeight(), false);
  53700. }
  53701. if (! overlayColour.isTransparent())
  53702. {
  53703. g.setColour (overlayColour);
  53704. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53705. 0, 0, image->getWidth(), image->getHeight(), true);
  53706. }
  53707. }
  53708. void LookAndFeel::drawCornerResizer (Graphics& g,
  53709. int w, int h,
  53710. bool /*isMouseOver*/,
  53711. bool /*isMouseDragging*/)
  53712. {
  53713. const float lineThickness = jmin (w, h) * 0.075f;
  53714. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53715. {
  53716. g.setColour (Colours::lightgrey);
  53717. g.drawLine (w * i,
  53718. h + 1.0f,
  53719. w + 1.0f,
  53720. h * i,
  53721. lineThickness);
  53722. g.setColour (Colours::darkgrey);
  53723. g.drawLine (w * i + lineThickness,
  53724. h + 1.0f,
  53725. w + 1.0f,
  53726. h * i + lineThickness,
  53727. lineThickness);
  53728. }
  53729. }
  53730. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53731. {
  53732. if (! border.isEmpty())
  53733. {
  53734. const Rectangle<int> fullSize (0, 0, w, h);
  53735. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53736. g.saveState();
  53737. g.excludeClipRegion (centreArea);
  53738. g.setColour (Colour (0x50000000));
  53739. g.drawRect (fullSize);
  53740. g.setColour (Colour (0x19000000));
  53741. g.drawRect (centreArea.expanded (1, 1));
  53742. g.restoreState();
  53743. }
  53744. }
  53745. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53746. const BorderSize& /*border*/, ResizableWindow& window)
  53747. {
  53748. g.fillAll (window.getBackgroundColour());
  53749. }
  53750. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53751. const BorderSize& /*border*/, ResizableWindow&)
  53752. {
  53753. }
  53754. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53755. Graphics& g, int w, int h,
  53756. int titleSpaceX, int titleSpaceW,
  53757. const Image* icon,
  53758. bool drawTitleTextOnLeft)
  53759. {
  53760. const bool isActive = window.isActiveWindow();
  53761. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53762. 0.0f, 0.0f,
  53763. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53764. 0.0f, (float) h, false));
  53765. g.fillAll();
  53766. Font font (h * 0.65f, Font::bold);
  53767. g.setFont (font);
  53768. int textW = font.getStringWidth (window.getName());
  53769. int iconW = 0;
  53770. int iconH = 0;
  53771. if (icon != 0)
  53772. {
  53773. iconH = (int) font.getHeight();
  53774. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53775. }
  53776. textW = jmin (titleSpaceW, textW + iconW);
  53777. int textX = drawTitleTextOnLeft ? titleSpaceX
  53778. : jmax (titleSpaceX, (w - textW) / 2);
  53779. if (textX + textW > titleSpaceX + titleSpaceW)
  53780. textX = titleSpaceX + titleSpaceW - textW;
  53781. if (icon != 0)
  53782. {
  53783. g.setOpacity (isActive ? 1.0f : 0.6f);
  53784. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53785. RectanglePlacement::centred, false);
  53786. textX += iconW;
  53787. textW -= iconW;
  53788. }
  53789. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53790. g.setColour (findColour (DocumentWindow::textColourId));
  53791. else
  53792. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53793. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53794. }
  53795. class GlassWindowButton : public Button
  53796. {
  53797. public:
  53798. GlassWindowButton (const String& name, const Colour& col,
  53799. const Path& normalShape_,
  53800. const Path& toggledShape_) throw()
  53801. : Button (name),
  53802. colour (col),
  53803. normalShape (normalShape_),
  53804. toggledShape (toggledShape_)
  53805. {
  53806. }
  53807. ~GlassWindowButton()
  53808. {
  53809. }
  53810. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53811. {
  53812. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53813. if (! isEnabled())
  53814. alpha *= 0.5f;
  53815. float x = 0, y = 0, diam;
  53816. if (getWidth() < getHeight())
  53817. {
  53818. diam = (float) getWidth();
  53819. y = (getHeight() - getWidth()) * 0.5f;
  53820. }
  53821. else
  53822. {
  53823. diam = (float) getHeight();
  53824. y = (getWidth() - getHeight()) * 0.5f;
  53825. }
  53826. x += diam * 0.05f;
  53827. y += diam * 0.05f;
  53828. diam *= 0.9f;
  53829. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53830. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53831. g.fillEllipse (x, y, diam, diam);
  53832. x += 2.0f;
  53833. y += 2.0f;
  53834. diam -= 4.0f;
  53835. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53836. Path& p = getToggleState() ? toggledShape : normalShape;
  53837. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53838. diam * 0.4f, diam * 0.4f, true));
  53839. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53840. g.fillPath (p, t);
  53841. }
  53842. juce_UseDebuggingNewOperator
  53843. private:
  53844. Colour colour;
  53845. Path normalShape, toggledShape;
  53846. GlassWindowButton (const GlassWindowButton&);
  53847. GlassWindowButton& operator= (const GlassWindowButton&);
  53848. };
  53849. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53850. {
  53851. Path shape;
  53852. const float crossThickness = 0.25f;
  53853. if (buttonType == DocumentWindow::closeButton)
  53854. {
  53855. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53856. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53857. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53858. }
  53859. else if (buttonType == DocumentWindow::minimiseButton)
  53860. {
  53861. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53862. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53863. }
  53864. else if (buttonType == DocumentWindow::maximiseButton)
  53865. {
  53866. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53867. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53868. Path fullscreenShape;
  53869. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53870. fullscreenShape.lineTo (0.0f, 100.0f);
  53871. fullscreenShape.lineTo (0.0f, 0.0f);
  53872. fullscreenShape.lineTo (100.0f, 0.0f);
  53873. fullscreenShape.lineTo (100.0f, 45.0f);
  53874. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53875. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53876. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53877. }
  53878. jassertfalse;
  53879. return 0;
  53880. }
  53881. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53882. int titleBarX,
  53883. int titleBarY,
  53884. int titleBarW,
  53885. int titleBarH,
  53886. Button* minimiseButton,
  53887. Button* maximiseButton,
  53888. Button* closeButton,
  53889. bool positionTitleBarButtonsOnLeft)
  53890. {
  53891. const int buttonW = titleBarH - titleBarH / 8;
  53892. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53893. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53894. if (closeButton != 0)
  53895. {
  53896. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53897. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53898. }
  53899. if (positionTitleBarButtonsOnLeft)
  53900. swapVariables (minimiseButton, maximiseButton);
  53901. if (maximiseButton != 0)
  53902. {
  53903. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53904. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53905. }
  53906. if (minimiseButton != 0)
  53907. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53908. }
  53909. int LookAndFeel::getDefaultMenuBarHeight()
  53910. {
  53911. return 24;
  53912. }
  53913. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53914. {
  53915. return new DropShadower (0.4f, 1, 5, 10);
  53916. }
  53917. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53918. int w, int h,
  53919. bool /*isVerticalBar*/,
  53920. bool isMouseOver,
  53921. bool isMouseDragging)
  53922. {
  53923. float alpha = 0.5f;
  53924. if (isMouseOver || isMouseDragging)
  53925. {
  53926. g.fillAll (Colour (0x190000ff));
  53927. alpha = 1.0f;
  53928. }
  53929. const float cx = w * 0.5f;
  53930. const float cy = h * 0.5f;
  53931. const float cr = jmin (w, h) * 0.4f;
  53932. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53933. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53934. true));
  53935. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53936. }
  53937. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53938. const String& text,
  53939. const Justification& position,
  53940. GroupComponent& group)
  53941. {
  53942. const float textH = 15.0f;
  53943. const float indent = 3.0f;
  53944. const float textEdgeGap = 4.0f;
  53945. float cs = 5.0f;
  53946. Font f (textH);
  53947. Path p;
  53948. float x = indent;
  53949. float y = f.getAscent() - 3.0f;
  53950. float w = jmax (0.0f, width - x * 2.0f);
  53951. float h = jmax (0.0f, height - y - indent);
  53952. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53953. const float cs2 = 2.0f * cs;
  53954. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53955. float textX = cs + textEdgeGap;
  53956. if (position.testFlags (Justification::horizontallyCentred))
  53957. textX = cs + (w - cs2 - textW) * 0.5f;
  53958. else if (position.testFlags (Justification::right))
  53959. textX = w - cs - textW - textEdgeGap;
  53960. p.startNewSubPath (x + textX + textW, y);
  53961. p.lineTo (x + w - cs, y);
  53962. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53963. p.lineTo (x + w, y + h - cs);
  53964. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53965. p.lineTo (x + cs, y + h);
  53966. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53967. p.lineTo (x, y + cs);
  53968. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53969. p.lineTo (x + textX, y);
  53970. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53971. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53972. .withMultipliedAlpha (alpha));
  53973. g.strokePath (p, PathStrokeType (2.0f));
  53974. g.setColour (group.findColour (GroupComponent::textColourId)
  53975. .withMultipliedAlpha (alpha));
  53976. g.setFont (f);
  53977. g.drawText (text,
  53978. roundToInt (x + textX), 0,
  53979. roundToInt (textW),
  53980. roundToInt (textH),
  53981. Justification::centred, true);
  53982. }
  53983. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53984. {
  53985. return 1 + tabDepth / 3;
  53986. }
  53987. int LookAndFeel::getTabButtonSpaceAroundImage()
  53988. {
  53989. return 4;
  53990. }
  53991. void LookAndFeel::createTabButtonShape (Path& p,
  53992. int width, int height,
  53993. int /*tabIndex*/,
  53994. const String& /*text*/,
  53995. Button& /*button*/,
  53996. TabbedButtonBar::Orientation orientation,
  53997. const bool /*isMouseOver*/,
  53998. const bool /*isMouseDown*/,
  53999. const bool /*isFrontTab*/)
  54000. {
  54001. const float w = (float) width;
  54002. const float h = (float) height;
  54003. float length = w;
  54004. float depth = h;
  54005. if (orientation == TabbedButtonBar::TabsAtLeft
  54006. || orientation == TabbedButtonBar::TabsAtRight)
  54007. {
  54008. swapVariables (length, depth);
  54009. }
  54010. const float indent = (float) getTabButtonOverlap ((int) depth);
  54011. const float overhang = 4.0f;
  54012. if (orientation == TabbedButtonBar::TabsAtLeft)
  54013. {
  54014. p.startNewSubPath (w, 0.0f);
  54015. p.lineTo (0.0f, indent);
  54016. p.lineTo (0.0f, h - indent);
  54017. p.lineTo (w, h);
  54018. p.lineTo (w + overhang, h + overhang);
  54019. p.lineTo (w + overhang, -overhang);
  54020. }
  54021. else if (orientation == TabbedButtonBar::TabsAtRight)
  54022. {
  54023. p.startNewSubPath (0.0f, 0.0f);
  54024. p.lineTo (w, indent);
  54025. p.lineTo (w, h - indent);
  54026. p.lineTo (0.0f, h);
  54027. p.lineTo (-overhang, h + overhang);
  54028. p.lineTo (-overhang, -overhang);
  54029. }
  54030. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54031. {
  54032. p.startNewSubPath (0.0f, 0.0f);
  54033. p.lineTo (indent, h);
  54034. p.lineTo (w - indent, h);
  54035. p.lineTo (w, 0.0f);
  54036. p.lineTo (w + overhang, -overhang);
  54037. p.lineTo (-overhang, -overhang);
  54038. }
  54039. else
  54040. {
  54041. p.startNewSubPath (0.0f, h);
  54042. p.lineTo (indent, 0.0f);
  54043. p.lineTo (w - indent, 0.0f);
  54044. p.lineTo (w, h);
  54045. p.lineTo (w + overhang, h + overhang);
  54046. p.lineTo (-overhang, h + overhang);
  54047. }
  54048. p.closeSubPath();
  54049. p = p.createPathWithRoundedCorners (3.0f);
  54050. }
  54051. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54052. const Path& path,
  54053. const Colour& preferredColour,
  54054. int /*tabIndex*/,
  54055. const String& /*text*/,
  54056. Button& button,
  54057. TabbedButtonBar::Orientation /*orientation*/,
  54058. const bool /*isMouseOver*/,
  54059. const bool /*isMouseDown*/,
  54060. const bool isFrontTab)
  54061. {
  54062. g.setColour (isFrontTab ? preferredColour
  54063. : preferredColour.withMultipliedAlpha (0.9f));
  54064. g.fillPath (path);
  54065. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54066. : TabbedButtonBar::tabOutlineColourId, false)
  54067. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54068. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54069. }
  54070. void LookAndFeel::drawTabButtonText (Graphics& g,
  54071. int x, int y, int w, int h,
  54072. const Colour& preferredBackgroundColour,
  54073. int /*tabIndex*/,
  54074. const String& text,
  54075. Button& button,
  54076. TabbedButtonBar::Orientation orientation,
  54077. const bool isMouseOver,
  54078. const bool isMouseDown,
  54079. const bool isFrontTab)
  54080. {
  54081. int length = w;
  54082. int depth = h;
  54083. if (orientation == TabbedButtonBar::TabsAtLeft
  54084. || orientation == TabbedButtonBar::TabsAtRight)
  54085. {
  54086. swapVariables (length, depth);
  54087. }
  54088. Font font (depth * 0.6f);
  54089. font.setUnderline (button.hasKeyboardFocus (false));
  54090. GlyphArrangement textLayout;
  54091. textLayout.addFittedText (font, text.trim(),
  54092. 0.0f, 0.0f, (float) length, (float) depth,
  54093. Justification::centred,
  54094. jmax (1, depth / 12));
  54095. AffineTransform transform;
  54096. if (orientation == TabbedButtonBar::TabsAtLeft)
  54097. {
  54098. transform = transform.rotated (float_Pi * -0.5f)
  54099. .translated ((float) x, (float) (y + h));
  54100. }
  54101. else if (orientation == TabbedButtonBar::TabsAtRight)
  54102. {
  54103. transform = transform.rotated (float_Pi * 0.5f)
  54104. .translated ((float) (x + w), (float) y);
  54105. }
  54106. else
  54107. {
  54108. transform = transform.translated ((float) x, (float) y);
  54109. }
  54110. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54111. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54112. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54113. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54114. else
  54115. g.setColour (preferredBackgroundColour.contrasting());
  54116. if (! (isMouseOver || isMouseDown))
  54117. g.setOpacity (0.8f);
  54118. if (! button.isEnabled())
  54119. g.setOpacity (0.3f);
  54120. textLayout.draw (g, transform);
  54121. }
  54122. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54123. const String& text,
  54124. int tabDepth,
  54125. Button&)
  54126. {
  54127. Font f (tabDepth * 0.6f);
  54128. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54129. }
  54130. void LookAndFeel::drawTabButton (Graphics& g,
  54131. int w, int h,
  54132. const Colour& preferredColour,
  54133. int tabIndex,
  54134. const String& text,
  54135. Button& button,
  54136. TabbedButtonBar::Orientation orientation,
  54137. const bool isMouseOver,
  54138. const bool isMouseDown,
  54139. const bool isFrontTab)
  54140. {
  54141. int length = w;
  54142. int depth = h;
  54143. if (orientation == TabbedButtonBar::TabsAtLeft
  54144. || orientation == TabbedButtonBar::TabsAtRight)
  54145. {
  54146. swapVariables (length, depth);
  54147. }
  54148. Path tabShape;
  54149. createTabButtonShape (tabShape, w, h,
  54150. tabIndex, text, button, orientation,
  54151. isMouseOver, isMouseDown, isFrontTab);
  54152. fillTabButtonShape (g, tabShape, preferredColour,
  54153. tabIndex, text, button, orientation,
  54154. isMouseOver, isMouseDown, isFrontTab);
  54155. const int indent = getTabButtonOverlap (depth);
  54156. int x = 0, y = 0;
  54157. if (orientation == TabbedButtonBar::TabsAtLeft
  54158. || orientation == TabbedButtonBar::TabsAtRight)
  54159. {
  54160. y += indent;
  54161. h -= indent * 2;
  54162. }
  54163. else
  54164. {
  54165. x += indent;
  54166. w -= indent * 2;
  54167. }
  54168. drawTabButtonText (g, x, y, w, h, preferredColour,
  54169. tabIndex, text, button, orientation,
  54170. isMouseOver, isMouseDown, isFrontTab);
  54171. }
  54172. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54173. int w, int h,
  54174. TabbedButtonBar& tabBar,
  54175. TabbedButtonBar::Orientation orientation)
  54176. {
  54177. const float shadowSize = 0.2f;
  54178. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54179. Rectangle<int> shadowRect;
  54180. if (orientation == TabbedButtonBar::TabsAtLeft)
  54181. {
  54182. x1 = (float) w;
  54183. x2 = w * (1.0f - shadowSize);
  54184. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54185. }
  54186. else if (orientation == TabbedButtonBar::TabsAtRight)
  54187. {
  54188. x2 = w * shadowSize;
  54189. shadowRect.setBounds (0, 0, (int) x2, h);
  54190. }
  54191. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54192. {
  54193. y2 = h * shadowSize;
  54194. shadowRect.setBounds (0, 0, w, (int) y2);
  54195. }
  54196. else
  54197. {
  54198. y1 = (float) h;
  54199. y2 = h * (1.0f - shadowSize);
  54200. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54201. }
  54202. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54203. Colours::transparentBlack, x2, y2, false));
  54204. shadowRect.expand (2, 2);
  54205. g.fillRect (shadowRect);
  54206. g.setColour (Colour (0x80000000));
  54207. if (orientation == TabbedButtonBar::TabsAtLeft)
  54208. {
  54209. g.fillRect (w - 1, 0, 1, h);
  54210. }
  54211. else if (orientation == TabbedButtonBar::TabsAtRight)
  54212. {
  54213. g.fillRect (0, 0, 1, h);
  54214. }
  54215. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54216. {
  54217. g.fillRect (0, 0, w, 1);
  54218. }
  54219. else
  54220. {
  54221. g.fillRect (0, h - 1, w, 1);
  54222. }
  54223. }
  54224. Button* LookAndFeel::createTabBarExtrasButton()
  54225. {
  54226. const float thickness = 7.0f;
  54227. const float indent = 22.0f;
  54228. Path p;
  54229. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54230. DrawablePath ellipse;
  54231. ellipse.setPath (p);
  54232. ellipse.setFill (Colour (0x99ffffff));
  54233. p.clear();
  54234. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54235. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54236. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54237. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54238. p.setUsingNonZeroWinding (false);
  54239. DrawablePath dp;
  54240. dp.setPath (p);
  54241. dp.setFill (Colour (0x59000000));
  54242. DrawableComposite normalImage;
  54243. normalImage.insertDrawable (ellipse);
  54244. normalImage.insertDrawable (dp);
  54245. dp.setFill (Colour (0xcc000000));
  54246. DrawableComposite overImage;
  54247. overImage.insertDrawable (ellipse);
  54248. overImage.insertDrawable (dp);
  54249. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54250. db->setImages (&normalImage, &overImage, 0);
  54251. return db;
  54252. }
  54253. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54254. {
  54255. g.fillAll (Colours::white);
  54256. const int w = header.getWidth();
  54257. const int h = header.getHeight();
  54258. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54259. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54260. false));
  54261. g.fillRect (0, h / 2, w, h);
  54262. g.setColour (Colour (0x33000000));
  54263. g.fillRect (0, h - 1, w, 1);
  54264. for (int i = header.getNumColumns (true); --i >= 0;)
  54265. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54266. }
  54267. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54268. int width, int height,
  54269. bool isMouseOver, bool isMouseDown,
  54270. int columnFlags)
  54271. {
  54272. if (isMouseDown)
  54273. g.fillAll (Colour (0x8899aadd));
  54274. else if (isMouseOver)
  54275. g.fillAll (Colour (0x5599aadd));
  54276. int rightOfText = width - 4;
  54277. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54278. {
  54279. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54280. const float bottom = height - top;
  54281. const float w = height * 0.5f;
  54282. const float x = rightOfText - (w * 1.25f);
  54283. rightOfText = (int) x;
  54284. Path sortArrow;
  54285. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54286. g.setColour (Colour (0x99000000));
  54287. g.fillPath (sortArrow);
  54288. }
  54289. g.setColour (Colours::black);
  54290. g.setFont (height * 0.5f, Font::bold);
  54291. const int textX = 4;
  54292. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54293. }
  54294. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54295. {
  54296. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54297. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54298. background.darker (0.1f),
  54299. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54300. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54301. false));
  54302. g.fillAll();
  54303. }
  54304. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54305. {
  54306. return createTabBarExtrasButton();
  54307. }
  54308. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54309. bool isMouseOver, bool isMouseDown,
  54310. ToolbarItemComponent& component)
  54311. {
  54312. if (isMouseDown)
  54313. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54314. else if (isMouseOver)
  54315. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54316. }
  54317. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54318. const String& text, ToolbarItemComponent& component)
  54319. {
  54320. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54321. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54322. const float fontHeight = jmin (14.0f, height * 0.85f);
  54323. g.setFont (fontHeight);
  54324. g.drawFittedText (text,
  54325. x, y, width, height,
  54326. Justification::centred,
  54327. jmax (1, height / (int) fontHeight));
  54328. }
  54329. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54330. bool isOpen, int width, int height)
  54331. {
  54332. const int buttonSize = (height * 3) / 4;
  54333. const int buttonIndent = (height - buttonSize) / 2;
  54334. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54335. const int textX = buttonIndent * 2 + buttonSize + 2;
  54336. g.setColour (Colours::black);
  54337. g.setFont (height * 0.7f, Font::bold);
  54338. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54339. }
  54340. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54341. PropertyComponent&)
  54342. {
  54343. g.setColour (Colour (0x66ffffff));
  54344. g.fillRect (0, 0, width, height - 1);
  54345. }
  54346. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54347. PropertyComponent& component)
  54348. {
  54349. g.setColour (Colours::black);
  54350. if (! component.isEnabled())
  54351. g.setOpacity (0.6f);
  54352. g.setFont (jmin (height, 24) * 0.65f);
  54353. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54354. g.drawFittedText (component.getName(),
  54355. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54356. Justification::centredLeft, 2);
  54357. }
  54358. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54359. {
  54360. return Rectangle<int> (component.getWidth() / 3, 1,
  54361. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54362. }
  54363. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54364. {
  54365. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54366. {
  54367. Graphics g2 (content);
  54368. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54369. g2.fillPath (path);
  54370. g2.setColour (Colours::white.withAlpha (0.8f));
  54371. g2.strokePath (path, PathStrokeType (2.0f));
  54372. }
  54373. DropShadowEffect shadow;
  54374. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54375. shadow.applyEffect (content, g);
  54376. }
  54377. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54378. const String& instructions,
  54379. GlyphArrangement& text,
  54380. int width)
  54381. {
  54382. text.clear();
  54383. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54384. 8.0f, 22.0f, width - 16.0f,
  54385. Justification::centred);
  54386. text.addJustifiedText (Font (14.0f), instructions,
  54387. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54388. Justification::centred);
  54389. }
  54390. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54391. const String& filename, Image* icon,
  54392. const String& fileSizeDescription,
  54393. const String& fileTimeDescription,
  54394. const bool isDirectory,
  54395. const bool isItemSelected,
  54396. const int /*itemIndex*/,
  54397. DirectoryContentsDisplayComponent&)
  54398. {
  54399. if (isItemSelected)
  54400. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54401. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54402. g.setFont (height * 0.7f);
  54403. Image im;
  54404. if (icon != 0)
  54405. im = *icon;
  54406. if (im.isNull())
  54407. im = isDirectory ? getDefaultFolderImage()
  54408. : getDefaultDocumentFileImage();
  54409. const int x = 32;
  54410. if (im.isValid())
  54411. {
  54412. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54413. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54414. false);
  54415. }
  54416. if (width > 450 && ! isDirectory)
  54417. {
  54418. const int sizeX = roundToInt (width * 0.7f);
  54419. const int dateX = roundToInt (width * 0.8f);
  54420. g.drawFittedText (filename,
  54421. x, 0, sizeX - x, height,
  54422. Justification::centredLeft, 1);
  54423. g.setFont (height * 0.5f);
  54424. g.setColour (Colours::darkgrey);
  54425. if (! isDirectory)
  54426. {
  54427. g.drawFittedText (fileSizeDescription,
  54428. sizeX, 0, dateX - sizeX - 8, height,
  54429. Justification::centredRight, 1);
  54430. g.drawFittedText (fileTimeDescription,
  54431. dateX, 0, width - 8 - dateX, height,
  54432. Justification::centredRight, 1);
  54433. }
  54434. }
  54435. else
  54436. {
  54437. g.drawFittedText (filename,
  54438. x, 0, width - x, height,
  54439. Justification::centredLeft, 1);
  54440. }
  54441. }
  54442. Button* LookAndFeel::createFileBrowserGoUpButton()
  54443. {
  54444. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54445. Path arrowPath;
  54446. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54447. DrawablePath arrowImage;
  54448. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54449. arrowImage.setPath (arrowPath);
  54450. goUpButton->setImages (&arrowImage);
  54451. return goUpButton;
  54452. }
  54453. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54454. DirectoryContentsDisplayComponent* fileListComponent,
  54455. FilePreviewComponent* previewComp,
  54456. ComboBox* currentPathBox,
  54457. TextEditor* filenameBox,
  54458. Button* goUpButton)
  54459. {
  54460. const int x = 8;
  54461. int w = browserComp.getWidth() - x - x;
  54462. if (previewComp != 0)
  54463. {
  54464. const int previewWidth = w / 3;
  54465. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54466. w -= previewWidth + 4;
  54467. }
  54468. int y = 4;
  54469. const int controlsHeight = 22;
  54470. const int bottomSectionHeight = controlsHeight + 8;
  54471. const int upButtonWidth = 50;
  54472. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54473. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54474. y += controlsHeight + 4;
  54475. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54476. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54477. y = listAsComp->getBottom() + 4;
  54478. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54479. }
  54480. const Image LookAndFeel::getDefaultFolderImage()
  54481. {
  54482. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  54483. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  54484. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  54485. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  54486. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  54487. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  54488. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  54489. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  54490. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  54491. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  54492. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  54493. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  54494. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  54495. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  54496. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  54497. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  54498. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  54499. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  54500. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  54501. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  54502. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  54503. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  54504. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  54505. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  54506. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  54507. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  54508. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  54509. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  54510. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  54511. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  54512. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  54513. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  54514. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  54515. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  54516. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  54517. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  54518. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  54519. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  54520. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  54521. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  54522. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  54523. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  54524. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  54525. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  54526. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54527. }
  54528. const Image LookAndFeel::getDefaultDocumentFileImage()
  54529. {
  54530. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  54531. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  54532. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  54533. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  54534. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  54535. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  54536. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  54537. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  54538. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  54539. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  54540. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  54541. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  54542. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  54543. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  54544. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  54545. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  54546. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  54547. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  54548. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  54549. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  54550. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  54551. 174,66,96,130,0,0};
  54552. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54553. }
  54554. void LookAndFeel::playAlertSound()
  54555. {
  54556. PlatformUtilities::beep();
  54557. }
  54558. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54559. {
  54560. g.setColour (Colours::white.withAlpha (0.7f));
  54561. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54562. g.setColour (Colours::black.withAlpha (0.2f));
  54563. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54564. const int totalBlocks = 7;
  54565. const int numBlocks = roundToInt (totalBlocks * level);
  54566. const float w = (width - 6.0f) / (float) totalBlocks;
  54567. for (int i = 0; i < totalBlocks; ++i)
  54568. {
  54569. if (i >= numBlocks)
  54570. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54571. else
  54572. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54573. : Colours::red);
  54574. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54575. }
  54576. }
  54577. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54578. {
  54579. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54580. if (keyDescription.isNotEmpty())
  54581. {
  54582. if (button.isEnabled())
  54583. {
  54584. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54585. g.fillAll (textColour.withAlpha (alpha));
  54586. g.setOpacity (0.3f);
  54587. g.drawBevel (0, 0, width, height, 2);
  54588. }
  54589. g.setColour (textColour);
  54590. g.setFont (height * 0.6f);
  54591. g.drawFittedText (keyDescription,
  54592. 3, 0, width - 6, height,
  54593. Justification::centred, 1);
  54594. }
  54595. else
  54596. {
  54597. const float thickness = 7.0f;
  54598. const float indent = 22.0f;
  54599. Path p;
  54600. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54601. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54602. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54603. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54604. p.setUsingNonZeroWinding (false);
  54605. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54606. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54607. }
  54608. if (button.hasKeyboardFocus (false))
  54609. {
  54610. g.setColour (textColour.withAlpha (0.4f));
  54611. g.drawRect (0, 0, width, height);
  54612. }
  54613. }
  54614. static void createRoundedPath (Path& p,
  54615. const float x, const float y,
  54616. const float w, const float h,
  54617. const float cs,
  54618. const bool curveTopLeft, const bool curveTopRight,
  54619. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54620. {
  54621. const float cs2 = 2.0f * cs;
  54622. if (curveTopLeft)
  54623. {
  54624. p.startNewSubPath (x, y + cs);
  54625. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54626. }
  54627. else
  54628. {
  54629. p.startNewSubPath (x, y);
  54630. }
  54631. if (curveTopRight)
  54632. {
  54633. p.lineTo (x + w - cs, y);
  54634. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54635. }
  54636. else
  54637. {
  54638. p.lineTo (x + w, y);
  54639. }
  54640. if (curveBottomRight)
  54641. {
  54642. p.lineTo (x + w, y + h - cs);
  54643. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54644. }
  54645. else
  54646. {
  54647. p.lineTo (x + w, y + h);
  54648. }
  54649. if (curveBottomLeft)
  54650. {
  54651. p.lineTo (x + cs, y + h);
  54652. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54653. }
  54654. else
  54655. {
  54656. p.lineTo (x, y + h);
  54657. }
  54658. p.closeSubPath();
  54659. }
  54660. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54661. float x, float y, float w, float h,
  54662. float maxCornerSize,
  54663. const Colour& baseColour,
  54664. const float strokeWidth,
  54665. const bool flatOnLeft,
  54666. const bool flatOnRight,
  54667. const bool flatOnTop,
  54668. const bool flatOnBottom) throw()
  54669. {
  54670. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54671. return;
  54672. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54673. Path outline;
  54674. createRoundedPath (outline, x, y, w, h, cs,
  54675. ! (flatOnLeft || flatOnTop),
  54676. ! (flatOnRight || flatOnTop),
  54677. ! (flatOnLeft || flatOnBottom),
  54678. ! (flatOnRight || flatOnBottom));
  54679. ColourGradient cg (baseColour, 0.0f, y,
  54680. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54681. false);
  54682. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54683. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54684. g.setGradientFill (cg);
  54685. g.fillPath (outline);
  54686. g.setColour (Colour (0x80000000));
  54687. g.strokePath (outline, PathStrokeType (strokeWidth));
  54688. }
  54689. void LookAndFeel::drawGlassSphere (Graphics& g,
  54690. const float x, const float y,
  54691. const float diameter,
  54692. const Colour& colour,
  54693. const float outlineThickness) throw()
  54694. {
  54695. if (diameter <= outlineThickness)
  54696. return;
  54697. Path p;
  54698. p.addEllipse (x, y, diameter, diameter);
  54699. {
  54700. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54701. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54702. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54703. g.setGradientFill (cg);
  54704. g.fillPath (p);
  54705. }
  54706. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54707. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54708. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54709. ColourGradient cg (Colours::transparentBlack,
  54710. x + diameter * 0.5f, y + diameter * 0.5f,
  54711. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54712. x, y + diameter * 0.5f, true);
  54713. cg.addColour (0.7, Colours::transparentBlack);
  54714. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54715. g.setGradientFill (cg);
  54716. g.fillPath (p);
  54717. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54718. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54719. }
  54720. void LookAndFeel::drawGlassPointer (Graphics& g,
  54721. const float x, const float y,
  54722. const float diameter,
  54723. const Colour& colour, const float outlineThickness,
  54724. const int direction) throw()
  54725. {
  54726. if (diameter <= outlineThickness)
  54727. return;
  54728. Path p;
  54729. p.startNewSubPath (x + diameter * 0.5f, y);
  54730. p.lineTo (x + diameter, y + diameter * 0.6f);
  54731. p.lineTo (x + diameter, y + diameter);
  54732. p.lineTo (x, y + diameter);
  54733. p.lineTo (x, y + diameter * 0.6f);
  54734. p.closeSubPath();
  54735. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54736. {
  54737. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54738. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54739. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54740. g.setGradientFill (cg);
  54741. g.fillPath (p);
  54742. }
  54743. ColourGradient cg (Colours::transparentBlack,
  54744. x + diameter * 0.5f, y + diameter * 0.5f,
  54745. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54746. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54747. cg.addColour (0.5, Colours::transparentBlack);
  54748. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54749. g.setGradientFill (cg);
  54750. g.fillPath (p);
  54751. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54752. g.strokePath (p, PathStrokeType (outlineThickness));
  54753. }
  54754. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54755. const float x, const float y,
  54756. const float width, const float height,
  54757. const Colour& colour,
  54758. const float outlineThickness,
  54759. const float cornerSize,
  54760. const bool flatOnLeft,
  54761. const bool flatOnRight,
  54762. const bool flatOnTop,
  54763. const bool flatOnBottom) throw()
  54764. {
  54765. if (width <= outlineThickness || height <= outlineThickness)
  54766. return;
  54767. const int intX = (int) x;
  54768. const int intY = (int) y;
  54769. const int intW = (int) width;
  54770. const int intH = (int) height;
  54771. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54772. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54773. const int intEdge = (int) edgeBlurRadius;
  54774. Path outline;
  54775. createRoundedPath (outline, x, y, width, height, cs,
  54776. ! (flatOnLeft || flatOnTop),
  54777. ! (flatOnRight || flatOnTop),
  54778. ! (flatOnLeft || flatOnBottom),
  54779. ! (flatOnRight || flatOnBottom));
  54780. {
  54781. ColourGradient cg (colour.darker (0.2f), 0, y,
  54782. colour.darker (0.2f), 0, y + height, false);
  54783. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54784. cg.addColour (0.4, colour);
  54785. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54786. g.setGradientFill (cg);
  54787. g.fillPath (outline);
  54788. }
  54789. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54790. colour.darker (0.2f), x, y + height * 0.5f, true);
  54791. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54792. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54793. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54794. {
  54795. g.saveState();
  54796. g.setGradientFill (cg);
  54797. g.reduceClipRegion (intX, intY, intEdge, intH);
  54798. g.fillPath (outline);
  54799. g.restoreState();
  54800. }
  54801. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54802. {
  54803. cg.point1.setX (x + width - edgeBlurRadius);
  54804. cg.point2.setX (x + width);
  54805. g.saveState();
  54806. g.setGradientFill (cg);
  54807. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54808. g.fillPath (outline);
  54809. g.restoreState();
  54810. }
  54811. {
  54812. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54813. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54814. Path highlight;
  54815. createRoundedPath (highlight,
  54816. x + leftIndent,
  54817. y + cs * 0.1f,
  54818. width - (leftIndent + rightIndent),
  54819. height * 0.4f, cs * 0.4f,
  54820. ! (flatOnLeft || flatOnTop),
  54821. ! (flatOnRight || flatOnTop),
  54822. ! (flatOnLeft || flatOnBottom),
  54823. ! (flatOnRight || flatOnBottom));
  54824. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54825. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54826. g.fillPath (highlight);
  54827. }
  54828. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54829. g.strokePath (outline, PathStrokeType (outlineThickness));
  54830. }
  54831. END_JUCE_NAMESPACE
  54832. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54833. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54834. BEGIN_JUCE_NAMESPACE
  54835. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54836. {
  54837. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54838. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54839. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54840. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54841. setColour (Slider::thumbColourId, Colours::white);
  54842. setColour (Slider::trackColourId, Colour (0x7f000000));
  54843. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54844. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54845. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54846. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54847. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54848. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54849. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54850. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54851. }
  54852. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54853. {
  54854. }
  54855. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54856. Button& button,
  54857. const Colour& backgroundColour,
  54858. bool isMouseOverButton,
  54859. bool isButtonDown)
  54860. {
  54861. const int width = button.getWidth();
  54862. const int height = button.getHeight();
  54863. const float indent = 2.0f;
  54864. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54865. roundToInt (height * 0.4f));
  54866. Path p;
  54867. p.addRoundedRectangle (indent, indent,
  54868. width - indent * 2.0f,
  54869. height - indent * 2.0f,
  54870. (float) cornerSize);
  54871. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54872. if (isMouseOverButton)
  54873. {
  54874. if (isButtonDown)
  54875. bc = bc.brighter();
  54876. else if (bc.getBrightness() > 0.5f)
  54877. bc = bc.darker (0.1f);
  54878. else
  54879. bc = bc.brighter (0.1f);
  54880. }
  54881. g.setColour (bc);
  54882. g.fillPath (p);
  54883. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54884. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54885. }
  54886. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54887. Component& /*component*/,
  54888. float x, float y, float w, float h,
  54889. const bool ticked,
  54890. const bool isEnabled,
  54891. const bool /*isMouseOverButton*/,
  54892. const bool isButtonDown)
  54893. {
  54894. Path box;
  54895. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54896. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54897. : Colours::lightgrey.withAlpha (0.1f));
  54898. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54899. g.fillPath (box, trans);
  54900. g.setColour (Colours::black.withAlpha (0.6f));
  54901. g.strokePath (box, PathStrokeType (0.9f), trans);
  54902. if (ticked)
  54903. {
  54904. Path tick;
  54905. tick.startNewSubPath (1.5f, 3.0f);
  54906. tick.lineTo (3.0f, 6.0f);
  54907. tick.lineTo (6.0f, 0.0f);
  54908. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54909. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54910. }
  54911. }
  54912. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54913. ToggleButton& button,
  54914. bool isMouseOverButton,
  54915. bool isButtonDown)
  54916. {
  54917. if (button.hasKeyboardFocus (true))
  54918. {
  54919. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54920. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54921. }
  54922. const int tickWidth = jmin (20, button.getHeight() - 4);
  54923. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54924. (float) tickWidth, (float) tickWidth,
  54925. button.getToggleState(),
  54926. button.isEnabled(),
  54927. isMouseOverButton,
  54928. isButtonDown);
  54929. g.setColour (button.findColour (ToggleButton::textColourId));
  54930. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54931. if (! button.isEnabled())
  54932. g.setOpacity (0.5f);
  54933. const int textX = tickWidth + 5;
  54934. g.drawFittedText (button.getButtonText(),
  54935. textX, 4,
  54936. button.getWidth() - textX - 2, button.getHeight() - 8,
  54937. Justification::centredLeft, 10);
  54938. }
  54939. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54940. int width, int height,
  54941. double progress, const String& textToShow)
  54942. {
  54943. if (progress < 0 || progress >= 1.0)
  54944. {
  54945. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54946. }
  54947. else
  54948. {
  54949. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54950. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54951. g.fillAll (background);
  54952. g.setColour (foreground);
  54953. g.fillRect (1, 1,
  54954. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54955. height - 2);
  54956. if (textToShow.isNotEmpty())
  54957. {
  54958. g.setColour (Colour::contrasting (background, foreground));
  54959. g.setFont (height * 0.6f);
  54960. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54961. }
  54962. }
  54963. }
  54964. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54965. ScrollBar& bar,
  54966. int width, int height,
  54967. int buttonDirection,
  54968. bool isScrollbarVertical,
  54969. bool isMouseOverButton,
  54970. bool isButtonDown)
  54971. {
  54972. if (isScrollbarVertical)
  54973. width -= 2;
  54974. else
  54975. height -= 2;
  54976. Path p;
  54977. if (buttonDirection == 0)
  54978. p.addTriangle (width * 0.5f, height * 0.2f,
  54979. width * 0.1f, height * 0.7f,
  54980. width * 0.9f, height * 0.7f);
  54981. else if (buttonDirection == 1)
  54982. p.addTriangle (width * 0.8f, height * 0.5f,
  54983. width * 0.3f, height * 0.1f,
  54984. width * 0.3f, height * 0.9f);
  54985. else if (buttonDirection == 2)
  54986. p.addTriangle (width * 0.5f, height * 0.8f,
  54987. width * 0.1f, height * 0.3f,
  54988. width * 0.9f, height * 0.3f);
  54989. else if (buttonDirection == 3)
  54990. p.addTriangle (width * 0.2f, height * 0.5f,
  54991. width * 0.7f, height * 0.1f,
  54992. width * 0.7f, height * 0.9f);
  54993. if (isButtonDown)
  54994. g.setColour (Colours::white);
  54995. else if (isMouseOverButton)
  54996. g.setColour (Colours::white.withAlpha (0.7f));
  54997. else
  54998. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54999. g.fillPath (p);
  55000. g.setColour (Colours::black.withAlpha (0.5f));
  55001. g.strokePath (p, PathStrokeType (0.5f));
  55002. }
  55003. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  55004. ScrollBar& bar,
  55005. int x, int y,
  55006. int width, int height,
  55007. bool isScrollbarVertical,
  55008. int thumbStartPosition,
  55009. int thumbSize,
  55010. bool isMouseOver,
  55011. bool isMouseDown)
  55012. {
  55013. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  55014. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55015. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  55016. if (thumbSize > 0.0f)
  55017. {
  55018. Rectangle<int> thumb;
  55019. if (isScrollbarVertical)
  55020. {
  55021. width -= 2;
  55022. g.fillRect (x + roundToInt (width * 0.35f), y,
  55023. roundToInt (width * 0.3f), height);
  55024. thumb.setBounds (x + 1, thumbStartPosition,
  55025. width - 2, thumbSize);
  55026. }
  55027. else
  55028. {
  55029. height -= 2;
  55030. g.fillRect (x, y + roundToInt (height * 0.35f),
  55031. width, roundToInt (height * 0.3f));
  55032. thumb.setBounds (thumbStartPosition, y + 1,
  55033. thumbSize, height - 2);
  55034. }
  55035. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55036. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  55037. g.fillRect (thumb);
  55038. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  55039. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  55040. if (thumbSize > 16)
  55041. {
  55042. for (int i = 3; --i >= 0;)
  55043. {
  55044. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  55045. g.setColour (Colours::black.withAlpha (0.15f));
  55046. if (isScrollbarVertical)
  55047. {
  55048. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55049. g.setColour (Colours::white.withAlpha (0.15f));
  55050. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55051. }
  55052. else
  55053. {
  55054. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55055. g.setColour (Colours::white.withAlpha (0.15f));
  55056. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55057. }
  55058. }
  55059. }
  55060. }
  55061. }
  55062. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55063. {
  55064. return &scrollbarShadow;
  55065. }
  55066. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55067. {
  55068. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55069. g.setColour (Colours::black.withAlpha (0.6f));
  55070. g.drawRect (0, 0, width, height);
  55071. }
  55072. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55073. bool, MenuBarComponent& menuBar)
  55074. {
  55075. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55076. }
  55077. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55078. {
  55079. if (textEditor.isEnabled())
  55080. {
  55081. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55082. g.drawRect (0, 0, width, height);
  55083. }
  55084. }
  55085. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55086. const bool isButtonDown,
  55087. int buttonX, int buttonY,
  55088. int buttonW, int buttonH,
  55089. ComboBox& box)
  55090. {
  55091. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55092. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55093. : ComboBox::backgroundColourId));
  55094. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55095. g.setColour (box.findColour (ComboBox::outlineColourId));
  55096. g.drawRect (0, 0, width, height);
  55097. const float arrowX = 0.2f;
  55098. const float arrowH = 0.3f;
  55099. if (box.isEnabled())
  55100. {
  55101. Path p;
  55102. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55103. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55104. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55105. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55106. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55107. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55108. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55109. : ComboBox::buttonColourId));
  55110. g.fillPath (p);
  55111. }
  55112. }
  55113. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55114. {
  55115. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55116. f.setHorizontalScale (0.9f);
  55117. return f;
  55118. }
  55119. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55120. {
  55121. Path p;
  55122. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55123. g.setColour (fill);
  55124. g.fillPath (p);
  55125. g.setColour (outline);
  55126. g.strokePath (p, PathStrokeType (0.3f));
  55127. }
  55128. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55129. int x, int y,
  55130. int w, int h,
  55131. float sliderPos,
  55132. float minSliderPos,
  55133. float maxSliderPos,
  55134. const Slider::SliderStyle style,
  55135. Slider& slider)
  55136. {
  55137. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55138. if (style == Slider::LinearBar)
  55139. {
  55140. g.setColour (slider.findColour (Slider::thumbColourId));
  55141. g.fillRect (x, y, (int) sliderPos - x, h);
  55142. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55143. g.drawRect (x, y, (int) sliderPos - x, h);
  55144. }
  55145. else
  55146. {
  55147. g.setColour (slider.findColour (Slider::trackColourId)
  55148. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55149. if (slider.isHorizontal())
  55150. {
  55151. g.fillRect (x, y + roundToInt (h * 0.6f),
  55152. w, roundToInt (h * 0.2f));
  55153. }
  55154. else
  55155. {
  55156. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55157. jmin (4, roundToInt (w * 0.2f)), h);
  55158. }
  55159. float alpha = 0.35f;
  55160. if (slider.isEnabled())
  55161. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55162. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55163. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55164. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55165. {
  55166. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55167. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55168. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55169. fill, outline);
  55170. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55171. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55172. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55173. fill, outline);
  55174. }
  55175. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55176. {
  55177. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55178. minSliderPos - 7.0f, y + h * 0.9f ,
  55179. minSliderPos, y + h * 0.9f,
  55180. fill, outline);
  55181. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55182. maxSliderPos, y + h * 0.9f,
  55183. maxSliderPos + 7.0f, y + h * 0.9f,
  55184. fill, outline);
  55185. }
  55186. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55187. {
  55188. drawTriangle (g, sliderPos, y + h * 0.9f,
  55189. sliderPos - 7.0f, y + h * 0.2f,
  55190. sliderPos + 7.0f, y + h * 0.2f,
  55191. fill, outline);
  55192. }
  55193. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55194. {
  55195. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55196. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55197. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55198. fill, outline);
  55199. }
  55200. }
  55201. }
  55202. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55203. {
  55204. if (isIncrement)
  55205. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55206. else
  55207. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55208. }
  55209. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55210. {
  55211. return &scrollbarShadow;
  55212. }
  55213. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55214. {
  55215. return 8;
  55216. }
  55217. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55218. int w, int h,
  55219. bool isMouseOver,
  55220. bool isMouseDragging)
  55221. {
  55222. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55223. : Colours::darkgrey);
  55224. const float lineThickness = jmin (w, h) * 0.1f;
  55225. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55226. {
  55227. g.drawLine (w * i,
  55228. h + 1.0f,
  55229. w + 1.0f,
  55230. h * i,
  55231. lineThickness);
  55232. }
  55233. }
  55234. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55235. {
  55236. Path shape;
  55237. if (buttonType == DocumentWindow::closeButton)
  55238. {
  55239. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55240. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55241. ShapeButton* const b = new ShapeButton ("close",
  55242. Colour (0x7fff3333),
  55243. Colour (0xd7ff3333),
  55244. Colour (0xf7ff3333));
  55245. b->setShape (shape, true, true, true);
  55246. return b;
  55247. }
  55248. else if (buttonType == DocumentWindow::minimiseButton)
  55249. {
  55250. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55251. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55252. DrawablePath dp;
  55253. dp.setPath (shape);
  55254. dp.setFill (Colours::black.withAlpha (0.3f));
  55255. b->setImages (&dp);
  55256. return b;
  55257. }
  55258. else if (buttonType == DocumentWindow::maximiseButton)
  55259. {
  55260. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55261. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55262. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55263. DrawablePath dp;
  55264. dp.setPath (shape);
  55265. dp.setFill (Colours::black.withAlpha (0.3f));
  55266. b->setImages (&dp);
  55267. return b;
  55268. }
  55269. jassertfalse;
  55270. return 0;
  55271. }
  55272. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55273. int titleBarX,
  55274. int titleBarY,
  55275. int titleBarW,
  55276. int titleBarH,
  55277. Button* minimiseButton,
  55278. Button* maximiseButton,
  55279. Button* closeButton,
  55280. bool positionTitleBarButtonsOnLeft)
  55281. {
  55282. titleBarY += titleBarH / 8;
  55283. titleBarH -= titleBarH / 4;
  55284. const int buttonW = titleBarH;
  55285. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55286. : titleBarX + titleBarW - buttonW - 4;
  55287. if (closeButton != 0)
  55288. {
  55289. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55290. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55291. : -(buttonW + buttonW / 5);
  55292. }
  55293. if (positionTitleBarButtonsOnLeft)
  55294. swapVariables (minimiseButton, maximiseButton);
  55295. if (maximiseButton != 0)
  55296. {
  55297. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55298. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55299. }
  55300. if (minimiseButton != 0)
  55301. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55302. }
  55303. END_JUCE_NAMESPACE
  55304. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55305. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55306. BEGIN_JUCE_NAMESPACE
  55307. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55308. : model (0),
  55309. itemUnderMouse (-1),
  55310. currentPopupIndex (-1),
  55311. topLevelIndexClicked (0),
  55312. lastMouseX (0),
  55313. lastMouseY (0)
  55314. {
  55315. setRepaintsOnMouseActivity (true);
  55316. setWantsKeyboardFocus (false);
  55317. setMouseClickGrabsKeyboardFocus (false);
  55318. setModel (model_);
  55319. }
  55320. MenuBarComponent::~MenuBarComponent()
  55321. {
  55322. setModel (0);
  55323. Desktop::getInstance().removeGlobalMouseListener (this);
  55324. }
  55325. MenuBarModel* MenuBarComponent::getModel() const throw()
  55326. {
  55327. return model;
  55328. }
  55329. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55330. {
  55331. if (model != newModel)
  55332. {
  55333. if (model != 0)
  55334. model->removeListener (this);
  55335. model = newModel;
  55336. if (model != 0)
  55337. model->addListener (this);
  55338. repaint();
  55339. menuBarItemsChanged (0);
  55340. }
  55341. }
  55342. void MenuBarComponent::paint (Graphics& g)
  55343. {
  55344. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55345. getLookAndFeel().drawMenuBarBackground (g,
  55346. getWidth(),
  55347. getHeight(),
  55348. isMouseOverBar,
  55349. *this);
  55350. if (model != 0)
  55351. {
  55352. for (int i = 0; i < menuNames.size(); ++i)
  55353. {
  55354. g.saveState();
  55355. g.setOrigin (xPositions [i], 0);
  55356. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55357. getLookAndFeel().drawMenuBarItem (g,
  55358. xPositions[i + 1] - xPositions[i],
  55359. getHeight(),
  55360. i,
  55361. menuNames[i],
  55362. i == itemUnderMouse,
  55363. i == currentPopupIndex,
  55364. isMouseOverBar,
  55365. *this);
  55366. g.restoreState();
  55367. }
  55368. }
  55369. }
  55370. void MenuBarComponent::resized()
  55371. {
  55372. xPositions.clear();
  55373. int x = 0;
  55374. xPositions.add (x);
  55375. for (int i = 0; i < menuNames.size(); ++i)
  55376. {
  55377. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55378. xPositions.add (x);
  55379. }
  55380. }
  55381. int MenuBarComponent::getItemAt (const int x, const int y)
  55382. {
  55383. for (int i = 0; i < xPositions.size(); ++i)
  55384. if (x >= xPositions[i] && x < xPositions[i + 1])
  55385. return reallyContains (x, y, true) ? i : -1;
  55386. return -1;
  55387. }
  55388. void MenuBarComponent::repaintMenuItem (int index)
  55389. {
  55390. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55391. {
  55392. const int x1 = xPositions [index];
  55393. const int x2 = xPositions [index + 1];
  55394. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55395. }
  55396. }
  55397. void MenuBarComponent::setItemUnderMouse (const int index)
  55398. {
  55399. if (itemUnderMouse != index)
  55400. {
  55401. repaintMenuItem (itemUnderMouse);
  55402. itemUnderMouse = index;
  55403. repaintMenuItem (itemUnderMouse);
  55404. }
  55405. }
  55406. void MenuBarComponent::setOpenItem (int index)
  55407. {
  55408. if (currentPopupIndex != index)
  55409. {
  55410. repaintMenuItem (currentPopupIndex);
  55411. currentPopupIndex = index;
  55412. repaintMenuItem (currentPopupIndex);
  55413. if (index >= 0)
  55414. Desktop::getInstance().addGlobalMouseListener (this);
  55415. else
  55416. Desktop::getInstance().removeGlobalMouseListener (this);
  55417. }
  55418. }
  55419. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55420. {
  55421. setItemUnderMouse (getItemAt (x, y));
  55422. }
  55423. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55424. {
  55425. public:
  55426. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55427. : bar (bar_), topLevelIndex (topLevelIndex_)
  55428. {
  55429. }
  55430. ~AsyncCallback() {}
  55431. void modalStateFinished (int returnValue)
  55432. {
  55433. if (bar != 0)
  55434. bar->menuDismissed (topLevelIndex, returnValue);
  55435. }
  55436. private:
  55437. Component::SafePointer<MenuBarComponent> bar;
  55438. const int topLevelIndex;
  55439. AsyncCallback (const AsyncCallback&);
  55440. AsyncCallback& operator= (const AsyncCallback&);
  55441. };
  55442. void MenuBarComponent::showMenu (int index)
  55443. {
  55444. if (index != currentPopupIndex)
  55445. {
  55446. PopupMenu::dismissAllActiveMenus();
  55447. menuBarItemsChanged (0);
  55448. setOpenItem (index);
  55449. setItemUnderMouse (index);
  55450. if (index >= 0)
  55451. {
  55452. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55453. menuNames [itemUnderMouse]));
  55454. if (m.lookAndFeel == 0)
  55455. m.setLookAndFeel (&getLookAndFeel());
  55456. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55457. m.showMenu (itemPos + getScreenPosition(),
  55458. 0, itemPos.getWidth(), 0, 0, true, this,
  55459. new AsyncCallback (this, index));
  55460. }
  55461. }
  55462. }
  55463. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55464. {
  55465. topLevelIndexClicked = topLevelIndex;
  55466. postCommandMessage (itemId);
  55467. }
  55468. void MenuBarComponent::handleCommandMessage (int commandId)
  55469. {
  55470. const Point<int> mousePos (getMouseXYRelative());
  55471. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55472. if (currentPopupIndex == topLevelIndexClicked)
  55473. setOpenItem (-1);
  55474. if (commandId != 0 && model != 0)
  55475. model->menuItemSelected (commandId, topLevelIndexClicked);
  55476. }
  55477. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55478. {
  55479. if (e.eventComponent == this)
  55480. updateItemUnderMouse (e.x, e.y);
  55481. }
  55482. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55483. {
  55484. if (e.eventComponent == this)
  55485. updateItemUnderMouse (e.x, e.y);
  55486. }
  55487. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55488. {
  55489. if (currentPopupIndex < 0)
  55490. {
  55491. const MouseEvent e2 (e.getEventRelativeTo (this));
  55492. updateItemUnderMouse (e2.x, e2.y);
  55493. currentPopupIndex = -2;
  55494. showMenu (itemUnderMouse);
  55495. }
  55496. }
  55497. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55498. {
  55499. const MouseEvent e2 (e.getEventRelativeTo (this));
  55500. const int item = getItemAt (e2.x, e2.y);
  55501. if (item >= 0)
  55502. showMenu (item);
  55503. }
  55504. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55505. {
  55506. const MouseEvent e2 (e.getEventRelativeTo (this));
  55507. updateItemUnderMouse (e2.x, e2.y);
  55508. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55509. {
  55510. setOpenItem (-1);
  55511. PopupMenu::dismissAllActiveMenus();
  55512. }
  55513. }
  55514. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55515. {
  55516. const MouseEvent e2 (e.getEventRelativeTo (this));
  55517. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55518. {
  55519. if (currentPopupIndex >= 0)
  55520. {
  55521. const int item = getItemAt (e2.x, e2.y);
  55522. if (item >= 0)
  55523. showMenu (item);
  55524. }
  55525. else
  55526. {
  55527. updateItemUnderMouse (e2.x, e2.y);
  55528. }
  55529. lastMouseX = e2.x;
  55530. lastMouseY = e2.y;
  55531. }
  55532. }
  55533. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55534. {
  55535. bool used = false;
  55536. const int numMenus = menuNames.size();
  55537. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55538. if (key.isKeyCode (KeyPress::leftKey))
  55539. {
  55540. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55541. used = true;
  55542. }
  55543. else if (key.isKeyCode (KeyPress::rightKey))
  55544. {
  55545. showMenu ((currentIndex + 1) % numMenus);
  55546. used = true;
  55547. }
  55548. return used;
  55549. }
  55550. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55551. {
  55552. StringArray newNames;
  55553. if (model != 0)
  55554. newNames = model->getMenuBarNames();
  55555. if (newNames != menuNames)
  55556. {
  55557. menuNames = newNames;
  55558. repaint();
  55559. resized();
  55560. }
  55561. }
  55562. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55563. const ApplicationCommandTarget::InvocationInfo& info)
  55564. {
  55565. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55566. return;
  55567. for (int i = 0; i < menuNames.size(); ++i)
  55568. {
  55569. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55570. if (menu.containsCommandItem (info.commandID))
  55571. {
  55572. setItemUnderMouse (i);
  55573. startTimer (200);
  55574. break;
  55575. }
  55576. }
  55577. }
  55578. void MenuBarComponent::timerCallback()
  55579. {
  55580. stopTimer();
  55581. const Point<int> mousePos (getMouseXYRelative());
  55582. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55583. }
  55584. END_JUCE_NAMESPACE
  55585. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55586. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55587. BEGIN_JUCE_NAMESPACE
  55588. MenuBarModel::MenuBarModel() throw()
  55589. : manager (0)
  55590. {
  55591. }
  55592. MenuBarModel::~MenuBarModel()
  55593. {
  55594. setApplicationCommandManagerToWatch (0);
  55595. }
  55596. void MenuBarModel::menuItemsChanged()
  55597. {
  55598. triggerAsyncUpdate();
  55599. }
  55600. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55601. {
  55602. if (manager != newManager)
  55603. {
  55604. if (manager != 0)
  55605. manager->removeListener (this);
  55606. manager = newManager;
  55607. if (manager != 0)
  55608. manager->addListener (this);
  55609. }
  55610. }
  55611. void MenuBarModel::addListener (Listener* const newListener) throw()
  55612. {
  55613. listeners.add (newListener);
  55614. }
  55615. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55616. {
  55617. // Trying to remove a listener that isn't on the list!
  55618. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55619. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55620. jassert (listeners.contains (listenerToRemove));
  55621. listeners.remove (listenerToRemove);
  55622. }
  55623. void MenuBarModel::handleAsyncUpdate()
  55624. {
  55625. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55626. }
  55627. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55628. {
  55629. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55630. }
  55631. void MenuBarModel::applicationCommandListChanged()
  55632. {
  55633. menuItemsChanged();
  55634. }
  55635. END_JUCE_NAMESPACE
  55636. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55637. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55638. BEGIN_JUCE_NAMESPACE
  55639. class PopupMenu::Item
  55640. {
  55641. public:
  55642. Item()
  55643. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55644. usesColour (false), customComp (0), commandManager (0)
  55645. {
  55646. }
  55647. Item (const int itemId_,
  55648. const String& text_,
  55649. const bool active_,
  55650. const bool isTicked_,
  55651. const Image& im,
  55652. const Colour& textColour_,
  55653. const bool usesColour_,
  55654. PopupMenuCustomComponent* const customComp_,
  55655. const PopupMenu* const subMenu_,
  55656. ApplicationCommandManager* const commandManager_)
  55657. : itemId (itemId_), text (text_), textColour (textColour_),
  55658. active (active_), isSeparator (false), isTicked (isTicked_),
  55659. usesColour (usesColour_), image (im), customComp (customComp_),
  55660. commandManager (commandManager_)
  55661. {
  55662. if (subMenu_ != 0)
  55663. subMenu = new PopupMenu (*subMenu_);
  55664. if (commandManager_ != 0 && itemId_ != 0)
  55665. {
  55666. String shortcutKey;
  55667. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55668. ->getKeyPressesAssignedToCommand (itemId_));
  55669. for (int i = 0; i < keyPresses.size(); ++i)
  55670. {
  55671. const String key (keyPresses.getReference(i).getTextDescription());
  55672. if (shortcutKey.isNotEmpty())
  55673. shortcutKey << ", ";
  55674. if (key.length() == 1)
  55675. shortcutKey << "shortcut: '" << key << '\'';
  55676. else
  55677. shortcutKey << key;
  55678. }
  55679. shortcutKey = shortcutKey.trim();
  55680. if (shortcutKey.isNotEmpty())
  55681. text << "<end>" << shortcutKey;
  55682. }
  55683. }
  55684. Item (const Item& other)
  55685. : itemId (other.itemId),
  55686. text (other.text),
  55687. textColour (other.textColour),
  55688. active (other.active),
  55689. isSeparator (other.isSeparator),
  55690. isTicked (other.isTicked),
  55691. usesColour (other.usesColour),
  55692. image (other.image),
  55693. customComp (other.customComp),
  55694. commandManager (other.commandManager)
  55695. {
  55696. if (other.subMenu != 0)
  55697. subMenu = new PopupMenu (*(other.subMenu));
  55698. }
  55699. ~Item()
  55700. {
  55701. customComp = 0;
  55702. }
  55703. bool canBeTriggered() const throw()
  55704. {
  55705. return active && ! (isSeparator || (subMenu != 0));
  55706. }
  55707. bool hasActiveSubMenu() const throw()
  55708. {
  55709. return active && (subMenu != 0);
  55710. }
  55711. const int itemId;
  55712. String text;
  55713. const Colour textColour;
  55714. const bool active, isSeparator, isTicked, usesColour;
  55715. Image image;
  55716. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55717. ScopedPointer <PopupMenu> subMenu;
  55718. ApplicationCommandManager* const commandManager;
  55719. juce_UseDebuggingNewOperator
  55720. private:
  55721. Item& operator= (const Item&);
  55722. };
  55723. class PopupMenu::ItemComponent : public Component
  55724. {
  55725. public:
  55726. ItemComponent (const PopupMenu::Item& itemInfo_)
  55727. : itemInfo (itemInfo_),
  55728. isHighlighted (false)
  55729. {
  55730. if (itemInfo.customComp != 0)
  55731. addAndMakeVisible (itemInfo.customComp);
  55732. }
  55733. ~ItemComponent()
  55734. {
  55735. if (itemInfo.customComp != 0)
  55736. removeChildComponent (itemInfo.customComp);
  55737. }
  55738. void getIdealSize (int& idealWidth,
  55739. int& idealHeight,
  55740. const int standardItemHeight)
  55741. {
  55742. if (itemInfo.customComp != 0)
  55743. {
  55744. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55745. }
  55746. else
  55747. {
  55748. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55749. itemInfo.isSeparator,
  55750. standardItemHeight,
  55751. idealWidth,
  55752. idealHeight);
  55753. }
  55754. }
  55755. void paint (Graphics& g)
  55756. {
  55757. if (itemInfo.customComp == 0)
  55758. {
  55759. String mainText (itemInfo.text);
  55760. String endText;
  55761. const int endIndex = mainText.indexOf ("<end>");
  55762. if (endIndex >= 0)
  55763. {
  55764. endText = mainText.substring (endIndex + 5).trim();
  55765. mainText = mainText.substring (0, endIndex);
  55766. }
  55767. getLookAndFeel()
  55768. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55769. itemInfo.isSeparator,
  55770. itemInfo.active,
  55771. isHighlighted,
  55772. itemInfo.isTicked,
  55773. itemInfo.subMenu != 0,
  55774. mainText, endText,
  55775. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55776. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55777. }
  55778. }
  55779. void resized()
  55780. {
  55781. if (getNumChildComponents() > 0)
  55782. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55783. }
  55784. void setHighlighted (bool shouldBeHighlighted)
  55785. {
  55786. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55787. if (isHighlighted != shouldBeHighlighted)
  55788. {
  55789. isHighlighted = shouldBeHighlighted;
  55790. if (itemInfo.customComp != 0)
  55791. {
  55792. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55793. itemInfo.customComp->repaint();
  55794. }
  55795. repaint();
  55796. }
  55797. }
  55798. PopupMenu::Item itemInfo;
  55799. juce_UseDebuggingNewOperator
  55800. private:
  55801. bool isHighlighted;
  55802. ItemComponent (const ItemComponent&);
  55803. ItemComponent& operator= (const ItemComponent&);
  55804. };
  55805. namespace PopupMenuSettings
  55806. {
  55807. static const int scrollZone = 24;
  55808. static const int borderSize = 2;
  55809. static const int timerInterval = 50;
  55810. static const int dismissCommandId = 0x6287345f;
  55811. }
  55812. class PopupMenu::Window : public Component,
  55813. private Timer
  55814. {
  55815. public:
  55816. Window()
  55817. : Component ("menu"),
  55818. owner (0),
  55819. currentChild (0),
  55820. activeSubMenu (0),
  55821. managerOfChosenCommand (0),
  55822. minimumWidth (0),
  55823. maximumNumColumns (7),
  55824. standardItemHeight (0),
  55825. isOver (false),
  55826. hasBeenOver (false),
  55827. isDown (false),
  55828. needsToScroll (false),
  55829. hideOnExit (false),
  55830. disableMouseMoves (false),
  55831. hasAnyJuceCompHadFocus (false),
  55832. numColumns (0),
  55833. contentHeight (0),
  55834. childYOffset (0),
  55835. timeEnteredCurrentChildComp (0),
  55836. scrollAcceleration (1.0)
  55837. {
  55838. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55839. setWantsKeyboardFocus (true);
  55840. setMouseClickGrabsKeyboardFocus (false);
  55841. setAlwaysOnTop (true);
  55842. Desktop::getInstance().addGlobalMouseListener (this);
  55843. getActiveWindows().add (this);
  55844. }
  55845. ~Window()
  55846. {
  55847. getActiveWindows().removeValue (this);
  55848. Desktop::getInstance().removeGlobalMouseListener (this);
  55849. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55850. activeSubMenu = 0;
  55851. deleteAllChildren();
  55852. }
  55853. static Window* create (const PopupMenu& menu,
  55854. const bool dismissOnMouseUp,
  55855. Window* const owner_,
  55856. const Rectangle<int>& target,
  55857. const int minimumWidth,
  55858. const int maximumNumColumns,
  55859. const int standardItemHeight,
  55860. const bool alignToRectangle,
  55861. const int itemIdThatMustBeVisible,
  55862. ApplicationCommandManager** managerOfChosenCommand,
  55863. Component* const componentAttachedTo)
  55864. {
  55865. if (menu.items.size() > 0)
  55866. {
  55867. int totalItems = 0;
  55868. ScopedPointer <Window> mw (new Window());
  55869. mw->setLookAndFeel (menu.lookAndFeel);
  55870. mw->setWantsKeyboardFocus (false);
  55871. mw->setOpaque (mw->getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55872. mw->minimumWidth = minimumWidth;
  55873. mw->maximumNumColumns = maximumNumColumns;
  55874. mw->standardItemHeight = standardItemHeight;
  55875. mw->dismissOnMouseUp = dismissOnMouseUp;
  55876. for (int i = 0; i < menu.items.size(); ++i)
  55877. {
  55878. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55879. mw->addItem (*item);
  55880. ++totalItems;
  55881. }
  55882. if (totalItems > 0)
  55883. {
  55884. mw->owner = owner_;
  55885. mw->managerOfChosenCommand = managerOfChosenCommand;
  55886. mw->componentAttachedTo = componentAttachedTo;
  55887. mw->componentAttachedToOriginal = componentAttachedTo;
  55888. mw->calculateWindowPos (target, alignToRectangle);
  55889. mw->setTopLeftPosition (mw->windowPos.getX(),
  55890. mw->windowPos.getY());
  55891. mw->updateYPositions();
  55892. if (itemIdThatMustBeVisible != 0)
  55893. {
  55894. const int y = target.getY() - mw->windowPos.getY();
  55895. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55896. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55897. }
  55898. mw->resizeToBestWindowPos();
  55899. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55900. | mw->getLookAndFeel().getMenuWindowFlags());
  55901. return mw.release();
  55902. }
  55903. }
  55904. return 0;
  55905. }
  55906. void paint (Graphics& g)
  55907. {
  55908. if (isOpaque())
  55909. g.fillAll (Colours::white);
  55910. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55911. }
  55912. void paintOverChildren (Graphics& g)
  55913. {
  55914. if (isScrolling())
  55915. {
  55916. LookAndFeel& lf = getLookAndFeel();
  55917. if (isScrollZoneActive (false))
  55918. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55919. if (isScrollZoneActive (true))
  55920. {
  55921. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55922. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55923. }
  55924. }
  55925. }
  55926. bool isScrollZoneActive (bool bottomOne) const
  55927. {
  55928. return isScrolling()
  55929. && (bottomOne
  55930. ? childYOffset < contentHeight - windowPos.getHeight()
  55931. : childYOffset > 0);
  55932. }
  55933. void addItem (const PopupMenu::Item& item)
  55934. {
  55935. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55936. addAndMakeVisible (mic);
  55937. int itemW = 80;
  55938. int itemH = 16;
  55939. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55940. mic->setSize (itemW, jlimit (2, 600, itemH));
  55941. mic->addMouseListener (this, false);
  55942. }
  55943. // hide this and all sub-comps
  55944. void hide (const PopupMenu::Item* const item)
  55945. {
  55946. if (isVisible())
  55947. {
  55948. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55949. activeSubMenu = 0;
  55950. currentChild = 0;
  55951. exitModalState (item != 0 ? item->itemId : 0);
  55952. setVisible (false);
  55953. if (item != 0
  55954. && item->commandManager != 0
  55955. && item->itemId != 0)
  55956. {
  55957. *managerOfChosenCommand = item->commandManager;
  55958. }
  55959. }
  55960. }
  55961. void dismissMenu (const PopupMenu::Item* const item)
  55962. {
  55963. if (owner != 0)
  55964. {
  55965. owner->dismissMenu (item);
  55966. }
  55967. else
  55968. {
  55969. if (item != 0)
  55970. {
  55971. // need a copy of this on the stack as the one passed in will get deleted during this call
  55972. const PopupMenu::Item mi (*item);
  55973. hide (&mi);
  55974. }
  55975. else
  55976. {
  55977. hide (0);
  55978. }
  55979. }
  55980. }
  55981. void mouseMove (const MouseEvent&)
  55982. {
  55983. timerCallback();
  55984. }
  55985. void mouseDown (const MouseEvent&)
  55986. {
  55987. timerCallback();
  55988. }
  55989. void mouseDrag (const MouseEvent&)
  55990. {
  55991. timerCallback();
  55992. }
  55993. void mouseUp (const MouseEvent&)
  55994. {
  55995. timerCallback();
  55996. }
  55997. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55998. {
  55999. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  56000. lastMouse = Point<int> (-1, -1);
  56001. }
  56002. bool keyPressed (const KeyPress& key)
  56003. {
  56004. if (key.isKeyCode (KeyPress::downKey))
  56005. {
  56006. selectNextItem (1);
  56007. }
  56008. else if (key.isKeyCode (KeyPress::upKey))
  56009. {
  56010. selectNextItem (-1);
  56011. }
  56012. else if (key.isKeyCode (KeyPress::leftKey))
  56013. {
  56014. if (owner != 0)
  56015. {
  56016. Component::SafePointer<Window> parentWindow (owner);
  56017. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  56018. hide (0);
  56019. if (parentWindow != 0)
  56020. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  56021. disableTimerUntilMouseMoves();
  56022. }
  56023. else if (componentAttachedTo != 0)
  56024. {
  56025. componentAttachedTo->keyPressed (key);
  56026. }
  56027. }
  56028. else if (key.isKeyCode (KeyPress::rightKey))
  56029. {
  56030. disableTimerUntilMouseMoves();
  56031. if (showSubMenuFor (currentChild))
  56032. {
  56033. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56034. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  56035. activeSubMenu->selectNextItem (1);
  56036. }
  56037. else if (componentAttachedTo != 0)
  56038. {
  56039. componentAttachedTo->keyPressed (key);
  56040. }
  56041. }
  56042. else if (key.isKeyCode (KeyPress::returnKey))
  56043. {
  56044. triggerCurrentlyHighlightedItem();
  56045. }
  56046. else if (key.isKeyCode (KeyPress::escapeKey))
  56047. {
  56048. dismissMenu (0);
  56049. }
  56050. else
  56051. {
  56052. return false;
  56053. }
  56054. return true;
  56055. }
  56056. void inputAttemptWhenModal()
  56057. {
  56058. Component::SafePointer<Component> deletionChecker (this);
  56059. timerCallback();
  56060. if (deletionChecker != 0 && ! isOverAnyMenu())
  56061. {
  56062. if (componentAttachedTo != 0)
  56063. {
  56064. // we want to dismiss the menu, but if we do it synchronously, then
  56065. // the mouse-click will be allowed to pass through. That's good, except
  56066. // when the user clicks on the button that orginally popped the menu up,
  56067. // as they'll expect the menu to go away, and in fact it'll just
  56068. // come back. So only dismiss synchronously if they're not on the original
  56069. // comp that we're attached to.
  56070. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56071. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56072. {
  56073. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56074. return;
  56075. }
  56076. }
  56077. dismissMenu (0);
  56078. }
  56079. }
  56080. void handleCommandMessage (int commandId)
  56081. {
  56082. Component::handleCommandMessage (commandId);
  56083. if (commandId == PopupMenuSettings::dismissCommandId)
  56084. dismissMenu (0);
  56085. }
  56086. void timerCallback()
  56087. {
  56088. if (! isVisible())
  56089. return;
  56090. if (componentAttachedTo != componentAttachedToOriginal)
  56091. {
  56092. dismissMenu (0);
  56093. return;
  56094. }
  56095. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56096. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56097. return;
  56098. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56099. // move rather than a real timer callback
  56100. const Point<int> globalMousePos (Desktop::getMousePosition());
  56101. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56102. const uint32 now = Time::getMillisecondCounter();
  56103. if (now > timeEnteredCurrentChildComp + 100
  56104. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56105. && currentChild->isValidComponent()
  56106. && (! disableMouseMoves)
  56107. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56108. {
  56109. showSubMenuFor (currentChild);
  56110. }
  56111. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56112. {
  56113. highlightItemUnderMouse (globalMousePos, localMousePos);
  56114. }
  56115. bool overScrollArea = false;
  56116. if (isScrolling()
  56117. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56118. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56119. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56120. {
  56121. if (now > lastScroll + 20)
  56122. {
  56123. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56124. int amount = 0;
  56125. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56126. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56127. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56128. lastScroll = now;
  56129. }
  56130. overScrollArea = true;
  56131. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56132. }
  56133. else
  56134. {
  56135. scrollAcceleration = 1.0;
  56136. }
  56137. const bool wasDown = isDown;
  56138. bool isOverAny = isOverAnyMenu();
  56139. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56140. {
  56141. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56142. isOverAny = isOverAnyMenu();
  56143. }
  56144. if (hideOnExit && hasBeenOver && ! isOverAny)
  56145. {
  56146. hide (0);
  56147. }
  56148. else
  56149. {
  56150. isDown = hasBeenOver
  56151. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56152. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56153. bool anyFocused = Process::isForegroundProcess();
  56154. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56155. {
  56156. // because no component at all may have focus, our test here will
  56157. // only be triggered when something has focus and then loses it.
  56158. anyFocused = ! hasAnyJuceCompHadFocus;
  56159. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56160. {
  56161. if (ComponentPeer::getPeer (i)->isFocused())
  56162. {
  56163. anyFocused = true;
  56164. hasAnyJuceCompHadFocus = true;
  56165. break;
  56166. }
  56167. }
  56168. }
  56169. if (! anyFocused)
  56170. {
  56171. if (now > lastFocused + 10)
  56172. {
  56173. wasHiddenBecauseOfAppChange() = true;
  56174. dismissMenu (0);
  56175. return; // may have been deleted by the previous call..
  56176. }
  56177. }
  56178. else if (wasDown && now > menuCreationTime + 250
  56179. && ! (isDown || overScrollArea))
  56180. {
  56181. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56182. if (isOver)
  56183. {
  56184. triggerCurrentlyHighlightedItem();
  56185. }
  56186. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56187. {
  56188. dismissMenu (0);
  56189. }
  56190. return; // may have been deleted by the previous calls..
  56191. }
  56192. else
  56193. {
  56194. lastFocused = now;
  56195. }
  56196. }
  56197. }
  56198. static Array<Window*>& getActiveWindows()
  56199. {
  56200. static Array<Window*> activeMenuWindows;
  56201. return activeMenuWindows;
  56202. }
  56203. static bool& wasHiddenBecauseOfAppChange() throw()
  56204. {
  56205. static bool b = false;
  56206. return b;
  56207. }
  56208. juce_UseDebuggingNewOperator
  56209. private:
  56210. Window* owner;
  56211. PopupMenu::ItemComponent* currentChild;
  56212. ScopedPointer <Window> activeSubMenu;
  56213. ApplicationCommandManager** managerOfChosenCommand;
  56214. Component::SafePointer<Component> componentAttachedTo;
  56215. Component* componentAttachedToOriginal;
  56216. Rectangle<int> windowPos;
  56217. Point<int> lastMouse;
  56218. int minimumWidth, maximumNumColumns, standardItemHeight;
  56219. bool isOver, hasBeenOver, isDown, needsToScroll;
  56220. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56221. int numColumns, contentHeight, childYOffset;
  56222. Array <int> columnWidths;
  56223. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56224. double scrollAcceleration;
  56225. bool overlaps (const Rectangle<int>& r) const
  56226. {
  56227. return r.intersects (getBounds())
  56228. || (owner != 0 && owner->overlaps (r));
  56229. }
  56230. bool isOverAnyMenu() const
  56231. {
  56232. return (owner != 0) ? owner->isOverAnyMenu()
  56233. : isOverChildren();
  56234. }
  56235. bool isOverChildren() const
  56236. {
  56237. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56238. return isVisible()
  56239. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56240. }
  56241. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56242. {
  56243. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56244. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56245. if (activeSubMenu != 0)
  56246. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56247. }
  56248. bool treeContains (const Window* const window) const throw()
  56249. {
  56250. const Window* mw = this;
  56251. while (mw->owner != 0)
  56252. mw = mw->owner;
  56253. while (mw != 0)
  56254. {
  56255. if (mw == window)
  56256. return true;
  56257. mw = mw->activeSubMenu;
  56258. }
  56259. return false;
  56260. }
  56261. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56262. {
  56263. const Rectangle<int> mon (Desktop::getInstance()
  56264. .getMonitorAreaContaining (target.getCentre(),
  56265. #if JUCE_MAC
  56266. true));
  56267. #else
  56268. false)); // on windows, don't stop the menu overlapping the taskbar
  56269. #endif
  56270. int x, y, widthToUse, heightToUse;
  56271. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56272. if (alignToRectangle)
  56273. {
  56274. x = target.getX();
  56275. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56276. const int spaceOver = target.getY() - mon.getY();
  56277. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56278. y = target.getBottom();
  56279. else
  56280. y = target.getY() - heightToUse;
  56281. }
  56282. else
  56283. {
  56284. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56285. if (owner != 0)
  56286. {
  56287. if (owner->owner != 0)
  56288. {
  56289. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56290. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56291. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56292. tendTowardsRight = true;
  56293. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56294. tendTowardsRight = false;
  56295. }
  56296. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56297. {
  56298. tendTowardsRight = true;
  56299. }
  56300. }
  56301. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56302. target.getX() - mon.getX()) - 32;
  56303. if (biggestSpace < widthToUse)
  56304. {
  56305. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56306. if (numColumns > 1)
  56307. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56308. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56309. }
  56310. if (tendTowardsRight)
  56311. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56312. else
  56313. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56314. y = target.getY();
  56315. if (target.getCentreY() > mon.getCentreY())
  56316. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56317. }
  56318. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56319. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56320. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56321. // sets this flag if it's big enough to obscure any of its parent menus
  56322. hideOnExit = (owner != 0)
  56323. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56324. }
  56325. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56326. {
  56327. numColumns = 0;
  56328. contentHeight = 0;
  56329. const int maxMenuH = getParentHeight() - 24;
  56330. int totalW;
  56331. do
  56332. {
  56333. ++numColumns;
  56334. totalW = workOutBestSize (maxMenuW);
  56335. if (totalW > maxMenuW)
  56336. {
  56337. numColumns = jmax (1, numColumns - 1);
  56338. totalW = workOutBestSize (maxMenuW); // to update col widths
  56339. break;
  56340. }
  56341. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56342. {
  56343. break;
  56344. }
  56345. } while (numColumns < maximumNumColumns);
  56346. const int actualH = jmin (contentHeight, maxMenuH);
  56347. needsToScroll = contentHeight > actualH;
  56348. width = updateYPositions();
  56349. height = actualH + PopupMenuSettings::borderSize * 2;
  56350. }
  56351. int workOutBestSize (const int maxMenuW)
  56352. {
  56353. int totalW = 0;
  56354. contentHeight = 0;
  56355. int childNum = 0;
  56356. for (int col = 0; col < numColumns; ++col)
  56357. {
  56358. int i, colW = 50, colH = 0;
  56359. const int numChildren = jmin (getNumChildComponents() - childNum,
  56360. (getNumChildComponents() + numColumns - 1) / numColumns);
  56361. for (i = numChildren; --i >= 0;)
  56362. {
  56363. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56364. colH += getChildComponent (childNum + i)->getHeight();
  56365. }
  56366. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56367. columnWidths.set (col, colW);
  56368. totalW += colW;
  56369. contentHeight = jmax (contentHeight, colH);
  56370. childNum += numChildren;
  56371. }
  56372. if (totalW < minimumWidth)
  56373. {
  56374. totalW = minimumWidth;
  56375. for (int col = 0; col < numColumns; ++col)
  56376. columnWidths.set (0, totalW / numColumns);
  56377. }
  56378. return totalW;
  56379. }
  56380. void ensureItemIsVisible (const int itemId, int wantedY)
  56381. {
  56382. jassert (itemId != 0)
  56383. for (int i = getNumChildComponents(); --i >= 0;)
  56384. {
  56385. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56386. if (m != 0
  56387. && m->itemInfo.itemId == itemId
  56388. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56389. {
  56390. const int currentY = m->getY();
  56391. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56392. {
  56393. if (wantedY < 0)
  56394. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56395. jmax (PopupMenuSettings::scrollZone,
  56396. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56397. currentY);
  56398. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56399. int deltaY = wantedY - currentY;
  56400. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56401. jmin (windowPos.getHeight(), mon.getHeight()));
  56402. const int newY = jlimit (mon.getY(),
  56403. mon.getBottom() - windowPos.getHeight(),
  56404. windowPos.getY() + deltaY);
  56405. deltaY -= newY - windowPos.getY();
  56406. childYOffset -= deltaY;
  56407. windowPos.setPosition (windowPos.getX(), newY);
  56408. updateYPositions();
  56409. }
  56410. break;
  56411. }
  56412. }
  56413. }
  56414. void resizeToBestWindowPos()
  56415. {
  56416. Rectangle<int> r (windowPos);
  56417. if (childYOffset < 0)
  56418. {
  56419. r.setBounds (r.getX(), r.getY() - childYOffset,
  56420. r.getWidth(), r.getHeight() + childYOffset);
  56421. }
  56422. else if (childYOffset > 0)
  56423. {
  56424. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56425. if (spaceAtBottom > 0)
  56426. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56427. }
  56428. setBounds (r);
  56429. updateYPositions();
  56430. }
  56431. void alterChildYPos (const int delta)
  56432. {
  56433. if (isScrolling())
  56434. {
  56435. childYOffset += delta;
  56436. if (delta < 0)
  56437. {
  56438. childYOffset = jmax (childYOffset, 0);
  56439. }
  56440. else if (delta > 0)
  56441. {
  56442. childYOffset = jmin (childYOffset,
  56443. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56444. }
  56445. updateYPositions();
  56446. }
  56447. else
  56448. {
  56449. childYOffset = 0;
  56450. }
  56451. resizeToBestWindowPos();
  56452. repaint();
  56453. }
  56454. int updateYPositions()
  56455. {
  56456. int x = 0;
  56457. int childNum = 0;
  56458. for (int col = 0; col < numColumns; ++col)
  56459. {
  56460. const int numChildren = jmin (getNumChildComponents() - childNum,
  56461. (getNumChildComponents() + numColumns - 1) / numColumns);
  56462. const int colW = columnWidths [col];
  56463. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56464. for (int i = 0; i < numChildren; ++i)
  56465. {
  56466. Component* const c = getChildComponent (childNum + i);
  56467. c->setBounds (x, y, colW, c->getHeight());
  56468. y += c->getHeight();
  56469. }
  56470. x += colW;
  56471. childNum += numChildren;
  56472. }
  56473. return x;
  56474. }
  56475. bool isScrolling() const throw()
  56476. {
  56477. return childYOffset != 0 || needsToScroll;
  56478. }
  56479. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56480. {
  56481. if (currentChild->isValidComponent())
  56482. currentChild->setHighlighted (false);
  56483. currentChild = child;
  56484. if (currentChild != 0)
  56485. {
  56486. currentChild->setHighlighted (true);
  56487. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56488. }
  56489. }
  56490. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56491. {
  56492. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56493. activeSubMenu = 0;
  56494. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56495. {
  56496. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56497. dismissOnMouseUp,
  56498. this,
  56499. childComp->getScreenBounds(),
  56500. 0, maximumNumColumns,
  56501. standardItemHeight,
  56502. false, 0, managerOfChosenCommand,
  56503. componentAttachedTo);
  56504. if (activeSubMenu != 0)
  56505. {
  56506. activeSubMenu->setVisible (true);
  56507. activeSubMenu->enterModalState (false);
  56508. activeSubMenu->toFront (false);
  56509. return true;
  56510. }
  56511. }
  56512. return false;
  56513. }
  56514. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56515. {
  56516. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56517. if (isOver)
  56518. hasBeenOver = true;
  56519. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56520. {
  56521. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56522. if (disableMouseMoves && isOver)
  56523. disableMouseMoves = false;
  56524. }
  56525. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56526. return;
  56527. bool isMovingTowardsMenu = false;
  56528. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56529. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56530. {
  56531. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56532. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56533. // extends from the last mouse pos to the submenu's rectangle..
  56534. float subX = (float) activeSubMenu->getScreenX();
  56535. if (activeSubMenu->getX() > getX())
  56536. {
  56537. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56538. }
  56539. else
  56540. {
  56541. lastMouse += Point<int> (2, 0);
  56542. subX += activeSubMenu->getWidth();
  56543. }
  56544. Path areaTowardsSubMenu;
  56545. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56546. (float) lastMouse.getY(),
  56547. subX,
  56548. (float) activeSubMenu->getScreenY(),
  56549. subX,
  56550. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56551. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56552. }
  56553. lastMouse = globalMousePos;
  56554. if (! isMovingTowardsMenu)
  56555. {
  56556. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56557. if (c == this)
  56558. c = 0;
  56559. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56560. if (mic == 0 && c != 0)
  56561. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56562. if (mic != currentChild
  56563. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56564. {
  56565. if (isOver && (c != 0) && (activeSubMenu != 0))
  56566. {
  56567. activeSubMenu->hide (0);
  56568. }
  56569. if (! isOver)
  56570. mic = 0;
  56571. setCurrentlyHighlightedChild (mic);
  56572. }
  56573. }
  56574. }
  56575. void triggerCurrentlyHighlightedItem()
  56576. {
  56577. if (currentChild->isValidComponent()
  56578. && currentChild->itemInfo.canBeTriggered()
  56579. && (currentChild->itemInfo.customComp == 0
  56580. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56581. {
  56582. dismissMenu (&currentChild->itemInfo);
  56583. }
  56584. }
  56585. void selectNextItem (const int delta)
  56586. {
  56587. disableTimerUntilMouseMoves();
  56588. PopupMenu::ItemComponent* mic = 0;
  56589. bool wasLastOne = (currentChild == 0);
  56590. const int numItems = getNumChildComponents();
  56591. for (int i = 0; i < numItems + 1; ++i)
  56592. {
  56593. int index = (delta > 0) ? i : (numItems - 1 - i);
  56594. index = (index + numItems) % numItems;
  56595. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56596. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56597. && wasLastOne)
  56598. break;
  56599. if (mic == currentChild)
  56600. wasLastOne = true;
  56601. }
  56602. setCurrentlyHighlightedChild (mic);
  56603. }
  56604. void disableTimerUntilMouseMoves()
  56605. {
  56606. disableMouseMoves = true;
  56607. if (owner != 0)
  56608. owner->disableTimerUntilMouseMoves();
  56609. }
  56610. Window (const Window&);
  56611. Window& operator= (const Window&);
  56612. };
  56613. PopupMenu::PopupMenu()
  56614. : lookAndFeel (0),
  56615. separatorPending (false)
  56616. {
  56617. }
  56618. PopupMenu::PopupMenu (const PopupMenu& other)
  56619. : lookAndFeel (other.lookAndFeel),
  56620. separatorPending (false)
  56621. {
  56622. items.addCopiesOf (other.items);
  56623. }
  56624. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56625. {
  56626. if (this != &other)
  56627. {
  56628. lookAndFeel = other.lookAndFeel;
  56629. clear();
  56630. items.addCopiesOf (other.items);
  56631. }
  56632. return *this;
  56633. }
  56634. PopupMenu::~PopupMenu()
  56635. {
  56636. clear();
  56637. }
  56638. void PopupMenu::clear()
  56639. {
  56640. items.clear();
  56641. separatorPending = false;
  56642. }
  56643. void PopupMenu::addSeparatorIfPending()
  56644. {
  56645. if (separatorPending)
  56646. {
  56647. separatorPending = false;
  56648. if (items.size() > 0)
  56649. items.add (new Item());
  56650. }
  56651. }
  56652. void PopupMenu::addItem (const int itemResultId,
  56653. const String& itemText,
  56654. const bool isActive,
  56655. const bool isTicked,
  56656. const Image& iconToUse)
  56657. {
  56658. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56659. // didn't pick anything, so you shouldn't use it as the id
  56660. // for an item..
  56661. addSeparatorIfPending();
  56662. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56663. Colours::black, false, 0, 0, 0));
  56664. }
  56665. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56666. const int commandID,
  56667. const String& displayName)
  56668. {
  56669. jassert (commandManager != 0 && commandID != 0);
  56670. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56671. if (registeredInfo != 0)
  56672. {
  56673. ApplicationCommandInfo info (*registeredInfo);
  56674. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56675. addSeparatorIfPending();
  56676. items.add (new Item (commandID,
  56677. displayName.isNotEmpty() ? displayName
  56678. : info.shortName,
  56679. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56680. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56681. Image::null,
  56682. Colours::black,
  56683. false,
  56684. 0, 0,
  56685. commandManager));
  56686. }
  56687. }
  56688. void PopupMenu::addColouredItem (const int itemResultId,
  56689. const String& itemText,
  56690. const Colour& itemTextColour,
  56691. const bool isActive,
  56692. const bool isTicked,
  56693. const Image& iconToUse)
  56694. {
  56695. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56696. // didn't pick anything, so you shouldn't use it as the id
  56697. // for an item..
  56698. addSeparatorIfPending();
  56699. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56700. itemTextColour, true, 0, 0, 0));
  56701. }
  56702. void PopupMenu::addCustomItem (const int itemResultId,
  56703. PopupMenuCustomComponent* const customComponent)
  56704. {
  56705. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56706. // didn't pick anything, so you shouldn't use it as the id
  56707. // for an item..
  56708. addSeparatorIfPending();
  56709. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56710. Colours::black, false, customComponent, 0, 0));
  56711. }
  56712. class NormalComponentWrapper : public PopupMenuCustomComponent
  56713. {
  56714. public:
  56715. NormalComponentWrapper (Component* const comp,
  56716. const int w, const int h,
  56717. const bool triggerMenuItemAutomaticallyWhenClicked)
  56718. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56719. width (w),
  56720. height (h)
  56721. {
  56722. addAndMakeVisible (comp);
  56723. }
  56724. ~NormalComponentWrapper() {}
  56725. void getIdealSize (int& idealWidth, int& idealHeight)
  56726. {
  56727. idealWidth = width;
  56728. idealHeight = height;
  56729. }
  56730. void resized()
  56731. {
  56732. if (getChildComponent(0) != 0)
  56733. getChildComponent(0)->setBounds (getLocalBounds());
  56734. }
  56735. juce_UseDebuggingNewOperator
  56736. private:
  56737. const int width, height;
  56738. NormalComponentWrapper (const NormalComponentWrapper&);
  56739. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56740. };
  56741. void PopupMenu::addCustomItem (const int itemResultId,
  56742. Component* customComponent,
  56743. int idealWidth, int idealHeight,
  56744. const bool triggerMenuItemAutomaticallyWhenClicked)
  56745. {
  56746. addCustomItem (itemResultId,
  56747. new NormalComponentWrapper (customComponent,
  56748. idealWidth, idealHeight,
  56749. triggerMenuItemAutomaticallyWhenClicked));
  56750. }
  56751. void PopupMenu::addSubMenu (const String& subMenuName,
  56752. const PopupMenu& subMenu,
  56753. const bool isActive,
  56754. const Image& iconToUse,
  56755. const bool isTicked)
  56756. {
  56757. addSeparatorIfPending();
  56758. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56759. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56760. }
  56761. void PopupMenu::addSeparator()
  56762. {
  56763. separatorPending = true;
  56764. }
  56765. class HeaderItemComponent : public PopupMenuCustomComponent
  56766. {
  56767. public:
  56768. HeaderItemComponent (const String& name)
  56769. : PopupMenuCustomComponent (false)
  56770. {
  56771. setName (name);
  56772. }
  56773. ~HeaderItemComponent()
  56774. {
  56775. }
  56776. void paint (Graphics& g)
  56777. {
  56778. Font f (getLookAndFeel().getPopupMenuFont());
  56779. f.setBold (true);
  56780. g.setFont (f);
  56781. g.setColour (findColour (PopupMenu::headerTextColourId));
  56782. g.drawFittedText (getName(),
  56783. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56784. Justification::bottomLeft, 1);
  56785. }
  56786. void getIdealSize (int& idealWidth,
  56787. int& idealHeight)
  56788. {
  56789. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56790. idealHeight += idealHeight / 2;
  56791. idealWidth += idealWidth / 4;
  56792. }
  56793. juce_UseDebuggingNewOperator
  56794. };
  56795. void PopupMenu::addSectionHeader (const String& title)
  56796. {
  56797. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56798. }
  56799. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56800. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56801. {
  56802. public:
  56803. PopupMenuCompletionCallback()
  56804. : managerOfChosenCommand (0)
  56805. {
  56806. }
  56807. ~PopupMenuCompletionCallback() {}
  56808. void modalStateFinished (int result)
  56809. {
  56810. if (managerOfChosenCommand != 0 && result != 0)
  56811. {
  56812. ApplicationCommandTarget::InvocationInfo info (result);
  56813. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56814. managerOfChosenCommand->invoke (info, true);
  56815. }
  56816. }
  56817. ApplicationCommandManager* managerOfChosenCommand;
  56818. ScopedPointer<Component> component;
  56819. private:
  56820. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56821. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56822. };
  56823. int PopupMenu::showMenu (const Rectangle<int>& target,
  56824. const int itemIdThatMustBeVisible,
  56825. const int minimumWidth,
  56826. const int maximumNumColumns,
  56827. const int standardItemHeight,
  56828. const bool alignToRectangle,
  56829. Component* const componentAttachedTo,
  56830. ModalComponentManager::Callback* userCallback)
  56831. {
  56832. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56833. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56834. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56835. Window::wasHiddenBecauseOfAppChange() = false;
  56836. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56837. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56838. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56839. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56840. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56841. &callback->managerOfChosenCommand, componentAttachedTo);
  56842. if (callback->component == 0)
  56843. return 0;
  56844. callbackDeleter.release();
  56845. callback->component->enterModalState (false, userCallbackDeleter.release());
  56846. callback->component->toFront (false); // need to do this after making it modal, or it could
  56847. // be stuck behind other comps that are already modal..
  56848. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56849. if (userCallback != 0)
  56850. return 0;
  56851. const int result = callback->component->runModalLoop();
  56852. if (! Window::wasHiddenBecauseOfAppChange())
  56853. {
  56854. if (prevTopLevel != 0)
  56855. prevTopLevel->toFront (true);
  56856. if (prevFocused != 0)
  56857. prevFocused->grabKeyboardFocus();
  56858. }
  56859. return result;
  56860. }
  56861. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56862. const int minimumWidth,
  56863. const int maximumNumColumns,
  56864. const int standardItemHeight,
  56865. ModalComponentManager::Callback* callback)
  56866. {
  56867. const Point<int> mousePos (Desktop::getMousePosition());
  56868. return showAt (mousePos.getX(), mousePos.getY(),
  56869. itemIdThatMustBeVisible,
  56870. minimumWidth,
  56871. maximumNumColumns,
  56872. standardItemHeight,
  56873. callback);
  56874. }
  56875. int PopupMenu::showAt (const int screenX,
  56876. const int screenY,
  56877. const int itemIdThatMustBeVisible,
  56878. const int minimumWidth,
  56879. const int maximumNumColumns,
  56880. const int standardItemHeight,
  56881. ModalComponentManager::Callback* callback)
  56882. {
  56883. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56884. itemIdThatMustBeVisible,
  56885. minimumWidth, maximumNumColumns,
  56886. standardItemHeight,
  56887. false, 0, callback);
  56888. }
  56889. int PopupMenu::showAt (Component* componentToAttachTo,
  56890. const int itemIdThatMustBeVisible,
  56891. const int minimumWidth,
  56892. const int maximumNumColumns,
  56893. const int standardItemHeight,
  56894. ModalComponentManager::Callback* callback)
  56895. {
  56896. if (componentToAttachTo != 0)
  56897. {
  56898. return showMenu (componentToAttachTo->getScreenBounds(),
  56899. itemIdThatMustBeVisible,
  56900. minimumWidth,
  56901. maximumNumColumns,
  56902. standardItemHeight,
  56903. true, componentToAttachTo, callback);
  56904. }
  56905. else
  56906. {
  56907. return show (itemIdThatMustBeVisible,
  56908. minimumWidth,
  56909. maximumNumColumns,
  56910. standardItemHeight,
  56911. callback);
  56912. }
  56913. }
  56914. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56915. {
  56916. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56917. {
  56918. Window* const pmw = Window::getActiveWindows()[i];
  56919. if (pmw != 0)
  56920. pmw->dismissMenu (0);
  56921. }
  56922. }
  56923. int PopupMenu::getNumItems() const throw()
  56924. {
  56925. int num = 0;
  56926. for (int i = items.size(); --i >= 0;)
  56927. if (! (items.getUnchecked(i))->isSeparator)
  56928. ++num;
  56929. return num;
  56930. }
  56931. bool PopupMenu::containsCommandItem (const int commandID) const
  56932. {
  56933. for (int i = items.size(); --i >= 0;)
  56934. {
  56935. const Item* mi = items.getUnchecked (i);
  56936. if ((mi->itemId == commandID && mi->commandManager != 0)
  56937. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56938. {
  56939. return true;
  56940. }
  56941. }
  56942. return false;
  56943. }
  56944. bool PopupMenu::containsAnyActiveItems() const throw()
  56945. {
  56946. for (int i = items.size(); --i >= 0;)
  56947. {
  56948. const Item* const mi = items.getUnchecked (i);
  56949. if (mi->subMenu != 0)
  56950. {
  56951. if (mi->subMenu->containsAnyActiveItems())
  56952. return true;
  56953. }
  56954. else if (mi->active)
  56955. {
  56956. return true;
  56957. }
  56958. }
  56959. return false;
  56960. }
  56961. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56962. {
  56963. lookAndFeel = newLookAndFeel;
  56964. }
  56965. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56966. : isHighlighted (false),
  56967. isTriggeredAutomatically (isTriggeredAutomatically_)
  56968. {
  56969. }
  56970. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56971. {
  56972. }
  56973. void PopupMenuCustomComponent::triggerMenuItem()
  56974. {
  56975. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56976. if (mic != 0)
  56977. {
  56978. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56979. if (pmw != 0)
  56980. {
  56981. pmw->dismissMenu (&mic->itemInfo);
  56982. }
  56983. else
  56984. {
  56985. // something must have gone wrong with the component hierarchy if this happens..
  56986. jassertfalse;
  56987. }
  56988. }
  56989. else
  56990. {
  56991. // why isn't this component inside a menu? Not much point triggering the item if
  56992. // there's no menu.
  56993. jassertfalse;
  56994. }
  56995. }
  56996. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56997. : subMenu (0),
  56998. itemId (0),
  56999. isSeparator (false),
  57000. isTicked (false),
  57001. isEnabled (false),
  57002. isCustomComponent (false),
  57003. isSectionHeader (false),
  57004. customColour (0),
  57005. customImage (0),
  57006. menu (menu_),
  57007. index (0)
  57008. {
  57009. }
  57010. PopupMenu::MenuItemIterator::~MenuItemIterator()
  57011. {
  57012. }
  57013. bool PopupMenu::MenuItemIterator::next()
  57014. {
  57015. if (index >= menu.items.size())
  57016. return false;
  57017. const Item* const item = menu.items.getUnchecked (index);
  57018. ++index;
  57019. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  57020. subMenu = item->subMenu;
  57021. itemId = item->itemId;
  57022. isSeparator = item->isSeparator;
  57023. isTicked = item->isTicked;
  57024. isEnabled = item->active;
  57025. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  57026. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  57027. customColour = item->usesColour ? &(item->textColour) : 0;
  57028. customImage = item->image;
  57029. commandManager = item->commandManager;
  57030. return true;
  57031. }
  57032. END_JUCE_NAMESPACE
  57033. /*** End of inlined file: juce_PopupMenu.cpp ***/
  57034. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  57035. BEGIN_JUCE_NAMESPACE
  57036. ComponentDragger::ComponentDragger()
  57037. : constrainer (0)
  57038. {
  57039. }
  57040. ComponentDragger::~ComponentDragger()
  57041. {
  57042. }
  57043. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  57044. ComponentBoundsConstrainer* const constrainer_)
  57045. {
  57046. jassert (componentToDrag->isValidComponent());
  57047. if (componentToDrag != 0)
  57048. {
  57049. constrainer = constrainer_;
  57050. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  57051. }
  57052. }
  57053. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  57054. {
  57055. jassert (componentToDrag->isValidComponent());
  57056. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  57057. if (componentToDrag != 0)
  57058. {
  57059. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57060. const Component* const parentComp = componentToDrag->getParentComponent();
  57061. if (parentComp != 0)
  57062. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57063. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57064. if (constrainer != 0)
  57065. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57066. else
  57067. componentToDrag->setBounds (bounds);
  57068. }
  57069. }
  57070. END_JUCE_NAMESPACE
  57071. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57072. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57073. BEGIN_JUCE_NAMESPACE
  57074. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57075. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57076. class DragImageComponent : public Component,
  57077. public Timer
  57078. {
  57079. public:
  57080. DragImageComponent (const Image& im,
  57081. const String& desc,
  57082. Component* const sourceComponent,
  57083. Component* const mouseDragSource_,
  57084. DragAndDropContainer* const o,
  57085. const Point<int>& imageOffset_)
  57086. : image (im),
  57087. source (sourceComponent),
  57088. mouseDragSource (mouseDragSource_),
  57089. owner (o),
  57090. dragDesc (desc),
  57091. imageOffset (imageOffset_),
  57092. hasCheckedForExternalDrag (false),
  57093. drawImage (true)
  57094. {
  57095. setSize (im.getWidth(), im.getHeight());
  57096. if (mouseDragSource == 0)
  57097. mouseDragSource = source;
  57098. mouseDragSource->addMouseListener (this, false);
  57099. startTimer (200);
  57100. setInterceptsMouseClicks (false, false);
  57101. setAlwaysOnTop (true);
  57102. }
  57103. ~DragImageComponent()
  57104. {
  57105. if (owner->dragImageComponent == this)
  57106. owner->dragImageComponent.release();
  57107. if (mouseDragSource != 0)
  57108. {
  57109. mouseDragSource->removeMouseListener (this);
  57110. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57111. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57112. }
  57113. }
  57114. void paint (Graphics& g)
  57115. {
  57116. if (isOpaque())
  57117. g.fillAll (Colours::white);
  57118. if (drawImage)
  57119. {
  57120. g.setOpacity (1.0f);
  57121. g.drawImageAt (image, 0, 0);
  57122. }
  57123. }
  57124. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57125. {
  57126. Component* hit = getParentComponent();
  57127. if (hit == 0)
  57128. {
  57129. hit = Desktop::getInstance().findComponentAt (screenPos);
  57130. }
  57131. else
  57132. {
  57133. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57134. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57135. }
  57136. // (note: use a local copy of the dragDesc member in case the callback runs
  57137. // a modal loop and deletes this object before the method completes)
  57138. const String dragDescLocal (dragDesc);
  57139. while (hit != 0)
  57140. {
  57141. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57142. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57143. {
  57144. relativePos = hit->globalPositionToRelative (screenPos);
  57145. return ddt;
  57146. }
  57147. hit = hit->getParentComponent();
  57148. }
  57149. return 0;
  57150. }
  57151. void mouseUp (const MouseEvent& e)
  57152. {
  57153. if (e.originalComponent != this)
  57154. {
  57155. if (mouseDragSource != 0)
  57156. mouseDragSource->removeMouseListener (this);
  57157. bool dropAccepted = false;
  57158. DragAndDropTarget* ddt = 0;
  57159. Point<int> relPos;
  57160. if (isVisible())
  57161. {
  57162. setVisible (false);
  57163. ddt = findTarget (e.getScreenPosition(), relPos);
  57164. // fade this component and remove it - it'll be deleted later by the timer callback
  57165. dropAccepted = ddt != 0;
  57166. setVisible (true);
  57167. if (dropAccepted || source == 0)
  57168. {
  57169. fadeOutComponent (120);
  57170. }
  57171. else
  57172. {
  57173. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57174. source->getHeight() / 2)));
  57175. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57176. getHeight() / 2)));
  57177. fadeOutComponent (120,
  57178. target.getX() - ourCentre.getX(),
  57179. target.getY() - ourCentre.getY());
  57180. }
  57181. }
  57182. if (getParentComponent() != 0)
  57183. getParentComponent()->removeChildComponent (this);
  57184. if (dropAccepted && ddt != 0)
  57185. {
  57186. // (note: use a local copy of the dragDesc member in case the callback runs
  57187. // a modal loop and deletes this object before the method completes)
  57188. const String dragDescLocal (dragDesc);
  57189. currentlyOverComp = 0;
  57190. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57191. }
  57192. // careful - this object could now be deleted..
  57193. }
  57194. }
  57195. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57196. {
  57197. // (note: use a local copy of the dragDesc member in case the callback runs
  57198. // a modal loop and deletes this object before it returns)
  57199. const String dragDescLocal (dragDesc);
  57200. Point<int> newPos (screenPos + imageOffset);
  57201. if (getParentComponent() != 0)
  57202. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57203. //if (newX != getX() || newY != getY())
  57204. {
  57205. setTopLeftPosition (newPos.getX(), newPos.getY());
  57206. Point<int> relPos;
  57207. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57208. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57209. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57210. if (ddtComp != currentlyOverComp)
  57211. {
  57212. if (currentlyOverComp != 0 && source != 0
  57213. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57214. {
  57215. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57216. }
  57217. currentlyOverComp = ddtComp;
  57218. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57219. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57220. }
  57221. DragAndDropTarget* target = getCurrentlyOver();
  57222. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57223. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57224. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57225. {
  57226. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57227. {
  57228. hasCheckedForExternalDrag = true;
  57229. StringArray files;
  57230. bool canMoveFiles = false;
  57231. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57232. && files.size() > 0)
  57233. {
  57234. Component::SafePointer<Component> cdw (this);
  57235. setVisible (false);
  57236. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57237. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57238. if (cdw != 0)
  57239. delete this;
  57240. return;
  57241. }
  57242. }
  57243. }
  57244. }
  57245. }
  57246. void mouseDrag (const MouseEvent& e)
  57247. {
  57248. if (e.originalComponent != this)
  57249. updateLocation (true, e.getScreenPosition());
  57250. }
  57251. void timerCallback()
  57252. {
  57253. if (source == 0)
  57254. {
  57255. delete this;
  57256. }
  57257. else if (! isMouseButtonDownAnywhere())
  57258. {
  57259. if (mouseDragSource != 0)
  57260. mouseDragSource->removeMouseListener (this);
  57261. delete this;
  57262. }
  57263. }
  57264. private:
  57265. Image image;
  57266. Component::SafePointer<Component> source;
  57267. Component::SafePointer<Component> mouseDragSource;
  57268. DragAndDropContainer* const owner;
  57269. Component::SafePointer<Component> currentlyOverComp;
  57270. DragAndDropTarget* getCurrentlyOver()
  57271. {
  57272. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57273. }
  57274. String dragDesc;
  57275. const Point<int> imageOffset;
  57276. bool hasCheckedForExternalDrag, drawImage;
  57277. DragImageComponent (const DragImageComponent&);
  57278. DragImageComponent& operator= (const DragImageComponent&);
  57279. };
  57280. DragAndDropContainer::DragAndDropContainer()
  57281. {
  57282. }
  57283. DragAndDropContainer::~DragAndDropContainer()
  57284. {
  57285. dragImageComponent = 0;
  57286. }
  57287. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57288. Component* sourceComponent,
  57289. const Image& dragImage_,
  57290. const bool allowDraggingToExternalWindows,
  57291. const Point<int>* imageOffsetFromMouse)
  57292. {
  57293. Image dragImage (dragImage_);
  57294. if (dragImageComponent == 0)
  57295. {
  57296. Component* const thisComp = dynamic_cast <Component*> (this);
  57297. if (thisComp == 0)
  57298. {
  57299. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57300. return;
  57301. }
  57302. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57303. if (draggingSource == 0 || ! draggingSource->isDragging())
  57304. {
  57305. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57306. return;
  57307. }
  57308. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57309. Point<int> imageOffset;
  57310. if (dragImage.isNull())
  57311. {
  57312. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57313. .convertedToFormat (Image::ARGB);
  57314. dragImage.multiplyAllAlphas (0.6f);
  57315. const int lo = 150;
  57316. const int hi = 400;
  57317. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57318. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57319. for (int y = dragImage.getHeight(); --y >= 0;)
  57320. {
  57321. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57322. for (int x = dragImage.getWidth(); --x >= 0;)
  57323. {
  57324. const int dx = x - clipped.getX();
  57325. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57326. if (distance > lo)
  57327. {
  57328. const float alpha = (distance > hi) ? 0
  57329. : (hi - distance) / (float) (hi - lo)
  57330. + Random::getSystemRandom().nextFloat() * 0.008f;
  57331. dragImage.multiplyAlphaAt (x, y, alpha);
  57332. }
  57333. }
  57334. }
  57335. imageOffset = -clipped;
  57336. }
  57337. else
  57338. {
  57339. if (imageOffsetFromMouse == 0)
  57340. imageOffset = -dragImage.getBounds().getCentre();
  57341. else
  57342. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57343. }
  57344. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57345. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57346. currentDragDesc = sourceDescription;
  57347. if (allowDraggingToExternalWindows)
  57348. {
  57349. if (! Desktop::canUseSemiTransparentWindows())
  57350. dragImageComponent->setOpaque (true);
  57351. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57352. | ComponentPeer::windowIsTemporary
  57353. | ComponentPeer::windowIgnoresKeyPresses);
  57354. }
  57355. else
  57356. thisComp->addChildComponent (dragImageComponent);
  57357. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57358. dragImageComponent->setVisible (true);
  57359. }
  57360. }
  57361. bool DragAndDropContainer::isDragAndDropActive() const
  57362. {
  57363. return dragImageComponent != 0;
  57364. }
  57365. const String DragAndDropContainer::getCurrentDragDescription() const
  57366. {
  57367. return (dragImageComponent != 0) ? currentDragDesc
  57368. : String::empty;
  57369. }
  57370. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57371. {
  57372. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57373. }
  57374. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57375. {
  57376. return false;
  57377. }
  57378. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57379. {
  57380. }
  57381. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57382. {
  57383. }
  57384. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57385. {
  57386. }
  57387. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57388. {
  57389. return true;
  57390. }
  57391. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57392. {
  57393. }
  57394. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57395. {
  57396. }
  57397. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57398. {
  57399. }
  57400. END_JUCE_NAMESPACE
  57401. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57402. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57403. BEGIN_JUCE_NAMESPACE
  57404. class MouseCursor::SharedCursorHandle
  57405. {
  57406. public:
  57407. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57408. : handle (createStandardMouseCursor (type)),
  57409. refCount (1),
  57410. standardType (type),
  57411. isStandard (true)
  57412. {
  57413. }
  57414. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57415. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57416. refCount (1),
  57417. standardType (MouseCursor::NormalCursor),
  57418. isStandard (false)
  57419. {
  57420. }
  57421. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57422. {
  57423. const ScopedLock sl (getLock());
  57424. for (int i = 0; i < getCursors().size(); ++i)
  57425. {
  57426. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57427. if (sc->standardType == type)
  57428. return sc->retain();
  57429. }
  57430. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57431. getCursors().add (sc);
  57432. return sc;
  57433. }
  57434. SharedCursorHandle* retain() throw()
  57435. {
  57436. ++refCount;
  57437. return this;
  57438. }
  57439. void release()
  57440. {
  57441. if (--refCount == 0)
  57442. {
  57443. if (isStandard)
  57444. {
  57445. const ScopedLock sl (getLock());
  57446. getCursors().removeValue (this);
  57447. }
  57448. delete this;
  57449. }
  57450. }
  57451. void* getHandle() const throw() { return handle; }
  57452. juce_UseDebuggingNewOperator
  57453. private:
  57454. void* const handle;
  57455. Atomic <int> refCount;
  57456. const MouseCursor::StandardCursorType standardType;
  57457. const bool isStandard;
  57458. static CriticalSection& getLock()
  57459. {
  57460. static CriticalSection lock;
  57461. return lock;
  57462. }
  57463. static Array <SharedCursorHandle*>& getCursors()
  57464. {
  57465. static Array <SharedCursorHandle*> cursors;
  57466. return cursors;
  57467. }
  57468. ~SharedCursorHandle()
  57469. {
  57470. deleteMouseCursor (handle, isStandard);
  57471. }
  57472. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57473. };
  57474. MouseCursor::MouseCursor()
  57475. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57476. {
  57477. jassert (cursorHandle != 0);
  57478. }
  57479. MouseCursor::MouseCursor (const StandardCursorType type)
  57480. : cursorHandle (SharedCursorHandle::createStandard (type))
  57481. {
  57482. jassert (cursorHandle != 0);
  57483. }
  57484. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57485. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57486. {
  57487. }
  57488. MouseCursor::MouseCursor (const MouseCursor& other)
  57489. : cursorHandle (other.cursorHandle->retain())
  57490. {
  57491. }
  57492. MouseCursor::~MouseCursor()
  57493. {
  57494. cursorHandle->release();
  57495. }
  57496. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57497. {
  57498. other.cursorHandle->retain();
  57499. cursorHandle->release();
  57500. cursorHandle = other.cursorHandle;
  57501. return *this;
  57502. }
  57503. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57504. {
  57505. return getHandle() == other.getHandle();
  57506. }
  57507. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57508. {
  57509. return getHandle() != other.getHandle();
  57510. }
  57511. void* MouseCursor::getHandle() const throw()
  57512. {
  57513. return cursorHandle->getHandle();
  57514. }
  57515. void MouseCursor::showWaitCursor()
  57516. {
  57517. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57518. }
  57519. void MouseCursor::hideWaitCursor()
  57520. {
  57521. Desktop::getInstance().getMainMouseSource().revealCursor();
  57522. }
  57523. END_JUCE_NAMESPACE
  57524. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57525. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57526. BEGIN_JUCE_NAMESPACE
  57527. MouseEvent::MouseEvent (MouseInputSource& source_,
  57528. const Point<int>& position,
  57529. const ModifierKeys& mods_,
  57530. Component* const eventComponent_,
  57531. Component* const originator,
  57532. const Time& eventTime_,
  57533. const Point<int> mouseDownPos_,
  57534. const Time& mouseDownTime_,
  57535. const int numberOfClicks_,
  57536. const bool mouseWasDragged) throw()
  57537. : x (position.getX()),
  57538. y (position.getY()),
  57539. mods (mods_),
  57540. eventComponent (eventComponent_),
  57541. originalComponent (originator),
  57542. eventTime (eventTime_),
  57543. source (source_),
  57544. mouseDownPos (mouseDownPos_),
  57545. mouseDownTime (mouseDownTime_),
  57546. numberOfClicks (numberOfClicks_),
  57547. wasMovedSinceMouseDown (mouseWasDragged)
  57548. {
  57549. }
  57550. MouseEvent::~MouseEvent() throw()
  57551. {
  57552. }
  57553. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57554. {
  57555. if (otherComponent == 0)
  57556. {
  57557. jassertfalse;
  57558. return *this;
  57559. }
  57560. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57561. mods, otherComponent, originalComponent, eventTime,
  57562. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57563. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57564. }
  57565. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57566. {
  57567. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57568. eventTime, mouseDownPos, mouseDownTime,
  57569. numberOfClicks, wasMovedSinceMouseDown);
  57570. }
  57571. bool MouseEvent::mouseWasClicked() const throw()
  57572. {
  57573. return ! wasMovedSinceMouseDown;
  57574. }
  57575. int MouseEvent::getMouseDownX() const throw()
  57576. {
  57577. return mouseDownPos.getX();
  57578. }
  57579. int MouseEvent::getMouseDownY() const throw()
  57580. {
  57581. return mouseDownPos.getY();
  57582. }
  57583. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57584. {
  57585. return mouseDownPos;
  57586. }
  57587. int MouseEvent::getDistanceFromDragStartX() const throw()
  57588. {
  57589. return x - mouseDownPos.getX();
  57590. }
  57591. int MouseEvent::getDistanceFromDragStartY() const throw()
  57592. {
  57593. return y - mouseDownPos.getY();
  57594. }
  57595. int MouseEvent::getDistanceFromDragStart() const throw()
  57596. {
  57597. return mouseDownPos.getDistanceFrom (getPosition());
  57598. }
  57599. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57600. {
  57601. return getPosition() - mouseDownPos;
  57602. }
  57603. int MouseEvent::getLengthOfMousePress() const throw()
  57604. {
  57605. if (mouseDownTime.toMilliseconds() > 0)
  57606. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57607. return 0;
  57608. }
  57609. const Point<int> MouseEvent::getPosition() const throw()
  57610. {
  57611. return Point<int> (x, y);
  57612. }
  57613. int MouseEvent::getScreenX() const
  57614. {
  57615. return getScreenPosition().getX();
  57616. }
  57617. int MouseEvent::getScreenY() const
  57618. {
  57619. return getScreenPosition().getY();
  57620. }
  57621. const Point<int> MouseEvent::getScreenPosition() const
  57622. {
  57623. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57624. }
  57625. int MouseEvent::getMouseDownScreenX() const
  57626. {
  57627. return getMouseDownScreenPosition().getX();
  57628. }
  57629. int MouseEvent::getMouseDownScreenY() const
  57630. {
  57631. return getMouseDownScreenPosition().getY();
  57632. }
  57633. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57634. {
  57635. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57636. }
  57637. int MouseEvent::doubleClickTimeOutMs = 400;
  57638. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57639. {
  57640. doubleClickTimeOutMs = newTime;
  57641. }
  57642. int MouseEvent::getDoubleClickTimeout() throw()
  57643. {
  57644. return doubleClickTimeOutMs;
  57645. }
  57646. END_JUCE_NAMESPACE
  57647. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57648. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57649. BEGIN_JUCE_NAMESPACE
  57650. class MouseInputSourceInternal : public AsyncUpdater
  57651. {
  57652. public:
  57653. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57654. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57655. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57656. mouseEventCounter (0), lastTime (0)
  57657. {
  57658. zerostruct (mouseDowns);
  57659. }
  57660. ~MouseInputSourceInternal()
  57661. {
  57662. }
  57663. bool isDragging() const throw()
  57664. {
  57665. return buttonState.isAnyMouseButtonDown();
  57666. }
  57667. Component* getComponentUnderMouse() const
  57668. {
  57669. return static_cast <Component*> (componentUnderMouse);
  57670. }
  57671. const ModifierKeys getCurrentModifiers() const
  57672. {
  57673. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57674. }
  57675. ComponentPeer* getPeer()
  57676. {
  57677. if (! ComponentPeer::isValidPeer (lastPeer))
  57678. lastPeer = 0;
  57679. return lastPeer;
  57680. }
  57681. Component* findComponentAt (const Point<int>& screenPos)
  57682. {
  57683. ComponentPeer* const peer = getPeer();
  57684. if (peer != 0)
  57685. {
  57686. Component* const comp = peer->getComponent();
  57687. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57688. // (the contains() call is needed to test for overlapping desktop windows)
  57689. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57690. return comp->getComponentAt (relativePos);
  57691. }
  57692. return 0;
  57693. }
  57694. const Point<int> getScreenPosition() const throw()
  57695. {
  57696. return lastScreenPos + unboundedMouseOffset;
  57697. }
  57698. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57699. {
  57700. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57701. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57702. }
  57703. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57704. {
  57705. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57706. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57707. }
  57708. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57709. {
  57710. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57711. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57712. }
  57713. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57714. {
  57715. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57716. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57717. }
  57718. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57719. {
  57720. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57721. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57722. }
  57723. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57724. {
  57725. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57726. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57727. }
  57728. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57729. {
  57730. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57731. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57732. }
  57733. // (returns true if the button change caused a modal event loop)
  57734. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57735. {
  57736. if (buttonState == newButtonState)
  57737. return false;
  57738. setScreenPos (screenPos, time, false);
  57739. // (ignore secondary clicks when there's already a button down)
  57740. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57741. {
  57742. buttonState = newButtonState;
  57743. return false;
  57744. }
  57745. const int lastCounter = mouseEventCounter;
  57746. if (buttonState.isAnyMouseButtonDown())
  57747. {
  57748. Component* const current = getComponentUnderMouse();
  57749. if (current != 0)
  57750. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57751. enableUnboundedMouseMovement (false, false);
  57752. }
  57753. buttonState = newButtonState;
  57754. if (buttonState.isAnyMouseButtonDown())
  57755. {
  57756. Desktop::getInstance().incrementMouseClickCounter();
  57757. Component* const current = getComponentUnderMouse();
  57758. if (current != 0)
  57759. {
  57760. registerMouseDown (screenPos, time, current, buttonState);
  57761. sendMouseDown (current, screenPos, time);
  57762. }
  57763. }
  57764. return lastCounter != mouseEventCounter;
  57765. }
  57766. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57767. {
  57768. Component* current = getComponentUnderMouse();
  57769. if (newComponent != current)
  57770. {
  57771. Component::SafePointer<Component> safeNewComp (newComponent);
  57772. const ModifierKeys originalButtonState (buttonState);
  57773. if (current != 0)
  57774. {
  57775. setButtons (screenPos, time, ModifierKeys());
  57776. sendMouseExit (current, screenPos, time);
  57777. buttonState = originalButtonState;
  57778. }
  57779. componentUnderMouse = safeNewComp;
  57780. current = getComponentUnderMouse();
  57781. if (current != 0)
  57782. sendMouseEnter (current, screenPos, time);
  57783. revealCursor (false);
  57784. setButtons (screenPos, time, originalButtonState);
  57785. }
  57786. }
  57787. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57788. {
  57789. ModifierKeys::updateCurrentModifiers();
  57790. if (newPeer != lastPeer)
  57791. {
  57792. setComponentUnderMouse (0, screenPos, time);
  57793. lastPeer = newPeer;
  57794. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57795. }
  57796. }
  57797. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57798. {
  57799. if (! isDragging())
  57800. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57801. if (newScreenPos != lastScreenPos || forceUpdate)
  57802. {
  57803. cancelPendingUpdate();
  57804. lastScreenPos = newScreenPos;
  57805. Component* const current = getComponentUnderMouse();
  57806. if (current != 0)
  57807. {
  57808. if (isDragging())
  57809. {
  57810. registerMouseDrag (newScreenPos);
  57811. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57812. if (isUnboundedMouseModeOn)
  57813. handleUnboundedDrag (current);
  57814. }
  57815. else
  57816. {
  57817. sendMouseMove (current, newScreenPos, time);
  57818. }
  57819. }
  57820. revealCursor (false);
  57821. }
  57822. }
  57823. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57824. {
  57825. jassert (newPeer != 0);
  57826. lastTime = time;
  57827. ++mouseEventCounter;
  57828. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57829. if (isDragging() && newMods.isAnyMouseButtonDown())
  57830. {
  57831. setScreenPos (screenPos, time, false);
  57832. }
  57833. else
  57834. {
  57835. setPeer (newPeer, screenPos, time);
  57836. ComponentPeer* peer = getPeer();
  57837. if (peer != 0)
  57838. {
  57839. if (setButtons (screenPos, time, newMods))
  57840. return; // some modal events have been dispatched, so the current event is now out-of-date
  57841. peer = getPeer();
  57842. if (peer != 0)
  57843. setScreenPos (screenPos, time, false);
  57844. }
  57845. }
  57846. }
  57847. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57848. {
  57849. jassert (peer != 0);
  57850. lastTime = time;
  57851. ++mouseEventCounter;
  57852. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57853. setPeer (peer, screenPos, time);
  57854. setScreenPos (screenPos, time, false);
  57855. triggerFakeMove();
  57856. if (! isDragging())
  57857. {
  57858. Component* current = getComponentUnderMouse();
  57859. if (current != 0)
  57860. sendMouseWheel (current, screenPos, time, x, y);
  57861. }
  57862. }
  57863. const Time getLastMouseDownTime() const throw()
  57864. {
  57865. return Time (mouseDowns[0].time);
  57866. }
  57867. const Point<int> getLastMouseDownPosition() const throw()
  57868. {
  57869. return mouseDowns[0].position;
  57870. }
  57871. int getNumberOfMultipleClicks() const throw()
  57872. {
  57873. int numClicks = 0;
  57874. if (mouseDowns[0].time != 0)
  57875. {
  57876. if (! mouseMovedSignificantlySincePressed)
  57877. ++numClicks;
  57878. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57879. {
  57880. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[1], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57881. ++numClicks;
  57882. else
  57883. break;
  57884. }
  57885. }
  57886. return numClicks;
  57887. }
  57888. bool hasMouseMovedSignificantlySincePressed() const throw()
  57889. {
  57890. return mouseMovedSignificantlySincePressed
  57891. || lastTime > mouseDowns[0].time + 300;
  57892. }
  57893. void triggerFakeMove()
  57894. {
  57895. triggerAsyncUpdate();
  57896. }
  57897. void handleAsyncUpdate()
  57898. {
  57899. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57900. }
  57901. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57902. {
  57903. enable = enable && isDragging();
  57904. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57905. if (enable != isUnboundedMouseModeOn)
  57906. {
  57907. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57908. {
  57909. // when released, return the mouse to within the component's bounds
  57910. Component* current = getComponentUnderMouse();
  57911. if (current != 0)
  57912. Desktop::setMousePosition (current->getScreenBounds()
  57913. .getConstrainedPoint (lastScreenPos));
  57914. }
  57915. isUnboundedMouseModeOn = enable;
  57916. unboundedMouseOffset = Point<int>();
  57917. revealCursor (true);
  57918. }
  57919. }
  57920. void handleUnboundedDrag (Component* current)
  57921. {
  57922. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57923. if (! screenArea.contains (lastScreenPos))
  57924. {
  57925. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57926. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57927. Desktop::setMousePosition (componentCentre);
  57928. }
  57929. else if (isCursorVisibleUntilOffscreen
  57930. && (! unboundedMouseOffset.isOrigin())
  57931. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57932. {
  57933. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57934. unboundedMouseOffset = Point<int>();
  57935. }
  57936. }
  57937. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57938. {
  57939. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57940. {
  57941. cursor = MouseCursor::NoCursor;
  57942. forcedUpdate = true;
  57943. }
  57944. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57945. {
  57946. currentCursorHandle = cursor.getHandle();
  57947. cursor.showInWindow (getPeer());
  57948. }
  57949. }
  57950. void hideCursor()
  57951. {
  57952. showMouseCursor (MouseCursor::NoCursor, true);
  57953. }
  57954. void revealCursor (bool forcedUpdate)
  57955. {
  57956. MouseCursor mc (MouseCursor::NormalCursor);
  57957. Component* current = getComponentUnderMouse();
  57958. if (current != 0)
  57959. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57960. showMouseCursor (mc, forcedUpdate);
  57961. }
  57962. int index;
  57963. bool isMouseDevice;
  57964. Point<int> lastScreenPos;
  57965. ModifierKeys buttonState;
  57966. private:
  57967. MouseInputSource& source;
  57968. Component::SafePointer<Component> componentUnderMouse;
  57969. ComponentPeer* lastPeer;
  57970. Point<int> unboundedMouseOffset;
  57971. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57972. void* currentCursorHandle;
  57973. int mouseEventCounter;
  57974. struct RecentMouseDown
  57975. {
  57976. Point<int> position;
  57977. int64 time;
  57978. Component* component;
  57979. ModifierKeys buttons;
  57980. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, int maxTimeBetween) const
  57981. {
  57982. return time - other.time < maxTimeBetween
  57983. && abs (position.getX() - other.position.getX()) < 8
  57984. && abs (position.getY() - other.position.getY()) < 8
  57985. && buttons == other.buttons;;
  57986. }
  57987. };
  57988. RecentMouseDown mouseDowns[4];
  57989. bool mouseMovedSignificantlySincePressed;
  57990. int64 lastTime;
  57991. void registerMouseDown (const Point<int>& screenPos, const int64 time,
  57992. Component* const component, const ModifierKeys& modifiers) throw()
  57993. {
  57994. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57995. mouseDowns[i] = mouseDowns[i - 1];
  57996. mouseDowns[0].position = screenPos;
  57997. mouseDowns[0].time = time;
  57998. mouseDowns[0].component = component;
  57999. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  58000. mouseMovedSignificantlySincePressed = false;
  58001. }
  58002. void registerMouseDrag (const Point<int>& screenPos) throw()
  58003. {
  58004. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  58005. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  58006. }
  58007. MouseInputSourceInternal (const MouseInputSourceInternal&);
  58008. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  58009. };
  58010. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  58011. {
  58012. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  58013. }
  58014. MouseInputSource::~MouseInputSource()
  58015. {
  58016. }
  58017. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  58018. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  58019. bool MouseInputSource::canHover() const { return isMouse(); }
  58020. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  58021. int MouseInputSource::getIndex() const { return pimpl->index; }
  58022. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  58023. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  58024. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  58025. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  58026. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  58027. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  58028. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  58029. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  58030. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  58031. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  58032. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  58033. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  58034. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  58035. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  58036. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  58037. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  58038. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  58039. {
  58040. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  58041. }
  58042. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  58043. {
  58044. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  58045. }
  58046. END_JUCE_NAMESPACE
  58047. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  58048. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  58049. BEGIN_JUCE_NAMESPACE
  58050. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  58051. : source (0),
  58052. hoverTimeMillisecs (hoverTimeMillisecs_),
  58053. hasJustHovered (false)
  58054. {
  58055. internalTimer.owner = this;
  58056. }
  58057. MouseHoverDetector::~MouseHoverDetector()
  58058. {
  58059. setHoverComponent (0);
  58060. }
  58061. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58062. {
  58063. hoverTimeMillisecs = newTimeInMillisecs;
  58064. }
  58065. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58066. {
  58067. if (source != newSourceComponent)
  58068. {
  58069. internalTimer.stopTimer();
  58070. hasJustHovered = false;
  58071. if (source != 0)
  58072. {
  58073. // ! you need to delete the hover detector before deleting its component
  58074. jassert (source->isValidComponent());
  58075. source->removeMouseListener (&internalTimer);
  58076. }
  58077. source = newSourceComponent;
  58078. if (newSourceComponent != 0)
  58079. newSourceComponent->addMouseListener (&internalTimer, false);
  58080. }
  58081. }
  58082. void MouseHoverDetector::hoverTimerCallback()
  58083. {
  58084. internalTimer.stopTimer();
  58085. if (source != 0)
  58086. {
  58087. const Point<int> pos (source->getMouseXYRelative());
  58088. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58089. {
  58090. hasJustHovered = true;
  58091. mouseHovered (pos.getX(), pos.getY());
  58092. }
  58093. }
  58094. }
  58095. void MouseHoverDetector::checkJustHoveredCallback()
  58096. {
  58097. if (hasJustHovered)
  58098. {
  58099. hasJustHovered = false;
  58100. mouseMovedAfterHover();
  58101. }
  58102. }
  58103. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58104. {
  58105. owner->hoverTimerCallback();
  58106. }
  58107. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58108. {
  58109. stopTimer();
  58110. owner->checkJustHoveredCallback();
  58111. }
  58112. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58113. {
  58114. stopTimer();
  58115. owner->checkJustHoveredCallback();
  58116. }
  58117. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58118. {
  58119. stopTimer();
  58120. owner->checkJustHoveredCallback();
  58121. }
  58122. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58123. {
  58124. stopTimer();
  58125. owner->checkJustHoveredCallback();
  58126. }
  58127. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58128. {
  58129. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58130. {
  58131. lastX = e.x;
  58132. lastY = e.y;
  58133. if (owner->source != 0)
  58134. startTimer (owner->hoverTimeMillisecs);
  58135. owner->checkJustHoveredCallback();
  58136. }
  58137. }
  58138. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58139. {
  58140. stopTimer();
  58141. owner->checkJustHoveredCallback();
  58142. }
  58143. END_JUCE_NAMESPACE
  58144. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58145. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58146. BEGIN_JUCE_NAMESPACE
  58147. void MouseListener::mouseEnter (const MouseEvent&)
  58148. {
  58149. }
  58150. void MouseListener::mouseExit (const MouseEvent&)
  58151. {
  58152. }
  58153. void MouseListener::mouseDown (const MouseEvent&)
  58154. {
  58155. }
  58156. void MouseListener::mouseUp (const MouseEvent&)
  58157. {
  58158. }
  58159. void MouseListener::mouseDrag (const MouseEvent&)
  58160. {
  58161. }
  58162. void MouseListener::mouseMove (const MouseEvent&)
  58163. {
  58164. }
  58165. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58166. {
  58167. }
  58168. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58169. {
  58170. }
  58171. END_JUCE_NAMESPACE
  58172. /*** End of inlined file: juce_MouseListener.cpp ***/
  58173. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58174. BEGIN_JUCE_NAMESPACE
  58175. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58176. const String& buttonTextWhenTrue,
  58177. const String& buttonTextWhenFalse)
  58178. : PropertyComponent (name),
  58179. onText (buttonTextWhenTrue),
  58180. offText (buttonTextWhenFalse)
  58181. {
  58182. addAndMakeVisible (&button);
  58183. button.setClickingTogglesState (false);
  58184. button.addButtonListener (this);
  58185. }
  58186. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58187. const String& name,
  58188. const String& buttonText)
  58189. : PropertyComponent (name),
  58190. onText (buttonText),
  58191. offText (buttonText)
  58192. {
  58193. addAndMakeVisible (&button);
  58194. button.setClickingTogglesState (false);
  58195. button.setButtonText (buttonText);
  58196. button.getToggleStateValue().referTo (valueToControl);
  58197. button.setClickingTogglesState (true);
  58198. }
  58199. BooleanPropertyComponent::~BooleanPropertyComponent()
  58200. {
  58201. }
  58202. void BooleanPropertyComponent::setState (const bool newState)
  58203. {
  58204. button.setToggleState (newState, true);
  58205. }
  58206. bool BooleanPropertyComponent::getState() const
  58207. {
  58208. return button.getToggleState();
  58209. }
  58210. void BooleanPropertyComponent::paint (Graphics& g)
  58211. {
  58212. PropertyComponent::paint (g);
  58213. g.setColour (Colours::white);
  58214. g.fillRect (button.getBounds());
  58215. g.setColour (findColour (ComboBox::outlineColourId));
  58216. g.drawRect (button.getBounds());
  58217. }
  58218. void BooleanPropertyComponent::refresh()
  58219. {
  58220. button.setToggleState (getState(), false);
  58221. button.setButtonText (button.getToggleState() ? onText : offText);
  58222. }
  58223. void BooleanPropertyComponent::buttonClicked (Button*)
  58224. {
  58225. setState (! getState());
  58226. }
  58227. END_JUCE_NAMESPACE
  58228. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58229. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58230. BEGIN_JUCE_NAMESPACE
  58231. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58232. const bool triggerOnMouseDown)
  58233. : PropertyComponent (name)
  58234. {
  58235. addAndMakeVisible (&button);
  58236. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58237. button.addButtonListener (this);
  58238. }
  58239. ButtonPropertyComponent::~ButtonPropertyComponent()
  58240. {
  58241. }
  58242. void ButtonPropertyComponent::refresh()
  58243. {
  58244. button.setButtonText (getButtonText());
  58245. }
  58246. void ButtonPropertyComponent::buttonClicked (Button*)
  58247. {
  58248. buttonClicked();
  58249. }
  58250. END_JUCE_NAMESPACE
  58251. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58252. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58253. BEGIN_JUCE_NAMESPACE
  58254. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58255. public Value::Listener
  58256. {
  58257. public:
  58258. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58259. : sourceValue (sourceValue_),
  58260. mappings (mappings_)
  58261. {
  58262. sourceValue.addListener (this);
  58263. }
  58264. ~RemapperValueSource() {}
  58265. const var getValue() const
  58266. {
  58267. return mappings.indexOf (sourceValue.getValue()) + 1;
  58268. }
  58269. void setValue (const var& newValue)
  58270. {
  58271. const var remappedVal (mappings [(int) newValue - 1]);
  58272. if (remappedVal != sourceValue)
  58273. sourceValue = remappedVal;
  58274. }
  58275. void valueChanged (Value&)
  58276. {
  58277. sendChangeMessage (true);
  58278. }
  58279. juce_UseDebuggingNewOperator
  58280. protected:
  58281. Value sourceValue;
  58282. Array<var> mappings;
  58283. RemapperValueSource (const RemapperValueSource&);
  58284. const RemapperValueSource& operator= (const RemapperValueSource&);
  58285. };
  58286. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58287. : PropertyComponent (name),
  58288. isCustomClass (true)
  58289. {
  58290. }
  58291. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58292. const String& name,
  58293. const StringArray& choices_,
  58294. const Array <var>& correspondingValues)
  58295. : PropertyComponent (name),
  58296. choices (choices_),
  58297. isCustomClass (false)
  58298. {
  58299. // The array of corresponding values must contain one value for each of the items in
  58300. // the choices array!
  58301. jassert (correspondingValues.size() == choices.size());
  58302. createComboBox();
  58303. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58304. }
  58305. ChoicePropertyComponent::~ChoicePropertyComponent()
  58306. {
  58307. }
  58308. void ChoicePropertyComponent::createComboBox()
  58309. {
  58310. addAndMakeVisible (&comboBox);
  58311. for (int i = 0; i < choices.size(); ++i)
  58312. {
  58313. if (choices[i].isNotEmpty())
  58314. comboBox.addItem (choices[i], i + 1);
  58315. else
  58316. comboBox.addSeparator();
  58317. }
  58318. comboBox.setEditableText (false);
  58319. }
  58320. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58321. {
  58322. jassertfalse; // you need to override this method in your subclass!
  58323. }
  58324. int ChoicePropertyComponent::getIndex() const
  58325. {
  58326. jassertfalse; // you need to override this method in your subclass!
  58327. return -1;
  58328. }
  58329. const StringArray& ChoicePropertyComponent::getChoices() const
  58330. {
  58331. return choices;
  58332. }
  58333. void ChoicePropertyComponent::refresh()
  58334. {
  58335. if (isCustomClass)
  58336. {
  58337. if (! comboBox.isVisible())
  58338. {
  58339. createComboBox();
  58340. comboBox.addListener (this);
  58341. }
  58342. comboBox.setSelectedId (getIndex() + 1, true);
  58343. }
  58344. }
  58345. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58346. {
  58347. if (isCustomClass)
  58348. {
  58349. const int newIndex = comboBox.getSelectedId() - 1;
  58350. if (newIndex != getIndex())
  58351. setIndex (newIndex);
  58352. }
  58353. }
  58354. END_JUCE_NAMESPACE
  58355. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58356. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58357. BEGIN_JUCE_NAMESPACE
  58358. PropertyComponent::PropertyComponent (const String& name,
  58359. const int preferredHeight_)
  58360. : Component (name),
  58361. preferredHeight (preferredHeight_)
  58362. {
  58363. jassert (name.isNotEmpty());
  58364. }
  58365. PropertyComponent::~PropertyComponent()
  58366. {
  58367. }
  58368. void PropertyComponent::paint (Graphics& g)
  58369. {
  58370. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58371. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58372. }
  58373. void PropertyComponent::resized()
  58374. {
  58375. if (getNumChildComponents() > 0)
  58376. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58377. }
  58378. void PropertyComponent::enablementChanged()
  58379. {
  58380. repaint();
  58381. }
  58382. END_JUCE_NAMESPACE
  58383. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58384. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58385. BEGIN_JUCE_NAMESPACE
  58386. class PropertyPanel::PropertyHolderComponent : public Component
  58387. {
  58388. public:
  58389. PropertyHolderComponent()
  58390. {
  58391. }
  58392. ~PropertyHolderComponent()
  58393. {
  58394. deleteAllChildren();
  58395. }
  58396. void paint (Graphics&)
  58397. {
  58398. }
  58399. void updateLayout (int width);
  58400. void refreshAll() const;
  58401. private:
  58402. PropertyHolderComponent (const PropertyHolderComponent&);
  58403. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58404. };
  58405. class PropertySectionComponent : public Component
  58406. {
  58407. public:
  58408. PropertySectionComponent (const String& sectionTitle,
  58409. const Array <PropertyComponent*>& newProperties,
  58410. const bool open)
  58411. : Component (sectionTitle),
  58412. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58413. isOpen_ (open)
  58414. {
  58415. for (int i = newProperties.size(); --i >= 0;)
  58416. {
  58417. addAndMakeVisible (newProperties.getUnchecked(i));
  58418. newProperties.getUnchecked(i)->refresh();
  58419. }
  58420. }
  58421. ~PropertySectionComponent()
  58422. {
  58423. deleteAllChildren();
  58424. }
  58425. void paint (Graphics& g)
  58426. {
  58427. if (titleHeight > 0)
  58428. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58429. }
  58430. void resized()
  58431. {
  58432. int y = titleHeight;
  58433. for (int i = getNumChildComponents(); --i >= 0;)
  58434. {
  58435. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58436. if (pec != 0)
  58437. {
  58438. const int prefH = pec->getPreferredHeight();
  58439. pec->setBounds (1, y, getWidth() - 2, prefH);
  58440. y += prefH;
  58441. }
  58442. }
  58443. }
  58444. int getPreferredHeight() const
  58445. {
  58446. int y = titleHeight;
  58447. if (isOpen())
  58448. {
  58449. for (int i = 0; i < getNumChildComponents(); ++i)
  58450. {
  58451. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58452. if (pec != 0)
  58453. y += pec->getPreferredHeight();
  58454. }
  58455. }
  58456. return y;
  58457. }
  58458. void setOpen (const bool open)
  58459. {
  58460. if (isOpen_ != open)
  58461. {
  58462. isOpen_ = open;
  58463. for (int i = 0; i < getNumChildComponents(); ++i)
  58464. {
  58465. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58466. if (pec != 0)
  58467. pec->setVisible (open);
  58468. }
  58469. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58470. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58471. if (pp != 0)
  58472. pp->resized();
  58473. }
  58474. }
  58475. bool isOpen() const
  58476. {
  58477. return isOpen_;
  58478. }
  58479. void refreshAll() const
  58480. {
  58481. for (int i = 0; i < getNumChildComponents(); ++i)
  58482. {
  58483. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58484. if (pec != 0)
  58485. pec->refresh();
  58486. }
  58487. }
  58488. void mouseDown (const MouseEvent&)
  58489. {
  58490. }
  58491. void mouseUp (const MouseEvent& e)
  58492. {
  58493. if (e.getMouseDownX() < titleHeight
  58494. && e.x < titleHeight
  58495. && e.y < titleHeight
  58496. && e.getNumberOfClicks() != 2)
  58497. {
  58498. setOpen (! isOpen());
  58499. }
  58500. }
  58501. void mouseDoubleClick (const MouseEvent& e)
  58502. {
  58503. if (e.y < titleHeight)
  58504. setOpen (! isOpen());
  58505. }
  58506. private:
  58507. int titleHeight;
  58508. bool isOpen_;
  58509. PropertySectionComponent (const PropertySectionComponent&);
  58510. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58511. };
  58512. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58513. {
  58514. int y = 0;
  58515. for (int i = getNumChildComponents(); --i >= 0;)
  58516. {
  58517. PropertySectionComponent* const section
  58518. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58519. if (section != 0)
  58520. {
  58521. const int prefH = section->getPreferredHeight();
  58522. section->setBounds (0, y, width, prefH);
  58523. y += prefH;
  58524. }
  58525. }
  58526. setSize (width, y);
  58527. repaint();
  58528. }
  58529. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58530. {
  58531. for (int i = getNumChildComponents(); --i >= 0;)
  58532. {
  58533. PropertySectionComponent* const section
  58534. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58535. if (section != 0)
  58536. section->refreshAll();
  58537. }
  58538. }
  58539. PropertyPanel::PropertyPanel()
  58540. {
  58541. messageWhenEmpty = TRANS("(nothing selected)");
  58542. addAndMakeVisible (&viewport);
  58543. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58544. viewport.setFocusContainer (true);
  58545. }
  58546. PropertyPanel::~PropertyPanel()
  58547. {
  58548. clear();
  58549. }
  58550. void PropertyPanel::paint (Graphics& g)
  58551. {
  58552. if (propertyHolderComponent->getNumChildComponents() == 0)
  58553. {
  58554. g.setColour (Colours::black.withAlpha (0.5f));
  58555. g.setFont (14.0f);
  58556. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58557. Justification::centred, true);
  58558. }
  58559. }
  58560. void PropertyPanel::resized()
  58561. {
  58562. viewport.setBounds (getLocalBounds());
  58563. updatePropHolderLayout();
  58564. }
  58565. void PropertyPanel::clear()
  58566. {
  58567. if (propertyHolderComponent->getNumChildComponents() > 0)
  58568. {
  58569. propertyHolderComponent->deleteAllChildren();
  58570. repaint();
  58571. }
  58572. }
  58573. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58574. {
  58575. if (propertyHolderComponent->getNumChildComponents() == 0)
  58576. repaint();
  58577. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58578. newProperties,
  58579. true), 0);
  58580. updatePropHolderLayout();
  58581. }
  58582. void PropertyPanel::addSection (const String& sectionTitle,
  58583. const Array <PropertyComponent*>& newProperties,
  58584. const bool shouldBeOpen)
  58585. {
  58586. jassert (sectionTitle.isNotEmpty());
  58587. if (propertyHolderComponent->getNumChildComponents() == 0)
  58588. repaint();
  58589. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58590. newProperties,
  58591. shouldBeOpen), 0);
  58592. updatePropHolderLayout();
  58593. }
  58594. void PropertyPanel::updatePropHolderLayout() const
  58595. {
  58596. const int maxWidth = viewport.getMaximumVisibleWidth();
  58597. propertyHolderComponent->updateLayout (maxWidth);
  58598. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58599. if (maxWidth != newMaxWidth)
  58600. {
  58601. // need to do this twice because of scrollbars changing the size, etc.
  58602. propertyHolderComponent->updateLayout (newMaxWidth);
  58603. }
  58604. }
  58605. void PropertyPanel::refreshAll() const
  58606. {
  58607. propertyHolderComponent->refreshAll();
  58608. }
  58609. const StringArray PropertyPanel::getSectionNames() const
  58610. {
  58611. StringArray s;
  58612. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58613. {
  58614. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58615. if (section != 0 && section->getName().isNotEmpty())
  58616. s.add (section->getName());
  58617. }
  58618. return s;
  58619. }
  58620. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58621. {
  58622. int index = 0;
  58623. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58624. {
  58625. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58626. if (section != 0 && section->getName().isNotEmpty())
  58627. {
  58628. if (index == sectionIndex)
  58629. return section->isOpen();
  58630. ++index;
  58631. }
  58632. }
  58633. return false;
  58634. }
  58635. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58636. {
  58637. int index = 0;
  58638. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58639. {
  58640. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58641. if (section != 0 && section->getName().isNotEmpty())
  58642. {
  58643. if (index == sectionIndex)
  58644. {
  58645. section->setOpen (shouldBeOpen);
  58646. break;
  58647. }
  58648. ++index;
  58649. }
  58650. }
  58651. }
  58652. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58653. {
  58654. int index = 0;
  58655. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58656. {
  58657. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58658. if (section != 0 && section->getName().isNotEmpty())
  58659. {
  58660. if (index == sectionIndex)
  58661. {
  58662. section->setEnabled (shouldBeEnabled);
  58663. break;
  58664. }
  58665. ++index;
  58666. }
  58667. }
  58668. }
  58669. XmlElement* PropertyPanel::getOpennessState() const
  58670. {
  58671. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58672. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58673. const StringArray sections (getSectionNames());
  58674. for (int i = 0; i < sections.size(); ++i)
  58675. {
  58676. if (sections[i].isNotEmpty())
  58677. {
  58678. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58679. e->setAttribute ("name", sections[i]);
  58680. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58681. }
  58682. }
  58683. return xml;
  58684. }
  58685. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58686. {
  58687. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58688. {
  58689. const StringArray sections (getSectionNames());
  58690. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58691. {
  58692. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58693. e->getBoolAttribute ("open"));
  58694. }
  58695. viewport.setViewPosition (viewport.getViewPositionX(),
  58696. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58697. }
  58698. }
  58699. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58700. {
  58701. if (messageWhenEmpty != newMessage)
  58702. {
  58703. messageWhenEmpty = newMessage;
  58704. repaint();
  58705. }
  58706. }
  58707. const String& PropertyPanel::getMessageWhenEmpty() const
  58708. {
  58709. return messageWhenEmpty;
  58710. }
  58711. END_JUCE_NAMESPACE
  58712. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58713. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58714. BEGIN_JUCE_NAMESPACE
  58715. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58716. const double rangeMin,
  58717. const double rangeMax,
  58718. const double interval,
  58719. const double skewFactor)
  58720. : PropertyComponent (name)
  58721. {
  58722. addAndMakeVisible (&slider);
  58723. slider.setRange (rangeMin, rangeMax, interval);
  58724. slider.setSkewFactor (skewFactor);
  58725. slider.setSliderStyle (Slider::LinearBar);
  58726. slider.addListener (this);
  58727. }
  58728. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58729. const String& name,
  58730. const double rangeMin,
  58731. const double rangeMax,
  58732. const double interval,
  58733. const double skewFactor)
  58734. : PropertyComponent (name)
  58735. {
  58736. addAndMakeVisible (&slider);
  58737. slider.setRange (rangeMin, rangeMax, interval);
  58738. slider.setSkewFactor (skewFactor);
  58739. slider.setSliderStyle (Slider::LinearBar);
  58740. slider.getValueObject().referTo (valueToControl);
  58741. }
  58742. SliderPropertyComponent::~SliderPropertyComponent()
  58743. {
  58744. }
  58745. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58746. {
  58747. }
  58748. double SliderPropertyComponent::getValue() const
  58749. {
  58750. return slider.getValue();
  58751. }
  58752. void SliderPropertyComponent::refresh()
  58753. {
  58754. slider.setValue (getValue(), false);
  58755. }
  58756. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58757. {
  58758. if (getValue() != slider.getValue())
  58759. setValue (slider.getValue());
  58760. }
  58761. END_JUCE_NAMESPACE
  58762. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58763. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58764. BEGIN_JUCE_NAMESPACE
  58765. class TextPropLabel : public Label
  58766. {
  58767. TextPropertyComponent& owner;
  58768. int maxChars;
  58769. bool isMultiline;
  58770. public:
  58771. TextPropLabel (TextPropertyComponent& owner_,
  58772. const int maxChars_, const bool isMultiline_)
  58773. : Label (String::empty, String::empty),
  58774. owner (owner_),
  58775. maxChars (maxChars_),
  58776. isMultiline (isMultiline_)
  58777. {
  58778. setEditable (true, true, false);
  58779. setColour (backgroundColourId, Colours::white);
  58780. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58781. }
  58782. ~TextPropLabel()
  58783. {
  58784. }
  58785. TextEditor* createEditorComponent()
  58786. {
  58787. TextEditor* const textEditor = Label::createEditorComponent();
  58788. textEditor->setInputRestrictions (maxChars);
  58789. if (isMultiline)
  58790. {
  58791. textEditor->setMultiLine (true, true);
  58792. textEditor->setReturnKeyStartsNewLine (true);
  58793. }
  58794. return textEditor;
  58795. }
  58796. void textWasEdited()
  58797. {
  58798. owner.textWasEdited();
  58799. }
  58800. };
  58801. TextPropertyComponent::TextPropertyComponent (const String& name,
  58802. const int maxNumChars,
  58803. const bool isMultiLine)
  58804. : PropertyComponent (name)
  58805. {
  58806. createEditor (maxNumChars, isMultiLine);
  58807. }
  58808. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58809. const String& name,
  58810. const int maxNumChars,
  58811. const bool isMultiLine)
  58812. : PropertyComponent (name)
  58813. {
  58814. createEditor (maxNumChars, isMultiLine);
  58815. textEditor->getTextValue().referTo (valueToControl);
  58816. }
  58817. TextPropertyComponent::~TextPropertyComponent()
  58818. {
  58819. deleteAllChildren();
  58820. }
  58821. void TextPropertyComponent::setText (const String& newText)
  58822. {
  58823. textEditor->setText (newText, true);
  58824. }
  58825. const String TextPropertyComponent::getText() const
  58826. {
  58827. return textEditor->getText();
  58828. }
  58829. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58830. {
  58831. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58832. if (isMultiLine)
  58833. {
  58834. textEditor->setJustificationType (Justification::topLeft);
  58835. preferredHeight = 120;
  58836. }
  58837. }
  58838. void TextPropertyComponent::refresh()
  58839. {
  58840. textEditor->setText (getText(), false);
  58841. }
  58842. void TextPropertyComponent::textWasEdited()
  58843. {
  58844. const String newText (textEditor->getText());
  58845. if (getText() != newText)
  58846. setText (newText);
  58847. }
  58848. END_JUCE_NAMESPACE
  58849. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58850. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58851. BEGIN_JUCE_NAMESPACE
  58852. class SimpleDeviceManagerInputLevelMeter : public Component,
  58853. public Timer
  58854. {
  58855. public:
  58856. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58857. : manager (manager_),
  58858. level (0)
  58859. {
  58860. startTimer (50);
  58861. manager->enableInputLevelMeasurement (true);
  58862. }
  58863. ~SimpleDeviceManagerInputLevelMeter()
  58864. {
  58865. manager->enableInputLevelMeasurement (false);
  58866. }
  58867. void timerCallback()
  58868. {
  58869. const float newLevel = (float) manager->getCurrentInputLevel();
  58870. if (std::abs (level - newLevel) > 0.005f)
  58871. {
  58872. level = newLevel;
  58873. repaint();
  58874. }
  58875. }
  58876. void paint (Graphics& g)
  58877. {
  58878. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58879. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58880. }
  58881. private:
  58882. AudioDeviceManager* const manager;
  58883. float level;
  58884. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58885. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58886. };
  58887. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58888. public ListBoxModel
  58889. {
  58890. public:
  58891. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58892. const String& noItemsMessage_,
  58893. const int minNumber_,
  58894. const int maxNumber_)
  58895. : ListBox (String::empty, 0),
  58896. deviceManager (deviceManager_),
  58897. noItemsMessage (noItemsMessage_),
  58898. minNumber (minNumber_),
  58899. maxNumber (maxNumber_)
  58900. {
  58901. items = MidiInput::getDevices();
  58902. setModel (this);
  58903. setOutlineThickness (1);
  58904. }
  58905. ~MidiInputSelectorComponentListBox()
  58906. {
  58907. }
  58908. int getNumRows()
  58909. {
  58910. return items.size();
  58911. }
  58912. void paintListBoxItem (int row,
  58913. Graphics& g,
  58914. int width, int height,
  58915. bool rowIsSelected)
  58916. {
  58917. if (((unsigned int) row) < (unsigned int) items.size())
  58918. {
  58919. if (rowIsSelected)
  58920. g.fillAll (findColour (TextEditor::highlightColourId)
  58921. .withMultipliedAlpha (0.3f));
  58922. const String item (items [row]);
  58923. bool enabled = deviceManager.isMidiInputEnabled (item);
  58924. const int x = getTickX();
  58925. const float tickW = height * 0.75f;
  58926. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58927. enabled, true, true, false);
  58928. g.setFont (height * 0.6f);
  58929. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58930. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58931. }
  58932. }
  58933. void listBoxItemClicked (int row, const MouseEvent& e)
  58934. {
  58935. selectRow (row);
  58936. if (e.x < getTickX())
  58937. flipEnablement (row);
  58938. }
  58939. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58940. {
  58941. flipEnablement (row);
  58942. }
  58943. void returnKeyPressed (int row)
  58944. {
  58945. flipEnablement (row);
  58946. }
  58947. void paint (Graphics& g)
  58948. {
  58949. ListBox::paint (g);
  58950. if (items.size() == 0)
  58951. {
  58952. g.setColour (Colours::grey);
  58953. g.setFont (13.0f);
  58954. g.drawText (noItemsMessage,
  58955. 0, 0, getWidth(), getHeight() / 2,
  58956. Justification::centred, true);
  58957. }
  58958. }
  58959. int getBestHeight (const int preferredHeight)
  58960. {
  58961. const int extra = getOutlineThickness() * 2;
  58962. return jmax (getRowHeight() * 2 + extra,
  58963. jmin (getRowHeight() * getNumRows() + extra,
  58964. preferredHeight));
  58965. }
  58966. juce_UseDebuggingNewOperator
  58967. private:
  58968. AudioDeviceManager& deviceManager;
  58969. const String noItemsMessage;
  58970. StringArray items;
  58971. int minNumber, maxNumber;
  58972. void flipEnablement (const int row)
  58973. {
  58974. if (((unsigned int) row) < (unsigned int) items.size())
  58975. {
  58976. const String item (items [row]);
  58977. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58978. }
  58979. }
  58980. int getTickX() const
  58981. {
  58982. return getRowHeight() + 5;
  58983. }
  58984. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58985. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58986. };
  58987. class AudioDeviceSettingsPanel : public Component,
  58988. public ChangeListener,
  58989. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58990. public ButtonListener
  58991. {
  58992. public:
  58993. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58994. AudioIODeviceType::DeviceSetupDetails& setup_,
  58995. const bool hideAdvancedOptionsWithButton)
  58996. : type (type_),
  58997. setup (setup_)
  58998. {
  58999. if (hideAdvancedOptionsWithButton)
  59000. {
  59001. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  59002. showAdvancedSettingsButton->addButtonListener (this);
  59003. }
  59004. type->scanForDevices();
  59005. setup.manager->addChangeListener (this);
  59006. changeListenerCallback (0);
  59007. }
  59008. ~AudioDeviceSettingsPanel()
  59009. {
  59010. setup.manager->removeChangeListener (this);
  59011. }
  59012. void resized()
  59013. {
  59014. const int lx = proportionOfWidth (0.35f);
  59015. const int w = proportionOfWidth (0.4f);
  59016. const int h = 24;
  59017. const int space = 6;
  59018. const int dh = h + space;
  59019. int y = 0;
  59020. if (outputDeviceDropDown != 0)
  59021. {
  59022. outputDeviceDropDown->setBounds (lx, y, w, h);
  59023. if (testButton != 0)
  59024. testButton->setBounds (proportionOfWidth (0.77f),
  59025. outputDeviceDropDown->getY(),
  59026. proportionOfWidth (0.18f),
  59027. h);
  59028. y += dh;
  59029. }
  59030. if (inputDeviceDropDown != 0)
  59031. {
  59032. inputDeviceDropDown->setBounds (lx, y, w, h);
  59033. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  59034. inputDeviceDropDown->getY(),
  59035. proportionOfWidth (0.18f),
  59036. h);
  59037. y += dh;
  59038. }
  59039. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  59040. if (outputChanList != 0)
  59041. {
  59042. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  59043. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59044. y += bh + space;
  59045. }
  59046. if (inputChanList != 0)
  59047. {
  59048. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  59049. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59050. y += bh + space;
  59051. }
  59052. y += space * 2;
  59053. if (showAdvancedSettingsButton != 0)
  59054. {
  59055. showAdvancedSettingsButton->changeWidthToFitText (h);
  59056. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  59057. }
  59058. if (sampleRateDropDown != 0)
  59059. {
  59060. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  59061. || ! showAdvancedSettingsButton->isVisible());
  59062. sampleRateDropDown->setBounds (lx, y, w, h);
  59063. y += dh;
  59064. }
  59065. if (bufferSizeDropDown != 0)
  59066. {
  59067. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59068. || ! showAdvancedSettingsButton->isVisible());
  59069. bufferSizeDropDown->setBounds (lx, y, w, h);
  59070. y += dh;
  59071. }
  59072. if (showUIButton != 0)
  59073. {
  59074. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59075. || ! showAdvancedSettingsButton->isVisible());
  59076. showUIButton->changeWidthToFitText (h);
  59077. showUIButton->setTopLeftPosition (lx, y);
  59078. }
  59079. }
  59080. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59081. {
  59082. if (comboBoxThatHasChanged == 0)
  59083. return;
  59084. AudioDeviceManager::AudioDeviceSetup config;
  59085. setup.manager->getAudioDeviceSetup (config);
  59086. String error;
  59087. if (comboBoxThatHasChanged == outputDeviceDropDown
  59088. || comboBoxThatHasChanged == inputDeviceDropDown)
  59089. {
  59090. if (outputDeviceDropDown != 0)
  59091. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59092. : outputDeviceDropDown->getText();
  59093. if (inputDeviceDropDown != 0)
  59094. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59095. : inputDeviceDropDown->getText();
  59096. if (! type->hasSeparateInputsAndOutputs())
  59097. config.inputDeviceName = config.outputDeviceName;
  59098. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59099. config.useDefaultInputChannels = true;
  59100. else
  59101. config.useDefaultOutputChannels = true;
  59102. error = setup.manager->setAudioDeviceSetup (config, true);
  59103. showCorrectDeviceName (inputDeviceDropDown, true);
  59104. showCorrectDeviceName (outputDeviceDropDown, false);
  59105. updateControlPanelButton();
  59106. resized();
  59107. }
  59108. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59109. {
  59110. if (sampleRateDropDown->getSelectedId() > 0)
  59111. {
  59112. config.sampleRate = sampleRateDropDown->getSelectedId();
  59113. error = setup.manager->setAudioDeviceSetup (config, true);
  59114. }
  59115. }
  59116. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59117. {
  59118. if (bufferSizeDropDown->getSelectedId() > 0)
  59119. {
  59120. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59121. error = setup.manager->setAudioDeviceSetup (config, true);
  59122. }
  59123. }
  59124. if (error.isNotEmpty())
  59125. {
  59126. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59127. "Error when trying to open audio device!",
  59128. error);
  59129. }
  59130. }
  59131. void buttonClicked (Button* button)
  59132. {
  59133. if (button == showAdvancedSettingsButton)
  59134. {
  59135. showAdvancedSettingsButton->setVisible (false);
  59136. resized();
  59137. }
  59138. else if (button == showUIButton)
  59139. {
  59140. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59141. if (device != 0 && device->showControlPanel())
  59142. {
  59143. setup.manager->closeAudioDevice();
  59144. setup.manager->restartLastAudioDevice();
  59145. getTopLevelComponent()->toFront (true);
  59146. }
  59147. }
  59148. else if (button == testButton && testButton != 0)
  59149. {
  59150. setup.manager->playTestSound();
  59151. }
  59152. }
  59153. void updateControlPanelButton()
  59154. {
  59155. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59156. showUIButton = 0;
  59157. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59158. {
  59159. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59160. TRANS ("opens the device's own control panel")));
  59161. showUIButton->addButtonListener (this);
  59162. }
  59163. resized();
  59164. }
  59165. void changeListenerCallback (void*)
  59166. {
  59167. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59168. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59169. {
  59170. if (outputDeviceDropDown == 0)
  59171. {
  59172. outputDeviceDropDown = new ComboBox (String::empty);
  59173. outputDeviceDropDown->addListener (this);
  59174. addAndMakeVisible (outputDeviceDropDown);
  59175. outputDeviceLabel = new Label (String::empty,
  59176. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59177. : TRANS ("device:"));
  59178. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59179. if (setup.maxNumOutputChannels > 0)
  59180. {
  59181. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59182. testButton->addButtonListener (this);
  59183. }
  59184. }
  59185. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59186. }
  59187. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59188. {
  59189. if (inputDeviceDropDown == 0)
  59190. {
  59191. inputDeviceDropDown = new ComboBox (String::empty);
  59192. inputDeviceDropDown->addListener (this);
  59193. addAndMakeVisible (inputDeviceDropDown);
  59194. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59195. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59196. addAndMakeVisible (inputLevelMeter
  59197. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59198. }
  59199. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59200. }
  59201. updateControlPanelButton();
  59202. showCorrectDeviceName (inputDeviceDropDown, true);
  59203. showCorrectDeviceName (outputDeviceDropDown, false);
  59204. if (currentDevice != 0)
  59205. {
  59206. if (setup.maxNumOutputChannels > 0
  59207. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59208. {
  59209. if (outputChanList == 0)
  59210. {
  59211. addAndMakeVisible (outputChanList
  59212. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59213. TRANS ("(no audio output channels found)")));
  59214. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59215. outputChanLabel->attachToComponent (outputChanList, true);
  59216. }
  59217. outputChanList->refresh();
  59218. }
  59219. else
  59220. {
  59221. outputChanLabel = 0;
  59222. outputChanList = 0;
  59223. }
  59224. if (setup.maxNumInputChannels > 0
  59225. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59226. {
  59227. if (inputChanList == 0)
  59228. {
  59229. addAndMakeVisible (inputChanList
  59230. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59231. TRANS ("(no audio input channels found)")));
  59232. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59233. inputChanLabel->attachToComponent (inputChanList, true);
  59234. }
  59235. inputChanList->refresh();
  59236. }
  59237. else
  59238. {
  59239. inputChanLabel = 0;
  59240. inputChanList = 0;
  59241. }
  59242. // sample rate..
  59243. {
  59244. if (sampleRateDropDown == 0)
  59245. {
  59246. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59247. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59248. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59249. }
  59250. else
  59251. {
  59252. sampleRateDropDown->clear();
  59253. sampleRateDropDown->removeListener (this);
  59254. }
  59255. const int numRates = currentDevice->getNumSampleRates();
  59256. for (int i = 0; i < numRates; ++i)
  59257. {
  59258. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59259. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59260. }
  59261. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59262. sampleRateDropDown->addListener (this);
  59263. }
  59264. // buffer size
  59265. {
  59266. if (bufferSizeDropDown == 0)
  59267. {
  59268. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59269. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59270. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59271. }
  59272. else
  59273. {
  59274. bufferSizeDropDown->clear();
  59275. bufferSizeDropDown->removeListener (this);
  59276. }
  59277. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59278. double currentRate = currentDevice->getCurrentSampleRate();
  59279. if (currentRate == 0)
  59280. currentRate = 48000.0;
  59281. for (int i = 0; i < numBufferSizes; ++i)
  59282. {
  59283. const int bs = currentDevice->getBufferSizeSamples (i);
  59284. bufferSizeDropDown->addItem (String (bs)
  59285. + " samples ("
  59286. + String (bs * 1000.0 / currentRate, 1)
  59287. + " ms)",
  59288. bs);
  59289. }
  59290. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59291. bufferSizeDropDown->addListener (this);
  59292. }
  59293. }
  59294. else
  59295. {
  59296. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59297. sampleRateLabel = 0;
  59298. bufferSizeLabel = 0;
  59299. sampleRateDropDown = 0;
  59300. bufferSizeDropDown = 0;
  59301. if (outputDeviceDropDown != 0)
  59302. outputDeviceDropDown->setSelectedId (-1, true);
  59303. if (inputDeviceDropDown != 0)
  59304. inputDeviceDropDown->setSelectedId (-1, true);
  59305. }
  59306. resized();
  59307. setSize (getWidth(), getLowestY() + 4);
  59308. }
  59309. private:
  59310. AudioIODeviceType* const type;
  59311. const AudioIODeviceType::DeviceSetupDetails setup;
  59312. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59313. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59314. ScopedPointer<TextButton> testButton;
  59315. ScopedPointer<Component> inputLevelMeter;
  59316. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59317. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59318. {
  59319. if (box != 0)
  59320. {
  59321. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59322. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59323. box->setSelectedId (index + 1, true);
  59324. if (testButton != 0 && ! isInput)
  59325. testButton->setEnabled (index >= 0);
  59326. }
  59327. }
  59328. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59329. {
  59330. const StringArray devs (type->getDeviceNames (isInputs));
  59331. combo.clear (true);
  59332. for (int i = 0; i < devs.size(); ++i)
  59333. combo.addItem (devs[i], i + 1);
  59334. combo.addItem (TRANS("<< none >>"), -1);
  59335. combo.setSelectedId (-1, true);
  59336. }
  59337. int getLowestY() const
  59338. {
  59339. int y = 0;
  59340. for (int i = getNumChildComponents(); --i >= 0;)
  59341. y = jmax (y, getChildComponent (i)->getBottom());
  59342. return y;
  59343. }
  59344. public:
  59345. class ChannelSelectorListBox : public ListBox,
  59346. public ListBoxModel
  59347. {
  59348. public:
  59349. enum BoxType
  59350. {
  59351. audioInputType,
  59352. audioOutputType
  59353. };
  59354. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59355. const BoxType type_,
  59356. const String& noItemsMessage_)
  59357. : ListBox (String::empty, 0),
  59358. setup (setup_),
  59359. type (type_),
  59360. noItemsMessage (noItemsMessage_)
  59361. {
  59362. refresh();
  59363. setModel (this);
  59364. setOutlineThickness (1);
  59365. }
  59366. ~ChannelSelectorListBox()
  59367. {
  59368. }
  59369. void refresh()
  59370. {
  59371. items.clear();
  59372. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59373. if (currentDevice != 0)
  59374. {
  59375. if (type == audioInputType)
  59376. items = currentDevice->getInputChannelNames();
  59377. else if (type == audioOutputType)
  59378. items = currentDevice->getOutputChannelNames();
  59379. if (setup.useStereoPairs)
  59380. {
  59381. StringArray pairs;
  59382. for (int i = 0; i < items.size(); i += 2)
  59383. {
  59384. const String name (items[i]);
  59385. const String name2 (items[i + 1]);
  59386. String commonBit;
  59387. for (int j = 0; j < name.length(); ++j)
  59388. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59389. commonBit = name.substring (0, j);
  59390. // Make sure we only split the name at a space, because otherwise, things
  59391. // like "input 11" + "input 12" would become "input 11 + 2"
  59392. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59393. commonBit = commonBit.dropLastCharacters (1);
  59394. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59395. }
  59396. items = pairs;
  59397. }
  59398. }
  59399. updateContent();
  59400. repaint();
  59401. }
  59402. int getNumRows()
  59403. {
  59404. return items.size();
  59405. }
  59406. void paintListBoxItem (int row,
  59407. Graphics& g,
  59408. int width, int height,
  59409. bool rowIsSelected)
  59410. {
  59411. if (((unsigned int) row) < (unsigned int) items.size())
  59412. {
  59413. if (rowIsSelected)
  59414. g.fillAll (findColour (TextEditor::highlightColourId)
  59415. .withMultipliedAlpha (0.3f));
  59416. const String item (items [row]);
  59417. bool enabled = false;
  59418. AudioDeviceManager::AudioDeviceSetup config;
  59419. setup.manager->getAudioDeviceSetup (config);
  59420. if (setup.useStereoPairs)
  59421. {
  59422. if (type == audioInputType)
  59423. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59424. else if (type == audioOutputType)
  59425. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59426. }
  59427. else
  59428. {
  59429. if (type == audioInputType)
  59430. enabled = config.inputChannels [row];
  59431. else if (type == audioOutputType)
  59432. enabled = config.outputChannels [row];
  59433. }
  59434. const int x = getTickX();
  59435. const float tickW = height * 0.75f;
  59436. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59437. enabled, true, true, false);
  59438. g.setFont (height * 0.6f);
  59439. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59440. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59441. }
  59442. }
  59443. void listBoxItemClicked (int row, const MouseEvent& e)
  59444. {
  59445. selectRow (row);
  59446. if (e.x < getTickX())
  59447. flipEnablement (row);
  59448. }
  59449. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59450. {
  59451. flipEnablement (row);
  59452. }
  59453. void returnKeyPressed (int row)
  59454. {
  59455. flipEnablement (row);
  59456. }
  59457. void paint (Graphics& g)
  59458. {
  59459. ListBox::paint (g);
  59460. if (items.size() == 0)
  59461. {
  59462. g.setColour (Colours::grey);
  59463. g.setFont (13.0f);
  59464. g.drawText (noItemsMessage,
  59465. 0, 0, getWidth(), getHeight() / 2,
  59466. Justification::centred, true);
  59467. }
  59468. }
  59469. int getBestHeight (int maxHeight)
  59470. {
  59471. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59472. getNumRows())
  59473. + getOutlineThickness() * 2;
  59474. }
  59475. juce_UseDebuggingNewOperator
  59476. private:
  59477. const AudioIODeviceType::DeviceSetupDetails setup;
  59478. const BoxType type;
  59479. const String noItemsMessage;
  59480. StringArray items;
  59481. void flipEnablement (const int row)
  59482. {
  59483. jassert (type == audioInputType || type == audioOutputType);
  59484. if (((unsigned int) row) < (unsigned int) items.size())
  59485. {
  59486. AudioDeviceManager::AudioDeviceSetup config;
  59487. setup.manager->getAudioDeviceSetup (config);
  59488. if (setup.useStereoPairs)
  59489. {
  59490. BigInteger bits;
  59491. BigInteger& original = (type == audioInputType ? config.inputChannels
  59492. : config.outputChannels);
  59493. int i;
  59494. for (i = 0; i < 256; i += 2)
  59495. bits.setBit (i / 2, original [i] || original [i + 1]);
  59496. if (type == audioInputType)
  59497. {
  59498. config.useDefaultInputChannels = false;
  59499. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59500. }
  59501. else
  59502. {
  59503. config.useDefaultOutputChannels = false;
  59504. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59505. }
  59506. for (i = 0; i < 256; ++i)
  59507. original.setBit (i, bits [i / 2]);
  59508. }
  59509. else
  59510. {
  59511. if (type == audioInputType)
  59512. {
  59513. config.useDefaultInputChannels = false;
  59514. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59515. }
  59516. else
  59517. {
  59518. config.useDefaultOutputChannels = false;
  59519. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59520. }
  59521. }
  59522. String error (setup.manager->setAudioDeviceSetup (config, true));
  59523. if (! error.isEmpty())
  59524. {
  59525. //xxx
  59526. }
  59527. }
  59528. }
  59529. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59530. {
  59531. const int numActive = chans.countNumberOfSetBits();
  59532. if (chans [index])
  59533. {
  59534. if (numActive > minNumber)
  59535. chans.setBit (index, false);
  59536. }
  59537. else
  59538. {
  59539. if (numActive >= maxNumber)
  59540. {
  59541. const int firstActiveChan = chans.findNextSetBit();
  59542. chans.setBit (index > firstActiveChan
  59543. ? firstActiveChan : chans.getHighestBit(),
  59544. false);
  59545. }
  59546. chans.setBit (index, true);
  59547. }
  59548. }
  59549. int getTickX() const
  59550. {
  59551. return getRowHeight() + 5;
  59552. }
  59553. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59554. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59555. };
  59556. private:
  59557. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59558. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59559. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59560. };
  59561. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59562. const int minInputChannels_,
  59563. const int maxInputChannels_,
  59564. const int minOutputChannels_,
  59565. const int maxOutputChannels_,
  59566. const bool showMidiInputOptions,
  59567. const bool showMidiOutputSelector,
  59568. const bool showChannelsAsStereoPairs_,
  59569. const bool hideAdvancedOptionsWithButton_)
  59570. : deviceManager (deviceManager_),
  59571. deviceTypeDropDown (0),
  59572. deviceTypeDropDownLabel (0),
  59573. minOutputChannels (minOutputChannels_),
  59574. maxOutputChannels (maxOutputChannels_),
  59575. minInputChannels (minInputChannels_),
  59576. maxInputChannels (maxInputChannels_),
  59577. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59578. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59579. {
  59580. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59581. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59582. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59583. {
  59584. deviceTypeDropDown = new ComboBox (String::empty);
  59585. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59586. {
  59587. deviceTypeDropDown
  59588. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59589. i + 1);
  59590. }
  59591. addAndMakeVisible (deviceTypeDropDown);
  59592. deviceTypeDropDown->addListener (this);
  59593. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59594. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59595. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59596. }
  59597. if (showMidiInputOptions)
  59598. {
  59599. addAndMakeVisible (midiInputsList
  59600. = new MidiInputSelectorComponentListBox (deviceManager,
  59601. TRANS("(no midi inputs available)"),
  59602. 0, 0));
  59603. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59604. midiInputsLabel->setJustificationType (Justification::topRight);
  59605. midiInputsLabel->attachToComponent (midiInputsList, true);
  59606. }
  59607. else
  59608. {
  59609. midiInputsList = 0;
  59610. midiInputsLabel = 0;
  59611. }
  59612. if (showMidiOutputSelector)
  59613. {
  59614. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59615. midiOutputSelector->addListener (this);
  59616. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59617. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59618. }
  59619. else
  59620. {
  59621. midiOutputSelector = 0;
  59622. midiOutputLabel = 0;
  59623. }
  59624. deviceManager_.addChangeListener (this);
  59625. changeListenerCallback (0);
  59626. }
  59627. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59628. {
  59629. deviceManager.removeChangeListener (this);
  59630. }
  59631. void AudioDeviceSelectorComponent::resized()
  59632. {
  59633. const int lx = proportionOfWidth (0.35f);
  59634. const int w = proportionOfWidth (0.4f);
  59635. const int h = 24;
  59636. const int space = 6;
  59637. const int dh = h + space;
  59638. int y = 15;
  59639. if (deviceTypeDropDown != 0)
  59640. {
  59641. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59642. y += dh + space * 2;
  59643. }
  59644. if (audioDeviceSettingsComp != 0)
  59645. {
  59646. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59647. y += audioDeviceSettingsComp->getHeight() + space;
  59648. }
  59649. if (midiInputsList != 0)
  59650. {
  59651. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59652. midiInputsList->setBounds (lx, y, w, bh);
  59653. y += bh + space;
  59654. }
  59655. if (midiOutputSelector != 0)
  59656. midiOutputSelector->setBounds (lx, y, w, h);
  59657. }
  59658. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59659. {
  59660. if (child == audioDeviceSettingsComp)
  59661. resized();
  59662. }
  59663. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59664. {
  59665. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59666. if (device != 0 && device->hasControlPanel())
  59667. {
  59668. if (device->showControlPanel())
  59669. deviceManager.restartLastAudioDevice();
  59670. getTopLevelComponent()->toFront (true);
  59671. }
  59672. }
  59673. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59674. {
  59675. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59676. {
  59677. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59678. if (type != 0)
  59679. {
  59680. audioDeviceSettingsComp = 0;
  59681. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59682. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59683. }
  59684. }
  59685. else if (comboBoxThatHasChanged == midiOutputSelector)
  59686. {
  59687. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59688. }
  59689. }
  59690. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59691. {
  59692. if (deviceTypeDropDown != 0)
  59693. {
  59694. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59695. }
  59696. if (audioDeviceSettingsComp == 0
  59697. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59698. {
  59699. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59700. audioDeviceSettingsComp = 0;
  59701. AudioIODeviceType* const type
  59702. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59703. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59704. if (type != 0)
  59705. {
  59706. AudioIODeviceType::DeviceSetupDetails details;
  59707. details.manager = &deviceManager;
  59708. details.minNumInputChannels = minInputChannels;
  59709. details.maxNumInputChannels = maxInputChannels;
  59710. details.minNumOutputChannels = minOutputChannels;
  59711. details.maxNumOutputChannels = maxOutputChannels;
  59712. details.useStereoPairs = showChannelsAsStereoPairs;
  59713. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59714. if (audioDeviceSettingsComp != 0)
  59715. {
  59716. addAndMakeVisible (audioDeviceSettingsComp);
  59717. audioDeviceSettingsComp->resized();
  59718. }
  59719. }
  59720. }
  59721. if (midiInputsList != 0)
  59722. {
  59723. midiInputsList->updateContent();
  59724. midiInputsList->repaint();
  59725. }
  59726. if (midiOutputSelector != 0)
  59727. {
  59728. midiOutputSelector->clear();
  59729. const StringArray midiOuts (MidiOutput::getDevices());
  59730. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59731. midiOutputSelector->addSeparator();
  59732. for (int i = 0; i < midiOuts.size(); ++i)
  59733. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59734. int current = -1;
  59735. if (deviceManager.getDefaultMidiOutput() != 0)
  59736. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59737. midiOutputSelector->setSelectedId (current, true);
  59738. }
  59739. resized();
  59740. }
  59741. END_JUCE_NAMESPACE
  59742. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59743. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59744. BEGIN_JUCE_NAMESPACE
  59745. BubbleComponent::BubbleComponent()
  59746. : side (0),
  59747. allowablePlacements (above | below | left | right),
  59748. arrowTipX (0.0f),
  59749. arrowTipY (0.0f)
  59750. {
  59751. setInterceptsMouseClicks (false, false);
  59752. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59753. setComponentEffect (&shadow);
  59754. }
  59755. BubbleComponent::~BubbleComponent()
  59756. {
  59757. }
  59758. void BubbleComponent::paint (Graphics& g)
  59759. {
  59760. int x = content.getX();
  59761. int y = content.getY();
  59762. int w = content.getWidth();
  59763. int h = content.getHeight();
  59764. int cw, ch;
  59765. getContentSize (cw, ch);
  59766. if (side == 3)
  59767. x += w - cw;
  59768. else if (side != 1)
  59769. x += (w - cw) / 2;
  59770. w = cw;
  59771. if (side == 2)
  59772. y += h - ch;
  59773. else if (side != 0)
  59774. y += (h - ch) / 2;
  59775. h = ch;
  59776. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59777. (float) x, (float) y,
  59778. (float) w, (float) h);
  59779. const int cx = x + (w - cw) / 2;
  59780. const int cy = y + (h - ch) / 2;
  59781. const int indent = 3;
  59782. g.setOrigin (cx + indent, cy + indent);
  59783. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59784. paintContent (g, cw - indent * 2, ch - indent * 2);
  59785. }
  59786. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59787. {
  59788. allowablePlacements = newPlacement;
  59789. }
  59790. void BubbleComponent::setPosition (Component* componentToPointTo)
  59791. {
  59792. jassert (componentToPointTo->isValidComponent());
  59793. Point<int> pos;
  59794. if (getParentComponent() != 0)
  59795. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59796. else
  59797. pos = componentToPointTo->relativePositionToGlobal (pos);
  59798. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59799. }
  59800. void BubbleComponent::setPosition (const int arrowTipX_,
  59801. const int arrowTipY_)
  59802. {
  59803. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59804. }
  59805. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59806. {
  59807. Rectangle<int> availableSpace;
  59808. if (getParentComponent() != 0)
  59809. {
  59810. availableSpace.setSize (getParentComponent()->getWidth(),
  59811. getParentComponent()->getHeight());
  59812. }
  59813. else
  59814. {
  59815. availableSpace = getParentMonitorArea();
  59816. }
  59817. int x = 0;
  59818. int y = 0;
  59819. int w = 150;
  59820. int h = 30;
  59821. getContentSize (w, h);
  59822. w += 30;
  59823. h += 30;
  59824. const float edgeIndent = 2.0f;
  59825. const int arrowLength = jmin (10, h / 3, w / 3);
  59826. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59827. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59828. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59829. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59830. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59831. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59832. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59833. {
  59834. spaceLeft = spaceRight = 0;
  59835. }
  59836. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59837. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59838. {
  59839. spaceAbove = spaceBelow = 0;
  59840. }
  59841. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59842. {
  59843. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59844. arrowTipX = w * 0.5f;
  59845. content.setSize (w, h - arrowLength);
  59846. if (spaceAbove >= spaceBelow)
  59847. {
  59848. // above
  59849. y = rectangleToPointTo.getY() - h;
  59850. content.setPosition (0, 0);
  59851. arrowTipY = h - edgeIndent;
  59852. side = 2;
  59853. }
  59854. else
  59855. {
  59856. // below
  59857. y = rectangleToPointTo.getBottom();
  59858. content.setPosition (0, arrowLength);
  59859. arrowTipY = edgeIndent;
  59860. side = 0;
  59861. }
  59862. }
  59863. else
  59864. {
  59865. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59866. arrowTipY = h * 0.5f;
  59867. content.setSize (w - arrowLength, h);
  59868. if (spaceLeft > spaceRight)
  59869. {
  59870. // on the left
  59871. x = rectangleToPointTo.getX() - w;
  59872. content.setPosition (0, 0);
  59873. arrowTipX = w - edgeIndent;
  59874. side = 3;
  59875. }
  59876. else
  59877. {
  59878. // on the right
  59879. x = rectangleToPointTo.getRight();
  59880. content.setPosition (arrowLength, 0);
  59881. arrowTipX = edgeIndent;
  59882. side = 1;
  59883. }
  59884. }
  59885. setBounds (x, y, w, h);
  59886. }
  59887. END_JUCE_NAMESPACE
  59888. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59889. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59890. BEGIN_JUCE_NAMESPACE
  59891. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59892. : fadeOutLength (fadeOutLengthMs),
  59893. deleteAfterUse (false)
  59894. {
  59895. }
  59896. BubbleMessageComponent::~BubbleMessageComponent()
  59897. {
  59898. fadeOutComponent (fadeOutLength);
  59899. }
  59900. void BubbleMessageComponent::showAt (int x, int y,
  59901. const String& text,
  59902. const int numMillisecondsBeforeRemoving,
  59903. const bool removeWhenMouseClicked,
  59904. const bool deleteSelfAfterUse)
  59905. {
  59906. textLayout.clear();
  59907. textLayout.setText (text, Font (14.0f));
  59908. textLayout.layout (256, Justification::centredLeft, true);
  59909. setPosition (x, y);
  59910. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59911. }
  59912. void BubbleMessageComponent::showAt (Component* const component,
  59913. const String& text,
  59914. const int numMillisecondsBeforeRemoving,
  59915. const bool removeWhenMouseClicked,
  59916. const bool deleteSelfAfterUse)
  59917. {
  59918. textLayout.clear();
  59919. textLayout.setText (text, Font (14.0f));
  59920. textLayout.layout (256, Justification::centredLeft, true);
  59921. setPosition (component);
  59922. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59923. }
  59924. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59925. const bool removeWhenMouseClicked,
  59926. const bool deleteSelfAfterUse)
  59927. {
  59928. setVisible (true);
  59929. deleteAfterUse = deleteSelfAfterUse;
  59930. if (numMillisecondsBeforeRemoving > 0)
  59931. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59932. else
  59933. expiryTime = 0;
  59934. startTimer (77);
  59935. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59936. if (! (removeWhenMouseClicked && isShowing()))
  59937. mouseClickCounter += 0xfffff;
  59938. repaint();
  59939. }
  59940. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59941. {
  59942. w = textLayout.getWidth() + 16;
  59943. h = textLayout.getHeight() + 16;
  59944. }
  59945. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59946. {
  59947. g.setColour (findColour (TooltipWindow::textColourId));
  59948. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59949. }
  59950. void BubbleMessageComponent::timerCallback()
  59951. {
  59952. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59953. {
  59954. stopTimer();
  59955. setVisible (false);
  59956. if (deleteAfterUse)
  59957. delete this;
  59958. }
  59959. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59960. {
  59961. stopTimer();
  59962. fadeOutComponent (fadeOutLength);
  59963. if (deleteAfterUse)
  59964. delete this;
  59965. }
  59966. }
  59967. END_JUCE_NAMESPACE
  59968. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59969. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59970. BEGIN_JUCE_NAMESPACE
  59971. class ColourComponentSlider : public Slider
  59972. {
  59973. public:
  59974. ColourComponentSlider (const String& name)
  59975. : Slider (name)
  59976. {
  59977. setRange (0.0, 255.0, 1.0);
  59978. }
  59979. ~ColourComponentSlider()
  59980. {
  59981. }
  59982. const String getTextFromValue (double value)
  59983. {
  59984. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59985. }
  59986. double getValueFromText (const String& text)
  59987. {
  59988. return (double) text.getHexValue32();
  59989. }
  59990. private:
  59991. ColourComponentSlider (const ColourComponentSlider&);
  59992. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59993. };
  59994. class ColourSpaceMarker : public Component
  59995. {
  59996. public:
  59997. ColourSpaceMarker()
  59998. {
  59999. setInterceptsMouseClicks (false, false);
  60000. }
  60001. ~ColourSpaceMarker()
  60002. {
  60003. }
  60004. void paint (Graphics& g)
  60005. {
  60006. g.setColour (Colour::greyLevel (0.1f));
  60007. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  60008. g.setColour (Colour::greyLevel (0.9f));
  60009. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  60010. }
  60011. private:
  60012. ColourSpaceMarker (const ColourSpaceMarker&);
  60013. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  60014. };
  60015. class ColourSelector::ColourSpaceView : public Component
  60016. {
  60017. public:
  60018. ColourSpaceView (ColourSelector* owner_,
  60019. float& h_, float& s_, float& v_,
  60020. const int edgeSize)
  60021. : owner (owner_),
  60022. h (h_), s (s_), v (v_),
  60023. lastHue (0.0f),
  60024. edge (edgeSize)
  60025. {
  60026. addAndMakeVisible (&marker);
  60027. setMouseCursor (MouseCursor::CrosshairCursor);
  60028. }
  60029. ~ColourSpaceView()
  60030. {
  60031. }
  60032. void paint (Graphics& g)
  60033. {
  60034. if (colours.isNull())
  60035. {
  60036. const int width = getWidth() / 2;
  60037. const int height = getHeight() / 2;
  60038. colours = Image (Image::RGB, width, height, false);
  60039. Image::BitmapData pixels (colours, true);
  60040. for (int y = 0; y < height; ++y)
  60041. {
  60042. const float val = 1.0f - y / (float) height;
  60043. for (int x = 0; x < width; ++x)
  60044. {
  60045. const float sat = x / (float) width;
  60046. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  60047. }
  60048. }
  60049. }
  60050. g.setOpacity (1.0f);
  60051. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  60052. 0, 0, colours.getWidth(), colours.getHeight());
  60053. }
  60054. void mouseDown (const MouseEvent& e)
  60055. {
  60056. mouseDrag (e);
  60057. }
  60058. void mouseDrag (const MouseEvent& e)
  60059. {
  60060. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  60061. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60062. owner->setSV (sat, val);
  60063. }
  60064. void updateIfNeeded()
  60065. {
  60066. if (lastHue != h)
  60067. {
  60068. lastHue = h;
  60069. colours = Image::null;
  60070. repaint();
  60071. }
  60072. updateMarker();
  60073. }
  60074. void resized()
  60075. {
  60076. colours = Image::null;
  60077. updateMarker();
  60078. }
  60079. private:
  60080. ColourSelector* const owner;
  60081. float& h;
  60082. float& s;
  60083. float& v;
  60084. float lastHue;
  60085. ColourSpaceMarker marker;
  60086. const int edge;
  60087. Image colours;
  60088. void updateMarker()
  60089. {
  60090. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60091. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60092. edge * 2, edge * 2);
  60093. }
  60094. ColourSpaceView (const ColourSpaceView&);
  60095. ColourSpaceView& operator= (const ColourSpaceView&);
  60096. };
  60097. class HueSelectorMarker : public Component
  60098. {
  60099. public:
  60100. HueSelectorMarker()
  60101. {
  60102. setInterceptsMouseClicks (false, false);
  60103. }
  60104. ~HueSelectorMarker()
  60105. {
  60106. }
  60107. void paint (Graphics& g)
  60108. {
  60109. Path p;
  60110. p.addTriangle (1.0f, 1.0f,
  60111. getWidth() * 0.3f, getHeight() * 0.5f,
  60112. 1.0f, getHeight() - 1.0f);
  60113. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60114. getWidth() * 0.7f, getHeight() * 0.5f,
  60115. getWidth() - 1.0f, getHeight() - 1.0f);
  60116. g.setColour (Colours::white.withAlpha (0.75f));
  60117. g.fillPath (p);
  60118. g.setColour (Colours::black.withAlpha (0.75f));
  60119. g.strokePath (p, PathStrokeType (1.2f));
  60120. }
  60121. private:
  60122. HueSelectorMarker (const HueSelectorMarker&);
  60123. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60124. };
  60125. class ColourSelector::HueSelectorComp : public Component
  60126. {
  60127. public:
  60128. HueSelectorComp (ColourSelector* owner_,
  60129. float& h_, float& s_, float& v_,
  60130. const int edgeSize)
  60131. : owner (owner_),
  60132. h (h_), s (s_), v (v_),
  60133. lastHue (0.0f),
  60134. edge (edgeSize)
  60135. {
  60136. addAndMakeVisible (&marker);
  60137. }
  60138. ~HueSelectorComp()
  60139. {
  60140. }
  60141. void paint (Graphics& g)
  60142. {
  60143. const float yScale = 1.0f / (getHeight() - edge * 2);
  60144. const Rectangle<int> clip (g.getClipBounds());
  60145. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60146. {
  60147. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60148. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60149. }
  60150. }
  60151. void resized()
  60152. {
  60153. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60154. getWidth(), edge * 2);
  60155. }
  60156. void mouseDown (const MouseEvent& e)
  60157. {
  60158. mouseDrag (e);
  60159. }
  60160. void mouseDrag (const MouseEvent& e)
  60161. {
  60162. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60163. owner->setHue (hue);
  60164. }
  60165. void updateIfNeeded()
  60166. {
  60167. resized();
  60168. }
  60169. private:
  60170. ColourSelector* const owner;
  60171. float& h;
  60172. float& s;
  60173. float& v;
  60174. float lastHue;
  60175. HueSelectorMarker marker;
  60176. const int edge;
  60177. HueSelectorComp (const HueSelectorComp&);
  60178. HueSelectorComp& operator= (const HueSelectorComp&);
  60179. };
  60180. class ColourSelector::SwatchComponent : public Component
  60181. {
  60182. public:
  60183. SwatchComponent (ColourSelector* owner_, int index_)
  60184. : owner (owner_),
  60185. index (index_)
  60186. {
  60187. }
  60188. ~SwatchComponent()
  60189. {
  60190. }
  60191. void paint (Graphics& g)
  60192. {
  60193. const Colour colour (owner->getSwatchColour (index));
  60194. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60195. Colour (0xffdddddd).overlaidWith (colour),
  60196. Colour (0xffffffff).overlaidWith (colour));
  60197. }
  60198. void mouseDown (const MouseEvent&)
  60199. {
  60200. PopupMenu m;
  60201. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60202. m.addSeparator();
  60203. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60204. const int r = m.showAt (this);
  60205. if (r == 1)
  60206. {
  60207. owner->setCurrentColour (owner->getSwatchColour (index));
  60208. }
  60209. else if (r == 2)
  60210. {
  60211. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60212. {
  60213. owner->setSwatchColour (index, owner->getCurrentColour());
  60214. repaint();
  60215. }
  60216. }
  60217. }
  60218. private:
  60219. ColourSelector* const owner;
  60220. const int index;
  60221. SwatchComponent (const SwatchComponent&);
  60222. SwatchComponent& operator= (const SwatchComponent&);
  60223. };
  60224. ColourSelector::ColourSelector (const int flags_,
  60225. const int edgeGap_,
  60226. const int gapAroundColourSpaceComponent)
  60227. : colour (Colours::white),
  60228. colourSpace (0),
  60229. hueSelector (0),
  60230. flags (flags_),
  60231. edgeGap (edgeGap_)
  60232. {
  60233. // not much point having a selector with no components in it!
  60234. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60235. updateHSV();
  60236. if ((flags & showSliders) != 0)
  60237. {
  60238. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60239. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60240. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60241. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60242. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60243. for (int i = 4; --i >= 0;)
  60244. sliders[i]->addListener (this);
  60245. }
  60246. else
  60247. {
  60248. zeromem (sliders, sizeof (sliders));
  60249. }
  60250. if ((flags & showColourspace) != 0)
  60251. {
  60252. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60253. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60254. }
  60255. update();
  60256. }
  60257. ColourSelector::~ColourSelector()
  60258. {
  60259. dispatchPendingMessages();
  60260. swatchComponents.clear();
  60261. deleteAllChildren();
  60262. }
  60263. const Colour ColourSelector::getCurrentColour() const
  60264. {
  60265. return ((flags & showAlphaChannel) != 0) ? colour
  60266. : colour.withAlpha ((uint8) 0xff);
  60267. }
  60268. void ColourSelector::setCurrentColour (const Colour& c)
  60269. {
  60270. if (c != colour)
  60271. {
  60272. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60273. updateHSV();
  60274. update();
  60275. }
  60276. }
  60277. void ColourSelector::setHue (float newH)
  60278. {
  60279. newH = jlimit (0.0f, 1.0f, newH);
  60280. if (h != newH)
  60281. {
  60282. h = newH;
  60283. colour = Colour (h, s, v, colour.getFloatAlpha());
  60284. update();
  60285. }
  60286. }
  60287. void ColourSelector::setSV (float newS, float newV)
  60288. {
  60289. newS = jlimit (0.0f, 1.0f, newS);
  60290. newV = jlimit (0.0f, 1.0f, newV);
  60291. if (s != newS || v != newV)
  60292. {
  60293. s = newS;
  60294. v = newV;
  60295. colour = Colour (h, s, v, colour.getFloatAlpha());
  60296. update();
  60297. }
  60298. }
  60299. void ColourSelector::updateHSV()
  60300. {
  60301. colour.getHSB (h, s, v);
  60302. }
  60303. void ColourSelector::update()
  60304. {
  60305. if (sliders[0] != 0)
  60306. {
  60307. sliders[0]->setValue ((int) colour.getRed());
  60308. sliders[1]->setValue ((int) colour.getGreen());
  60309. sliders[2]->setValue ((int) colour.getBlue());
  60310. sliders[3]->setValue ((int) colour.getAlpha());
  60311. }
  60312. if (colourSpace != 0)
  60313. {
  60314. colourSpace->updateIfNeeded();
  60315. hueSelector->updateIfNeeded();
  60316. }
  60317. if ((flags & showColourAtTop) != 0)
  60318. repaint (previewArea);
  60319. sendChangeMessage (this);
  60320. }
  60321. void ColourSelector::paint (Graphics& g)
  60322. {
  60323. g.fillAll (findColour (backgroundColourId));
  60324. if ((flags & showColourAtTop) != 0)
  60325. {
  60326. const Colour currentColour (getCurrentColour());
  60327. g.fillCheckerBoard (previewArea, 10, 10,
  60328. Colour (0xffdddddd).overlaidWith (currentColour),
  60329. Colour (0xffffffff).overlaidWith (currentColour));
  60330. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60331. g.setFont (14.0f, true);
  60332. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60333. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60334. Justification::centred, false);
  60335. }
  60336. if ((flags & showSliders) != 0)
  60337. {
  60338. g.setColour (findColour (labelTextColourId));
  60339. g.setFont (11.0f);
  60340. for (int i = 4; --i >= 0;)
  60341. {
  60342. if (sliders[i]->isVisible())
  60343. g.drawText (sliders[i]->getName() + ":",
  60344. 0, sliders[i]->getY(),
  60345. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60346. Justification::centredRight, false);
  60347. }
  60348. }
  60349. }
  60350. void ColourSelector::resized()
  60351. {
  60352. const int swatchesPerRow = 8;
  60353. const int swatchHeight = 22;
  60354. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60355. const int numSwatches = getNumSwatches();
  60356. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60357. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60358. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60359. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60360. int y = topSpace;
  60361. if ((flags & showColourspace) != 0)
  60362. {
  60363. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60364. colourSpace->setBounds (edgeGap, y,
  60365. getWidth() - hueWidth - edgeGap - 4,
  60366. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60367. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60368. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60369. colourSpace->getHeight());
  60370. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60371. }
  60372. if ((flags & showSliders) != 0)
  60373. {
  60374. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60375. for (int i = 0; i < numSliders; ++i)
  60376. {
  60377. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60378. proportionOfWidth (0.72f), sliderHeight - 2);
  60379. y += sliderHeight;
  60380. }
  60381. }
  60382. if (numSwatches > 0)
  60383. {
  60384. const int startX = 8;
  60385. const int xGap = 4;
  60386. const int yGap = 4;
  60387. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60388. y += edgeGap;
  60389. if (swatchComponents.size() != numSwatches)
  60390. {
  60391. swatchComponents.clear();
  60392. for (int i = 0; i < numSwatches; ++i)
  60393. {
  60394. SwatchComponent* const sc = new SwatchComponent (this, i);
  60395. swatchComponents.add (sc);
  60396. addAndMakeVisible (sc);
  60397. }
  60398. }
  60399. int x = startX;
  60400. for (int i = 0; i < swatchComponents.size(); ++i)
  60401. {
  60402. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60403. sc->setBounds (x + xGap / 2,
  60404. y + yGap / 2,
  60405. swatchWidth - xGap,
  60406. swatchHeight - yGap);
  60407. if (((i + 1) % swatchesPerRow) == 0)
  60408. {
  60409. x = startX;
  60410. y += swatchHeight;
  60411. }
  60412. else
  60413. {
  60414. x += swatchWidth;
  60415. }
  60416. }
  60417. }
  60418. }
  60419. void ColourSelector::sliderValueChanged (Slider*)
  60420. {
  60421. if (sliders[0] != 0)
  60422. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60423. (uint8) sliders[1]->getValue(),
  60424. (uint8) sliders[2]->getValue(),
  60425. (uint8) sliders[3]->getValue()));
  60426. }
  60427. int ColourSelector::getNumSwatches() const
  60428. {
  60429. return 0;
  60430. }
  60431. const Colour ColourSelector::getSwatchColour (const int) const
  60432. {
  60433. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60434. return Colours::black;
  60435. }
  60436. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60437. {
  60438. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60439. }
  60440. END_JUCE_NAMESPACE
  60441. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60442. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60443. BEGIN_JUCE_NAMESPACE
  60444. class ShadowWindow : public Component
  60445. {
  60446. Component* owner;
  60447. Image shadowImageSections [12];
  60448. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60449. public:
  60450. ShadowWindow (Component* const owner_,
  60451. const int type_,
  60452. const Image shadowImageSections_ [12])
  60453. : owner (owner_),
  60454. type (type_)
  60455. {
  60456. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60457. shadowImageSections [i] = shadowImageSections_ [i];
  60458. setInterceptsMouseClicks (false, false);
  60459. if (owner_->isOnDesktop())
  60460. {
  60461. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60462. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60463. | ComponentPeer::windowIsTemporary
  60464. | ComponentPeer::windowIgnoresKeyPresses);
  60465. }
  60466. else if (owner_->getParentComponent() != 0)
  60467. {
  60468. owner_->getParentComponent()->addChildComponent (this);
  60469. }
  60470. }
  60471. ~ShadowWindow()
  60472. {
  60473. }
  60474. void paint (Graphics& g)
  60475. {
  60476. const Image& topLeft = shadowImageSections [type * 3];
  60477. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60478. const Image& filler = shadowImageSections [type * 3 + 2];
  60479. g.setOpacity (1.0f);
  60480. if (type < 2)
  60481. {
  60482. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60483. g.drawImage (topLeft,
  60484. 0, 0, topLeft.getWidth(), imH,
  60485. 0, 0, topLeft.getWidth(), imH);
  60486. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60487. g.drawImage (bottomRight,
  60488. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60489. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60490. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60491. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60492. }
  60493. else
  60494. {
  60495. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60496. g.drawImage (topLeft,
  60497. 0, 0, imW, topLeft.getHeight(),
  60498. 0, 0, imW, topLeft.getHeight());
  60499. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60500. g.drawImage (bottomRight,
  60501. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60502. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60503. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60504. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60505. }
  60506. }
  60507. void resized()
  60508. {
  60509. repaint(); // (needed for correct repainting)
  60510. }
  60511. private:
  60512. ShadowWindow (const ShadowWindow&);
  60513. ShadowWindow& operator= (const ShadowWindow&);
  60514. };
  60515. DropShadower::DropShadower (const float alpha_,
  60516. const int xOffset_,
  60517. const int yOffset_,
  60518. const float blurRadius_)
  60519. : owner (0),
  60520. numShadows (0),
  60521. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60522. xOffset (xOffset_),
  60523. yOffset (yOffset_),
  60524. alpha (alpha_),
  60525. blurRadius (blurRadius_),
  60526. inDestructor (false),
  60527. reentrant (false)
  60528. {
  60529. }
  60530. DropShadower::~DropShadower()
  60531. {
  60532. if (owner != 0)
  60533. owner->removeComponentListener (this);
  60534. inDestructor = true;
  60535. deleteShadowWindows();
  60536. }
  60537. void DropShadower::deleteShadowWindows()
  60538. {
  60539. if (numShadows > 0)
  60540. {
  60541. int i;
  60542. for (i = numShadows; --i >= 0;)
  60543. delete shadowWindows[i];
  60544. numShadows = 0;
  60545. }
  60546. }
  60547. void DropShadower::setOwner (Component* componentToFollow)
  60548. {
  60549. if (componentToFollow != owner)
  60550. {
  60551. if (owner != 0)
  60552. owner->removeComponentListener (this);
  60553. // (the component can't be null)
  60554. jassert (componentToFollow != 0);
  60555. owner = componentToFollow;
  60556. jassert (owner != 0);
  60557. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60558. owner->addComponentListener (this);
  60559. updateShadows();
  60560. }
  60561. }
  60562. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60563. {
  60564. updateShadows();
  60565. }
  60566. void DropShadower::componentBroughtToFront (Component&)
  60567. {
  60568. bringShadowWindowsToFront();
  60569. }
  60570. void DropShadower::componentChildrenChanged (Component&)
  60571. {
  60572. }
  60573. void DropShadower::componentParentHierarchyChanged (Component&)
  60574. {
  60575. deleteShadowWindows();
  60576. updateShadows();
  60577. }
  60578. void DropShadower::componentVisibilityChanged (Component&)
  60579. {
  60580. updateShadows();
  60581. }
  60582. void DropShadower::updateShadows()
  60583. {
  60584. if (reentrant || inDestructor || (owner == 0))
  60585. return;
  60586. reentrant = true;
  60587. ComponentPeer* const nw = owner->getPeer();
  60588. const bool isOwnerVisible = owner->isVisible()
  60589. && (nw == 0 || ! nw->isMinimised());
  60590. const bool createShadowWindows = numShadows == 0
  60591. && owner->getWidth() > 0
  60592. && owner->getHeight() > 0
  60593. && isOwnerVisible
  60594. && (Desktop::canUseSemiTransparentWindows()
  60595. || owner->getParentComponent() != 0);
  60596. if (createShadowWindows)
  60597. {
  60598. // keep a cached version of the image to save doing the gaussian too often
  60599. String imageId;
  60600. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60601. const int hash = imageId.hashCode();
  60602. Image bigIm (ImageCache::getFromHashCode (hash));
  60603. if (bigIm.isNull())
  60604. {
  60605. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60606. Graphics bigG (bigIm);
  60607. bigG.setColour (Colours::black.withAlpha (alpha));
  60608. bigG.fillRect (shadowEdge + xOffset,
  60609. shadowEdge + yOffset,
  60610. bigIm.getWidth() - (shadowEdge * 2),
  60611. bigIm.getHeight() - (shadowEdge * 2));
  60612. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60613. blurKernel.createGaussianBlur (blurRadius);
  60614. blurKernel.applyToImage (bigIm, bigIm,
  60615. Rectangle<int> (xOffset, yOffset,
  60616. bigIm.getWidth(), bigIm.getHeight()));
  60617. ImageCache::addImageToCache (bigIm, hash);
  60618. }
  60619. const int iw = bigIm.getWidth();
  60620. const int ih = bigIm.getHeight();
  60621. const int shadowEdge2 = shadowEdge * 2;
  60622. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60623. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60624. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60625. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60626. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60627. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60628. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60629. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60630. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60631. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60632. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60633. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60634. for (int i = 0; i < 4; ++i)
  60635. {
  60636. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60637. ++numShadows;
  60638. }
  60639. }
  60640. if (numShadows > 0)
  60641. {
  60642. for (int i = numShadows; --i >= 0;)
  60643. {
  60644. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60645. shadowWindows[i]->setVisible (isOwnerVisible);
  60646. }
  60647. const int x = owner->getX();
  60648. const int y = owner->getY() - shadowEdge;
  60649. const int w = owner->getWidth();
  60650. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60651. shadowWindows[0]->setBounds (x - shadowEdge,
  60652. y,
  60653. shadowEdge,
  60654. h);
  60655. shadowWindows[1]->setBounds (x + w,
  60656. y,
  60657. shadowEdge,
  60658. h);
  60659. shadowWindows[2]->setBounds (x,
  60660. y,
  60661. w,
  60662. shadowEdge);
  60663. shadowWindows[3]->setBounds (x,
  60664. owner->getBottom(),
  60665. w,
  60666. shadowEdge);
  60667. }
  60668. reentrant = false;
  60669. if (createShadowWindows)
  60670. bringShadowWindowsToFront();
  60671. }
  60672. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60673. const int sx, const int sy)
  60674. {
  60675. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60676. Graphics g (shadowImageSections[num]);
  60677. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60678. }
  60679. void DropShadower::bringShadowWindowsToFront()
  60680. {
  60681. if (! (inDestructor || reentrant))
  60682. {
  60683. updateShadows();
  60684. reentrant = true;
  60685. for (int i = numShadows; --i >= 0;)
  60686. shadowWindows[i]->toBehind (owner);
  60687. reentrant = false;
  60688. }
  60689. }
  60690. END_JUCE_NAMESPACE
  60691. /*** End of inlined file: juce_DropShadower.cpp ***/
  60692. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60693. BEGIN_JUCE_NAMESPACE
  60694. class MagnifyingPeer : public ComponentPeer
  60695. {
  60696. public:
  60697. MagnifyingPeer (Component* const component_,
  60698. MagnifierComponent* const magnifierComp_)
  60699. : ComponentPeer (component_, 0),
  60700. magnifierComp (magnifierComp_)
  60701. {
  60702. }
  60703. ~MagnifyingPeer()
  60704. {
  60705. }
  60706. void* getNativeHandle() const { return 0; }
  60707. void setVisible (bool) {}
  60708. void setTitle (const String&) {}
  60709. void setPosition (int, int) {}
  60710. void setSize (int, int) {}
  60711. void setBounds (int, int, int, int, bool) {}
  60712. void setMinimised (bool) {}
  60713. bool isMinimised() const { return false; }
  60714. void setFullScreen (bool) {}
  60715. bool isFullScreen() const { return false; }
  60716. const BorderSize getFrameSize() const { return BorderSize (0); }
  60717. bool setAlwaysOnTop (bool) { return true; }
  60718. void toFront (bool) {}
  60719. void toBehind (ComponentPeer*) {}
  60720. void setIcon (const Image&) {}
  60721. bool isFocused() const
  60722. {
  60723. return magnifierComp->hasKeyboardFocus (true);
  60724. }
  60725. void grabFocus()
  60726. {
  60727. ComponentPeer* peer = magnifierComp->getPeer();
  60728. if (peer != 0)
  60729. peer->grabFocus();
  60730. }
  60731. void textInputRequired (const Point<int>& position)
  60732. {
  60733. ComponentPeer* peer = magnifierComp->getPeer();
  60734. if (peer != 0)
  60735. peer->textInputRequired (position);
  60736. }
  60737. const Rectangle<int> getBounds() const
  60738. {
  60739. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60740. component->getWidth(), component->getHeight());
  60741. }
  60742. const Point<int> getScreenPosition() const
  60743. {
  60744. return magnifierComp->getScreenPosition();
  60745. }
  60746. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60747. {
  60748. const double zoom = magnifierComp->getScaleFactor();
  60749. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60750. roundToInt (relativePosition.getY() * zoom)));
  60751. }
  60752. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60753. {
  60754. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60755. const double zoom = magnifierComp->getScaleFactor();
  60756. return Point<int> (roundToInt (p.getX() / zoom),
  60757. roundToInt (p.getY() / zoom));
  60758. }
  60759. bool contains (const Point<int>& position, bool) const
  60760. {
  60761. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60762. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60763. }
  60764. void repaint (const Rectangle<int>& area)
  60765. {
  60766. const double zoom = magnifierComp->getScaleFactor();
  60767. magnifierComp->repaint ((int) (area.getX() * zoom),
  60768. (int) (area.getY() * zoom),
  60769. roundToInt (area.getWidth() * zoom) + 1,
  60770. roundToInt (area.getHeight() * zoom) + 1);
  60771. }
  60772. void performAnyPendingRepaintsNow()
  60773. {
  60774. }
  60775. juce_UseDebuggingNewOperator
  60776. private:
  60777. MagnifierComponent* const magnifierComp;
  60778. MagnifyingPeer (const MagnifyingPeer&);
  60779. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60780. };
  60781. class PeerHolderComp : public Component
  60782. {
  60783. public:
  60784. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60785. : magnifierComp (magnifierComp_)
  60786. {
  60787. setVisible (true);
  60788. }
  60789. ~PeerHolderComp()
  60790. {
  60791. }
  60792. ComponentPeer* createNewPeer (int, void*)
  60793. {
  60794. return new MagnifyingPeer (this, magnifierComp);
  60795. }
  60796. void childBoundsChanged (Component* c)
  60797. {
  60798. if (c != 0)
  60799. {
  60800. setSize (c->getWidth(), c->getHeight());
  60801. magnifierComp->childBoundsChanged (this);
  60802. }
  60803. }
  60804. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60805. {
  60806. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60807. Component* const p = magnifierComp->getParentComponent();
  60808. if (p != 0)
  60809. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60810. }
  60811. private:
  60812. MagnifierComponent* const magnifierComp;
  60813. PeerHolderComp (const PeerHolderComp&);
  60814. PeerHolderComp& operator= (const PeerHolderComp&);
  60815. };
  60816. MagnifierComponent::MagnifierComponent (Component* const content_,
  60817. const bool deleteContentCompWhenNoLongerNeeded)
  60818. : content (content_),
  60819. scaleFactor (0.0),
  60820. peer (0),
  60821. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60822. quality (Graphics::lowResamplingQuality),
  60823. mouseSource (0, true)
  60824. {
  60825. holderComp = new PeerHolderComp (this);
  60826. setScaleFactor (1.0);
  60827. }
  60828. MagnifierComponent::~MagnifierComponent()
  60829. {
  60830. delete holderComp;
  60831. if (deleteContent)
  60832. delete content;
  60833. }
  60834. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60835. {
  60836. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60837. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60838. if (scaleFactor != newScaleFactor)
  60839. {
  60840. scaleFactor = newScaleFactor;
  60841. if (scaleFactor == 1.0)
  60842. {
  60843. holderComp->removeFromDesktop();
  60844. peer = 0;
  60845. addChildComponent (content);
  60846. childBoundsChanged (content);
  60847. }
  60848. else
  60849. {
  60850. holderComp->addAndMakeVisible (content);
  60851. holderComp->childBoundsChanged (content);
  60852. childBoundsChanged (holderComp);
  60853. holderComp->addToDesktop (0);
  60854. peer = holderComp->getPeer();
  60855. }
  60856. repaint();
  60857. }
  60858. }
  60859. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60860. {
  60861. quality = newQuality;
  60862. }
  60863. void MagnifierComponent::paint (Graphics& g)
  60864. {
  60865. const int w = holderComp->getWidth();
  60866. const int h = holderComp->getHeight();
  60867. if (w == 0 || h == 0)
  60868. return;
  60869. const Rectangle<int> r (g.getClipBounds());
  60870. const int srcX = (int) (r.getX() / scaleFactor);
  60871. const int srcY = (int) (r.getY() / scaleFactor);
  60872. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60873. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60874. if (scaleFactor >= 1.0)
  60875. {
  60876. ++srcW;
  60877. ++srcH;
  60878. }
  60879. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60880. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60881. {
  60882. Graphics g2 (temp);
  60883. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60884. holderComp->paintEntireComponent (g2);
  60885. }
  60886. g.setImageResamplingQuality (quality);
  60887. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60888. }
  60889. void MagnifierComponent::childBoundsChanged (Component* c)
  60890. {
  60891. if (c != 0)
  60892. setSize (roundToInt (c->getWidth() * scaleFactor),
  60893. roundToInt (c->getHeight() * scaleFactor));
  60894. }
  60895. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60896. {
  60897. if (peer != 0)
  60898. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60899. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60900. }
  60901. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60902. {
  60903. passOnMouseEventToPeer (e);
  60904. }
  60905. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60906. {
  60907. passOnMouseEventToPeer (e);
  60908. }
  60909. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60910. {
  60911. passOnMouseEventToPeer (e);
  60912. }
  60913. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60914. {
  60915. passOnMouseEventToPeer (e);
  60916. }
  60917. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60918. {
  60919. passOnMouseEventToPeer (e);
  60920. }
  60921. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60922. {
  60923. passOnMouseEventToPeer (e);
  60924. }
  60925. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60926. {
  60927. if (peer != 0)
  60928. peer->handleMouseWheel (e.source.getIndex(),
  60929. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60930. ix * 256.0f, iy * 256.0f);
  60931. else
  60932. Component::mouseWheelMove (e, ix, iy);
  60933. }
  60934. int MagnifierComponent::scaleInt (const int n) const
  60935. {
  60936. return roundToInt (n / scaleFactor);
  60937. }
  60938. END_JUCE_NAMESPACE
  60939. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60940. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60941. BEGIN_JUCE_NAMESPACE
  60942. class MidiKeyboardUpDownButton : public Button
  60943. {
  60944. public:
  60945. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60946. const int delta_)
  60947. : Button (String::empty),
  60948. owner (owner_),
  60949. delta (delta_)
  60950. {
  60951. setOpaque (true);
  60952. }
  60953. ~MidiKeyboardUpDownButton()
  60954. {
  60955. }
  60956. void clicked()
  60957. {
  60958. int note = owner->getLowestVisibleKey();
  60959. if (delta < 0)
  60960. note = (note - 1) / 12;
  60961. else
  60962. note = note / 12 + 1;
  60963. owner->setLowestVisibleKey (note * 12);
  60964. }
  60965. void paintButton (Graphics& g,
  60966. bool isMouseOverButton,
  60967. bool isButtonDown)
  60968. {
  60969. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60970. isMouseOverButton, isButtonDown,
  60971. delta > 0);
  60972. }
  60973. private:
  60974. MidiKeyboardComponent* const owner;
  60975. const int delta;
  60976. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60977. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60978. };
  60979. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60980. const Orientation orientation_)
  60981. : state (state_),
  60982. xOffset (0),
  60983. blackNoteLength (1),
  60984. keyWidth (16.0f),
  60985. orientation (orientation_),
  60986. midiChannel (1),
  60987. midiInChannelMask (0xffff),
  60988. velocity (1.0f),
  60989. noteUnderMouse (-1),
  60990. mouseDownNote (-1),
  60991. rangeStart (0),
  60992. rangeEnd (127),
  60993. firstKey (12 * 4),
  60994. canScroll (true),
  60995. mouseDragging (false),
  60996. useMousePositionForVelocity (true),
  60997. keyMappingOctave (6),
  60998. octaveNumForMiddleC (3)
  60999. {
  61000. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  61001. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  61002. // initialise with a default set of querty key-mappings..
  61003. const char* const keymap = "awsedftgyhujkolp;";
  61004. for (int i = String (keymap).length(); --i >= 0;)
  61005. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  61006. setOpaque (true);
  61007. setWantsKeyboardFocus (true);
  61008. state.addListener (this);
  61009. }
  61010. MidiKeyboardComponent::~MidiKeyboardComponent()
  61011. {
  61012. state.removeListener (this);
  61013. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  61014. deleteAllChildren();
  61015. }
  61016. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  61017. {
  61018. keyWidth = widthInPixels;
  61019. resized();
  61020. }
  61021. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  61022. {
  61023. if (orientation != newOrientation)
  61024. {
  61025. orientation = newOrientation;
  61026. resized();
  61027. }
  61028. }
  61029. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  61030. const int highestNote)
  61031. {
  61032. jassert (lowestNote >= 0 && lowestNote <= 127);
  61033. jassert (highestNote >= 0 && highestNote <= 127);
  61034. jassert (lowestNote <= highestNote);
  61035. if (rangeStart != lowestNote || rangeEnd != highestNote)
  61036. {
  61037. rangeStart = jlimit (0, 127, lowestNote);
  61038. rangeEnd = jlimit (0, 127, highestNote);
  61039. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  61040. resized();
  61041. }
  61042. }
  61043. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  61044. {
  61045. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  61046. if (noteNumber != firstKey)
  61047. {
  61048. firstKey = noteNumber;
  61049. sendChangeMessage (this);
  61050. resized();
  61051. }
  61052. }
  61053. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  61054. {
  61055. if (canScroll != canScroll_)
  61056. {
  61057. canScroll = canScroll_;
  61058. resized();
  61059. }
  61060. }
  61061. void MidiKeyboardComponent::colourChanged()
  61062. {
  61063. repaint();
  61064. }
  61065. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61066. {
  61067. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61068. if (midiChannel != midiChannelNumber)
  61069. {
  61070. resetAnyKeysInUse();
  61071. midiChannel = jlimit (1, 16, midiChannelNumber);
  61072. }
  61073. }
  61074. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61075. {
  61076. midiInChannelMask = midiChannelMask;
  61077. triggerAsyncUpdate();
  61078. }
  61079. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61080. {
  61081. velocity = jlimit (0.0f, 1.0f, velocity_);
  61082. useMousePositionForVelocity = useMousePositionForVelocity_;
  61083. }
  61084. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61085. {
  61086. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61087. static const float blackNoteWidth = 0.7f;
  61088. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61089. 1.0f, 2 - blackNoteWidth * 0.4f,
  61090. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61091. 4.0f, 5 - blackNoteWidth * 0.5f,
  61092. 5.0f, 6 - blackNoteWidth * 0.3f,
  61093. 6.0f };
  61094. static const float widths[] = { 1.0f, blackNoteWidth,
  61095. 1.0f, blackNoteWidth,
  61096. 1.0f, 1.0f, blackNoteWidth,
  61097. 1.0f, blackNoteWidth,
  61098. 1.0f, blackNoteWidth,
  61099. 1.0f };
  61100. const int octave = midiNoteNumber / 12;
  61101. const int note = midiNoteNumber % 12;
  61102. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61103. w = roundToInt (widths [note] * keyWidth_);
  61104. }
  61105. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61106. {
  61107. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61108. int rx, rw;
  61109. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61110. x -= xOffset + rx;
  61111. }
  61112. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61113. {
  61114. int x, y;
  61115. getKeyPos (midiNoteNumber, x, y);
  61116. return x;
  61117. }
  61118. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61119. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61120. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61121. {
  61122. if (! reallyContains (pos.getX(), pos.getY(), false))
  61123. return -1;
  61124. Point<int> p (pos);
  61125. if (orientation != horizontalKeyboard)
  61126. {
  61127. p = Point<int> (p.getY(), p.getX());
  61128. if (orientation == verticalKeyboardFacingLeft)
  61129. p = Point<int> (p.getX(), getWidth() - p.getY());
  61130. else
  61131. p = Point<int> (getHeight() - p.getX(), p.getY());
  61132. }
  61133. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61134. }
  61135. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61136. {
  61137. if (pos.getY() < blackNoteLength)
  61138. {
  61139. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61140. {
  61141. for (int i = 0; i < 5; ++i)
  61142. {
  61143. const int note = octaveStart + blackNotes [i];
  61144. if (note >= rangeStart && note <= rangeEnd)
  61145. {
  61146. int kx, kw;
  61147. getKeyPos (note, kx, kw);
  61148. kx += xOffset;
  61149. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61150. {
  61151. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61152. return note;
  61153. }
  61154. }
  61155. }
  61156. }
  61157. }
  61158. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61159. {
  61160. for (int i = 0; i < 7; ++i)
  61161. {
  61162. const int note = octaveStart + whiteNotes [i];
  61163. if (note >= rangeStart && note <= rangeEnd)
  61164. {
  61165. int kx, kw;
  61166. getKeyPos (note, kx, kw);
  61167. kx += xOffset;
  61168. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61169. {
  61170. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61171. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61172. return note;
  61173. }
  61174. }
  61175. }
  61176. }
  61177. mousePositionVelocity = 0;
  61178. return -1;
  61179. }
  61180. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61181. {
  61182. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61183. {
  61184. int x, w;
  61185. getKeyPos (noteNum, x, w);
  61186. if (orientation == horizontalKeyboard)
  61187. repaint (x, 0, w, getHeight());
  61188. else if (orientation == verticalKeyboardFacingLeft)
  61189. repaint (0, x, getWidth(), w);
  61190. else if (orientation == verticalKeyboardFacingRight)
  61191. repaint (0, getHeight() - x - w, getWidth(), w);
  61192. }
  61193. }
  61194. void MidiKeyboardComponent::paint (Graphics& g)
  61195. {
  61196. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61197. const Colour lineColour (findColour (keySeparatorLineColourId));
  61198. const Colour textColour (findColour (textLabelColourId));
  61199. int x, w, octave;
  61200. for (octave = 0; octave < 128; octave += 12)
  61201. {
  61202. for (int white = 0; white < 7; ++white)
  61203. {
  61204. const int noteNum = octave + whiteNotes [white];
  61205. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61206. {
  61207. getKeyPos (noteNum, x, w);
  61208. if (orientation == horizontalKeyboard)
  61209. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61210. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61211. noteUnderMouse == noteNum,
  61212. lineColour, textColour);
  61213. else if (orientation == verticalKeyboardFacingLeft)
  61214. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61215. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61216. noteUnderMouse == noteNum,
  61217. lineColour, textColour);
  61218. else if (orientation == verticalKeyboardFacingRight)
  61219. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61220. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61221. noteUnderMouse == noteNum,
  61222. lineColour, textColour);
  61223. }
  61224. }
  61225. }
  61226. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61227. if (orientation == verticalKeyboardFacingLeft)
  61228. {
  61229. x1 = getWidth() - 1.0f;
  61230. x2 = getWidth() - 5.0f;
  61231. }
  61232. else if (orientation == verticalKeyboardFacingRight)
  61233. x2 = 5.0f;
  61234. else
  61235. y2 = 5.0f;
  61236. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61237. Colours::transparentBlack, x2, y2, false));
  61238. getKeyPos (rangeEnd, x, w);
  61239. x += w;
  61240. if (orientation == verticalKeyboardFacingLeft)
  61241. g.fillRect (getWidth() - 5, 0, 5, x);
  61242. else if (orientation == verticalKeyboardFacingRight)
  61243. g.fillRect (0, 0, 5, x);
  61244. else
  61245. g.fillRect (0, 0, x, 5);
  61246. g.setColour (lineColour);
  61247. if (orientation == verticalKeyboardFacingLeft)
  61248. g.fillRect (0, 0, 1, x);
  61249. else if (orientation == verticalKeyboardFacingRight)
  61250. g.fillRect (getWidth() - 1, 0, 1, x);
  61251. else
  61252. g.fillRect (0, getHeight() - 1, x, 1);
  61253. const Colour blackNoteColour (findColour (blackNoteColourId));
  61254. for (octave = 0; octave < 128; octave += 12)
  61255. {
  61256. for (int black = 0; black < 5; ++black)
  61257. {
  61258. const int noteNum = octave + blackNotes [black];
  61259. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61260. {
  61261. getKeyPos (noteNum, x, w);
  61262. if (orientation == horizontalKeyboard)
  61263. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61264. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61265. noteUnderMouse == noteNum,
  61266. blackNoteColour);
  61267. else if (orientation == verticalKeyboardFacingLeft)
  61268. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61269. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61270. noteUnderMouse == noteNum,
  61271. blackNoteColour);
  61272. else if (orientation == verticalKeyboardFacingRight)
  61273. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61274. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61275. noteUnderMouse == noteNum,
  61276. blackNoteColour);
  61277. }
  61278. }
  61279. }
  61280. }
  61281. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61282. Graphics& g, int x, int y, int w, int h,
  61283. bool isDown, bool isOver,
  61284. const Colour& lineColour,
  61285. const Colour& textColour)
  61286. {
  61287. Colour c (Colours::transparentWhite);
  61288. if (isDown)
  61289. c = findColour (keyDownOverlayColourId);
  61290. if (isOver)
  61291. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61292. g.setColour (c);
  61293. g.fillRect (x, y, w, h);
  61294. const String text (getWhiteNoteText (midiNoteNumber));
  61295. if (! text.isEmpty())
  61296. {
  61297. g.setColour (textColour);
  61298. Font f (jmin (12.0f, keyWidth * 0.9f));
  61299. f.setHorizontalScale (0.8f);
  61300. g.setFont (f);
  61301. Justification justification (Justification::centredBottom);
  61302. if (orientation == verticalKeyboardFacingLeft)
  61303. justification = Justification::centredLeft;
  61304. else if (orientation == verticalKeyboardFacingRight)
  61305. justification = Justification::centredRight;
  61306. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61307. }
  61308. g.setColour (lineColour);
  61309. if (orientation == horizontalKeyboard)
  61310. g.fillRect (x, y, 1, h);
  61311. else if (orientation == verticalKeyboardFacingLeft)
  61312. g.fillRect (x, y, w, 1);
  61313. else if (orientation == verticalKeyboardFacingRight)
  61314. g.fillRect (x, y + h - 1, w, 1);
  61315. if (midiNoteNumber == rangeEnd)
  61316. {
  61317. if (orientation == horizontalKeyboard)
  61318. g.fillRect (x + w, y, 1, h);
  61319. else if (orientation == verticalKeyboardFacingLeft)
  61320. g.fillRect (x, y + h, w, 1);
  61321. else if (orientation == verticalKeyboardFacingRight)
  61322. g.fillRect (x, y - 1, w, 1);
  61323. }
  61324. }
  61325. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61326. Graphics& g, int x, int y, int w, int h,
  61327. bool isDown, bool isOver,
  61328. const Colour& noteFillColour)
  61329. {
  61330. Colour c (noteFillColour);
  61331. if (isDown)
  61332. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61333. if (isOver)
  61334. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61335. g.setColour (c);
  61336. g.fillRect (x, y, w, h);
  61337. if (isDown)
  61338. {
  61339. g.setColour (noteFillColour);
  61340. g.drawRect (x, y, w, h);
  61341. }
  61342. else
  61343. {
  61344. const int xIndent = jmax (1, jmin (w, h) / 8);
  61345. g.setColour (c.brighter());
  61346. if (orientation == horizontalKeyboard)
  61347. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61348. else if (orientation == verticalKeyboardFacingLeft)
  61349. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61350. else if (orientation == verticalKeyboardFacingRight)
  61351. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61352. }
  61353. }
  61354. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61355. {
  61356. octaveNumForMiddleC = octaveNumForMiddleC_;
  61357. repaint();
  61358. }
  61359. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61360. {
  61361. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61362. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61363. return String::empty;
  61364. }
  61365. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61366. const bool isMouseOver_,
  61367. const bool isButtonDown,
  61368. const bool movesOctavesUp)
  61369. {
  61370. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61371. float angle;
  61372. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61373. angle = movesOctavesUp ? 0.0f : 0.5f;
  61374. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61375. angle = movesOctavesUp ? 0.25f : 0.75f;
  61376. else
  61377. angle = movesOctavesUp ? 0.75f : 0.25f;
  61378. Path path;
  61379. path.lineTo (0.0f, 1.0f);
  61380. path.lineTo (1.0f, 0.5f);
  61381. path.closeSubPath();
  61382. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61383. g.setColour (findColour (upDownButtonArrowColourId)
  61384. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61385. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61386. w - 2.0f,
  61387. h - 2.0f,
  61388. true));
  61389. }
  61390. void MidiKeyboardComponent::resized()
  61391. {
  61392. int w = getWidth();
  61393. int h = getHeight();
  61394. if (w > 0 && h > 0)
  61395. {
  61396. if (orientation != horizontalKeyboard)
  61397. swapVariables (w, h);
  61398. blackNoteLength = roundToInt (h * 0.7f);
  61399. int kx2, kw2;
  61400. getKeyPos (rangeEnd, kx2, kw2);
  61401. kx2 += kw2;
  61402. if (firstKey != rangeStart)
  61403. {
  61404. int kx1, kw1;
  61405. getKeyPos (rangeStart, kx1, kw1);
  61406. if (kx2 - kx1 <= w)
  61407. {
  61408. firstKey = rangeStart;
  61409. sendChangeMessage (this);
  61410. repaint();
  61411. }
  61412. }
  61413. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61414. scrollDown->setVisible (showScrollButtons);
  61415. scrollUp->setVisible (showScrollButtons);
  61416. xOffset = 0;
  61417. if (showScrollButtons)
  61418. {
  61419. const int scrollButtonW = jmin (12, w / 2);
  61420. if (orientation == horizontalKeyboard)
  61421. {
  61422. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61423. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61424. }
  61425. else if (orientation == verticalKeyboardFacingLeft)
  61426. {
  61427. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61428. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61429. }
  61430. else if (orientation == verticalKeyboardFacingRight)
  61431. {
  61432. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61433. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61434. }
  61435. int endOfLastKey, kw;
  61436. getKeyPos (rangeEnd, endOfLastKey, kw);
  61437. endOfLastKey += kw;
  61438. float mousePositionVelocity;
  61439. const int spaceAvailable = w - scrollButtonW * 2;
  61440. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61441. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61442. {
  61443. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61444. sendChangeMessage (this);
  61445. }
  61446. int newOffset = 0;
  61447. getKeyPos (firstKey, newOffset, kw);
  61448. xOffset = newOffset - scrollButtonW;
  61449. }
  61450. else
  61451. {
  61452. firstKey = rangeStart;
  61453. }
  61454. timerCallback();
  61455. repaint();
  61456. }
  61457. }
  61458. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61459. {
  61460. triggerAsyncUpdate();
  61461. }
  61462. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61463. {
  61464. triggerAsyncUpdate();
  61465. }
  61466. void MidiKeyboardComponent::handleAsyncUpdate()
  61467. {
  61468. for (int i = rangeStart; i <= rangeEnd; ++i)
  61469. {
  61470. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61471. {
  61472. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61473. repaintNote (i);
  61474. }
  61475. }
  61476. }
  61477. void MidiKeyboardComponent::resetAnyKeysInUse()
  61478. {
  61479. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61480. {
  61481. state.allNotesOff (midiChannel);
  61482. keysPressed.clear();
  61483. mouseDownNote = -1;
  61484. }
  61485. }
  61486. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61487. {
  61488. float mousePositionVelocity = 0.0f;
  61489. const int newNote = (mouseDragging || isMouseOver())
  61490. ? xyToNote (pos, mousePositionVelocity) : -1;
  61491. if (noteUnderMouse != newNote)
  61492. {
  61493. if (mouseDownNote >= 0)
  61494. {
  61495. state.noteOff (midiChannel, mouseDownNote);
  61496. mouseDownNote = -1;
  61497. }
  61498. if (mouseDragging && newNote >= 0)
  61499. {
  61500. if (! useMousePositionForVelocity)
  61501. mousePositionVelocity = 1.0f;
  61502. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61503. mouseDownNote = newNote;
  61504. }
  61505. repaintNote (noteUnderMouse);
  61506. noteUnderMouse = newNote;
  61507. repaintNote (noteUnderMouse);
  61508. }
  61509. else if (mouseDownNote >= 0 && ! mouseDragging)
  61510. {
  61511. state.noteOff (midiChannel, mouseDownNote);
  61512. mouseDownNote = -1;
  61513. }
  61514. }
  61515. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61516. {
  61517. updateNoteUnderMouse (e.getPosition());
  61518. stopTimer();
  61519. }
  61520. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61521. {
  61522. float mousePositionVelocity;
  61523. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61524. if (newNote >= 0)
  61525. mouseDraggedToKey (newNote, e);
  61526. updateNoteUnderMouse (e.getPosition());
  61527. }
  61528. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61529. {
  61530. return true;
  61531. }
  61532. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61533. {
  61534. }
  61535. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61536. {
  61537. float mousePositionVelocity;
  61538. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61539. mouseDragging = false;
  61540. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61541. {
  61542. repaintNote (noteUnderMouse);
  61543. noteUnderMouse = -1;
  61544. mouseDragging = true;
  61545. updateNoteUnderMouse (e.getPosition());
  61546. startTimer (500);
  61547. }
  61548. }
  61549. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61550. {
  61551. mouseDragging = false;
  61552. updateNoteUnderMouse (e.getPosition());
  61553. stopTimer();
  61554. }
  61555. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61556. {
  61557. updateNoteUnderMouse (e.getPosition());
  61558. }
  61559. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61560. {
  61561. updateNoteUnderMouse (e.getPosition());
  61562. }
  61563. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61564. {
  61565. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61566. }
  61567. void MidiKeyboardComponent::timerCallback()
  61568. {
  61569. updateNoteUnderMouse (getMouseXYRelative());
  61570. }
  61571. void MidiKeyboardComponent::clearKeyMappings()
  61572. {
  61573. resetAnyKeysInUse();
  61574. keyPressNotes.clear();
  61575. keyPresses.clear();
  61576. }
  61577. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61578. const int midiNoteOffsetFromC)
  61579. {
  61580. removeKeyPressForNote (midiNoteOffsetFromC);
  61581. keyPressNotes.add (midiNoteOffsetFromC);
  61582. keyPresses.add (key);
  61583. }
  61584. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61585. {
  61586. for (int i = keyPressNotes.size(); --i >= 0;)
  61587. {
  61588. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61589. {
  61590. keyPressNotes.remove (i);
  61591. keyPresses.remove (i);
  61592. }
  61593. }
  61594. }
  61595. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61596. {
  61597. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61598. keyMappingOctave = newOctaveNumber;
  61599. }
  61600. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61601. {
  61602. bool keyPressUsed = false;
  61603. for (int i = keyPresses.size(); --i >= 0;)
  61604. {
  61605. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61606. if (keyPresses.getReference(i).isCurrentlyDown())
  61607. {
  61608. if (! keysPressed [note])
  61609. {
  61610. keysPressed.setBit (note);
  61611. state.noteOn (midiChannel, note, velocity);
  61612. keyPressUsed = true;
  61613. }
  61614. }
  61615. else
  61616. {
  61617. if (keysPressed [note])
  61618. {
  61619. keysPressed.clearBit (note);
  61620. state.noteOff (midiChannel, note);
  61621. keyPressUsed = true;
  61622. }
  61623. }
  61624. }
  61625. return keyPressUsed;
  61626. }
  61627. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61628. {
  61629. resetAnyKeysInUse();
  61630. }
  61631. END_JUCE_NAMESPACE
  61632. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61633. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61634. #if JUCE_OPENGL
  61635. BEGIN_JUCE_NAMESPACE
  61636. extern void juce_glViewport (const int w, const int h);
  61637. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61638. const int alphaBits_,
  61639. const int depthBufferBits_,
  61640. const int stencilBufferBits_)
  61641. : redBits (bitsPerRGBComponent),
  61642. greenBits (bitsPerRGBComponent),
  61643. blueBits (bitsPerRGBComponent),
  61644. alphaBits (alphaBits_),
  61645. depthBufferBits (depthBufferBits_),
  61646. stencilBufferBits (stencilBufferBits_),
  61647. accumulationBufferRedBits (0),
  61648. accumulationBufferGreenBits (0),
  61649. accumulationBufferBlueBits (0),
  61650. accumulationBufferAlphaBits (0),
  61651. fullSceneAntiAliasingNumSamples (0)
  61652. {
  61653. }
  61654. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61655. : redBits (other.redBits),
  61656. greenBits (other.greenBits),
  61657. blueBits (other.blueBits),
  61658. alphaBits (other.alphaBits),
  61659. depthBufferBits (other.depthBufferBits),
  61660. stencilBufferBits (other.stencilBufferBits),
  61661. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61662. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61663. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61664. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61665. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61666. {
  61667. }
  61668. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61669. {
  61670. redBits = other.redBits;
  61671. greenBits = other.greenBits;
  61672. blueBits = other.blueBits;
  61673. alphaBits = other.alphaBits;
  61674. depthBufferBits = other.depthBufferBits;
  61675. stencilBufferBits = other.stencilBufferBits;
  61676. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61677. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61678. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61679. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61680. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61681. return *this;
  61682. }
  61683. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61684. {
  61685. return redBits == other.redBits
  61686. && greenBits == other.greenBits
  61687. && blueBits == other.blueBits
  61688. && alphaBits == other.alphaBits
  61689. && depthBufferBits == other.depthBufferBits
  61690. && stencilBufferBits == other.stencilBufferBits
  61691. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61692. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61693. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61694. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61695. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61696. }
  61697. static Array<OpenGLContext*> knownContexts;
  61698. OpenGLContext::OpenGLContext() throw()
  61699. {
  61700. knownContexts.add (this);
  61701. }
  61702. OpenGLContext::~OpenGLContext()
  61703. {
  61704. knownContexts.removeValue (this);
  61705. }
  61706. OpenGLContext* OpenGLContext::getCurrentContext()
  61707. {
  61708. for (int i = knownContexts.size(); --i >= 0;)
  61709. {
  61710. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61711. if (oglc->isActive())
  61712. return oglc;
  61713. }
  61714. return 0;
  61715. }
  61716. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61717. {
  61718. public:
  61719. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61720. : ComponentMovementWatcher (owner_),
  61721. owner (owner_),
  61722. wasShowing (false)
  61723. {
  61724. }
  61725. ~OpenGLComponentWatcher() {}
  61726. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61727. {
  61728. owner->updateContextPosition();
  61729. }
  61730. void componentPeerChanged()
  61731. {
  61732. const ScopedLock sl (owner->getContextLock());
  61733. owner->deleteContext();
  61734. }
  61735. void componentVisibilityChanged (Component&)
  61736. {
  61737. const bool isShowingNow = owner->isShowing();
  61738. if (wasShowing != isShowingNow)
  61739. {
  61740. wasShowing = isShowingNow;
  61741. if (! isShowingNow)
  61742. {
  61743. const ScopedLock sl (owner->getContextLock());
  61744. owner->deleteContext();
  61745. }
  61746. }
  61747. }
  61748. juce_UseDebuggingNewOperator
  61749. private:
  61750. OpenGLComponent* const owner;
  61751. bool wasShowing;
  61752. };
  61753. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61754. : type (type_),
  61755. contextToShareListsWith (0),
  61756. needToUpdateViewport (true)
  61757. {
  61758. setOpaque (true);
  61759. componentWatcher = new OpenGLComponentWatcher (this);
  61760. }
  61761. OpenGLComponent::~OpenGLComponent()
  61762. {
  61763. deleteContext();
  61764. componentWatcher = 0;
  61765. }
  61766. void OpenGLComponent::deleteContext()
  61767. {
  61768. const ScopedLock sl (contextLock);
  61769. context = 0;
  61770. }
  61771. void OpenGLComponent::updateContextPosition()
  61772. {
  61773. needToUpdateViewport = true;
  61774. if (getWidth() > 0 && getHeight() > 0)
  61775. {
  61776. Component* const topComp = getTopLevelComponent();
  61777. if (topComp->getPeer() != 0)
  61778. {
  61779. const ScopedLock sl (contextLock);
  61780. if (context != 0)
  61781. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61782. getScreenY() - topComp->getScreenY(),
  61783. getWidth(),
  61784. getHeight(),
  61785. topComp->getHeight());
  61786. }
  61787. }
  61788. }
  61789. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61790. {
  61791. OpenGLPixelFormat pf;
  61792. const ScopedLock sl (contextLock);
  61793. if (context != 0)
  61794. pf = context->getPixelFormat();
  61795. return pf;
  61796. }
  61797. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61798. {
  61799. if (! (preferredPixelFormat == formatToUse))
  61800. {
  61801. const ScopedLock sl (contextLock);
  61802. deleteContext();
  61803. preferredPixelFormat = formatToUse;
  61804. }
  61805. }
  61806. void OpenGLComponent::shareWith (OpenGLContext* c)
  61807. {
  61808. if (contextToShareListsWith != c)
  61809. {
  61810. const ScopedLock sl (contextLock);
  61811. deleteContext();
  61812. contextToShareListsWith = c;
  61813. }
  61814. }
  61815. bool OpenGLComponent::makeCurrentContextActive()
  61816. {
  61817. if (context == 0)
  61818. {
  61819. const ScopedLock sl (contextLock);
  61820. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61821. {
  61822. context = createContext();
  61823. if (context != 0)
  61824. {
  61825. updateContextPosition();
  61826. if (context->makeActive())
  61827. newOpenGLContextCreated();
  61828. }
  61829. }
  61830. }
  61831. return context != 0 && context->makeActive();
  61832. }
  61833. void OpenGLComponent::makeCurrentContextInactive()
  61834. {
  61835. if (context != 0)
  61836. context->makeInactive();
  61837. }
  61838. bool OpenGLComponent::isActiveContext() const throw()
  61839. {
  61840. return context != 0 && context->isActive();
  61841. }
  61842. void OpenGLComponent::swapBuffers()
  61843. {
  61844. if (context != 0)
  61845. context->swapBuffers();
  61846. }
  61847. void OpenGLComponent::paint (Graphics&)
  61848. {
  61849. if (renderAndSwapBuffers())
  61850. {
  61851. ComponentPeer* const peer = getPeer();
  61852. if (peer != 0)
  61853. {
  61854. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61855. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61856. }
  61857. }
  61858. }
  61859. bool OpenGLComponent::renderAndSwapBuffers()
  61860. {
  61861. const ScopedLock sl (contextLock);
  61862. if (! makeCurrentContextActive())
  61863. return false;
  61864. if (needToUpdateViewport)
  61865. {
  61866. needToUpdateViewport = false;
  61867. juce_glViewport (getWidth(), getHeight());
  61868. }
  61869. renderOpenGL();
  61870. swapBuffers();
  61871. return true;
  61872. }
  61873. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61874. {
  61875. Component::internalRepaint (x, y, w, h);
  61876. if (context != 0)
  61877. context->repaint();
  61878. }
  61879. END_JUCE_NAMESPACE
  61880. #endif
  61881. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61882. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61883. BEGIN_JUCE_NAMESPACE
  61884. PreferencesPanel::PreferencesPanel()
  61885. : buttonSize (70)
  61886. {
  61887. }
  61888. PreferencesPanel::~PreferencesPanel()
  61889. {
  61890. currentPage = 0;
  61891. deleteAllChildren();
  61892. }
  61893. void PreferencesPanel::addSettingsPage (const String& title,
  61894. const Drawable* icon,
  61895. const Drawable* overIcon,
  61896. const Drawable* downIcon)
  61897. {
  61898. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61899. button->setImages (icon, overIcon, downIcon);
  61900. button->setRadioGroupId (1);
  61901. button->addButtonListener (this);
  61902. button->setClickingTogglesState (true);
  61903. button->setWantsKeyboardFocus (false);
  61904. addAndMakeVisible (button);
  61905. resized();
  61906. if (currentPage == 0)
  61907. setCurrentPage (title);
  61908. }
  61909. void PreferencesPanel::addSettingsPage (const String& title,
  61910. const void* imageData,
  61911. const int imageDataSize)
  61912. {
  61913. DrawableImage icon, iconOver, iconDown;
  61914. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61915. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61916. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61917. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61918. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61919. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61920. }
  61921. class PrefsDialogWindow : public DialogWindow
  61922. {
  61923. public:
  61924. PrefsDialogWindow (const String& dialogtitle,
  61925. const Colour& backgroundColour)
  61926. : DialogWindow (dialogtitle, backgroundColour, true)
  61927. {
  61928. }
  61929. ~PrefsDialogWindow()
  61930. {
  61931. }
  61932. void closeButtonPressed()
  61933. {
  61934. exitModalState (0);
  61935. }
  61936. private:
  61937. PrefsDialogWindow (const PrefsDialogWindow&);
  61938. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61939. };
  61940. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61941. int dialogWidth,
  61942. int dialogHeight,
  61943. const Colour& backgroundColour)
  61944. {
  61945. setSize (dialogWidth, dialogHeight);
  61946. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61947. dw.setContentComponent (this, true, true);
  61948. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61949. dw.runModalLoop();
  61950. dw.setContentComponent (0, false, false);
  61951. }
  61952. void PreferencesPanel::resized()
  61953. {
  61954. int x = 0;
  61955. for (int i = 0; i < getNumChildComponents(); ++i)
  61956. {
  61957. Component* c = getChildComponent (i);
  61958. if (dynamic_cast <DrawableButton*> (c) == 0)
  61959. {
  61960. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61961. }
  61962. else
  61963. {
  61964. c->setBounds (x, 0, buttonSize, buttonSize);
  61965. x += buttonSize;
  61966. }
  61967. }
  61968. }
  61969. void PreferencesPanel::paint (Graphics& g)
  61970. {
  61971. g.setColour (Colours::grey);
  61972. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61973. }
  61974. void PreferencesPanel::setCurrentPage (const String& pageName)
  61975. {
  61976. if (currentPageName != pageName)
  61977. {
  61978. currentPageName = pageName;
  61979. currentPage = 0;
  61980. currentPage = createComponentForPage (pageName);
  61981. if (currentPage != 0)
  61982. {
  61983. addAndMakeVisible (currentPage);
  61984. currentPage->toBack();
  61985. resized();
  61986. }
  61987. for (int i = 0; i < getNumChildComponents(); ++i)
  61988. {
  61989. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61990. if (db != 0 && db->getName() == pageName)
  61991. {
  61992. db->setToggleState (true, false);
  61993. break;
  61994. }
  61995. }
  61996. }
  61997. }
  61998. void PreferencesPanel::buttonClicked (Button*)
  61999. {
  62000. for (int i = 0; i < getNumChildComponents(); ++i)
  62001. {
  62002. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  62003. if (db != 0 && db->getToggleState())
  62004. {
  62005. setCurrentPage (db->getName());
  62006. break;
  62007. }
  62008. }
  62009. }
  62010. END_JUCE_NAMESPACE
  62011. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  62012. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62013. #if JUCE_WINDOWS || JUCE_LINUX
  62014. BEGIN_JUCE_NAMESPACE
  62015. SystemTrayIconComponent::SystemTrayIconComponent()
  62016. {
  62017. addToDesktop (0);
  62018. }
  62019. SystemTrayIconComponent::~SystemTrayIconComponent()
  62020. {
  62021. }
  62022. END_JUCE_NAMESPACE
  62023. #endif
  62024. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62025. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  62026. BEGIN_JUCE_NAMESPACE
  62027. class AlertWindowTextEditor : public TextEditor
  62028. {
  62029. public:
  62030. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  62031. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  62032. {
  62033. setSelectAllWhenFocused (true);
  62034. }
  62035. ~AlertWindowTextEditor()
  62036. {
  62037. }
  62038. void returnPressed()
  62039. {
  62040. // pass these up the component hierarchy to be trigger the buttons
  62041. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  62042. }
  62043. void escapePressed()
  62044. {
  62045. // pass these up the component hierarchy to be trigger the buttons
  62046. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  62047. }
  62048. private:
  62049. AlertWindowTextEditor (const AlertWindowTextEditor&);
  62050. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  62051. static juce_wchar getDefaultPasswordChar() throw()
  62052. {
  62053. #if JUCE_LINUX
  62054. return 0x2022;
  62055. #else
  62056. return 0x25cf;
  62057. #endif
  62058. }
  62059. };
  62060. AlertWindow::AlertWindow (const String& title,
  62061. const String& message,
  62062. AlertIconType iconType,
  62063. Component* associatedComponent_)
  62064. : TopLevelWindow (title, true),
  62065. alertIconType (iconType),
  62066. associatedComponent (associatedComponent_)
  62067. {
  62068. if (message.isEmpty())
  62069. text = " "; // to force an update if the message is empty
  62070. setMessage (message);
  62071. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62072. {
  62073. Component* const c = Desktop::getInstance().getComponent (i);
  62074. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62075. {
  62076. setAlwaysOnTop (true);
  62077. break;
  62078. }
  62079. }
  62080. if (! JUCEApplication::isStandaloneApp())
  62081. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62082. lookAndFeelChanged();
  62083. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62084. }
  62085. AlertWindow::~AlertWindow()
  62086. {
  62087. for (int i = customComps.size(); --i >= 0;)
  62088. removeChildComponent ((Component*) customComps[i]);
  62089. deleteAllChildren();
  62090. }
  62091. void AlertWindow::userTriedToCloseWindow()
  62092. {
  62093. exitModalState (0);
  62094. }
  62095. void AlertWindow::setMessage (const String& message)
  62096. {
  62097. const String newMessage (message.substring (0, 2048));
  62098. if (text != newMessage)
  62099. {
  62100. text = newMessage;
  62101. font.setHeight (15.0f);
  62102. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62103. textLayout.setText (getName() + "\n\n", titleFont);
  62104. textLayout.appendText (text, font);
  62105. updateLayout (true);
  62106. repaint();
  62107. }
  62108. }
  62109. void AlertWindow::buttonClicked (Button* button)
  62110. {
  62111. for (int i = 0; i < buttons.size(); i++)
  62112. {
  62113. TextButton* const c = (TextButton*) buttons[i];
  62114. if (button->getName() == c->getName())
  62115. {
  62116. if (c->getParentComponent() != 0)
  62117. c->getParentComponent()->exitModalState (c->getCommandID());
  62118. break;
  62119. }
  62120. }
  62121. }
  62122. void AlertWindow::addButton (const String& name,
  62123. const int returnValue,
  62124. const KeyPress& shortcutKey1,
  62125. const KeyPress& shortcutKey2)
  62126. {
  62127. TextButton* const b = new TextButton (name, String::empty);
  62128. b->setWantsKeyboardFocus (true);
  62129. b->setMouseClickGrabsKeyboardFocus (false);
  62130. b->setCommandToTrigger (0, returnValue, false);
  62131. b->addShortcut (shortcutKey1);
  62132. b->addShortcut (shortcutKey2);
  62133. b->addButtonListener (this);
  62134. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62135. addAndMakeVisible (b, 0);
  62136. buttons.add (b);
  62137. updateLayout (false);
  62138. }
  62139. int AlertWindow::getNumButtons() const
  62140. {
  62141. return buttons.size();
  62142. }
  62143. void AlertWindow::triggerButtonClick (const String& buttonName)
  62144. {
  62145. for (int i = buttons.size(); --i >= 0;)
  62146. {
  62147. TextButton* const b = (TextButton*) buttons[i];
  62148. if (buttonName == b->getName())
  62149. {
  62150. b->triggerClick();
  62151. break;
  62152. }
  62153. }
  62154. }
  62155. void AlertWindow::addTextEditor (const String& name,
  62156. const String& initialContents,
  62157. const String& onScreenLabel,
  62158. const bool isPasswordBox)
  62159. {
  62160. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62161. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62162. tc->setFont (font);
  62163. tc->setText (initialContents);
  62164. tc->setCaretPosition (initialContents.length());
  62165. addAndMakeVisible (tc);
  62166. textBoxes.add (tc);
  62167. allComps.add (tc);
  62168. textboxNames.add (onScreenLabel);
  62169. updateLayout (false);
  62170. }
  62171. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  62172. {
  62173. for (int i = textBoxes.size(); --i >= 0;)
  62174. if (static_cast <TextEditor*> (textBoxes.getUnchecked(i))->getName() == nameOfTextEditor)
  62175. return static_cast <TextEditor*> (textBoxes.getUnchecked(i));
  62176. return 0;
  62177. }
  62178. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62179. {
  62180. TextEditor* const t = getTextEditor (nameOfTextEditor);
  62181. return t != 0 ? t->getText() : String::empty;
  62182. }
  62183. void AlertWindow::addComboBox (const String& name,
  62184. const StringArray& items,
  62185. const String& onScreenLabel)
  62186. {
  62187. ComboBox* const cb = new ComboBox (name);
  62188. for (int i = 0; i < items.size(); ++i)
  62189. cb->addItem (items[i], i + 1);
  62190. addAndMakeVisible (cb);
  62191. cb->setSelectedItemIndex (0);
  62192. comboBoxes.add (cb);
  62193. allComps.add (cb);
  62194. comboBoxNames.add (onScreenLabel);
  62195. updateLayout (false);
  62196. }
  62197. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62198. {
  62199. for (int i = comboBoxes.size(); --i >= 0;)
  62200. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62201. return (ComboBox*) comboBoxes[i];
  62202. return 0;
  62203. }
  62204. class AlertTextComp : public TextEditor
  62205. {
  62206. public:
  62207. AlertTextComp (const String& message,
  62208. const Font& font)
  62209. {
  62210. setReadOnly (true);
  62211. setMultiLine (true, true);
  62212. setCaretVisible (false);
  62213. setScrollbarsShown (true);
  62214. lookAndFeelChanged();
  62215. setWantsKeyboardFocus (false);
  62216. setFont (font);
  62217. setText (message, false);
  62218. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62219. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62220. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62221. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62222. }
  62223. ~AlertTextComp()
  62224. {
  62225. }
  62226. int getPreferredWidth() const throw() { return bestWidth; }
  62227. void updateLayout (const int width)
  62228. {
  62229. TextLayout text;
  62230. text.appendText (getText(), getFont());
  62231. text.layout (width - 8, Justification::topLeft, true);
  62232. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62233. }
  62234. private:
  62235. int bestWidth;
  62236. AlertTextComp (const AlertTextComp&);
  62237. AlertTextComp& operator= (const AlertTextComp&);
  62238. };
  62239. void AlertWindow::addTextBlock (const String& textBlock)
  62240. {
  62241. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62242. textBlocks.add (c);
  62243. allComps.add (c);
  62244. addAndMakeVisible (c);
  62245. updateLayout (false);
  62246. }
  62247. void AlertWindow::addProgressBarComponent (double& progressValue)
  62248. {
  62249. ProgressBar* const pb = new ProgressBar (progressValue);
  62250. progressBars.add (pb);
  62251. allComps.add (pb);
  62252. addAndMakeVisible (pb);
  62253. updateLayout (false);
  62254. }
  62255. void AlertWindow::addCustomComponent (Component* const component)
  62256. {
  62257. customComps.add (component);
  62258. allComps.add (component);
  62259. addAndMakeVisible (component);
  62260. updateLayout (false);
  62261. }
  62262. int AlertWindow::getNumCustomComponents() const
  62263. {
  62264. return customComps.size();
  62265. }
  62266. Component* AlertWindow::getCustomComponent (const int index) const
  62267. {
  62268. return (Component*) customComps [index];
  62269. }
  62270. Component* AlertWindow::removeCustomComponent (const int index)
  62271. {
  62272. Component* const c = getCustomComponent (index);
  62273. if (c != 0)
  62274. {
  62275. customComps.removeValue (c);
  62276. allComps.removeValue (c);
  62277. removeChildComponent (c);
  62278. updateLayout (false);
  62279. }
  62280. return c;
  62281. }
  62282. void AlertWindow::paint (Graphics& g)
  62283. {
  62284. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62285. g.setColour (findColour (textColourId));
  62286. g.setFont (getLookAndFeel().getAlertWindowFont());
  62287. int i;
  62288. for (i = textBoxes.size(); --i >= 0;)
  62289. {
  62290. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62291. g.drawFittedText (textboxNames[i],
  62292. te->getX(), te->getY() - 14,
  62293. te->getWidth(), 14,
  62294. Justification::centredLeft, 1);
  62295. }
  62296. for (i = comboBoxNames.size(); --i >= 0;)
  62297. {
  62298. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62299. g.drawFittedText (comboBoxNames[i],
  62300. cb->getX(), cb->getY() - 14,
  62301. cb->getWidth(), 14,
  62302. Justification::centredLeft, 1);
  62303. }
  62304. for (i = customComps.size(); --i >= 0;)
  62305. {
  62306. const Component* const c = (Component*) customComps[i];
  62307. g.drawFittedText (c->getName(),
  62308. c->getX(), c->getY() - 14,
  62309. c->getWidth(), 14,
  62310. Justification::centredLeft, 1);
  62311. }
  62312. }
  62313. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62314. {
  62315. const int titleH = 24;
  62316. const int iconWidth = 80;
  62317. const int wid = jmax (font.getStringWidth (text),
  62318. font.getStringWidth (getName()));
  62319. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62320. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62321. const int edgeGap = 10;
  62322. const int labelHeight = 18;
  62323. int iconSpace;
  62324. if (alertIconType == NoIcon)
  62325. {
  62326. textLayout.layout (w, Justification::horizontallyCentred, true);
  62327. iconSpace = 0;
  62328. }
  62329. else
  62330. {
  62331. textLayout.layout (w, Justification::left, true);
  62332. iconSpace = iconWidth;
  62333. }
  62334. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62335. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62336. const int textLayoutH = textLayout.getHeight();
  62337. const int textBottom = 16 + titleH + textLayoutH;
  62338. int h = textBottom;
  62339. int buttonW = 40;
  62340. int i;
  62341. for (i = 0; i < buttons.size(); ++i)
  62342. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62343. w = jmax (buttonW, w);
  62344. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62345. if (buttons.size() > 0)
  62346. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62347. for (i = customComps.size(); --i >= 0;)
  62348. {
  62349. Component* c = (Component*) customComps[i];
  62350. w = jmax (w, (c->getWidth() * 100) / 80);
  62351. h += 10 + c->getHeight();
  62352. if (c->getName().isNotEmpty())
  62353. h += labelHeight;
  62354. }
  62355. for (i = textBlocks.size(); --i >= 0;)
  62356. {
  62357. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62358. w = jmax (w, ac->getPreferredWidth());
  62359. }
  62360. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62361. for (i = textBlocks.size(); --i >= 0;)
  62362. {
  62363. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62364. ac->updateLayout ((int) (w * 0.8f));
  62365. h += ac->getHeight() + 10;
  62366. }
  62367. h = jmin (getParentHeight() - 50, h);
  62368. if (onlyIncreaseSize)
  62369. {
  62370. w = jmax (w, getWidth());
  62371. h = jmax (h, getHeight());
  62372. }
  62373. if (! isVisible())
  62374. {
  62375. centreAroundComponent (associatedComponent, w, h);
  62376. }
  62377. else
  62378. {
  62379. const int cx = getX() + getWidth() / 2;
  62380. const int cy = getY() + getHeight() / 2;
  62381. setBounds (cx - w / 2,
  62382. cy - h / 2,
  62383. w, h);
  62384. }
  62385. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62386. const int spacer = 16;
  62387. int totalWidth = -spacer;
  62388. for (i = buttons.size(); --i >= 0;)
  62389. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62390. int x = (w - totalWidth) / 2;
  62391. int y = (int) (getHeight() * 0.95f);
  62392. for (i = 0; i < buttons.size(); ++i)
  62393. {
  62394. TextButton* const c = (TextButton*) buttons[i];
  62395. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62396. c->setTopLeftPosition (x, ny);
  62397. if (ny < y)
  62398. y = ny;
  62399. x += c->getWidth() + spacer;
  62400. c->toFront (false);
  62401. }
  62402. y = textBottom;
  62403. for (i = 0; i < allComps.size(); ++i)
  62404. {
  62405. Component* const c = (Component*) allComps[i];
  62406. h = 22;
  62407. const int comboIndex = comboBoxes.indexOf (c);
  62408. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62409. y += labelHeight;
  62410. const int tbIndex = textBoxes.indexOf (c);
  62411. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62412. y += labelHeight;
  62413. if (customComps.contains (c))
  62414. {
  62415. if (c->getName().isNotEmpty())
  62416. y += labelHeight;
  62417. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62418. h = c->getHeight();
  62419. }
  62420. else if (textBlocks.contains (c))
  62421. {
  62422. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62423. h = c->getHeight();
  62424. }
  62425. else
  62426. {
  62427. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62428. }
  62429. y += h + 10;
  62430. }
  62431. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62432. }
  62433. bool AlertWindow::containsAnyExtraComponents() const
  62434. {
  62435. return textBoxes.size()
  62436. + comboBoxes.size()
  62437. + progressBars.size()
  62438. + customComps.size() > 0;
  62439. }
  62440. void AlertWindow::mouseDown (const MouseEvent&)
  62441. {
  62442. dragger.startDraggingComponent (this, &constrainer);
  62443. }
  62444. void AlertWindow::mouseDrag (const MouseEvent& e)
  62445. {
  62446. dragger.dragComponent (this, e);
  62447. }
  62448. bool AlertWindow::keyPressed (const KeyPress& key)
  62449. {
  62450. for (int i = buttons.size(); --i >= 0;)
  62451. {
  62452. TextButton* const b = (TextButton*) buttons[i];
  62453. if (b->isRegisteredForShortcut (key))
  62454. {
  62455. b->triggerClick();
  62456. return true;
  62457. }
  62458. }
  62459. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62460. {
  62461. exitModalState (0);
  62462. return true;
  62463. }
  62464. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62465. {
  62466. ((TextButton*) buttons.getFirst())->triggerClick();
  62467. return true;
  62468. }
  62469. return false;
  62470. }
  62471. void AlertWindow::lookAndFeelChanged()
  62472. {
  62473. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62474. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62475. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62476. }
  62477. int AlertWindow::getDesktopWindowStyleFlags() const
  62478. {
  62479. return getLookAndFeel().getAlertBoxWindowFlags();
  62480. }
  62481. struct AlertWindowInfo
  62482. {
  62483. String title, message, button1, button2, button3;
  62484. AlertWindow::AlertIconType iconType;
  62485. int numButtons;
  62486. Component::SafePointer<Component> associatedComponent;
  62487. int run() const
  62488. {
  62489. return (int) (pointer_sized_int)
  62490. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62491. }
  62492. private:
  62493. int show() const
  62494. {
  62495. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62496. : LookAndFeel::getDefaultLookAndFeel();
  62497. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62498. iconType, numButtons, associatedComponent));
  62499. jassert (alertBox != 0); // you have to return one of these!
  62500. return alertBox->runModalLoop();
  62501. }
  62502. static void* showCallback (void* userData)
  62503. {
  62504. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62505. }
  62506. };
  62507. void AlertWindow::showMessageBox (AlertIconType iconType,
  62508. const String& title,
  62509. const String& message,
  62510. const String& buttonText,
  62511. Component* associatedComponent)
  62512. {
  62513. AlertWindowInfo info;
  62514. info.title = title;
  62515. info.message = message;
  62516. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62517. info.iconType = iconType;
  62518. info.numButtons = 1;
  62519. info.associatedComponent = associatedComponent;
  62520. info.run();
  62521. }
  62522. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62523. const String& title,
  62524. const String& message,
  62525. const String& button1Text,
  62526. const String& button2Text,
  62527. Component* associatedComponent)
  62528. {
  62529. AlertWindowInfo info;
  62530. info.title = title;
  62531. info.message = message;
  62532. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62533. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62534. info.iconType = iconType;
  62535. info.numButtons = 2;
  62536. info.associatedComponent = associatedComponent;
  62537. return info.run() != 0;
  62538. }
  62539. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62540. const String& title,
  62541. const String& message,
  62542. const String& button1Text,
  62543. const String& button2Text,
  62544. const String& button3Text,
  62545. Component* associatedComponent)
  62546. {
  62547. AlertWindowInfo info;
  62548. info.title = title;
  62549. info.message = message;
  62550. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62551. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62552. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62553. info.iconType = iconType;
  62554. info.numButtons = 3;
  62555. info.associatedComponent = associatedComponent;
  62556. return info.run();
  62557. }
  62558. END_JUCE_NAMESPACE
  62559. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62560. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62561. BEGIN_JUCE_NAMESPACE
  62562. CallOutBox::CallOutBox (Component& contentComponent,
  62563. Component& componentToPointTo,
  62564. Component* const parentComponent)
  62565. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62566. {
  62567. addAndMakeVisible (&content);
  62568. if (parentComponent != 0)
  62569. {
  62570. parentComponent->addChildComponent (this);
  62571. updatePosition (componentToPointTo.getLocalBounds()
  62572. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()),
  62573. parentComponent->getLocalBounds());
  62574. setVisible (true);
  62575. }
  62576. else
  62577. {
  62578. if (! JUCEApplication::isStandaloneApp())
  62579. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62580. updatePosition (componentToPointTo.getScreenBounds(),
  62581. componentToPointTo.getParentMonitorArea());
  62582. addToDesktop (ComponentPeer::windowIsTemporary);
  62583. }
  62584. }
  62585. CallOutBox::~CallOutBox()
  62586. {
  62587. }
  62588. void CallOutBox::setArrowSize (const float newSize)
  62589. {
  62590. arrowSize = newSize;
  62591. borderSpace = jmax (20, (int) arrowSize);
  62592. refreshPath();
  62593. }
  62594. void CallOutBox::paint (Graphics& g)
  62595. {
  62596. if (background.isNull())
  62597. {
  62598. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62599. Graphics g (background);
  62600. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62601. }
  62602. g.setColour (Colours::black);
  62603. g.drawImageAt (background, 0, 0);
  62604. }
  62605. void CallOutBox::resized()
  62606. {
  62607. content.setTopLeftPosition (borderSpace, borderSpace);
  62608. refreshPath();
  62609. }
  62610. void CallOutBox::moved()
  62611. {
  62612. refreshPath();
  62613. }
  62614. void CallOutBox::childBoundsChanged (Component*)
  62615. {
  62616. updatePosition (targetArea, availableArea);
  62617. }
  62618. bool CallOutBox::hitTest (int x, int y)
  62619. {
  62620. return outline.contains ((float) x, (float) y);
  62621. }
  62622. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62623. void CallOutBox::inputAttemptWhenModal()
  62624. {
  62625. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62626. if (targetArea.contains (mousePos))
  62627. {
  62628. // if you click on the area that originally popped-up the callout, you expect it
  62629. // to get rid of the box, but deleting the box here allows the click to pass through and
  62630. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62631. postCommandMessage (callOutBoxDismissCommandId);
  62632. }
  62633. else
  62634. {
  62635. exitModalState (0);
  62636. setVisible (false);
  62637. }
  62638. }
  62639. void CallOutBox::handleCommandMessage (int commandId)
  62640. {
  62641. Component::handleCommandMessage (commandId);
  62642. if (commandId == callOutBoxDismissCommandId)
  62643. {
  62644. exitModalState (0);
  62645. setVisible (false);
  62646. }
  62647. }
  62648. bool CallOutBox::keyPressed (const KeyPress& key)
  62649. {
  62650. if (key.isKeyCode (KeyPress::escapeKey))
  62651. {
  62652. inputAttemptWhenModal();
  62653. return true;
  62654. }
  62655. return false;
  62656. }
  62657. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62658. {
  62659. targetArea = newAreaToPointTo;
  62660. availableArea = newAreaToFitIn;
  62661. Rectangle<int> bounds (0, 0,
  62662. content.getWidth() + borderSpace * 2,
  62663. content.getHeight() + borderSpace * 2);
  62664. const int hw = bounds.getWidth() / 2;
  62665. const int hh = bounds.getHeight() / 2;
  62666. const float hwReduced = (float) (hw - borderSpace * 3);
  62667. const float hhReduced = (float) (hh - borderSpace * 3);
  62668. const float arrowIndent = borderSpace - arrowSize;
  62669. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62670. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62671. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62672. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62673. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62674. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62675. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62676. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62677. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62678. float nearest = 1.0e9f;
  62679. for (int i = 0; i < 4; ++i)
  62680. {
  62681. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62682. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62683. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62684. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62685. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62686. distanceFromCentre *= 2.0f;
  62687. if (distanceFromCentre < nearest)
  62688. {
  62689. nearest = distanceFromCentre;
  62690. targetPoint = targets[i];
  62691. bounds.setPosition ((int) (centre.getX() - hw),
  62692. (int) (centre.getY() - hh));
  62693. }
  62694. }
  62695. setBounds (bounds);
  62696. }
  62697. void CallOutBox::refreshPath()
  62698. {
  62699. repaint();
  62700. background = Image::null;
  62701. outline.clear();
  62702. const float gap = 4.5f;
  62703. const float cornerSize = 9.0f;
  62704. const float cornerSize2 = 2.0f * cornerSize;
  62705. const float arrowBaseWidth = arrowSize * 0.7f;
  62706. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62707. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62708. outline.startNewSubPath (left + cornerSize, top);
  62709. if (targetY <= top)
  62710. {
  62711. outline.lineTo (targetX - arrowBaseWidth, top);
  62712. outline.lineTo (targetX, targetY);
  62713. outline.lineTo (targetX + arrowBaseWidth, top);
  62714. }
  62715. outline.lineTo (right - cornerSize, top);
  62716. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62717. if (targetX >= right)
  62718. {
  62719. outline.lineTo (right, targetY - arrowBaseWidth);
  62720. outline.lineTo (targetX, targetY);
  62721. outline.lineTo (right, targetY + arrowBaseWidth);
  62722. }
  62723. outline.lineTo (right, bottom - cornerSize);
  62724. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62725. if (targetY >= bottom)
  62726. {
  62727. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62728. outline.lineTo (targetX, targetY);
  62729. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62730. }
  62731. outline.lineTo (left + cornerSize, bottom);
  62732. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62733. if (targetX <= left)
  62734. {
  62735. outline.lineTo (left, targetY + arrowBaseWidth);
  62736. outline.lineTo (targetX, targetY);
  62737. outline.lineTo (left, targetY - arrowBaseWidth);
  62738. }
  62739. outline.lineTo (left, top + cornerSize);
  62740. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62741. outline.closeSubPath();
  62742. }
  62743. END_JUCE_NAMESPACE
  62744. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62745. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62746. BEGIN_JUCE_NAMESPACE
  62747. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62748. static Array <ComponentPeer*> heavyweightPeers;
  62749. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62750. : component (component_),
  62751. styleFlags (styleFlags_),
  62752. lastPaintTime (0),
  62753. constrainer (0),
  62754. lastDragAndDropCompUnderMouse (0),
  62755. fakeMouseMessageSent (false),
  62756. isWindowMinimised (false)
  62757. {
  62758. heavyweightPeers.add (this);
  62759. }
  62760. ComponentPeer::~ComponentPeer()
  62761. {
  62762. heavyweightPeers.removeValue (this);
  62763. Desktop::getInstance().triggerFocusCallback();
  62764. }
  62765. int ComponentPeer::getNumPeers() throw()
  62766. {
  62767. return heavyweightPeers.size();
  62768. }
  62769. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62770. {
  62771. return heavyweightPeers [index];
  62772. }
  62773. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62774. {
  62775. for (int i = heavyweightPeers.size(); --i >= 0;)
  62776. {
  62777. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62778. if (peer->getComponent() == component)
  62779. return peer;
  62780. }
  62781. return 0;
  62782. }
  62783. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62784. {
  62785. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62786. }
  62787. void ComponentPeer::updateCurrentModifiers() throw()
  62788. {
  62789. ModifierKeys::updateCurrentModifiers();
  62790. }
  62791. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62792. {
  62793. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62794. jassert (mouse != 0); // not enough sources!
  62795. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62796. }
  62797. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62798. {
  62799. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62800. jassert (mouse != 0); // not enough sources!
  62801. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62802. }
  62803. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62804. {
  62805. Graphics g (&contextToPaintTo);
  62806. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62807. g.saveState();
  62808. #endif
  62809. JUCE_TRY
  62810. {
  62811. component->paintEntireComponent (g);
  62812. }
  62813. JUCE_CATCH_EXCEPTION
  62814. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62815. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62816. // clearly when things are being repainted.
  62817. {
  62818. g.restoreState();
  62819. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62820. (uint8) Random::getSystemRandom().nextInt (255),
  62821. (uint8) Random::getSystemRandom().nextInt (255),
  62822. (uint8) 0x50));
  62823. }
  62824. #endif
  62825. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62826. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62827. mess up a lot of the calculations that the library needs to do.
  62828. */
  62829. jassert (roundToInt (10.1f) == 10);
  62830. }
  62831. bool ComponentPeer::handleKeyPress (const int keyCode,
  62832. const juce_wchar textCharacter)
  62833. {
  62834. updateCurrentModifiers();
  62835. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62836. ? Component::getCurrentlyFocusedComponent()
  62837. : component;
  62838. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62839. {
  62840. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62841. if (currentModalComp != 0)
  62842. target = currentModalComp;
  62843. }
  62844. const KeyPress keyInfo (keyCode,
  62845. ModifierKeys::getCurrentModifiers().getRawFlags()
  62846. & ModifierKeys::allKeyboardModifiers,
  62847. textCharacter);
  62848. bool keyWasUsed = false;
  62849. while (target != 0)
  62850. {
  62851. const Component::SafePointer<Component> deletionChecker (target);
  62852. if (target->keyListeners_ != 0)
  62853. {
  62854. for (int i = target->keyListeners_->size(); --i >= 0;)
  62855. {
  62856. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62857. if (keyWasUsed || deletionChecker == 0)
  62858. return keyWasUsed;
  62859. i = jmin (i, target->keyListeners_->size());
  62860. }
  62861. }
  62862. keyWasUsed = target->keyPressed (keyInfo);
  62863. if (keyWasUsed || deletionChecker == 0)
  62864. break;
  62865. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62866. {
  62867. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62868. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62869. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62870. break;
  62871. }
  62872. target = target->parentComponent_;
  62873. }
  62874. return keyWasUsed;
  62875. }
  62876. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62877. {
  62878. updateCurrentModifiers();
  62879. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62880. ? Component::getCurrentlyFocusedComponent()
  62881. : component;
  62882. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62883. {
  62884. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62885. if (currentModalComp != 0)
  62886. target = currentModalComp;
  62887. }
  62888. bool keyWasUsed = false;
  62889. while (target != 0)
  62890. {
  62891. const Component::SafePointer<Component> deletionChecker (target);
  62892. keyWasUsed = target->keyStateChanged (isKeyDown);
  62893. if (keyWasUsed || deletionChecker == 0)
  62894. break;
  62895. if (target->keyListeners_ != 0)
  62896. {
  62897. for (int i = target->keyListeners_->size(); --i >= 0;)
  62898. {
  62899. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62900. if (keyWasUsed || deletionChecker == 0)
  62901. return keyWasUsed;
  62902. i = jmin (i, target->keyListeners_->size());
  62903. }
  62904. }
  62905. target = target->parentComponent_;
  62906. }
  62907. return keyWasUsed;
  62908. }
  62909. void ComponentPeer::handleModifierKeysChange()
  62910. {
  62911. updateCurrentModifiers();
  62912. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62913. if (target == 0)
  62914. target = Component::getCurrentlyFocusedComponent();
  62915. if (target == 0)
  62916. target = component;
  62917. if (target != 0)
  62918. target->internalModifierKeysChanged();
  62919. }
  62920. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62921. {
  62922. Component* const c = Component::getCurrentlyFocusedComponent();
  62923. if (component->isParentOf (c))
  62924. {
  62925. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62926. if (ti != 0 && ti->isTextInputActive())
  62927. return ti;
  62928. }
  62929. return 0;
  62930. }
  62931. void ComponentPeer::handleBroughtToFront()
  62932. {
  62933. updateCurrentModifiers();
  62934. if (component != 0)
  62935. component->internalBroughtToFront();
  62936. }
  62937. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62938. {
  62939. constrainer = newConstrainer;
  62940. }
  62941. void ComponentPeer::handleMovedOrResized()
  62942. {
  62943. jassert (component->isValidComponent());
  62944. updateCurrentModifiers();
  62945. const bool nowMinimised = isMinimised();
  62946. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62947. {
  62948. const Component::SafePointer<Component> deletionChecker (component);
  62949. const Rectangle<int> newBounds (getBounds());
  62950. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62951. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62952. if (wasMoved || wasResized)
  62953. {
  62954. component->bounds_ = newBounds;
  62955. if (wasResized)
  62956. component->repaint();
  62957. component->sendMovedResizedMessages (wasMoved, wasResized);
  62958. if (deletionChecker == 0)
  62959. return;
  62960. }
  62961. }
  62962. if (isWindowMinimised != nowMinimised)
  62963. {
  62964. isWindowMinimised = nowMinimised;
  62965. component->minimisationStateChanged (nowMinimised);
  62966. component->sendVisibilityChangeMessage();
  62967. }
  62968. if (! isFullScreen())
  62969. lastNonFullscreenBounds = component->getBounds();
  62970. }
  62971. void ComponentPeer::handleFocusGain()
  62972. {
  62973. updateCurrentModifiers();
  62974. if (component->isParentOf (lastFocusedComponent))
  62975. {
  62976. Component::currentlyFocusedComponent = lastFocusedComponent;
  62977. Desktop::getInstance().triggerFocusCallback();
  62978. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62979. }
  62980. else
  62981. {
  62982. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62983. component->grabKeyboardFocus();
  62984. else
  62985. Component::bringModalComponentToFront();
  62986. }
  62987. }
  62988. void ComponentPeer::handleFocusLoss()
  62989. {
  62990. updateCurrentModifiers();
  62991. if (component->hasKeyboardFocus (true))
  62992. {
  62993. lastFocusedComponent = Component::currentlyFocusedComponent;
  62994. if (lastFocusedComponent != 0)
  62995. {
  62996. Component::currentlyFocusedComponent = 0;
  62997. Desktop::getInstance().triggerFocusCallback();
  62998. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62999. }
  63000. }
  63001. }
  63002. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  63003. {
  63004. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  63005. ? static_cast <Component*> (lastFocusedComponent)
  63006. : component;
  63007. }
  63008. void ComponentPeer::handleScreenSizeChange()
  63009. {
  63010. updateCurrentModifiers();
  63011. component->parentSizeChanged();
  63012. handleMovedOrResized();
  63013. }
  63014. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  63015. {
  63016. lastNonFullscreenBounds = newBounds;
  63017. }
  63018. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  63019. {
  63020. return lastNonFullscreenBounds;
  63021. }
  63022. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  63023. const StringArray& files,
  63024. FileDragAndDropTarget* const lastOne)
  63025. {
  63026. while (c != 0)
  63027. {
  63028. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  63029. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  63030. return t;
  63031. c = c->getParentComponent();
  63032. }
  63033. return 0;
  63034. }
  63035. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  63036. {
  63037. updateCurrentModifiers();
  63038. FileDragAndDropTarget* lastTarget
  63039. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63040. FileDragAndDropTarget* newTarget = 0;
  63041. Component* const compUnderMouse = component->getComponentAt (position);
  63042. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  63043. {
  63044. lastDragAndDropCompUnderMouse = compUnderMouse;
  63045. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  63046. if (newTarget != lastTarget)
  63047. {
  63048. if (lastTarget != 0)
  63049. lastTarget->fileDragExit (files);
  63050. dragAndDropTargetComponent = 0;
  63051. if (newTarget != 0)
  63052. {
  63053. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  63054. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  63055. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  63056. }
  63057. }
  63058. }
  63059. else
  63060. {
  63061. newTarget = lastTarget;
  63062. }
  63063. if (newTarget != 0)
  63064. {
  63065. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63066. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63067. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63068. }
  63069. }
  63070. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63071. {
  63072. handleFileDragMove (files, Point<int> (-1, -1));
  63073. jassert (dragAndDropTargetComponent == 0);
  63074. lastDragAndDropCompUnderMouse = 0;
  63075. }
  63076. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63077. {
  63078. handleFileDragMove (files, position);
  63079. if (dragAndDropTargetComponent != 0)
  63080. {
  63081. FileDragAndDropTarget* const target
  63082. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63083. dragAndDropTargetComponent = 0;
  63084. lastDragAndDropCompUnderMouse = 0;
  63085. if (target != 0)
  63086. {
  63087. Component* const targetComp = dynamic_cast <Component*> (target);
  63088. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63089. {
  63090. targetComp->internalModalInputAttempt();
  63091. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63092. return;
  63093. }
  63094. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63095. target->filesDropped (files, pos.getX(), pos.getY());
  63096. }
  63097. }
  63098. }
  63099. void ComponentPeer::handleUserClosingWindow()
  63100. {
  63101. updateCurrentModifiers();
  63102. component->userTriedToCloseWindow();
  63103. }
  63104. void ComponentPeer::bringModalComponentToFront()
  63105. {
  63106. Component::bringModalComponentToFront();
  63107. }
  63108. void ComponentPeer::clearMaskedRegion()
  63109. {
  63110. maskedRegion.clear();
  63111. }
  63112. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63113. {
  63114. maskedRegion.add (x, y, w, h);
  63115. }
  63116. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63117. {
  63118. StringArray s;
  63119. s.add ("Software Renderer");
  63120. return s;
  63121. }
  63122. int ComponentPeer::getCurrentRenderingEngine() throw()
  63123. {
  63124. return 0;
  63125. }
  63126. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63127. {
  63128. }
  63129. END_JUCE_NAMESPACE
  63130. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63131. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63132. BEGIN_JUCE_NAMESPACE
  63133. DialogWindow::DialogWindow (const String& name,
  63134. const Colour& backgroundColour_,
  63135. const bool escapeKeyTriggersCloseButton_,
  63136. const bool addToDesktop_)
  63137. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63138. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63139. {
  63140. }
  63141. DialogWindow::~DialogWindow()
  63142. {
  63143. }
  63144. void DialogWindow::resized()
  63145. {
  63146. DocumentWindow::resized();
  63147. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63148. if (escapeKeyTriggersCloseButton
  63149. && getCloseButton() != 0
  63150. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63151. {
  63152. getCloseButton()->addShortcut (esc);
  63153. }
  63154. }
  63155. class TempDialogWindow : public DialogWindow
  63156. {
  63157. public:
  63158. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63159. : DialogWindow (title, colour, escapeCloses, true)
  63160. {
  63161. if (! JUCEApplication::isStandaloneApp())
  63162. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63163. }
  63164. ~TempDialogWindow()
  63165. {
  63166. }
  63167. void closeButtonPressed()
  63168. {
  63169. setVisible (false);
  63170. }
  63171. private:
  63172. TempDialogWindow (const TempDialogWindow&);
  63173. TempDialogWindow& operator= (const TempDialogWindow&);
  63174. };
  63175. int DialogWindow::showModalDialog (const String& dialogTitle,
  63176. Component* contentComponent,
  63177. Component* componentToCentreAround,
  63178. const Colour& colour,
  63179. const bool escapeKeyTriggersCloseButton,
  63180. const bool shouldBeResizable,
  63181. const bool useBottomRightCornerResizer)
  63182. {
  63183. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63184. dw.setContentComponent (contentComponent, true, true);
  63185. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63186. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63187. const int result = dw.runModalLoop();
  63188. dw.setContentComponent (0, false);
  63189. return result;
  63190. }
  63191. END_JUCE_NAMESPACE
  63192. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63193. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63194. BEGIN_JUCE_NAMESPACE
  63195. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63196. {
  63197. public:
  63198. ButtonListenerProxy (DocumentWindow& owner_)
  63199. : owner (owner_)
  63200. {
  63201. }
  63202. void buttonClicked (Button* button)
  63203. {
  63204. if (button == owner.getMinimiseButton())
  63205. owner.minimiseButtonPressed();
  63206. else if (button == owner.getMaximiseButton())
  63207. owner.maximiseButtonPressed();
  63208. else if (button == owner.getCloseButton())
  63209. owner.closeButtonPressed();
  63210. }
  63211. juce_UseDebuggingNewOperator
  63212. private:
  63213. DocumentWindow& owner;
  63214. ButtonListenerProxy (const ButtonListenerProxy&);
  63215. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63216. };
  63217. DocumentWindow::DocumentWindow (const String& title,
  63218. const Colour& backgroundColour,
  63219. const int requiredButtons_,
  63220. const bool addToDesktop_)
  63221. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63222. titleBarHeight (26),
  63223. menuBarHeight (24),
  63224. requiredButtons (requiredButtons_),
  63225. #if JUCE_MAC
  63226. positionTitleBarButtonsOnLeft (true),
  63227. #else
  63228. positionTitleBarButtonsOnLeft (false),
  63229. #endif
  63230. drawTitleTextCentred (true),
  63231. menuBarModel (0)
  63232. {
  63233. setResizeLimits (128, 128, 32768, 32768);
  63234. lookAndFeelChanged();
  63235. }
  63236. DocumentWindow::~DocumentWindow()
  63237. {
  63238. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63239. titleBarButtons[i] = 0;
  63240. menuBar = 0;
  63241. }
  63242. void DocumentWindow::repaintTitleBar()
  63243. {
  63244. repaint (getTitleBarArea());
  63245. }
  63246. void DocumentWindow::setName (const String& newName)
  63247. {
  63248. if (newName != getName())
  63249. {
  63250. Component::setName (newName);
  63251. repaintTitleBar();
  63252. }
  63253. }
  63254. void DocumentWindow::setIcon (const Image& imageToUse)
  63255. {
  63256. titleBarIcon = imageToUse;
  63257. repaintTitleBar();
  63258. }
  63259. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63260. {
  63261. titleBarHeight = newHeight;
  63262. resized();
  63263. repaintTitleBar();
  63264. }
  63265. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63266. const bool positionTitleBarButtonsOnLeft_)
  63267. {
  63268. requiredButtons = requiredButtons_;
  63269. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63270. lookAndFeelChanged();
  63271. }
  63272. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63273. {
  63274. drawTitleTextCentred = textShouldBeCentred;
  63275. repaintTitleBar();
  63276. }
  63277. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63278. const int menuBarHeight_)
  63279. {
  63280. if (menuBarModel != menuBarModel_)
  63281. {
  63282. menuBar = 0;
  63283. menuBarModel = menuBarModel_;
  63284. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63285. : getLookAndFeel().getDefaultMenuBarHeight();
  63286. if (menuBarModel != 0)
  63287. {
  63288. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63289. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63290. menuBar->setEnabled (isActiveWindow());
  63291. }
  63292. resized();
  63293. }
  63294. }
  63295. void DocumentWindow::closeButtonPressed()
  63296. {
  63297. /* If you've got a close button, you have to override this method to get
  63298. rid of your window!
  63299. If the window is just a pop-up, you should override this method and make
  63300. it delete the window in whatever way is appropriate for your app. E.g. you
  63301. might just want to call "delete this".
  63302. If your app is centred around this window such that the whole app should quit when
  63303. the window is closed, then you will probably want to use this method as an opportunity
  63304. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63305. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63306. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63307. or closing it via the taskbar icon on Windows).
  63308. */
  63309. jassertfalse;
  63310. }
  63311. void DocumentWindow::minimiseButtonPressed()
  63312. {
  63313. setMinimised (true);
  63314. }
  63315. void DocumentWindow::maximiseButtonPressed()
  63316. {
  63317. setFullScreen (! isFullScreen());
  63318. }
  63319. void DocumentWindow::paint (Graphics& g)
  63320. {
  63321. ResizableWindow::paint (g);
  63322. if (resizableBorder == 0)
  63323. {
  63324. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63325. const BorderSize border (getBorderThickness());
  63326. g.fillRect (0, 0, getWidth(), border.getTop());
  63327. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63328. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63329. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63330. }
  63331. const Rectangle<int> titleBarArea (getTitleBarArea());
  63332. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63333. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63334. int titleSpaceX1 = 6;
  63335. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63336. for (int i = 0; i < 3; ++i)
  63337. {
  63338. if (titleBarButtons[i] != 0)
  63339. {
  63340. if (positionTitleBarButtonsOnLeft)
  63341. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63342. else
  63343. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63344. }
  63345. }
  63346. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63347. titleBarArea.getWidth(),
  63348. titleBarArea.getHeight(),
  63349. titleSpaceX1,
  63350. jmax (1, titleSpaceX2 - titleSpaceX1),
  63351. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63352. ! drawTitleTextCentred);
  63353. }
  63354. void DocumentWindow::resized()
  63355. {
  63356. ResizableWindow::resized();
  63357. if (titleBarButtons[1] != 0)
  63358. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63359. const Rectangle<int> titleBarArea (getTitleBarArea());
  63360. getLookAndFeel()
  63361. .positionDocumentWindowButtons (*this,
  63362. titleBarArea.getX(), titleBarArea.getY(),
  63363. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63364. titleBarButtons[0],
  63365. titleBarButtons[1],
  63366. titleBarButtons[2],
  63367. positionTitleBarButtonsOnLeft);
  63368. if (menuBar != 0)
  63369. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63370. titleBarArea.getWidth(), menuBarHeight);
  63371. }
  63372. const BorderSize DocumentWindow::getBorderThickness()
  63373. {
  63374. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63375. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63376. }
  63377. const BorderSize DocumentWindow::getContentComponentBorder()
  63378. {
  63379. BorderSize border (getBorderThickness());
  63380. border.setTop (border.getTop()
  63381. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63382. + (menuBar != 0 ? menuBarHeight : 0));
  63383. return border;
  63384. }
  63385. int DocumentWindow::getTitleBarHeight() const
  63386. {
  63387. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63388. }
  63389. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63390. {
  63391. const BorderSize border (getBorderThickness());
  63392. return Rectangle<int> (border.getLeft(), border.getTop(),
  63393. getWidth() - border.getLeftAndRight(),
  63394. getTitleBarHeight());
  63395. }
  63396. Button* DocumentWindow::getCloseButton() const throw()
  63397. {
  63398. return titleBarButtons[2];
  63399. }
  63400. Button* DocumentWindow::getMinimiseButton() const throw()
  63401. {
  63402. return titleBarButtons[0];
  63403. }
  63404. Button* DocumentWindow::getMaximiseButton() const throw()
  63405. {
  63406. return titleBarButtons[1];
  63407. }
  63408. int DocumentWindow::getDesktopWindowStyleFlags() const
  63409. {
  63410. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63411. if ((requiredButtons & minimiseButton) != 0)
  63412. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63413. if ((requiredButtons & maximiseButton) != 0)
  63414. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63415. if ((requiredButtons & closeButton) != 0)
  63416. styleFlags |= ComponentPeer::windowHasCloseButton;
  63417. return styleFlags;
  63418. }
  63419. void DocumentWindow::lookAndFeelChanged()
  63420. {
  63421. int i;
  63422. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63423. titleBarButtons[i] = 0;
  63424. if (! isUsingNativeTitleBar())
  63425. {
  63426. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63427. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63428. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63429. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63430. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63431. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63432. for (i = 0; i < 3; ++i)
  63433. {
  63434. if (titleBarButtons[i] != 0)
  63435. {
  63436. if (buttonListener == 0)
  63437. buttonListener = new ButtonListenerProxy (*this);
  63438. titleBarButtons[i]->addButtonListener (buttonListener);
  63439. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63440. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63441. Component::addAndMakeVisible (titleBarButtons[i]);
  63442. }
  63443. }
  63444. if (getCloseButton() != 0)
  63445. {
  63446. #if JUCE_MAC
  63447. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63448. #else
  63449. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63450. #endif
  63451. }
  63452. }
  63453. activeWindowStatusChanged();
  63454. ResizableWindow::lookAndFeelChanged();
  63455. }
  63456. void DocumentWindow::parentHierarchyChanged()
  63457. {
  63458. lookAndFeelChanged();
  63459. }
  63460. void DocumentWindow::activeWindowStatusChanged()
  63461. {
  63462. ResizableWindow::activeWindowStatusChanged();
  63463. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63464. if (titleBarButtons[i] != 0)
  63465. titleBarButtons[i]->setEnabled (isActiveWindow());
  63466. if (menuBar != 0)
  63467. menuBar->setEnabled (isActiveWindow());
  63468. }
  63469. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63470. {
  63471. if (getTitleBarArea().contains (e.x, e.y)
  63472. && getMaximiseButton() != 0)
  63473. {
  63474. getMaximiseButton()->triggerClick();
  63475. }
  63476. }
  63477. void DocumentWindow::userTriedToCloseWindow()
  63478. {
  63479. closeButtonPressed();
  63480. }
  63481. END_JUCE_NAMESPACE
  63482. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63483. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63484. BEGIN_JUCE_NAMESPACE
  63485. ResizableWindow::ResizableWindow (const String& name,
  63486. const bool addToDesktop_)
  63487. : TopLevelWindow (name, addToDesktop_),
  63488. resizeToFitContent (false),
  63489. fullscreen (false),
  63490. lastNonFullScreenPos (50, 50, 256, 256),
  63491. constrainer (0)
  63492. #if JUCE_DEBUG
  63493. , hasBeenResized (false)
  63494. #endif
  63495. {
  63496. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63497. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63498. if (addToDesktop_)
  63499. Component::addToDesktop (getDesktopWindowStyleFlags());
  63500. }
  63501. ResizableWindow::ResizableWindow (const String& name,
  63502. const Colour& backgroundColour_,
  63503. const bool addToDesktop_)
  63504. : TopLevelWindow (name, addToDesktop_),
  63505. resizeToFitContent (false),
  63506. fullscreen (false),
  63507. lastNonFullScreenPos (50, 50, 256, 256),
  63508. constrainer (0)
  63509. #if JUCE_DEBUG
  63510. , hasBeenResized (false)
  63511. #endif
  63512. {
  63513. setBackgroundColour (backgroundColour_);
  63514. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63515. if (addToDesktop_)
  63516. Component::addToDesktop (getDesktopWindowStyleFlags());
  63517. }
  63518. ResizableWindow::~ResizableWindow()
  63519. {
  63520. resizableCorner = 0;
  63521. resizableBorder = 0;
  63522. contentComponent.deleteAndZero();
  63523. // have you been adding your own components directly to this window..? tut tut tut.
  63524. // Read the instructions for using a ResizableWindow!
  63525. jassert (getNumChildComponents() == 0);
  63526. }
  63527. int ResizableWindow::getDesktopWindowStyleFlags() const
  63528. {
  63529. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63530. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63531. styleFlags |= ComponentPeer::windowIsResizable;
  63532. return styleFlags;
  63533. }
  63534. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63535. const bool deleteOldOne,
  63536. const bool resizeToFit)
  63537. {
  63538. resizeToFitContent = resizeToFit;
  63539. if (newContentComponent != static_cast <Component*> (contentComponent))
  63540. {
  63541. if (deleteOldOne)
  63542. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63543. // external deletion of the content comp)
  63544. else
  63545. removeChildComponent (contentComponent);
  63546. contentComponent = newContentComponent;
  63547. Component::addAndMakeVisible (contentComponent);
  63548. }
  63549. if (resizeToFit)
  63550. childBoundsChanged (contentComponent);
  63551. resized(); // must always be called to position the new content comp
  63552. }
  63553. void ResizableWindow::setContentComponentSize (int width, int height)
  63554. {
  63555. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63556. const BorderSize border (getContentComponentBorder());
  63557. setSize (width + border.getLeftAndRight(),
  63558. height + border.getTopAndBottom());
  63559. }
  63560. const BorderSize ResizableWindow::getBorderThickness()
  63561. {
  63562. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63563. }
  63564. const BorderSize ResizableWindow::getContentComponentBorder()
  63565. {
  63566. return getBorderThickness();
  63567. }
  63568. void ResizableWindow::moved()
  63569. {
  63570. updateLastPos();
  63571. }
  63572. void ResizableWindow::visibilityChanged()
  63573. {
  63574. TopLevelWindow::visibilityChanged();
  63575. updateLastPos();
  63576. }
  63577. void ResizableWindow::resized()
  63578. {
  63579. if (resizableBorder != 0)
  63580. {
  63581. #if JUCE_WINDOWS || JUCE_LINUX
  63582. // hide the resizable border if the OS already provides one..
  63583. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63584. #else
  63585. resizableBorder->setVisible (! isFullScreen());
  63586. #endif
  63587. resizableBorder->setBorderThickness (getBorderThickness());
  63588. resizableBorder->setSize (getWidth(), getHeight());
  63589. resizableBorder->toBack();
  63590. }
  63591. if (resizableCorner != 0)
  63592. {
  63593. #if JUCE_MAC
  63594. // hide the resizable border if the OS already provides one..
  63595. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63596. #else
  63597. resizableCorner->setVisible (! isFullScreen());
  63598. #endif
  63599. const int resizerSize = 18;
  63600. resizableCorner->setBounds (getWidth() - resizerSize,
  63601. getHeight() - resizerSize,
  63602. resizerSize, resizerSize);
  63603. }
  63604. if (contentComponent != 0)
  63605. contentComponent->setBoundsInset (getContentComponentBorder());
  63606. updateLastPos();
  63607. #if JUCE_DEBUG
  63608. hasBeenResized = true;
  63609. #endif
  63610. }
  63611. void ResizableWindow::childBoundsChanged (Component* child)
  63612. {
  63613. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63614. {
  63615. // not going to look very good if this component has a zero size..
  63616. jassert (child->getWidth() > 0);
  63617. jassert (child->getHeight() > 0);
  63618. const BorderSize borders (getContentComponentBorder());
  63619. setSize (child->getWidth() + borders.getLeftAndRight(),
  63620. child->getHeight() + borders.getTopAndBottom());
  63621. }
  63622. }
  63623. void ResizableWindow::activeWindowStatusChanged()
  63624. {
  63625. const BorderSize border (getContentComponentBorder());
  63626. Rectangle<int> area (getLocalBounds());
  63627. repaint (area.removeFromTop (border.getTop()));
  63628. repaint (area.removeFromLeft (border.getLeft()));
  63629. repaint (area.removeFromRight (border.getRight()));
  63630. repaint (area.removeFromBottom (border.getBottom()));
  63631. }
  63632. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63633. const bool useBottomRightCornerResizer)
  63634. {
  63635. if (shouldBeResizable)
  63636. {
  63637. if (useBottomRightCornerResizer)
  63638. {
  63639. resizableBorder = 0;
  63640. if (resizableCorner == 0)
  63641. {
  63642. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63643. resizableCorner->setAlwaysOnTop (true);
  63644. }
  63645. }
  63646. else
  63647. {
  63648. resizableCorner = 0;
  63649. if (resizableBorder == 0)
  63650. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63651. }
  63652. }
  63653. else
  63654. {
  63655. resizableCorner = 0;
  63656. resizableBorder = 0;
  63657. }
  63658. if (isUsingNativeTitleBar())
  63659. recreateDesktopWindow();
  63660. childBoundsChanged (contentComponent);
  63661. resized();
  63662. }
  63663. bool ResizableWindow::isResizable() const throw()
  63664. {
  63665. return resizableCorner != 0
  63666. || resizableBorder != 0;
  63667. }
  63668. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63669. const int newMinimumHeight,
  63670. const int newMaximumWidth,
  63671. const int newMaximumHeight) throw()
  63672. {
  63673. // if you've set up a custom constrainer then these settings won't have any effect..
  63674. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63675. if (constrainer == 0)
  63676. setConstrainer (&defaultConstrainer);
  63677. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63678. newMaximumWidth, newMaximumHeight);
  63679. setBoundsConstrained (getBounds());
  63680. }
  63681. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63682. {
  63683. if (constrainer != newConstrainer)
  63684. {
  63685. constrainer = newConstrainer;
  63686. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63687. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63688. resizableCorner = 0;
  63689. resizableBorder = 0;
  63690. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63691. ComponentPeer* const peer = getPeer();
  63692. if (peer != 0)
  63693. peer->setConstrainer (newConstrainer);
  63694. }
  63695. }
  63696. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63697. {
  63698. if (constrainer != 0)
  63699. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63700. else
  63701. setBounds (bounds);
  63702. }
  63703. void ResizableWindow::paint (Graphics& g)
  63704. {
  63705. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63706. getBorderThickness(), *this);
  63707. if (! isFullScreen())
  63708. {
  63709. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63710. getBorderThickness(), *this);
  63711. }
  63712. #if JUCE_DEBUG
  63713. /* If this fails, then you've probably written a subclass with a resized()
  63714. callback but forgotten to make it call its parent class's resized() method.
  63715. It's important when you override methods like resized(), moved(),
  63716. etc., that you make sure the base class methods also get called.
  63717. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63718. because your content should all be inside the content component - and it's the
  63719. content component's resized() method that you should be using to do your
  63720. layout.
  63721. */
  63722. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63723. #endif
  63724. }
  63725. void ResizableWindow::lookAndFeelChanged()
  63726. {
  63727. resized();
  63728. if (isOnDesktop())
  63729. {
  63730. Component::addToDesktop (getDesktopWindowStyleFlags());
  63731. ComponentPeer* const peer = getPeer();
  63732. if (peer != 0)
  63733. peer->setConstrainer (constrainer);
  63734. }
  63735. }
  63736. const Colour ResizableWindow::getBackgroundColour() const throw()
  63737. {
  63738. return findColour (backgroundColourId, false);
  63739. }
  63740. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63741. {
  63742. Colour backgroundColour (newColour);
  63743. if (! Desktop::canUseSemiTransparentWindows())
  63744. backgroundColour = newColour.withAlpha (1.0f);
  63745. setColour (backgroundColourId, backgroundColour);
  63746. setOpaque (backgroundColour.isOpaque());
  63747. repaint();
  63748. }
  63749. bool ResizableWindow::isFullScreen() const
  63750. {
  63751. if (isOnDesktop())
  63752. {
  63753. ComponentPeer* const peer = getPeer();
  63754. return peer != 0 && peer->isFullScreen();
  63755. }
  63756. return fullscreen;
  63757. }
  63758. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63759. {
  63760. if (shouldBeFullScreen != isFullScreen())
  63761. {
  63762. updateLastPos();
  63763. fullscreen = shouldBeFullScreen;
  63764. if (isOnDesktop())
  63765. {
  63766. ComponentPeer* const peer = getPeer();
  63767. if (peer != 0)
  63768. {
  63769. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63770. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63771. peer->setFullScreen (shouldBeFullScreen);
  63772. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63773. setBounds (lastPos);
  63774. }
  63775. else
  63776. {
  63777. jassertfalse;
  63778. }
  63779. }
  63780. else
  63781. {
  63782. if (shouldBeFullScreen)
  63783. setBounds (0, 0, getParentWidth(), getParentHeight());
  63784. else
  63785. setBounds (lastNonFullScreenPos);
  63786. }
  63787. resized();
  63788. }
  63789. }
  63790. bool ResizableWindow::isMinimised() const
  63791. {
  63792. ComponentPeer* const peer = getPeer();
  63793. return (peer != 0) && peer->isMinimised();
  63794. }
  63795. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63796. {
  63797. if (shouldMinimise != isMinimised())
  63798. {
  63799. ComponentPeer* const peer = getPeer();
  63800. if (peer != 0)
  63801. {
  63802. updateLastPos();
  63803. peer->setMinimised (shouldMinimise);
  63804. }
  63805. else
  63806. {
  63807. jassertfalse;
  63808. }
  63809. }
  63810. }
  63811. void ResizableWindow::updateLastPos()
  63812. {
  63813. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63814. {
  63815. lastNonFullScreenPos = getBounds();
  63816. }
  63817. }
  63818. void ResizableWindow::parentSizeChanged()
  63819. {
  63820. if (isFullScreen() && getParentComponent() != 0)
  63821. {
  63822. setBounds (0, 0, getParentWidth(), getParentHeight());
  63823. }
  63824. }
  63825. const String ResizableWindow::getWindowStateAsString()
  63826. {
  63827. updateLastPos();
  63828. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63829. }
  63830. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63831. {
  63832. StringArray tokens;
  63833. tokens.addTokens (s, false);
  63834. tokens.removeEmptyStrings();
  63835. tokens.trim();
  63836. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63837. const int firstCoord = fs ? 1 : 0;
  63838. if (tokens.size() != firstCoord + 4)
  63839. return false;
  63840. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63841. tokens[firstCoord + 1].getIntValue(),
  63842. tokens[firstCoord + 2].getIntValue(),
  63843. tokens[firstCoord + 3].getIntValue());
  63844. if (newPos.isEmpty())
  63845. return false;
  63846. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63847. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63848. if (peer != 0)
  63849. peer->getFrameSize().addTo (newPos);
  63850. if (! screen.contains (newPos))
  63851. {
  63852. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63853. jmin (newPos.getHeight(), screen.getHeight()));
  63854. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63855. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63856. }
  63857. if (peer != 0)
  63858. {
  63859. peer->getFrameSize().subtractFrom (newPos);
  63860. peer->setNonFullScreenBounds (newPos);
  63861. }
  63862. lastNonFullScreenPos = newPos;
  63863. setFullScreen (fs);
  63864. if (! fs)
  63865. setBoundsConstrained (newPos);
  63866. return true;
  63867. }
  63868. void ResizableWindow::mouseDown (const MouseEvent&)
  63869. {
  63870. if (! isFullScreen())
  63871. dragger.startDraggingComponent (this, constrainer);
  63872. }
  63873. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63874. {
  63875. if (! isFullScreen())
  63876. dragger.dragComponent (this, e);
  63877. }
  63878. #if JUCE_DEBUG
  63879. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63880. {
  63881. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63882. manages its child components automatically, and if you add your own it'll cause
  63883. trouble. Instead, use setContentComponent() to give it a component which
  63884. will be automatically resized and kept in the right place - then you can add
  63885. subcomponents to the content comp. See the notes for the ResizableWindow class
  63886. for more info.
  63887. If you really know what you're doing and want to avoid this assertion, just call
  63888. Component::addChildComponent directly.
  63889. */
  63890. jassertfalse;
  63891. Component::addChildComponent (child, zOrder);
  63892. }
  63893. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63894. {
  63895. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63896. manages its child components automatically, and if you add your own it'll cause
  63897. trouble. Instead, use setContentComponent() to give it a component which
  63898. will be automatically resized and kept in the right place - then you can add
  63899. subcomponents to the content comp. See the notes for the ResizableWindow class
  63900. for more info.
  63901. If you really know what you're doing and want to avoid this assertion, just call
  63902. Component::addAndMakeVisible directly.
  63903. */
  63904. jassertfalse;
  63905. Component::addAndMakeVisible (child, zOrder);
  63906. }
  63907. #endif
  63908. END_JUCE_NAMESPACE
  63909. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63910. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63911. BEGIN_JUCE_NAMESPACE
  63912. SplashScreen::SplashScreen()
  63913. {
  63914. setOpaque (true);
  63915. }
  63916. SplashScreen::~SplashScreen()
  63917. {
  63918. }
  63919. void SplashScreen::show (const String& title,
  63920. const Image& backgroundImage_,
  63921. const int minimumTimeToDisplayFor,
  63922. const bool useDropShadow,
  63923. const bool removeOnMouseClick)
  63924. {
  63925. backgroundImage = backgroundImage_;
  63926. jassert (backgroundImage_.isValid());
  63927. if (backgroundImage_.isValid())
  63928. {
  63929. setOpaque (! backgroundImage_.hasAlphaChannel());
  63930. show (title,
  63931. backgroundImage_.getWidth(),
  63932. backgroundImage_.getHeight(),
  63933. minimumTimeToDisplayFor,
  63934. useDropShadow,
  63935. removeOnMouseClick);
  63936. }
  63937. }
  63938. void SplashScreen::show (const String& title,
  63939. const int width,
  63940. const int height,
  63941. const int minimumTimeToDisplayFor,
  63942. const bool useDropShadow,
  63943. const bool removeOnMouseClick)
  63944. {
  63945. setName (title);
  63946. setAlwaysOnTop (true);
  63947. setVisible (true);
  63948. centreWithSize (width, height);
  63949. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63950. toFront (false);
  63951. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63952. repaint();
  63953. originalClickCounter = removeOnMouseClick
  63954. ? Desktop::getMouseButtonClickCounter()
  63955. : std::numeric_limits<int>::max();
  63956. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63957. startTimer (50);
  63958. }
  63959. void SplashScreen::paint (Graphics& g)
  63960. {
  63961. g.setOpacity (1.0f);
  63962. g.drawImage (backgroundImage,
  63963. 0, 0, getWidth(), getHeight(),
  63964. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63965. }
  63966. void SplashScreen::timerCallback()
  63967. {
  63968. if (Time::getCurrentTime() > earliestTimeToDelete
  63969. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63970. {
  63971. delete this;
  63972. }
  63973. }
  63974. END_JUCE_NAMESPACE
  63975. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63976. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63977. BEGIN_JUCE_NAMESPACE
  63978. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63979. const bool hasProgressBar,
  63980. const bool hasCancelButton,
  63981. const int timeOutMsWhenCancelling_,
  63982. const String& cancelButtonText)
  63983. : Thread ("Juce Progress Window"),
  63984. progress (0.0),
  63985. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63986. {
  63987. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63988. .createAlertWindow (title, String::empty, cancelButtonText,
  63989. String::empty, String::empty,
  63990. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63991. if (hasProgressBar)
  63992. alertWindow->addProgressBarComponent (progress);
  63993. }
  63994. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63995. {
  63996. stopThread (timeOutMsWhenCancelling);
  63997. }
  63998. bool ThreadWithProgressWindow::runThread (const int priority)
  63999. {
  64000. startThread (priority);
  64001. startTimer (100);
  64002. {
  64003. const ScopedLock sl (messageLock);
  64004. alertWindow->setMessage (message);
  64005. }
  64006. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  64007. stopThread (timeOutMsWhenCancelling);
  64008. alertWindow->setVisible (false);
  64009. return finishedNaturally;
  64010. }
  64011. void ThreadWithProgressWindow::setProgress (const double newProgress)
  64012. {
  64013. progress = newProgress;
  64014. }
  64015. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  64016. {
  64017. const ScopedLock sl (messageLock);
  64018. message = newStatusMessage;
  64019. }
  64020. void ThreadWithProgressWindow::timerCallback()
  64021. {
  64022. if (! isThreadRunning())
  64023. {
  64024. // thread has finished normally..
  64025. alertWindow->exitModalState (1);
  64026. alertWindow->setVisible (false);
  64027. }
  64028. else
  64029. {
  64030. const ScopedLock sl (messageLock);
  64031. alertWindow->setMessage (message);
  64032. }
  64033. }
  64034. END_JUCE_NAMESPACE
  64035. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  64036. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  64037. BEGIN_JUCE_NAMESPACE
  64038. TooltipWindow::TooltipWindow (Component* const parentComponent,
  64039. const int millisecondsBeforeTipAppears_)
  64040. : Component ("tooltip"),
  64041. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  64042. mouseClicks (0),
  64043. lastHideTime (0),
  64044. lastComponentUnderMouse (0),
  64045. changedCompsSinceShown (true)
  64046. {
  64047. if (Desktop::getInstance().getMainMouseSource().canHover())
  64048. startTimer (123);
  64049. setAlwaysOnTop (true);
  64050. setOpaque (true);
  64051. if (parentComponent != 0)
  64052. parentComponent->addChildComponent (this);
  64053. }
  64054. TooltipWindow::~TooltipWindow()
  64055. {
  64056. hide();
  64057. }
  64058. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  64059. {
  64060. millisecondsBeforeTipAppears = newTimeMs;
  64061. }
  64062. void TooltipWindow::paint (Graphics& g)
  64063. {
  64064. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  64065. }
  64066. void TooltipWindow::mouseEnter (const MouseEvent&)
  64067. {
  64068. hide();
  64069. }
  64070. void TooltipWindow::showFor (const String& tip)
  64071. {
  64072. jassert (tip.isNotEmpty());
  64073. if (tipShowing != tip)
  64074. repaint();
  64075. tipShowing = tip;
  64076. Point<int> mousePos (Desktop::getMousePosition());
  64077. if (getParentComponent() != 0)
  64078. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64079. int x, y, w, h;
  64080. getLookAndFeel().getTooltipSize (tip, w, h);
  64081. if (mousePos.getX() > getParentWidth() / 2)
  64082. x = mousePos.getX() - (w + 12);
  64083. else
  64084. x = mousePos.getX() + 24;
  64085. if (mousePos.getY() > getParentHeight() / 2)
  64086. y = mousePos.getY() - (h + 6);
  64087. else
  64088. y = mousePos.getY() + 6;
  64089. setBounds (x, y, w, h);
  64090. setVisible (true);
  64091. if (getParentComponent() == 0)
  64092. {
  64093. addToDesktop (ComponentPeer::windowHasDropShadow
  64094. | ComponentPeer::windowIsTemporary
  64095. | ComponentPeer::windowIgnoresKeyPresses);
  64096. }
  64097. toFront (false);
  64098. }
  64099. const String TooltipWindow::getTipFor (Component* const c)
  64100. {
  64101. if (c != 0
  64102. && Process::isForegroundProcess()
  64103. && ! Component::isMouseButtonDownAnywhere())
  64104. {
  64105. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64106. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64107. return ttc->getTooltip();
  64108. }
  64109. return String::empty;
  64110. }
  64111. void TooltipWindow::hide()
  64112. {
  64113. tipShowing = String::empty;
  64114. removeFromDesktop();
  64115. setVisible (false);
  64116. }
  64117. void TooltipWindow::timerCallback()
  64118. {
  64119. const unsigned int now = Time::getApproximateMillisecondCounter();
  64120. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64121. const String newTip (getTipFor (newComp));
  64122. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64123. lastComponentUnderMouse = newComp;
  64124. lastTipUnderMouse = newTip;
  64125. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64126. const bool mouseWasClicked = clickCount > mouseClicks;
  64127. mouseClicks = clickCount;
  64128. const Point<int> mousePos (Desktop::getMousePosition());
  64129. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64130. lastMousePos = mousePos;
  64131. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64132. lastCompChangeTime = now;
  64133. if (isVisible() || now < lastHideTime + 500)
  64134. {
  64135. // if a tip is currently visible (or has just disappeared), update to a new one
  64136. // immediately if needed..
  64137. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64138. {
  64139. if (isVisible())
  64140. {
  64141. lastHideTime = now;
  64142. hide();
  64143. }
  64144. }
  64145. else if (tipChanged)
  64146. {
  64147. showFor (newTip);
  64148. }
  64149. }
  64150. else
  64151. {
  64152. // if there isn't currently a tip, but one is needed, only let it
  64153. // appear after a timeout..
  64154. if (newTip.isNotEmpty()
  64155. && newTip != tipShowing
  64156. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64157. {
  64158. showFor (newTip);
  64159. }
  64160. }
  64161. }
  64162. END_JUCE_NAMESPACE
  64163. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64164. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64165. BEGIN_JUCE_NAMESPACE
  64166. /** Keeps track of the active top level window.
  64167. */
  64168. class TopLevelWindowManager : public Timer,
  64169. public DeletedAtShutdown
  64170. {
  64171. public:
  64172. TopLevelWindowManager()
  64173. : currentActive (0)
  64174. {
  64175. }
  64176. ~TopLevelWindowManager()
  64177. {
  64178. clearSingletonInstance();
  64179. }
  64180. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64181. void timerCallback()
  64182. {
  64183. startTimer (jmin (1731, getTimerInterval() * 2));
  64184. TopLevelWindow* active = 0;
  64185. if (Process::isForegroundProcess())
  64186. {
  64187. active = currentActive;
  64188. Component* const c = Component::getCurrentlyFocusedComponent();
  64189. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64190. if (tlw == 0 && c != 0)
  64191. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64192. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64193. if (tlw != 0)
  64194. active = tlw;
  64195. }
  64196. if (active != currentActive)
  64197. {
  64198. currentActive = active;
  64199. for (int i = windows.size(); --i >= 0;)
  64200. {
  64201. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64202. tlw->setWindowActive (isWindowActive (tlw));
  64203. i = jmin (i, windows.size() - 1);
  64204. }
  64205. Desktop::getInstance().triggerFocusCallback();
  64206. }
  64207. }
  64208. bool addWindow (TopLevelWindow* const w)
  64209. {
  64210. windows.add (w);
  64211. startTimer (10);
  64212. return isWindowActive (w);
  64213. }
  64214. void removeWindow (TopLevelWindow* const w)
  64215. {
  64216. startTimer (10);
  64217. if (currentActive == w)
  64218. currentActive = 0;
  64219. windows.removeValue (w);
  64220. if (windows.size() == 0)
  64221. deleteInstance();
  64222. }
  64223. Array <TopLevelWindow*> windows;
  64224. private:
  64225. TopLevelWindow* currentActive;
  64226. bool isWindowActive (TopLevelWindow* const tlw) const
  64227. {
  64228. return (tlw == currentActive
  64229. || tlw->isParentOf (currentActive)
  64230. || tlw->hasKeyboardFocus (true))
  64231. && tlw->isShowing();
  64232. }
  64233. TopLevelWindowManager (const TopLevelWindowManager&);
  64234. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64235. };
  64236. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64237. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64238. {
  64239. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64240. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64241. }
  64242. TopLevelWindow::TopLevelWindow (const String& name,
  64243. const bool addToDesktop_)
  64244. : Component (name),
  64245. useDropShadow (true),
  64246. useNativeTitleBar (false),
  64247. windowIsActive_ (false)
  64248. {
  64249. setOpaque (true);
  64250. if (addToDesktop_)
  64251. Component::addToDesktop (getDesktopWindowStyleFlags());
  64252. else
  64253. setDropShadowEnabled (true);
  64254. setWantsKeyboardFocus (true);
  64255. setBroughtToFrontOnMouseClick (true);
  64256. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64257. }
  64258. TopLevelWindow::~TopLevelWindow()
  64259. {
  64260. shadower = 0;
  64261. TopLevelWindowManager::getInstance()->removeWindow (this);
  64262. }
  64263. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64264. {
  64265. if (hasKeyboardFocus (true))
  64266. TopLevelWindowManager::getInstance()->timerCallback();
  64267. else
  64268. TopLevelWindowManager::getInstance()->startTimer (10);
  64269. }
  64270. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64271. {
  64272. if (windowIsActive_ != isNowActive)
  64273. {
  64274. windowIsActive_ = isNowActive;
  64275. activeWindowStatusChanged();
  64276. }
  64277. }
  64278. void TopLevelWindow::activeWindowStatusChanged()
  64279. {
  64280. }
  64281. void TopLevelWindow::parentHierarchyChanged()
  64282. {
  64283. setDropShadowEnabled (useDropShadow);
  64284. }
  64285. void TopLevelWindow::visibilityChanged()
  64286. {
  64287. if (isShowing())
  64288. toFront (true);
  64289. }
  64290. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64291. {
  64292. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64293. if (useDropShadow)
  64294. styleFlags |= ComponentPeer::windowHasDropShadow;
  64295. if (useNativeTitleBar)
  64296. styleFlags |= ComponentPeer::windowHasTitleBar;
  64297. return styleFlags;
  64298. }
  64299. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64300. {
  64301. useDropShadow = useShadow;
  64302. if (isOnDesktop())
  64303. {
  64304. shadower = 0;
  64305. Component::addToDesktop (getDesktopWindowStyleFlags());
  64306. }
  64307. else
  64308. {
  64309. if (useShadow && isOpaque())
  64310. {
  64311. if (shadower == 0)
  64312. {
  64313. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64314. if (shadower != 0)
  64315. shadower->setOwner (this);
  64316. }
  64317. }
  64318. else
  64319. {
  64320. shadower = 0;
  64321. }
  64322. }
  64323. }
  64324. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64325. {
  64326. if (useNativeTitleBar != useNativeTitleBar_)
  64327. {
  64328. useNativeTitleBar = useNativeTitleBar_;
  64329. recreateDesktopWindow();
  64330. sendLookAndFeelChange();
  64331. }
  64332. }
  64333. void TopLevelWindow::recreateDesktopWindow()
  64334. {
  64335. if (isOnDesktop())
  64336. {
  64337. Component::addToDesktop (getDesktopWindowStyleFlags());
  64338. toFront (true);
  64339. }
  64340. }
  64341. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64342. {
  64343. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64344. because this class needs to make sure its layout corresponds with settings like whether
  64345. it's got a native title bar or not.
  64346. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64347. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64348. method, then add or remove whatever flags are necessary from this value before returning it.
  64349. */
  64350. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64351. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64352. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64353. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64354. sendLookAndFeelChange();
  64355. }
  64356. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64357. {
  64358. if (c == 0)
  64359. c = TopLevelWindow::getActiveTopLevelWindow();
  64360. if (c == 0)
  64361. {
  64362. centreWithSize (width, height);
  64363. }
  64364. else
  64365. {
  64366. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64367. (c->getHeight() - height) / 2)));
  64368. Rectangle<int> parentArea (c->getParentMonitorArea());
  64369. if (getParentComponent() != 0)
  64370. {
  64371. p = getParentComponent()->globalPositionToRelative (p);
  64372. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64373. }
  64374. parentArea.reduce (12, 12);
  64375. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64376. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64377. width, height);
  64378. }
  64379. }
  64380. int TopLevelWindow::getNumTopLevelWindows() throw()
  64381. {
  64382. return TopLevelWindowManager::getInstance()->windows.size();
  64383. }
  64384. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64385. {
  64386. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64387. }
  64388. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64389. {
  64390. TopLevelWindow* best = 0;
  64391. int bestNumTWLParents = -1;
  64392. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64393. {
  64394. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64395. if (tlw->isActiveWindow())
  64396. {
  64397. int numTWLParents = 0;
  64398. const Component* c = tlw->getParentComponent();
  64399. while (c != 0)
  64400. {
  64401. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64402. ++numTWLParents;
  64403. c = c->getParentComponent();
  64404. }
  64405. if (bestNumTWLParents < numTWLParents)
  64406. {
  64407. best = tlw;
  64408. bestNumTWLParents = numTWLParents;
  64409. }
  64410. }
  64411. }
  64412. return best;
  64413. }
  64414. END_JUCE_NAMESPACE
  64415. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64416. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64417. BEGIN_JUCE_NAMESPACE
  64418. namespace RelativeCoordinateHelpers
  64419. {
  64420. static void skipComma (const juce_wchar* const s, int& i)
  64421. {
  64422. while (CharacterFunctions::isWhitespace (s[i]))
  64423. ++i;
  64424. if (s[i] == ',')
  64425. ++i;
  64426. }
  64427. }
  64428. const String RelativeCoordinate::Strings::parent ("parent");
  64429. const String RelativeCoordinate::Strings::left ("left");
  64430. const String RelativeCoordinate::Strings::right ("right");
  64431. const String RelativeCoordinate::Strings::top ("top");
  64432. const String RelativeCoordinate::Strings::bottom ("bottom");
  64433. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64434. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64435. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64436. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64437. RelativeCoordinate::RelativeCoordinate()
  64438. {
  64439. }
  64440. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64441. : term (term_)
  64442. {
  64443. }
  64444. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64445. : term (other.term)
  64446. {
  64447. }
  64448. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64449. {
  64450. term = other.term;
  64451. return *this;
  64452. }
  64453. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64454. : term (absoluteDistanceFromOrigin)
  64455. {
  64456. }
  64457. RelativeCoordinate::RelativeCoordinate (const String& s)
  64458. {
  64459. try
  64460. {
  64461. term = Expression (s);
  64462. }
  64463. catch (...)
  64464. {}
  64465. }
  64466. RelativeCoordinate::~RelativeCoordinate()
  64467. {
  64468. }
  64469. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64470. {
  64471. return term.toString() == other.term.toString();
  64472. }
  64473. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64474. {
  64475. return ! operator== (other);
  64476. }
  64477. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64478. {
  64479. try
  64480. {
  64481. if (context != 0)
  64482. return term.evaluate (*context);
  64483. else
  64484. return term.evaluate();
  64485. }
  64486. catch (...)
  64487. {}
  64488. return 0.0;
  64489. }
  64490. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64491. {
  64492. try
  64493. {
  64494. if (context != 0)
  64495. term.evaluate (*context);
  64496. else
  64497. term.evaluate();
  64498. }
  64499. catch (...)
  64500. {
  64501. return true;
  64502. }
  64503. return false;
  64504. }
  64505. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64506. {
  64507. try
  64508. {
  64509. if (context != 0)
  64510. {
  64511. term = term.adjustedToGiveNewResult (newPos, *context);
  64512. }
  64513. else
  64514. {
  64515. Expression::EvaluationContext defaultContext;
  64516. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64517. }
  64518. }
  64519. catch (...)
  64520. {}
  64521. }
  64522. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64523. {
  64524. try
  64525. {
  64526. return term.referencesSymbol (coordName, context);
  64527. }
  64528. catch (...)
  64529. {}
  64530. return false;
  64531. }
  64532. bool RelativeCoordinate::isDynamic() const
  64533. {
  64534. return term.usesAnySymbols();
  64535. }
  64536. const String RelativeCoordinate::toString() const
  64537. {
  64538. return term.toString();
  64539. }
  64540. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64541. {
  64542. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64543. if (term.referencesSymbol (oldName, 0))
  64544. term = term.withRenamedSymbol (oldName, newName);
  64545. }
  64546. RelativePoint::RelativePoint()
  64547. {
  64548. }
  64549. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64550. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64551. {
  64552. }
  64553. RelativePoint::RelativePoint (const float x_, const float y_)
  64554. : x (x_), y (y_)
  64555. {
  64556. }
  64557. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64558. : x (x_), y (y_)
  64559. {
  64560. }
  64561. RelativePoint::RelativePoint (const String& s)
  64562. {
  64563. int i = 0;
  64564. x = RelativeCoordinate (Expression::parse (s, i));
  64565. RelativeCoordinateHelpers::skipComma (s, i);
  64566. y = RelativeCoordinate (Expression::parse (s, i));
  64567. }
  64568. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64569. {
  64570. return x == other.x && y == other.y;
  64571. }
  64572. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64573. {
  64574. return ! operator== (other);
  64575. }
  64576. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64577. {
  64578. return Point<float> ((float) x.resolve (context),
  64579. (float) y.resolve (context));
  64580. }
  64581. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64582. {
  64583. x.moveToAbsolute (newPos.getX(), context);
  64584. y.moveToAbsolute (newPos.getY(), context);
  64585. }
  64586. const String RelativePoint::toString() const
  64587. {
  64588. return x.toString() + ", " + y.toString();
  64589. }
  64590. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64591. {
  64592. x.renameSymbolIfUsed (oldName, newName);
  64593. y.renameSymbolIfUsed (oldName, newName);
  64594. }
  64595. bool RelativePoint::isDynamic() const
  64596. {
  64597. return x.isDynamic() || y.isDynamic();
  64598. }
  64599. RelativeRectangle::RelativeRectangle()
  64600. {
  64601. }
  64602. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64603. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64604. : left (left_), right (right_), top (top_), bottom (bottom_)
  64605. {
  64606. }
  64607. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64608. : left (rect.getX()),
  64609. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64610. top (rect.getY()),
  64611. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64612. {
  64613. }
  64614. RelativeRectangle::RelativeRectangle (const String& s)
  64615. {
  64616. int i = 0;
  64617. left = RelativeCoordinate (Expression::parse (s, i));
  64618. RelativeCoordinateHelpers::skipComma (s, i);
  64619. top = RelativeCoordinate (Expression::parse (s, i));
  64620. RelativeCoordinateHelpers::skipComma (s, i);
  64621. right = RelativeCoordinate (Expression::parse (s, i));
  64622. RelativeCoordinateHelpers::skipComma (s, i);
  64623. bottom = RelativeCoordinate (Expression::parse (s, i));
  64624. }
  64625. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64626. {
  64627. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64628. }
  64629. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64630. {
  64631. return ! operator== (other);
  64632. }
  64633. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64634. {
  64635. const double l = left.resolve (context);
  64636. const double r = right.resolve (context);
  64637. const double t = top.resolve (context);
  64638. const double b = bottom.resolve (context);
  64639. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64640. }
  64641. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64642. {
  64643. left.moveToAbsolute (newPos.getX(), context);
  64644. right.moveToAbsolute (newPos.getRight(), context);
  64645. top.moveToAbsolute (newPos.getY(), context);
  64646. bottom.moveToAbsolute (newPos.getBottom(), context);
  64647. }
  64648. const String RelativeRectangle::toString() const
  64649. {
  64650. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64651. }
  64652. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64653. {
  64654. left.renameSymbolIfUsed (oldName, newName);
  64655. right.renameSymbolIfUsed (oldName, newName);
  64656. top.renameSymbolIfUsed (oldName, newName);
  64657. bottom.renameSymbolIfUsed (oldName, newName);
  64658. }
  64659. RelativePointPath::RelativePointPath()
  64660. : usesNonZeroWinding (true),
  64661. containsDynamicPoints (false)
  64662. {
  64663. }
  64664. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64665. : usesNonZeroWinding (true),
  64666. containsDynamicPoints (false)
  64667. {
  64668. ValueTree state (DrawablePath::valueTreeType);
  64669. other.writeTo (state, 0);
  64670. parse (state);
  64671. }
  64672. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64673. : usesNonZeroWinding (true),
  64674. containsDynamicPoints (false)
  64675. {
  64676. parse (drawable);
  64677. }
  64678. RelativePointPath::RelativePointPath (const Path& path)
  64679. {
  64680. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64681. Path::Iterator i (path);
  64682. while (i.next())
  64683. {
  64684. switch (i.elementType)
  64685. {
  64686. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64687. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64688. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64689. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64690. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64691. default: jassertfalse; break;
  64692. }
  64693. }
  64694. }
  64695. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64696. {
  64697. DrawablePath::ValueTreeWrapper wrapper (state);
  64698. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64699. ValueTree pathTree (wrapper.getPathState());
  64700. pathTree.removeAllChildren (undoManager);
  64701. for (int i = 0; i < elements.size(); ++i)
  64702. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64703. }
  64704. void RelativePointPath::parse (const ValueTree& state)
  64705. {
  64706. DrawablePath::ValueTreeWrapper wrapper (state);
  64707. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64708. RelativePoint points[3];
  64709. const ValueTree pathTree (wrapper.getPathState());
  64710. const int num = pathTree.getNumChildren();
  64711. for (int i = 0; i < num; ++i)
  64712. {
  64713. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64714. const int numCps = e.getNumControlPoints();
  64715. for (int j = 0; j < numCps; ++j)
  64716. {
  64717. points[j] = e.getControlPoint (j);
  64718. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64719. }
  64720. const Identifier type (e.getType());
  64721. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64722. elements.add (new StartSubPath (points[0]));
  64723. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64724. elements.add (new CloseSubPath());
  64725. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64726. elements.add (new LineTo (points[0]));
  64727. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64728. elements.add (new QuadraticTo (points[0], points[1]));
  64729. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64730. elements.add (new CubicTo (points[0], points[1], points[2]));
  64731. else
  64732. jassertfalse;
  64733. }
  64734. }
  64735. RelativePointPath::~RelativePointPath()
  64736. {
  64737. }
  64738. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64739. {
  64740. elements.swapWithArray (other.elements);
  64741. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64742. }
  64743. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64744. {
  64745. for (int i = 0; i < elements.size(); ++i)
  64746. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64747. }
  64748. bool RelativePointPath::containsAnyDynamicPoints() const
  64749. {
  64750. return containsDynamicPoints;
  64751. }
  64752. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64753. {
  64754. }
  64755. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64756. : ElementBase (startSubPathElement), startPos (pos)
  64757. {
  64758. }
  64759. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64760. {
  64761. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64762. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64763. return v;
  64764. }
  64765. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64766. {
  64767. path.startNewSubPath (startPos.resolve (coordFinder));
  64768. }
  64769. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64770. {
  64771. numPoints = 1;
  64772. return &startPos;
  64773. }
  64774. RelativePointPath::CloseSubPath::CloseSubPath()
  64775. : ElementBase (closeSubPathElement)
  64776. {
  64777. }
  64778. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64779. {
  64780. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64781. }
  64782. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64783. {
  64784. path.closeSubPath();
  64785. }
  64786. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64787. {
  64788. numPoints = 0;
  64789. return 0;
  64790. }
  64791. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64792. : ElementBase (lineToElement), endPoint (endPoint_)
  64793. {
  64794. }
  64795. const ValueTree RelativePointPath::LineTo::createTree() const
  64796. {
  64797. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64798. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64799. return v;
  64800. }
  64801. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64802. {
  64803. path.lineTo (endPoint.resolve (coordFinder));
  64804. }
  64805. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64806. {
  64807. numPoints = 1;
  64808. return &endPoint;
  64809. }
  64810. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64811. : ElementBase (quadraticToElement)
  64812. {
  64813. controlPoints[0] = controlPoint;
  64814. controlPoints[1] = endPoint;
  64815. }
  64816. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64817. {
  64818. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64819. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64820. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64821. return v;
  64822. }
  64823. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64824. {
  64825. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64826. controlPoints[1].resolve (coordFinder));
  64827. }
  64828. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64829. {
  64830. numPoints = 2;
  64831. return controlPoints;
  64832. }
  64833. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64834. : ElementBase (cubicToElement)
  64835. {
  64836. controlPoints[0] = controlPoint1;
  64837. controlPoints[1] = controlPoint2;
  64838. controlPoints[2] = endPoint;
  64839. }
  64840. const ValueTree RelativePointPath::CubicTo::createTree() const
  64841. {
  64842. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64843. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64844. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64845. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64846. return v;
  64847. }
  64848. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64849. {
  64850. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64851. controlPoints[1].resolve (coordFinder),
  64852. controlPoints[2].resolve (coordFinder));
  64853. }
  64854. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64855. {
  64856. numPoints = 3;
  64857. return controlPoints;
  64858. }
  64859. RelativeParallelogram::RelativeParallelogram()
  64860. {
  64861. }
  64862. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64863. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64864. {
  64865. }
  64866. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64867. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64868. {
  64869. }
  64870. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64871. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64872. {
  64873. }
  64874. RelativeParallelogram::~RelativeParallelogram()
  64875. {
  64876. }
  64877. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64878. {
  64879. points[0] = topLeft.resolve (coordFinder);
  64880. points[1] = topRight.resolve (coordFinder);
  64881. points[2] = bottomLeft.resolve (coordFinder);
  64882. }
  64883. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64884. {
  64885. resolveThreePoints (points, coordFinder);
  64886. points[3] = points[1] + (points[2] - points[0]);
  64887. }
  64888. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64889. {
  64890. Point<float> points[4];
  64891. resolveFourCorners (points, coordFinder);
  64892. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64893. }
  64894. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64895. {
  64896. Point<float> points[4];
  64897. resolveFourCorners (points, coordFinder);
  64898. path.startNewSubPath (points[0]);
  64899. path.lineTo (points[1]);
  64900. path.lineTo (points[3]);
  64901. path.lineTo (points[2]);
  64902. path.closeSubPath();
  64903. }
  64904. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64905. {
  64906. Point<float> corners[3];
  64907. resolveThreePoints (corners, coordFinder);
  64908. const Line<float> top (corners[0], corners[1]);
  64909. const Line<float> left (corners[0], corners[2]);
  64910. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64911. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64912. topRight.moveToAbsolute (newTopRight, coordFinder);
  64913. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64914. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64915. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64916. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64917. }
  64918. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64919. {
  64920. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64921. }
  64922. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64923. {
  64924. return ! operator== (other);
  64925. }
  64926. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64927. {
  64928. const Point<float> tr (corners[1] - corners[0]);
  64929. const Point<float> bl (corners[2] - corners[0]);
  64930. target -= corners[0];
  64931. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64932. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64933. }
  64934. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64935. {
  64936. return corners[0]
  64937. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64938. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64939. }
  64940. END_JUCE_NAMESPACE
  64941. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64942. #endif
  64943. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64944. /*** Start of inlined file: juce_Colour.cpp ***/
  64945. BEGIN_JUCE_NAMESPACE
  64946. namespace ColourHelpers
  64947. {
  64948. static uint8 floatAlphaToInt (const float alpha) throw()
  64949. {
  64950. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64951. }
  64952. static void convertHSBtoRGB (float h, float s, float v,
  64953. uint8& r, uint8& g, uint8& b) throw()
  64954. {
  64955. v = jlimit (0.0f, 1.0f, v);
  64956. v *= 255.0f;
  64957. const uint8 intV = (uint8) roundToInt (v);
  64958. if (s <= 0)
  64959. {
  64960. r = intV;
  64961. g = intV;
  64962. b = intV;
  64963. }
  64964. else
  64965. {
  64966. s = jmin (1.0f, s);
  64967. h = jlimit (0.0f, 1.0f, h);
  64968. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64969. const float f = h - std::floor (h);
  64970. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64971. const float y = v * (1.0f - s * f);
  64972. const float z = v * (1.0f - (s * (1.0f - f)));
  64973. if (h < 1.0f)
  64974. {
  64975. r = intV;
  64976. g = (uint8) roundToInt (z);
  64977. b = x;
  64978. }
  64979. else if (h < 2.0f)
  64980. {
  64981. r = (uint8) roundToInt (y);
  64982. g = intV;
  64983. b = x;
  64984. }
  64985. else if (h < 3.0f)
  64986. {
  64987. r = x;
  64988. g = intV;
  64989. b = (uint8) roundToInt (z);
  64990. }
  64991. else if (h < 4.0f)
  64992. {
  64993. r = x;
  64994. g = (uint8) roundToInt (y);
  64995. b = intV;
  64996. }
  64997. else if (h < 5.0f)
  64998. {
  64999. r = (uint8) roundToInt (z);
  65000. g = x;
  65001. b = intV;
  65002. }
  65003. else if (h < 6.0f)
  65004. {
  65005. r = intV;
  65006. g = x;
  65007. b = (uint8) roundToInt (y);
  65008. }
  65009. else
  65010. {
  65011. r = 0;
  65012. g = 0;
  65013. b = 0;
  65014. }
  65015. }
  65016. }
  65017. }
  65018. Colour::Colour() throw()
  65019. : argb (0)
  65020. {
  65021. }
  65022. Colour::Colour (const Colour& other) throw()
  65023. : argb (other.argb)
  65024. {
  65025. }
  65026. Colour& Colour::operator= (const Colour& other) throw()
  65027. {
  65028. argb = other.argb;
  65029. return *this;
  65030. }
  65031. bool Colour::operator== (const Colour& other) const throw()
  65032. {
  65033. return argb.getARGB() == other.argb.getARGB();
  65034. }
  65035. bool Colour::operator!= (const Colour& other) const throw()
  65036. {
  65037. return argb.getARGB() != other.argb.getARGB();
  65038. }
  65039. Colour::Colour (const uint32 argb_) throw()
  65040. : argb (argb_)
  65041. {
  65042. }
  65043. Colour::Colour (const uint8 red,
  65044. const uint8 green,
  65045. const uint8 blue) throw()
  65046. {
  65047. argb.setARGB (0xff, red, green, blue);
  65048. }
  65049. const Colour Colour::fromRGB (const uint8 red,
  65050. const uint8 green,
  65051. const uint8 blue) throw()
  65052. {
  65053. return Colour (red, green, blue);
  65054. }
  65055. Colour::Colour (const uint8 red,
  65056. const uint8 green,
  65057. const uint8 blue,
  65058. const uint8 alpha) throw()
  65059. {
  65060. argb.setARGB (alpha, red, green, blue);
  65061. }
  65062. const Colour Colour::fromRGBA (const uint8 red,
  65063. const uint8 green,
  65064. const uint8 blue,
  65065. const uint8 alpha) throw()
  65066. {
  65067. return Colour (red, green, blue, alpha);
  65068. }
  65069. Colour::Colour (const uint8 red,
  65070. const uint8 green,
  65071. const uint8 blue,
  65072. const float alpha) throw()
  65073. {
  65074. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65075. }
  65076. const Colour Colour::fromRGBAFloat (const uint8 red,
  65077. const uint8 green,
  65078. const uint8 blue,
  65079. const float alpha) throw()
  65080. {
  65081. return Colour (red, green, blue, alpha);
  65082. }
  65083. Colour::Colour (const float hue,
  65084. const float saturation,
  65085. const float brightness,
  65086. const float alpha) throw()
  65087. {
  65088. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65089. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65090. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65091. }
  65092. const Colour Colour::fromHSV (const float hue,
  65093. const float saturation,
  65094. const float brightness,
  65095. const float alpha) throw()
  65096. {
  65097. return Colour (hue, saturation, brightness, alpha);
  65098. }
  65099. Colour::Colour (const float hue,
  65100. const float saturation,
  65101. const float brightness,
  65102. const uint8 alpha) throw()
  65103. {
  65104. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65105. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65106. argb.setARGB (alpha, r, g, b);
  65107. }
  65108. Colour::~Colour() throw()
  65109. {
  65110. }
  65111. const PixelARGB Colour::getPixelARGB() const throw()
  65112. {
  65113. PixelARGB p (argb);
  65114. p.premultiply();
  65115. return p;
  65116. }
  65117. uint32 Colour::getARGB() const throw()
  65118. {
  65119. return argb.getARGB();
  65120. }
  65121. bool Colour::isTransparent() const throw()
  65122. {
  65123. return getAlpha() == 0;
  65124. }
  65125. bool Colour::isOpaque() const throw()
  65126. {
  65127. return getAlpha() == 0xff;
  65128. }
  65129. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65130. {
  65131. PixelARGB newCol (argb);
  65132. newCol.setAlpha (newAlpha);
  65133. return Colour (newCol.getARGB());
  65134. }
  65135. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65136. {
  65137. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65138. PixelARGB newCol (argb);
  65139. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65140. return Colour (newCol.getARGB());
  65141. }
  65142. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65143. {
  65144. jassert (alphaMultiplier >= 0);
  65145. PixelARGB newCol (argb);
  65146. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65147. return Colour (newCol.getARGB());
  65148. }
  65149. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65150. {
  65151. const int destAlpha = getAlpha();
  65152. if (destAlpha > 0)
  65153. {
  65154. const int invA = 0xff - (int) src.getAlpha();
  65155. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65156. if (resA > 0)
  65157. {
  65158. const int da = (invA * destAlpha) / resA;
  65159. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65160. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65161. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65162. (uint8) resA);
  65163. }
  65164. return *this;
  65165. }
  65166. else
  65167. {
  65168. return src;
  65169. }
  65170. }
  65171. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65172. {
  65173. if (proportionOfOther <= 0)
  65174. return *this;
  65175. if (proportionOfOther >= 1.0f)
  65176. return other;
  65177. PixelARGB c1 (getPixelARGB());
  65178. const PixelARGB c2 (other.getPixelARGB());
  65179. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65180. c1.unpremultiply();
  65181. return Colour (c1.getARGB());
  65182. }
  65183. float Colour::getFloatRed() const throw()
  65184. {
  65185. return getRed() / 255.0f;
  65186. }
  65187. float Colour::getFloatGreen() const throw()
  65188. {
  65189. return getGreen() / 255.0f;
  65190. }
  65191. float Colour::getFloatBlue() const throw()
  65192. {
  65193. return getBlue() / 255.0f;
  65194. }
  65195. float Colour::getFloatAlpha() const throw()
  65196. {
  65197. return getAlpha() / 255.0f;
  65198. }
  65199. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65200. {
  65201. const int r = getRed();
  65202. const int g = getGreen();
  65203. const int b = getBlue();
  65204. const int hi = jmax (r, g, b);
  65205. const int lo = jmin (r, g, b);
  65206. if (hi != 0)
  65207. {
  65208. s = (hi - lo) / (float) hi;
  65209. if (s != 0)
  65210. {
  65211. const float invDiff = 1.0f / (hi - lo);
  65212. const float red = (hi - r) * invDiff;
  65213. const float green = (hi - g) * invDiff;
  65214. const float blue = (hi - b) * invDiff;
  65215. if (r == hi)
  65216. h = blue - green;
  65217. else if (g == hi)
  65218. h = 2.0f + red - blue;
  65219. else
  65220. h = 4.0f + green - red;
  65221. h *= 1.0f / 6.0f;
  65222. if (h < 0)
  65223. ++h;
  65224. }
  65225. else
  65226. {
  65227. h = 0;
  65228. }
  65229. }
  65230. else
  65231. {
  65232. s = 0;
  65233. h = 0;
  65234. }
  65235. v = hi / 255.0f;
  65236. }
  65237. float Colour::getHue() const throw()
  65238. {
  65239. float h, s, b;
  65240. getHSB (h, s, b);
  65241. return h;
  65242. }
  65243. const Colour Colour::withHue (const float hue) const throw()
  65244. {
  65245. float h, s, b;
  65246. getHSB (h, s, b);
  65247. return Colour (hue, s, b, getAlpha());
  65248. }
  65249. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65250. {
  65251. float h, s, b;
  65252. getHSB (h, s, b);
  65253. h += amountToRotate;
  65254. h -= std::floor (h);
  65255. return Colour (h, s, b, getAlpha());
  65256. }
  65257. float Colour::getSaturation() const throw()
  65258. {
  65259. float h, s, b;
  65260. getHSB (h, s, b);
  65261. return s;
  65262. }
  65263. const Colour Colour::withSaturation (const float saturation) const throw()
  65264. {
  65265. float h, s, b;
  65266. getHSB (h, s, b);
  65267. return Colour (h, saturation, b, getAlpha());
  65268. }
  65269. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65270. {
  65271. float h, s, b;
  65272. getHSB (h, s, b);
  65273. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65274. }
  65275. float Colour::getBrightness() const throw()
  65276. {
  65277. float h, s, b;
  65278. getHSB (h, s, b);
  65279. return b;
  65280. }
  65281. const Colour Colour::withBrightness (const float brightness) const throw()
  65282. {
  65283. float h, s, b;
  65284. getHSB (h, s, b);
  65285. return Colour (h, s, brightness, getAlpha());
  65286. }
  65287. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65288. {
  65289. float h, s, b;
  65290. getHSB (h, s, b);
  65291. b *= amount;
  65292. if (b > 1.0f)
  65293. b = 1.0f;
  65294. return Colour (h, s, b, getAlpha());
  65295. }
  65296. const Colour Colour::brighter (float amount) const throw()
  65297. {
  65298. amount = 1.0f / (1.0f + amount);
  65299. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65300. (uint8) (255 - (amount * (255 - getGreen()))),
  65301. (uint8) (255 - (amount * (255 - getBlue()))),
  65302. getAlpha());
  65303. }
  65304. const Colour Colour::darker (float amount) const throw()
  65305. {
  65306. amount = 1.0f / (1.0f + amount);
  65307. return Colour ((uint8) (amount * getRed()),
  65308. (uint8) (amount * getGreen()),
  65309. (uint8) (amount * getBlue()),
  65310. getAlpha());
  65311. }
  65312. const Colour Colour::greyLevel (const float brightness) throw()
  65313. {
  65314. const uint8 level
  65315. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65316. return Colour (level, level, level);
  65317. }
  65318. const Colour Colour::contrasting (const float amount) const throw()
  65319. {
  65320. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65321. ? Colours::black
  65322. : Colours::white).withAlpha (amount));
  65323. }
  65324. const Colour Colour::contrasting (const Colour& colour1,
  65325. const Colour& colour2) throw()
  65326. {
  65327. const float b1 = colour1.getBrightness();
  65328. const float b2 = colour2.getBrightness();
  65329. float best = 0.0f;
  65330. float bestDist = 0.0f;
  65331. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65332. {
  65333. const float d1 = std::abs (i - b1);
  65334. const float d2 = std::abs (i - b2);
  65335. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65336. if (dist > bestDist)
  65337. {
  65338. best = i;
  65339. bestDist = dist;
  65340. }
  65341. }
  65342. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65343. .withBrightness (best);
  65344. }
  65345. const String Colour::toString() const
  65346. {
  65347. return String::toHexString ((int) argb.getARGB());
  65348. }
  65349. const Colour Colour::fromString (const String& encodedColourString)
  65350. {
  65351. return Colour ((uint32) encodedColourString.getHexValue32());
  65352. }
  65353. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65354. {
  65355. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65356. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65357. .toUpperCase();
  65358. }
  65359. END_JUCE_NAMESPACE
  65360. /*** End of inlined file: juce_Colour.cpp ***/
  65361. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65362. BEGIN_JUCE_NAMESPACE
  65363. ColourGradient::ColourGradient() throw()
  65364. {
  65365. #if JUCE_DEBUG
  65366. point1.setX (987654.0f);
  65367. #endif
  65368. }
  65369. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65370. const Colour& colour2, const float x2_, const float y2_,
  65371. const bool isRadial_)
  65372. : point1 (x1_, y1_),
  65373. point2 (x2_, y2_),
  65374. isRadial (isRadial_)
  65375. {
  65376. colours.add (ColourPoint (0.0, colour1));
  65377. colours.add (ColourPoint (1.0, colour2));
  65378. }
  65379. ColourGradient::~ColourGradient()
  65380. {
  65381. }
  65382. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65383. {
  65384. return point1 == other.point1 && point2 == other.point2
  65385. && isRadial == other.isRadial
  65386. && colours == other.colours;
  65387. }
  65388. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65389. {
  65390. return ! operator== (other);
  65391. }
  65392. void ColourGradient::clearColours()
  65393. {
  65394. colours.clear();
  65395. }
  65396. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65397. {
  65398. // must be within the two end-points
  65399. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65400. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65401. int i;
  65402. for (i = 0; i < colours.size(); ++i)
  65403. if (colours.getReference(i).position > pos)
  65404. break;
  65405. colours.insert (i, ColourPoint (pos, colour));
  65406. return i;
  65407. }
  65408. void ColourGradient::removeColour (int index)
  65409. {
  65410. jassert (index > 0 && index < colours.size() - 1);
  65411. colours.remove (index);
  65412. }
  65413. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65414. {
  65415. for (int i = 0; i < colours.size(); ++i)
  65416. {
  65417. Colour& c = colours.getReference(i).colour;
  65418. c = c.withMultipliedAlpha (multiplier);
  65419. }
  65420. }
  65421. int ColourGradient::getNumColours() const throw()
  65422. {
  65423. return colours.size();
  65424. }
  65425. double ColourGradient::getColourPosition (const int index) const throw()
  65426. {
  65427. if (((unsigned int) index) < (unsigned int) colours.size())
  65428. return colours.getReference (index).position;
  65429. return 0;
  65430. }
  65431. const Colour ColourGradient::getColour (const int index) const throw()
  65432. {
  65433. if (((unsigned int) index) < (unsigned int) colours.size())
  65434. return colours.getReference (index).colour;
  65435. return Colour();
  65436. }
  65437. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65438. {
  65439. if (((unsigned int) index) < (unsigned int) colours.size())
  65440. colours.getReference (index).colour = newColour;
  65441. }
  65442. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65443. {
  65444. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65445. if (position <= 0 || colours.size() <= 1)
  65446. return colours.getReference(0).colour;
  65447. int i = colours.size() - 1;
  65448. while (position < colours.getReference(i).position)
  65449. --i;
  65450. const ColourPoint& p1 = colours.getReference (i);
  65451. if (i >= colours.size() - 1)
  65452. return p1.colour;
  65453. const ColourPoint& p2 = colours.getReference (i + 1);
  65454. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65455. }
  65456. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65457. {
  65458. #if JUCE_DEBUG
  65459. // trying to use the object without setting its co-ordinates? Have a careful read of
  65460. // the comments for the constructors.
  65461. jassert (point1.getX() != 987654.0f);
  65462. #endif
  65463. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65464. 3 * (int) point1.transformedBy (transform)
  65465. .getDistanceFrom (point2.transformedBy (transform)));
  65466. lookupTable.malloc (numEntries);
  65467. if (colours.size() >= 2)
  65468. {
  65469. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65470. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65471. int index = 0;
  65472. for (int j = 1; j < colours.size(); ++j)
  65473. {
  65474. const ColourPoint& p = colours.getReference (j);
  65475. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65476. const PixelARGB pix2 (p.colour.getPixelARGB());
  65477. for (int i = 0; i < numToDo; ++i)
  65478. {
  65479. jassert (index >= 0 && index < numEntries);
  65480. lookupTable[index] = pix1;
  65481. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65482. ++index;
  65483. }
  65484. pix1 = pix2;
  65485. }
  65486. while (index < numEntries)
  65487. lookupTable [index++] = pix1;
  65488. }
  65489. else
  65490. {
  65491. jassertfalse; // no colours specified!
  65492. }
  65493. return numEntries;
  65494. }
  65495. bool ColourGradient::isOpaque() const throw()
  65496. {
  65497. for (int i = 0; i < colours.size(); ++i)
  65498. if (! colours.getReference(i).colour.isOpaque())
  65499. return false;
  65500. return true;
  65501. }
  65502. bool ColourGradient::isInvisible() const throw()
  65503. {
  65504. for (int i = 0; i < colours.size(); ++i)
  65505. if (! colours.getReference(i).colour.isTransparent())
  65506. return false;
  65507. return true;
  65508. }
  65509. END_JUCE_NAMESPACE
  65510. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65511. /*** Start of inlined file: juce_Colours.cpp ***/
  65512. BEGIN_JUCE_NAMESPACE
  65513. const Colour Colours::transparentBlack (0);
  65514. const Colour Colours::transparentWhite (0x00ffffff);
  65515. const Colour Colours::aliceblue (0xfff0f8ff);
  65516. const Colour Colours::antiquewhite (0xfffaebd7);
  65517. const Colour Colours::aqua (0xff00ffff);
  65518. const Colour Colours::aquamarine (0xff7fffd4);
  65519. const Colour Colours::azure (0xfff0ffff);
  65520. const Colour Colours::beige (0xfff5f5dc);
  65521. const Colour Colours::bisque (0xffffe4c4);
  65522. const Colour Colours::black (0xff000000);
  65523. const Colour Colours::blanchedalmond (0xffffebcd);
  65524. const Colour Colours::blue (0xff0000ff);
  65525. const Colour Colours::blueviolet (0xff8a2be2);
  65526. const Colour Colours::brown (0xffa52a2a);
  65527. const Colour Colours::burlywood (0xffdeb887);
  65528. const Colour Colours::cadetblue (0xff5f9ea0);
  65529. const Colour Colours::chartreuse (0xff7fff00);
  65530. const Colour Colours::chocolate (0xffd2691e);
  65531. const Colour Colours::coral (0xffff7f50);
  65532. const Colour Colours::cornflowerblue (0xff6495ed);
  65533. const Colour Colours::cornsilk (0xfffff8dc);
  65534. const Colour Colours::crimson (0xffdc143c);
  65535. const Colour Colours::cyan (0xff00ffff);
  65536. const Colour Colours::darkblue (0xff00008b);
  65537. const Colour Colours::darkcyan (0xff008b8b);
  65538. const Colour Colours::darkgoldenrod (0xffb8860b);
  65539. const Colour Colours::darkgrey (0xff555555);
  65540. const Colour Colours::darkgreen (0xff006400);
  65541. const Colour Colours::darkkhaki (0xffbdb76b);
  65542. const Colour Colours::darkmagenta (0xff8b008b);
  65543. const Colour Colours::darkolivegreen (0xff556b2f);
  65544. const Colour Colours::darkorange (0xffff8c00);
  65545. const Colour Colours::darkorchid (0xff9932cc);
  65546. const Colour Colours::darkred (0xff8b0000);
  65547. const Colour Colours::darksalmon (0xffe9967a);
  65548. const Colour Colours::darkseagreen (0xff8fbc8f);
  65549. const Colour Colours::darkslateblue (0xff483d8b);
  65550. const Colour Colours::darkslategrey (0xff2f4f4f);
  65551. const Colour Colours::darkturquoise (0xff00ced1);
  65552. const Colour Colours::darkviolet (0xff9400d3);
  65553. const Colour Colours::deeppink (0xffff1493);
  65554. const Colour Colours::deepskyblue (0xff00bfff);
  65555. const Colour Colours::dimgrey (0xff696969);
  65556. const Colour Colours::dodgerblue (0xff1e90ff);
  65557. const Colour Colours::firebrick (0xffb22222);
  65558. const Colour Colours::floralwhite (0xfffffaf0);
  65559. const Colour Colours::forestgreen (0xff228b22);
  65560. const Colour Colours::fuchsia (0xffff00ff);
  65561. const Colour Colours::gainsboro (0xffdcdcdc);
  65562. const Colour Colours::gold (0xffffd700);
  65563. const Colour Colours::goldenrod (0xffdaa520);
  65564. const Colour Colours::grey (0xff808080);
  65565. const Colour Colours::green (0xff008000);
  65566. const Colour Colours::greenyellow (0xffadff2f);
  65567. const Colour Colours::honeydew (0xfff0fff0);
  65568. const Colour Colours::hotpink (0xffff69b4);
  65569. const Colour Colours::indianred (0xffcd5c5c);
  65570. const Colour Colours::indigo (0xff4b0082);
  65571. const Colour Colours::ivory (0xfffffff0);
  65572. const Colour Colours::khaki (0xfff0e68c);
  65573. const Colour Colours::lavender (0xffe6e6fa);
  65574. const Colour Colours::lavenderblush (0xfffff0f5);
  65575. const Colour Colours::lemonchiffon (0xfffffacd);
  65576. const Colour Colours::lightblue (0xffadd8e6);
  65577. const Colour Colours::lightcoral (0xfff08080);
  65578. const Colour Colours::lightcyan (0xffe0ffff);
  65579. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65580. const Colour Colours::lightgreen (0xff90ee90);
  65581. const Colour Colours::lightgrey (0xffd3d3d3);
  65582. const Colour Colours::lightpink (0xffffb6c1);
  65583. const Colour Colours::lightsalmon (0xffffa07a);
  65584. const Colour Colours::lightseagreen (0xff20b2aa);
  65585. const Colour Colours::lightskyblue (0xff87cefa);
  65586. const Colour Colours::lightslategrey (0xff778899);
  65587. const Colour Colours::lightsteelblue (0xffb0c4de);
  65588. const Colour Colours::lightyellow (0xffffffe0);
  65589. const Colour Colours::lime (0xff00ff00);
  65590. const Colour Colours::limegreen (0xff32cd32);
  65591. const Colour Colours::linen (0xfffaf0e6);
  65592. const Colour Colours::magenta (0xffff00ff);
  65593. const Colour Colours::maroon (0xff800000);
  65594. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65595. const Colour Colours::mediumblue (0xff0000cd);
  65596. const Colour Colours::mediumorchid (0xffba55d3);
  65597. const Colour Colours::mediumpurple (0xff9370db);
  65598. const Colour Colours::mediumseagreen (0xff3cb371);
  65599. const Colour Colours::mediumslateblue (0xff7b68ee);
  65600. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65601. const Colour Colours::mediumturquoise (0xff48d1cc);
  65602. const Colour Colours::mediumvioletred (0xffc71585);
  65603. const Colour Colours::midnightblue (0xff191970);
  65604. const Colour Colours::mintcream (0xfff5fffa);
  65605. const Colour Colours::mistyrose (0xffffe4e1);
  65606. const Colour Colours::navajowhite (0xffffdead);
  65607. const Colour Colours::navy (0xff000080);
  65608. const Colour Colours::oldlace (0xfffdf5e6);
  65609. const Colour Colours::olive (0xff808000);
  65610. const Colour Colours::olivedrab (0xff6b8e23);
  65611. const Colour Colours::orange (0xffffa500);
  65612. const Colour Colours::orangered (0xffff4500);
  65613. const Colour Colours::orchid (0xffda70d6);
  65614. const Colour Colours::palegoldenrod (0xffeee8aa);
  65615. const Colour Colours::palegreen (0xff98fb98);
  65616. const Colour Colours::paleturquoise (0xffafeeee);
  65617. const Colour Colours::palevioletred (0xffdb7093);
  65618. const Colour Colours::papayawhip (0xffffefd5);
  65619. const Colour Colours::peachpuff (0xffffdab9);
  65620. const Colour Colours::peru (0xffcd853f);
  65621. const Colour Colours::pink (0xffffc0cb);
  65622. const Colour Colours::plum (0xffdda0dd);
  65623. const Colour Colours::powderblue (0xffb0e0e6);
  65624. const Colour Colours::purple (0xff800080);
  65625. const Colour Colours::red (0xffff0000);
  65626. const Colour Colours::rosybrown (0xffbc8f8f);
  65627. const Colour Colours::royalblue (0xff4169e1);
  65628. const Colour Colours::saddlebrown (0xff8b4513);
  65629. const Colour Colours::salmon (0xfffa8072);
  65630. const Colour Colours::sandybrown (0xfff4a460);
  65631. const Colour Colours::seagreen (0xff2e8b57);
  65632. const Colour Colours::seashell (0xfffff5ee);
  65633. const Colour Colours::sienna (0xffa0522d);
  65634. const Colour Colours::silver (0xffc0c0c0);
  65635. const Colour Colours::skyblue (0xff87ceeb);
  65636. const Colour Colours::slateblue (0xff6a5acd);
  65637. const Colour Colours::slategrey (0xff708090);
  65638. const Colour Colours::snow (0xfffffafa);
  65639. const Colour Colours::springgreen (0xff00ff7f);
  65640. const Colour Colours::steelblue (0xff4682b4);
  65641. const Colour Colours::tan (0xffd2b48c);
  65642. const Colour Colours::teal (0xff008080);
  65643. const Colour Colours::thistle (0xffd8bfd8);
  65644. const Colour Colours::tomato (0xffff6347);
  65645. const Colour Colours::turquoise (0xff40e0d0);
  65646. const Colour Colours::violet (0xffee82ee);
  65647. const Colour Colours::wheat (0xfff5deb3);
  65648. const Colour Colours::white (0xffffffff);
  65649. const Colour Colours::whitesmoke (0xfff5f5f5);
  65650. const Colour Colours::yellow (0xffffff00);
  65651. const Colour Colours::yellowgreen (0xff9acd32);
  65652. const Colour Colours::findColourForName (const String& colourName,
  65653. const Colour& defaultColour)
  65654. {
  65655. static const int presets[] =
  65656. {
  65657. // (first value is the string's hashcode, second is ARGB)
  65658. 0x05978fff, 0xff000000, /* black */
  65659. 0x06bdcc29, 0xffffffff, /* white */
  65660. 0x002e305a, 0xff0000ff, /* blue */
  65661. 0x00308adf, 0xff808080, /* grey */
  65662. 0x05e0cf03, 0xff008000, /* green */
  65663. 0x0001b891, 0xffff0000, /* red */
  65664. 0xd43c6474, 0xffffff00, /* yellow */
  65665. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65666. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65667. 0x002dcebc, 0xff00ffff, /* aqua */
  65668. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65669. 0x0590228f, 0xfff0ffff, /* azure */
  65670. 0x05947fe4, 0xfff5f5dc, /* beige */
  65671. 0xad388e35, 0xffffe4c4, /* bisque */
  65672. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65673. 0x39129959, 0xff8a2be2, /* blueviolet */
  65674. 0x059a8136, 0xffa52a2a, /* brown */
  65675. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65676. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65677. 0x6b748956, 0xff7fff00, /* chartreuse */
  65678. 0x2903623c, 0xffd2691e, /* chocolate */
  65679. 0x05a74431, 0xffff7f50, /* coral */
  65680. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65681. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65682. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65683. 0x002ed323, 0xff00ffff, /* cyan */
  65684. 0x67cc74d0, 0xff00008b, /* darkblue */
  65685. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65686. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65687. 0x67cecf55, 0xff555555, /* darkgrey */
  65688. 0x920b194d, 0xff006400, /* darkgreen */
  65689. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65690. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65691. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65692. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65693. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65694. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65695. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65696. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65697. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65698. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65699. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65700. 0xc8769375, 0xff9400d3, /* darkviolet */
  65701. 0x25832862, 0xffff1493, /* deeppink */
  65702. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65703. 0x634c8b67, 0xff696969, /* dimgrey */
  65704. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65705. 0xef19e3cb, 0xffb22222, /* firebrick */
  65706. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65707. 0xd086fd06, 0xff228b22, /* forestgreen */
  65708. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65709. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65710. 0x00308060, 0xffffd700, /* gold */
  65711. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65712. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65713. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65714. 0x41892743, 0xffff69b4, /* hotpink */
  65715. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65716. 0xb969fed2, 0xff4b0082, /* indigo */
  65717. 0x05fef6a9, 0xfffffff0, /* ivory */
  65718. 0x06149302, 0xfff0e68c, /* khaki */
  65719. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65720. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65721. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65722. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65723. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65724. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65725. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65726. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65727. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65728. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65729. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65730. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65731. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65732. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65733. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65734. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65735. 0x0032afd5, 0xff00ff00, /* lime */
  65736. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65737. 0x06234efa, 0xfffaf0e6, /* linen */
  65738. 0x316858a9, 0xffff00ff, /* magenta */
  65739. 0xbf8ca470, 0xff800000, /* maroon */
  65740. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65741. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65742. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65743. 0x07556b71, 0xff9370db, /* mediumpurple */
  65744. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65745. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65746. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65747. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65748. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65749. 0x168eb32a, 0xff191970, /* midnightblue */
  65750. 0x4306b960, 0xfff5fffa, /* mintcream */
  65751. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65752. 0xe97218a6, 0xffffdead, /* navajowhite */
  65753. 0x00337bb6, 0xff000080, /* navy */
  65754. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65755. 0x064ee1db, 0xff808000, /* olive */
  65756. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65757. 0xc3de262e, 0xffffa500, /* orange */
  65758. 0x58bebba3, 0xffff4500, /* orangered */
  65759. 0xc3def8a3, 0xffda70d6, /* orchid */
  65760. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65761. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65762. 0x74022737, 0xffafeeee, /* paleturquoise */
  65763. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65764. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65765. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65766. 0x003472f8, 0xffcd853f, /* peru */
  65767. 0x00348176, 0xffffc0cb, /* pink */
  65768. 0x00348d94, 0xffdda0dd, /* plum */
  65769. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65770. 0xc5c507bc, 0xff800080, /* purple */
  65771. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65772. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65773. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65774. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65775. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65776. 0x34636c14, 0xff2e8b57, /* seagreen */
  65777. 0x3507fb41, 0xfffff5ee, /* seashell */
  65778. 0xca348772, 0xffa0522d, /* sienna */
  65779. 0xca37d30d, 0xffc0c0c0, /* silver */
  65780. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65781. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65782. 0x44ab37f8, 0xff708090, /* slategrey */
  65783. 0x0035f183, 0xfffffafa, /* snow */
  65784. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65785. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65786. 0x0001bfa1, 0xffd2b48c, /* tan */
  65787. 0x0036425c, 0xff008080, /* teal */
  65788. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65789. 0xcc41600a, 0xffff6347, /* tomato */
  65790. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65791. 0xcf57947f, 0xffee82ee, /* violet */
  65792. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65793. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65794. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65795. };
  65796. const int hash = colourName.trim().toLowerCase().hashCode();
  65797. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65798. if (presets [i] == hash)
  65799. return Colour (presets [i + 1]);
  65800. return defaultColour;
  65801. }
  65802. END_JUCE_NAMESPACE
  65803. /*** End of inlined file: juce_Colours.cpp ***/
  65804. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65805. BEGIN_JUCE_NAMESPACE
  65806. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65807. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65808. const Path& path, const AffineTransform& transform)
  65809. : bounds (bounds_),
  65810. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65811. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65812. needToCheckEmptinesss (true)
  65813. {
  65814. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65815. int* t = table;
  65816. for (int i = bounds.getHeight(); --i >= 0;)
  65817. {
  65818. *t = 0;
  65819. t += lineStrideElements;
  65820. }
  65821. const int topLimit = bounds.getY() << 8;
  65822. const int heightLimit = bounds.getHeight() << 8;
  65823. const int leftLimit = bounds.getX() << 8;
  65824. const int rightLimit = bounds.getRight() << 8;
  65825. PathFlatteningIterator iter (path, transform);
  65826. while (iter.next())
  65827. {
  65828. int y1 = roundToInt (iter.y1 * 256.0f);
  65829. int y2 = roundToInt (iter.y2 * 256.0f);
  65830. if (y1 != y2)
  65831. {
  65832. y1 -= topLimit;
  65833. y2 -= topLimit;
  65834. const int startY = y1;
  65835. int direction = -1;
  65836. if (y1 > y2)
  65837. {
  65838. swapVariables (y1, y2);
  65839. direction = 1;
  65840. }
  65841. if (y1 < 0)
  65842. y1 = 0;
  65843. if (y2 > heightLimit)
  65844. y2 = heightLimit;
  65845. if (y1 < y2)
  65846. {
  65847. const double startX = 256.0f * iter.x1;
  65848. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65849. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65850. do
  65851. {
  65852. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65853. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65854. if (x < leftLimit)
  65855. x = leftLimit;
  65856. else if (x >= rightLimit)
  65857. x = rightLimit - 1;
  65858. addEdgePoint (x, y1 >> 8, direction * step);
  65859. y1 += step;
  65860. }
  65861. while (y1 < y2);
  65862. }
  65863. }
  65864. }
  65865. sanitiseLevels (path.isUsingNonZeroWinding());
  65866. }
  65867. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65868. : bounds (rectangleToAdd),
  65869. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65870. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65871. needToCheckEmptinesss (true)
  65872. {
  65873. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65874. table[0] = 0;
  65875. const int x1 = rectangleToAdd.getX() << 8;
  65876. const int x2 = rectangleToAdd.getRight() << 8;
  65877. int* t = table;
  65878. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65879. {
  65880. t[0] = 2;
  65881. t[1] = x1;
  65882. t[2] = 255;
  65883. t[3] = x2;
  65884. t[4] = 0;
  65885. t += lineStrideElements;
  65886. }
  65887. }
  65888. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65889. : bounds (rectanglesToAdd.getBounds()),
  65890. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65891. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65892. needToCheckEmptinesss (true)
  65893. {
  65894. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65895. int* t = table;
  65896. for (int i = bounds.getHeight(); --i >= 0;)
  65897. {
  65898. *t = 0;
  65899. t += lineStrideElements;
  65900. }
  65901. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65902. {
  65903. const Rectangle<int>* const r = iter.getRectangle();
  65904. const int x1 = r->getX() << 8;
  65905. const int x2 = r->getRight() << 8;
  65906. int y = r->getY() - bounds.getY();
  65907. for (int j = r->getHeight(); --j >= 0;)
  65908. {
  65909. addEdgePoint (x1, y, 255);
  65910. addEdgePoint (x2, y, -255);
  65911. ++y;
  65912. }
  65913. }
  65914. sanitiseLevels (true);
  65915. }
  65916. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65917. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65918. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65919. 2 + (int) rectangleToAdd.getWidth(),
  65920. 2 + (int) rectangleToAdd.getHeight())),
  65921. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65922. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65923. needToCheckEmptinesss (true)
  65924. {
  65925. jassert (! rectangleToAdd.isEmpty());
  65926. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65927. table[0] = 0;
  65928. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65929. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65930. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65931. jassert (y1 < 256);
  65932. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65933. if (x2 <= x1 || y2 <= y1)
  65934. {
  65935. bounds.setHeight (0);
  65936. return;
  65937. }
  65938. int lineY = 0;
  65939. int* t = table;
  65940. if ((y1 >> 8) == (y2 >> 8))
  65941. {
  65942. t[0] = 2;
  65943. t[1] = x1;
  65944. t[2] = y2 - y1;
  65945. t[3] = x2;
  65946. t[4] = 0;
  65947. ++lineY;
  65948. t += lineStrideElements;
  65949. }
  65950. else
  65951. {
  65952. t[0] = 2;
  65953. t[1] = x1;
  65954. t[2] = 255 - (y1 & 255);
  65955. t[3] = x2;
  65956. t[4] = 0;
  65957. ++lineY;
  65958. t += lineStrideElements;
  65959. while (lineY < (y2 >> 8))
  65960. {
  65961. t[0] = 2;
  65962. t[1] = x1;
  65963. t[2] = 255;
  65964. t[3] = x2;
  65965. t[4] = 0;
  65966. ++lineY;
  65967. t += lineStrideElements;
  65968. }
  65969. jassert (lineY < bounds.getHeight());
  65970. t[0] = 2;
  65971. t[1] = x1;
  65972. t[2] = y2 & 255;
  65973. t[3] = x2;
  65974. t[4] = 0;
  65975. ++lineY;
  65976. t += lineStrideElements;
  65977. }
  65978. while (lineY < bounds.getHeight())
  65979. {
  65980. t[0] = 0;
  65981. t += lineStrideElements;
  65982. ++lineY;
  65983. }
  65984. }
  65985. EdgeTable::EdgeTable (const EdgeTable& other)
  65986. {
  65987. operator= (other);
  65988. }
  65989. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65990. {
  65991. bounds = other.bounds;
  65992. maxEdgesPerLine = other.maxEdgesPerLine;
  65993. lineStrideElements = other.lineStrideElements;
  65994. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65995. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65996. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65997. return *this;
  65998. }
  65999. EdgeTable::~EdgeTable()
  66000. {
  66001. }
  66002. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  66003. {
  66004. while (--numLines >= 0)
  66005. {
  66006. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  66007. src += srcLineStride;
  66008. dest += destLineStride;
  66009. }
  66010. }
  66011. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  66012. {
  66013. // Convert the table from relative windings to absolute levels..
  66014. int* lineStart = table;
  66015. for (int i = bounds.getHeight(); --i >= 0;)
  66016. {
  66017. int* line = lineStart;
  66018. lineStart += lineStrideElements;
  66019. int num = *line;
  66020. if (num == 0)
  66021. continue;
  66022. int level = 0;
  66023. if (useNonZeroWinding)
  66024. {
  66025. while (--num > 0)
  66026. {
  66027. line += 2;
  66028. level += *line;
  66029. int corrected = abs (level);
  66030. if (corrected >> 8)
  66031. corrected = 255;
  66032. *line = corrected;
  66033. }
  66034. }
  66035. else
  66036. {
  66037. while (--num > 0)
  66038. {
  66039. line += 2;
  66040. level += *line;
  66041. int corrected = abs (level);
  66042. if (corrected >> 8)
  66043. {
  66044. corrected &= 511;
  66045. if (corrected >> 8)
  66046. corrected = 511 - corrected;
  66047. }
  66048. *line = corrected;
  66049. }
  66050. }
  66051. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  66052. }
  66053. }
  66054. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  66055. {
  66056. if (newNumEdgesPerLine != maxEdgesPerLine)
  66057. {
  66058. maxEdgesPerLine = newNumEdgesPerLine;
  66059. jassert (bounds.getHeight() > 0);
  66060. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66061. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66062. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66063. table.swapWith (newTable);
  66064. lineStrideElements = newLineStrideElements;
  66065. }
  66066. }
  66067. void EdgeTable::optimiseTable() throw()
  66068. {
  66069. int maxLineElements = 0;
  66070. for (int i = bounds.getHeight(); --i >= 0;)
  66071. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66072. remapTableForNumEdges (maxLineElements);
  66073. }
  66074. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  66075. {
  66076. jassert (y >= 0 && y < bounds.getHeight());
  66077. int* line = table + lineStrideElements * y;
  66078. const int numPoints = line[0];
  66079. int n = numPoints << 1;
  66080. if (n > 0)
  66081. {
  66082. while (n > 0)
  66083. {
  66084. const int cx = line [n - 1];
  66085. if (cx <= x)
  66086. {
  66087. if (cx == x)
  66088. {
  66089. line [n] += winding;
  66090. return;
  66091. }
  66092. break;
  66093. }
  66094. n -= 2;
  66095. }
  66096. if (numPoints >= maxEdgesPerLine)
  66097. {
  66098. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66099. jassert (numPoints < maxEdgesPerLine);
  66100. line = table + lineStrideElements * y;
  66101. }
  66102. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66103. }
  66104. line [n + 1] = x;
  66105. line [n + 2] = winding;
  66106. line[0]++;
  66107. }
  66108. void EdgeTable::translate (float dx, const int dy) throw()
  66109. {
  66110. bounds.translate ((int) std::floor (dx), dy);
  66111. int* lineStart = table;
  66112. const int intDx = (int) (dx * 256.0f);
  66113. for (int i = bounds.getHeight(); --i >= 0;)
  66114. {
  66115. int* line = lineStart;
  66116. lineStart += lineStrideElements;
  66117. int num = *line++;
  66118. while (--num >= 0)
  66119. {
  66120. *line += intDx;
  66121. line += 2;
  66122. }
  66123. }
  66124. }
  66125. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66126. {
  66127. jassert (y >= 0 && y < bounds.getHeight());
  66128. int* dest = table + lineStrideElements * y;
  66129. if (dest[0] == 0)
  66130. return;
  66131. int otherNumPoints = *otherLine;
  66132. if (otherNumPoints == 0)
  66133. {
  66134. *dest = 0;
  66135. return;
  66136. }
  66137. const int right = bounds.getRight() << 8;
  66138. // optimise for the common case where our line lies entirely within a
  66139. // single pair of points, as happens when clipping to a simple rect.
  66140. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66141. {
  66142. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66143. return;
  66144. }
  66145. ++otherLine;
  66146. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66147. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66148. memcpy (temp, dest, lineSizeBytes);
  66149. const int* src1 = temp;
  66150. int srcNum1 = *src1++;
  66151. int x1 = *src1++;
  66152. const int* src2 = otherLine;
  66153. int srcNum2 = otherNumPoints;
  66154. int x2 = *src2++;
  66155. int destIndex = 0, destTotal = 0;
  66156. int level1 = 0, level2 = 0;
  66157. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66158. while (srcNum1 > 0 && srcNum2 > 0)
  66159. {
  66160. int nextX;
  66161. if (x1 < x2)
  66162. {
  66163. nextX = x1;
  66164. level1 = *src1++;
  66165. x1 = *src1++;
  66166. --srcNum1;
  66167. }
  66168. else if (x1 == x2)
  66169. {
  66170. nextX = x1;
  66171. level1 = *src1++;
  66172. level2 = *src2++;
  66173. x1 = *src1++;
  66174. x2 = *src2++;
  66175. --srcNum1;
  66176. --srcNum2;
  66177. }
  66178. else
  66179. {
  66180. nextX = x2;
  66181. level2 = *src2++;
  66182. x2 = *src2++;
  66183. --srcNum2;
  66184. }
  66185. if (nextX > lastX)
  66186. {
  66187. if (nextX >= right)
  66188. break;
  66189. lastX = nextX;
  66190. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66191. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66192. if (nextLevel != lastLevel)
  66193. {
  66194. if (destTotal >= maxEdgesPerLine)
  66195. {
  66196. dest[0] = destTotal;
  66197. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66198. dest = table + lineStrideElements * y;
  66199. }
  66200. ++destTotal;
  66201. lastLevel = nextLevel;
  66202. dest[++destIndex] = nextX;
  66203. dest[++destIndex] = nextLevel;
  66204. }
  66205. }
  66206. }
  66207. if (lastLevel > 0)
  66208. {
  66209. if (destTotal >= maxEdgesPerLine)
  66210. {
  66211. dest[0] = destTotal;
  66212. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66213. dest = table + lineStrideElements * y;
  66214. }
  66215. ++destTotal;
  66216. dest[++destIndex] = right;
  66217. dest[++destIndex] = 0;
  66218. }
  66219. dest[0] = destTotal;
  66220. #if JUCE_DEBUG
  66221. int last = std::numeric_limits<int>::min();
  66222. for (int i = 0; i < dest[0]; ++i)
  66223. {
  66224. jassert (dest[i * 2 + 1] > last);
  66225. last = dest[i * 2 + 1];
  66226. }
  66227. jassert (dest [dest[0] * 2] == 0);
  66228. #endif
  66229. }
  66230. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66231. {
  66232. int* lastItem = dest + (dest[0] * 2 - 1);
  66233. if (x2 < lastItem[0])
  66234. {
  66235. if (x2 <= dest[1])
  66236. {
  66237. dest[0] = 0;
  66238. return;
  66239. }
  66240. while (x2 < lastItem[-2])
  66241. {
  66242. --(dest[0]);
  66243. lastItem -= 2;
  66244. }
  66245. lastItem[0] = x2;
  66246. lastItem[1] = 0;
  66247. }
  66248. if (x1 > dest[1])
  66249. {
  66250. while (lastItem[0] > x1)
  66251. lastItem -= 2;
  66252. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66253. if (itemsRemoved > 0)
  66254. {
  66255. dest[0] -= itemsRemoved;
  66256. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66257. }
  66258. dest[1] = x1;
  66259. }
  66260. }
  66261. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66262. {
  66263. const Rectangle<int> clipped (r.getIntersection (bounds));
  66264. if (clipped.isEmpty())
  66265. {
  66266. needToCheckEmptinesss = false;
  66267. bounds.setHeight (0);
  66268. }
  66269. else
  66270. {
  66271. const int top = clipped.getY() - bounds.getY();
  66272. const int bottom = clipped.getBottom() - bounds.getY();
  66273. if (bottom < bounds.getHeight())
  66274. bounds.setHeight (bottom);
  66275. if (clipped.getRight() < bounds.getRight())
  66276. bounds.setRight (clipped.getRight());
  66277. for (int i = top; --i >= 0;)
  66278. table [lineStrideElements * i] = 0;
  66279. if (clipped.getX() > bounds.getX())
  66280. {
  66281. const int x1 = clipped.getX() << 8;
  66282. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66283. int* line = table + lineStrideElements * top;
  66284. for (int i = bottom - top; --i >= 0;)
  66285. {
  66286. if (line[0] != 0)
  66287. clipEdgeTableLineToRange (line, x1, x2);
  66288. line += lineStrideElements;
  66289. }
  66290. }
  66291. needToCheckEmptinesss = true;
  66292. }
  66293. }
  66294. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66295. {
  66296. const Rectangle<int> clipped (r.getIntersection (bounds));
  66297. if (! clipped.isEmpty())
  66298. {
  66299. const int top = clipped.getY() - bounds.getY();
  66300. const int bottom = clipped.getBottom() - bounds.getY();
  66301. //XXX optimise here by shortening the table if it fills top or bottom
  66302. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66303. clipped.getX() << 8, 0,
  66304. clipped.getRight() << 8, 255,
  66305. std::numeric_limits<int>::max(), 0 };
  66306. for (int i = top; i < bottom; ++i)
  66307. intersectWithEdgeTableLine (i, rectLine);
  66308. needToCheckEmptinesss = true;
  66309. }
  66310. }
  66311. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66312. {
  66313. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66314. if (clipped.isEmpty())
  66315. {
  66316. needToCheckEmptinesss = false;
  66317. bounds.setHeight (0);
  66318. }
  66319. else
  66320. {
  66321. const int top = clipped.getY() - bounds.getY();
  66322. const int bottom = clipped.getBottom() - bounds.getY();
  66323. if (bottom < bounds.getHeight())
  66324. bounds.setHeight (bottom);
  66325. if (clipped.getRight() < bounds.getRight())
  66326. bounds.setRight (clipped.getRight());
  66327. int i = 0;
  66328. for (i = top; --i >= 0;)
  66329. table [lineStrideElements * i] = 0;
  66330. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66331. for (i = top; i < bottom; ++i)
  66332. {
  66333. intersectWithEdgeTableLine (i, otherLine);
  66334. otherLine += other.lineStrideElements;
  66335. }
  66336. needToCheckEmptinesss = true;
  66337. }
  66338. }
  66339. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66340. {
  66341. y -= bounds.getY();
  66342. if (y < 0 || y >= bounds.getHeight())
  66343. return;
  66344. needToCheckEmptinesss = true;
  66345. if (numPixels <= 0)
  66346. {
  66347. table [lineStrideElements * y] = 0;
  66348. return;
  66349. }
  66350. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66351. int destIndex = 0, lastLevel = 0;
  66352. while (--numPixels >= 0)
  66353. {
  66354. const int alpha = *mask;
  66355. mask += maskStride;
  66356. if (alpha != lastLevel)
  66357. {
  66358. tempLine[++destIndex] = (x << 8);
  66359. tempLine[++destIndex] = alpha;
  66360. lastLevel = alpha;
  66361. }
  66362. ++x;
  66363. }
  66364. if (lastLevel > 0)
  66365. {
  66366. tempLine[++destIndex] = (x << 8);
  66367. tempLine[++destIndex] = 0;
  66368. }
  66369. tempLine[0] = destIndex >> 1;
  66370. intersectWithEdgeTableLine (y, tempLine);
  66371. }
  66372. bool EdgeTable::isEmpty() throw()
  66373. {
  66374. if (needToCheckEmptinesss)
  66375. {
  66376. needToCheckEmptinesss = false;
  66377. int* t = table;
  66378. for (int i = bounds.getHeight(); --i >= 0;)
  66379. {
  66380. if (t[0] > 1)
  66381. return false;
  66382. t += lineStrideElements;
  66383. }
  66384. bounds.setHeight (0);
  66385. }
  66386. return bounds.getHeight() == 0;
  66387. }
  66388. END_JUCE_NAMESPACE
  66389. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66390. /*** Start of inlined file: juce_FillType.cpp ***/
  66391. BEGIN_JUCE_NAMESPACE
  66392. FillType::FillType() throw()
  66393. : colour (0xff000000), image (0)
  66394. {
  66395. }
  66396. FillType::FillType (const Colour& colour_) throw()
  66397. : colour (colour_), image (0)
  66398. {
  66399. }
  66400. FillType::FillType (const ColourGradient& gradient_)
  66401. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66402. {
  66403. }
  66404. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66405. : colour (0xff000000), image (image_), transform (transform_)
  66406. {
  66407. }
  66408. FillType::FillType (const FillType& other)
  66409. : colour (other.colour),
  66410. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66411. image (other.image), transform (other.transform)
  66412. {
  66413. }
  66414. FillType& FillType::operator= (const FillType& other)
  66415. {
  66416. if (this != &other)
  66417. {
  66418. colour = other.colour;
  66419. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66420. image = other.image;
  66421. transform = other.transform;
  66422. }
  66423. return *this;
  66424. }
  66425. FillType::~FillType() throw()
  66426. {
  66427. }
  66428. bool FillType::operator== (const FillType& other) const
  66429. {
  66430. return colour == other.colour && image == other.image
  66431. && transform == other.transform
  66432. && (gradient == other.gradient
  66433. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66434. }
  66435. bool FillType::operator!= (const FillType& other) const
  66436. {
  66437. return ! operator== (other);
  66438. }
  66439. void FillType::setColour (const Colour& newColour) throw()
  66440. {
  66441. gradient = 0;
  66442. image = Image::null;
  66443. colour = newColour;
  66444. }
  66445. void FillType::setGradient (const ColourGradient& newGradient)
  66446. {
  66447. if (gradient != 0)
  66448. {
  66449. *gradient = newGradient;
  66450. }
  66451. else
  66452. {
  66453. image = Image::null;
  66454. gradient = new ColourGradient (newGradient);
  66455. colour = Colours::black;
  66456. }
  66457. }
  66458. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66459. {
  66460. gradient = 0;
  66461. image = image_;
  66462. transform = transform_;
  66463. colour = Colours::black;
  66464. }
  66465. void FillType::setOpacity (const float newOpacity) throw()
  66466. {
  66467. colour = colour.withAlpha (newOpacity);
  66468. }
  66469. bool FillType::isInvisible() const throw()
  66470. {
  66471. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66472. }
  66473. END_JUCE_NAMESPACE
  66474. /*** End of inlined file: juce_FillType.cpp ***/
  66475. /*** Start of inlined file: juce_Graphics.cpp ***/
  66476. BEGIN_JUCE_NAMESPACE
  66477. template <typename Type>
  66478. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66479. {
  66480. const int maxVal = 0x3fffffff;
  66481. return (int) x >= -maxVal && (int) x <= maxVal
  66482. && (int) y >= -maxVal && (int) y <= maxVal
  66483. && (int) w >= -maxVal && (int) w <= maxVal
  66484. && (int) h >= -maxVal && (int) h <= maxVal;
  66485. }
  66486. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66487. {
  66488. }
  66489. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66490. {
  66491. }
  66492. Graphics::Graphics (const Image& imageToDrawOnto)
  66493. : context (imageToDrawOnto.createLowLevelContext()),
  66494. contextToDelete (context),
  66495. saveStatePending (false)
  66496. {
  66497. }
  66498. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66499. : context (internalContext),
  66500. saveStatePending (false)
  66501. {
  66502. }
  66503. Graphics::~Graphics()
  66504. {
  66505. }
  66506. void Graphics::resetToDefaultState()
  66507. {
  66508. saveStateIfPending();
  66509. context->setFill (FillType());
  66510. context->setFont (Font());
  66511. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66512. }
  66513. bool Graphics::isVectorDevice() const
  66514. {
  66515. return context->isVectorDevice();
  66516. }
  66517. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66518. {
  66519. saveStateIfPending();
  66520. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66521. }
  66522. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66523. {
  66524. saveStateIfPending();
  66525. return context->clipToRectangleList (clipRegion);
  66526. }
  66527. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66528. {
  66529. saveStateIfPending();
  66530. context->clipToPath (path, transform);
  66531. return ! context->isClipEmpty();
  66532. }
  66533. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66534. {
  66535. saveStateIfPending();
  66536. context->clipToImageAlpha (image, transform);
  66537. return ! context->isClipEmpty();
  66538. }
  66539. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66540. {
  66541. saveStateIfPending();
  66542. context->excludeClipRectangle (rectangleToExclude);
  66543. }
  66544. bool Graphics::isClipEmpty() const
  66545. {
  66546. return context->isClipEmpty();
  66547. }
  66548. const Rectangle<int> Graphics::getClipBounds() const
  66549. {
  66550. return context->getClipBounds();
  66551. }
  66552. void Graphics::saveState()
  66553. {
  66554. saveStateIfPending();
  66555. saveStatePending = true;
  66556. }
  66557. void Graphics::restoreState()
  66558. {
  66559. if (saveStatePending)
  66560. saveStatePending = false;
  66561. else
  66562. context->restoreState();
  66563. }
  66564. void Graphics::saveStateIfPending()
  66565. {
  66566. if (saveStatePending)
  66567. {
  66568. saveStatePending = false;
  66569. context->saveState();
  66570. }
  66571. }
  66572. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66573. {
  66574. saveStateIfPending();
  66575. context->setOrigin (newOriginX, newOriginY);
  66576. }
  66577. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66578. {
  66579. return context->clipRegionIntersects (area);
  66580. }
  66581. void Graphics::setColour (const Colour& newColour)
  66582. {
  66583. saveStateIfPending();
  66584. context->setFill (newColour);
  66585. }
  66586. void Graphics::setOpacity (const float newOpacity)
  66587. {
  66588. saveStateIfPending();
  66589. context->setOpacity (newOpacity);
  66590. }
  66591. void Graphics::setGradientFill (const ColourGradient& gradient)
  66592. {
  66593. setFillType (gradient);
  66594. }
  66595. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66596. {
  66597. saveStateIfPending();
  66598. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66599. context->setOpacity (opacity);
  66600. }
  66601. void Graphics::setFillType (const FillType& newFill)
  66602. {
  66603. saveStateIfPending();
  66604. context->setFill (newFill);
  66605. }
  66606. void Graphics::setFont (const Font& newFont)
  66607. {
  66608. saveStateIfPending();
  66609. context->setFont (newFont);
  66610. }
  66611. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66612. {
  66613. saveStateIfPending();
  66614. Font f (context->getFont());
  66615. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66616. context->setFont (f);
  66617. }
  66618. const Font Graphics::getCurrentFont() const
  66619. {
  66620. return context->getFont();
  66621. }
  66622. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66623. {
  66624. if (text.isNotEmpty()
  66625. && startX < context->getClipBounds().getRight())
  66626. {
  66627. GlyphArrangement arr;
  66628. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66629. arr.draw (*this);
  66630. }
  66631. }
  66632. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66633. {
  66634. if (text.isNotEmpty())
  66635. {
  66636. GlyphArrangement arr;
  66637. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66638. arr.draw (*this, transform);
  66639. }
  66640. }
  66641. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66642. {
  66643. if (text.isNotEmpty()
  66644. && startX < context->getClipBounds().getRight())
  66645. {
  66646. GlyphArrangement arr;
  66647. arr.addJustifiedText (context->getFont(), text,
  66648. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66649. Justification::left);
  66650. arr.draw (*this);
  66651. }
  66652. }
  66653. void Graphics::drawText (const String& text,
  66654. const int x, const int y, const int width, const int height,
  66655. const Justification& justificationType,
  66656. const bool useEllipsesIfTooBig) const
  66657. {
  66658. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66659. {
  66660. GlyphArrangement arr;
  66661. arr.addCurtailedLineOfText (context->getFont(), text,
  66662. 0.0f, 0.0f, (float) width,
  66663. useEllipsesIfTooBig);
  66664. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66665. (float) x, (float) y, (float) width, (float) height,
  66666. justificationType);
  66667. arr.draw (*this);
  66668. }
  66669. }
  66670. void Graphics::drawFittedText (const String& text,
  66671. const int x, const int y, const int width, const int height,
  66672. const Justification& justification,
  66673. const int maximumNumberOfLines,
  66674. const float minimumHorizontalScale) const
  66675. {
  66676. if (text.isNotEmpty()
  66677. && width > 0 && height > 0
  66678. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66679. {
  66680. GlyphArrangement arr;
  66681. arr.addFittedText (context->getFont(), text,
  66682. (float) x, (float) y, (float) width, (float) height,
  66683. justification,
  66684. maximumNumberOfLines,
  66685. minimumHorizontalScale);
  66686. arr.draw (*this);
  66687. }
  66688. }
  66689. void Graphics::fillRect (int x, int y, int width, int height) const
  66690. {
  66691. // passing in a silly number can cause maths problems in rendering!
  66692. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66693. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66694. }
  66695. void Graphics::fillRect (const Rectangle<int>& r) const
  66696. {
  66697. context->fillRect (r, false);
  66698. }
  66699. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66700. {
  66701. // passing in a silly number can cause maths problems in rendering!
  66702. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66703. Path p;
  66704. p.addRectangle (x, y, width, height);
  66705. fillPath (p);
  66706. }
  66707. void Graphics::setPixel (int x, int y) const
  66708. {
  66709. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66710. }
  66711. void Graphics::fillAll() const
  66712. {
  66713. fillRect (context->getClipBounds());
  66714. }
  66715. void Graphics::fillAll (const Colour& colourToUse) const
  66716. {
  66717. if (! colourToUse.isTransparent())
  66718. {
  66719. const Rectangle<int> clip (context->getClipBounds());
  66720. context->saveState();
  66721. context->setFill (colourToUse);
  66722. context->fillRect (clip, false);
  66723. context->restoreState();
  66724. }
  66725. }
  66726. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66727. {
  66728. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66729. context->fillPath (path, transform);
  66730. }
  66731. void Graphics::strokePath (const Path& path,
  66732. const PathStrokeType& strokeType,
  66733. const AffineTransform& transform) const
  66734. {
  66735. Path stroke;
  66736. strokeType.createStrokedPath (stroke, path, transform);
  66737. fillPath (stroke);
  66738. }
  66739. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66740. const int lineThickness) const
  66741. {
  66742. // passing in a silly number can cause maths problems in rendering!
  66743. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66744. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66745. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66746. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66747. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66748. }
  66749. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66750. {
  66751. // passing in a silly number can cause maths problems in rendering!
  66752. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66753. Path p;
  66754. p.addRectangle (x, y, width, lineThickness);
  66755. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66756. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66757. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66758. fillPath (p);
  66759. }
  66760. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66761. {
  66762. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66763. }
  66764. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66765. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66766. const bool useGradient, const bool sharpEdgeOnOutside) const
  66767. {
  66768. // passing in a silly number can cause maths problems in rendering!
  66769. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66770. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66771. {
  66772. context->saveState();
  66773. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66774. const float ramp = oldOpacity / bevelThickness;
  66775. for (int i = bevelThickness; --i >= 0;)
  66776. {
  66777. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66778. : oldOpacity;
  66779. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66780. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66781. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66782. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66783. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66784. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66785. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66786. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66787. }
  66788. context->restoreState();
  66789. }
  66790. }
  66791. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66792. {
  66793. // passing in a silly number can cause maths problems in rendering!
  66794. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66795. Path p;
  66796. p.addEllipse (x, y, width, height);
  66797. fillPath (p);
  66798. }
  66799. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66800. const float lineThickness) const
  66801. {
  66802. // passing in a silly number can cause maths problems in rendering!
  66803. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66804. Path p;
  66805. p.addEllipse (x, y, width, height);
  66806. strokePath (p, PathStrokeType (lineThickness));
  66807. }
  66808. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66809. {
  66810. // passing in a silly number can cause maths problems in rendering!
  66811. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66812. Path p;
  66813. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66814. fillPath (p);
  66815. }
  66816. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66817. {
  66818. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66819. }
  66820. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66821. const float cornerSize, const float lineThickness) const
  66822. {
  66823. // passing in a silly number can cause maths problems in rendering!
  66824. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66825. Path p;
  66826. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66827. strokePath (p, PathStrokeType (lineThickness));
  66828. }
  66829. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66830. {
  66831. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66832. }
  66833. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66834. {
  66835. Path p;
  66836. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66837. fillPath (p);
  66838. }
  66839. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66840. const int checkWidth, const int checkHeight,
  66841. const Colour& colour1, const Colour& colour2) const
  66842. {
  66843. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66844. if (checkWidth > 0 && checkHeight > 0)
  66845. {
  66846. context->saveState();
  66847. if (colour1 == colour2)
  66848. {
  66849. context->setFill (colour1);
  66850. context->fillRect (area, false);
  66851. }
  66852. else
  66853. {
  66854. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66855. if (! clipped.isEmpty())
  66856. {
  66857. context->clipToRectangle (clipped);
  66858. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66859. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66860. const int startX = area.getX() + checkNumX * checkWidth;
  66861. const int startY = area.getY() + checkNumY * checkHeight;
  66862. const int right = clipped.getRight();
  66863. const int bottom = clipped.getBottom();
  66864. for (int i = 0; i < 2; ++i)
  66865. {
  66866. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66867. int cy = i;
  66868. for (int y = startY; y < bottom; y += checkHeight)
  66869. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66870. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66871. }
  66872. }
  66873. }
  66874. context->restoreState();
  66875. }
  66876. }
  66877. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66878. {
  66879. context->drawVerticalLine (x, top, bottom);
  66880. }
  66881. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66882. {
  66883. context->drawHorizontalLine (y, left, right);
  66884. }
  66885. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66886. {
  66887. context->drawLine (Line<float> (x1, y1, x2, y2));
  66888. }
  66889. void Graphics::drawLine (const float startX, const float startY,
  66890. const float endX, const float endY,
  66891. const float lineThickness) const
  66892. {
  66893. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66894. }
  66895. void Graphics::drawLine (const Line<float>& line) const
  66896. {
  66897. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66898. }
  66899. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66900. {
  66901. Path p;
  66902. p.addLineSegment (line, lineThickness);
  66903. fillPath (p);
  66904. }
  66905. void Graphics::drawDashedLine (const float startX, const float startY,
  66906. const float endX, const float endY,
  66907. const float* const dashLengths,
  66908. const int numDashLengths,
  66909. const float lineThickness) const
  66910. {
  66911. const double dx = endX - startX;
  66912. const double dy = endY - startY;
  66913. const double totalLen = juce_hypot (dx, dy);
  66914. if (totalLen >= 0.5)
  66915. {
  66916. const double onePixAlpha = 1.0 / totalLen;
  66917. double alpha = 0.0;
  66918. float x = startX;
  66919. float y = startY;
  66920. int n = 0;
  66921. while (alpha < 1.0f)
  66922. {
  66923. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66924. n = n % numDashLengths;
  66925. const float oldX = x;
  66926. const float oldY = y;
  66927. x = (float) (startX + dx * alpha);
  66928. y = (float) (startY + dy * alpha);
  66929. if ((n & 1) != 0)
  66930. {
  66931. if (lineThickness != 1.0f)
  66932. drawLine (oldX, oldY, x, y, lineThickness);
  66933. else
  66934. drawLine (oldX, oldY, x, y);
  66935. }
  66936. }
  66937. }
  66938. }
  66939. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66940. {
  66941. saveStateIfPending();
  66942. context->setInterpolationQuality (newQuality);
  66943. }
  66944. void Graphics::drawImageAt (const Image& imageToDraw,
  66945. const int topLeftX, const int topLeftY,
  66946. const bool fillAlphaChannelWithCurrentBrush) const
  66947. {
  66948. const int imageW = imageToDraw.getWidth();
  66949. const int imageH = imageToDraw.getHeight();
  66950. drawImage (imageToDraw,
  66951. topLeftX, topLeftY, imageW, imageH,
  66952. 0, 0, imageW, imageH,
  66953. fillAlphaChannelWithCurrentBrush);
  66954. }
  66955. void Graphics::drawImageWithin (const Image& imageToDraw,
  66956. const int destX, const int destY,
  66957. const int destW, const int destH,
  66958. const RectanglePlacement& placementWithinTarget,
  66959. const bool fillAlphaChannelWithCurrentBrush) const
  66960. {
  66961. // passing in a silly number can cause maths problems in rendering!
  66962. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66963. if (imageToDraw.isValid())
  66964. {
  66965. const int imageW = imageToDraw.getWidth();
  66966. const int imageH = imageToDraw.getHeight();
  66967. if (imageW > 0 && imageH > 0)
  66968. {
  66969. double newX = 0.0, newY = 0.0;
  66970. double newW = imageW;
  66971. double newH = imageH;
  66972. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66973. destX, destY, destW, destH);
  66974. if (newW > 0 && newH > 0)
  66975. {
  66976. drawImage (imageToDraw,
  66977. roundToInt (newX), roundToInt (newY),
  66978. roundToInt (newW), roundToInt (newH),
  66979. 0, 0, imageW, imageH,
  66980. fillAlphaChannelWithCurrentBrush);
  66981. }
  66982. }
  66983. }
  66984. }
  66985. void Graphics::drawImage (const Image& imageToDraw,
  66986. int dx, int dy, int dw, int dh,
  66987. int sx, int sy, int sw, int sh,
  66988. const bool fillAlphaChannelWithCurrentBrush) const
  66989. {
  66990. // passing in a silly number can cause maths problems in rendering!
  66991. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66992. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66993. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66994. {
  66995. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66996. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66997. .translated ((float) dx, (float) dy),
  66998. fillAlphaChannelWithCurrentBrush);
  66999. }
  67000. }
  67001. void Graphics::drawImageTransformed (const Image& imageToDraw,
  67002. const AffineTransform& transform,
  67003. const bool fillAlphaChannelWithCurrentBrush) const
  67004. {
  67005. if (imageToDraw.isValid() && ! context->isClipEmpty())
  67006. {
  67007. if (fillAlphaChannelWithCurrentBrush)
  67008. {
  67009. context->saveState();
  67010. context->clipToImageAlpha (imageToDraw, transform);
  67011. fillAll();
  67012. context->restoreState();
  67013. }
  67014. else
  67015. {
  67016. context->drawImage (imageToDraw, transform, false);
  67017. }
  67018. }
  67019. }
  67020. END_JUCE_NAMESPACE
  67021. /*** End of inlined file: juce_Graphics.cpp ***/
  67022. /*** Start of inlined file: juce_Justification.cpp ***/
  67023. BEGIN_JUCE_NAMESPACE
  67024. Justification::Justification (const Justification& other) throw()
  67025. : flags (other.flags)
  67026. {
  67027. }
  67028. Justification& Justification::operator= (const Justification& other) throw()
  67029. {
  67030. flags = other.flags;
  67031. return *this;
  67032. }
  67033. int Justification::getOnlyVerticalFlags() const throw()
  67034. {
  67035. return flags & (top | bottom | verticallyCentred);
  67036. }
  67037. int Justification::getOnlyHorizontalFlags() const throw()
  67038. {
  67039. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  67040. }
  67041. void Justification::applyToRectangle (int& x, int& y,
  67042. const int w, const int h,
  67043. const int spaceX, const int spaceY,
  67044. const int spaceW, const int spaceH) const throw()
  67045. {
  67046. if ((flags & horizontallyCentred) != 0)
  67047. x = spaceX + ((spaceW - w) >> 1);
  67048. else if ((flags & right) != 0)
  67049. x = spaceX + spaceW - w;
  67050. else
  67051. x = spaceX;
  67052. if ((flags & verticallyCentred) != 0)
  67053. y = spaceY + ((spaceH - h) >> 1);
  67054. else if ((flags & bottom) != 0)
  67055. y = spaceY + spaceH - h;
  67056. else
  67057. y = spaceY;
  67058. }
  67059. END_JUCE_NAMESPACE
  67060. /*** End of inlined file: juce_Justification.cpp ***/
  67061. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67062. BEGIN_JUCE_NAMESPACE
  67063. // this will throw an assertion if you try to draw something that's not
  67064. // possible in postscript
  67065. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67066. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67067. #define notPossibleInPostscriptAssert jassertfalse
  67068. #else
  67069. #define notPossibleInPostscriptAssert
  67070. #endif
  67071. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67072. const String& documentTitle,
  67073. const int totalWidth_,
  67074. const int totalHeight_)
  67075. : out (resultingPostScript),
  67076. totalWidth (totalWidth_),
  67077. totalHeight (totalHeight_),
  67078. needToClip (true)
  67079. {
  67080. stateStack.add (new SavedState());
  67081. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67082. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67083. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67084. "\n%%BoundingBox: 0 0 600 824"
  67085. "\n%%Pages: 0"
  67086. "\n%%Creator: Raw Material Software JUCE"
  67087. "\n%%Title: " << documentTitle <<
  67088. "\n%%CreationDate: none"
  67089. "\n%%LanguageLevel: 2"
  67090. "\n%%EndComments"
  67091. "\n%%BeginProlog"
  67092. "\n%%BeginResource: JRes"
  67093. "\n/bd {bind def} bind def"
  67094. "\n/c {setrgbcolor} bd"
  67095. "\n/m {moveto} bd"
  67096. "\n/l {lineto} bd"
  67097. "\n/rl {rlineto} bd"
  67098. "\n/ct {curveto} bd"
  67099. "\n/cp {closepath} bd"
  67100. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67101. "\n/doclip {initclip newpath} bd"
  67102. "\n/endclip {clip newpath} bd"
  67103. "\n%%EndResource"
  67104. "\n%%EndProlog"
  67105. "\n%%BeginSetup"
  67106. "\n%%EndSetup"
  67107. "\n%%Page: 1 1"
  67108. "\n%%BeginPageSetup"
  67109. "\n%%EndPageSetup\n\n"
  67110. << "40 800 translate\n"
  67111. << scale << ' ' << scale << " scale\n\n";
  67112. }
  67113. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67114. {
  67115. }
  67116. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67117. {
  67118. return true;
  67119. }
  67120. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67121. {
  67122. if (x != 0 || y != 0)
  67123. {
  67124. stateStack.getLast()->xOffset += x;
  67125. stateStack.getLast()->yOffset += y;
  67126. needToClip = true;
  67127. }
  67128. }
  67129. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67130. {
  67131. needToClip = true;
  67132. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67133. }
  67134. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67135. {
  67136. needToClip = true;
  67137. return stateStack.getLast()->clip.clipTo (clipRegion);
  67138. }
  67139. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67140. {
  67141. needToClip = true;
  67142. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67143. }
  67144. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67145. {
  67146. writeClip();
  67147. Path p (path);
  67148. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67149. writePath (p);
  67150. out << "clip\n";
  67151. }
  67152. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67153. {
  67154. needToClip = true;
  67155. jassertfalse; // xxx
  67156. }
  67157. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67158. {
  67159. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67160. }
  67161. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67162. {
  67163. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67164. -stateStack.getLast()->yOffset);
  67165. }
  67166. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67167. {
  67168. return stateStack.getLast()->clip.isEmpty();
  67169. }
  67170. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67171. : xOffset (0),
  67172. yOffset (0)
  67173. {
  67174. }
  67175. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67176. {
  67177. }
  67178. void LowLevelGraphicsPostScriptRenderer::saveState()
  67179. {
  67180. stateStack.add (new SavedState (*stateStack.getLast()));
  67181. }
  67182. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67183. {
  67184. jassert (stateStack.size() > 0);
  67185. if (stateStack.size() > 0)
  67186. stateStack.removeLast();
  67187. }
  67188. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67189. {
  67190. if (needToClip)
  67191. {
  67192. needToClip = false;
  67193. out << "doclip ";
  67194. int itemsOnLine = 0;
  67195. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67196. {
  67197. if (++itemsOnLine == 6)
  67198. {
  67199. itemsOnLine = 0;
  67200. out << '\n';
  67201. }
  67202. const Rectangle<int>& r = *i.getRectangle();
  67203. out << r.getX() << ' ' << -r.getY() << ' '
  67204. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67205. }
  67206. out << "endclip\n";
  67207. }
  67208. }
  67209. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67210. {
  67211. Colour c (Colours::white.overlaidWith (colour));
  67212. if (lastColour != c)
  67213. {
  67214. lastColour = c;
  67215. out << String (c.getFloatRed(), 3) << ' '
  67216. << String (c.getFloatGreen(), 3) << ' '
  67217. << String (c.getFloatBlue(), 3) << " c\n";
  67218. }
  67219. }
  67220. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67221. {
  67222. out << String (x, 2) << ' '
  67223. << String (-y, 2) << ' ';
  67224. }
  67225. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67226. {
  67227. out << "newpath ";
  67228. float lastX = 0.0f;
  67229. float lastY = 0.0f;
  67230. int itemsOnLine = 0;
  67231. Path::Iterator i (path);
  67232. while (i.next())
  67233. {
  67234. if (++itemsOnLine == 4)
  67235. {
  67236. itemsOnLine = 0;
  67237. out << '\n';
  67238. }
  67239. switch (i.elementType)
  67240. {
  67241. case Path::Iterator::startNewSubPath:
  67242. writeXY (i.x1, i.y1);
  67243. lastX = i.x1;
  67244. lastY = i.y1;
  67245. out << "m ";
  67246. break;
  67247. case Path::Iterator::lineTo:
  67248. writeXY (i.x1, i.y1);
  67249. lastX = i.x1;
  67250. lastY = i.y1;
  67251. out << "l ";
  67252. break;
  67253. case Path::Iterator::quadraticTo:
  67254. {
  67255. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67256. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67257. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67258. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67259. writeXY (cp1x, cp1y);
  67260. writeXY (cp2x, cp2y);
  67261. writeXY (i.x2, i.y2);
  67262. out << "ct ";
  67263. lastX = i.x2;
  67264. lastY = i.y2;
  67265. }
  67266. break;
  67267. case Path::Iterator::cubicTo:
  67268. writeXY (i.x1, i.y1);
  67269. writeXY (i.x2, i.y2);
  67270. writeXY (i.x3, i.y3);
  67271. out << "ct ";
  67272. lastX = i.x3;
  67273. lastY = i.y3;
  67274. break;
  67275. case Path::Iterator::closePath:
  67276. out << "cp ";
  67277. break;
  67278. default:
  67279. jassertfalse;
  67280. break;
  67281. }
  67282. }
  67283. out << '\n';
  67284. }
  67285. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67286. {
  67287. out << "[ "
  67288. << trans.mat00 << ' '
  67289. << trans.mat10 << ' '
  67290. << trans.mat01 << ' '
  67291. << trans.mat11 << ' '
  67292. << trans.mat02 << ' '
  67293. << trans.mat12 << " ] concat ";
  67294. }
  67295. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67296. {
  67297. stateStack.getLast()->fillType = fillType;
  67298. }
  67299. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67300. {
  67301. }
  67302. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67303. {
  67304. }
  67305. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67306. {
  67307. if (stateStack.getLast()->fillType.isColour())
  67308. {
  67309. writeClip();
  67310. writeColour (stateStack.getLast()->fillType.colour);
  67311. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67312. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67313. }
  67314. else
  67315. {
  67316. Path p;
  67317. p.addRectangle (r);
  67318. fillPath (p, AffineTransform::identity);
  67319. }
  67320. }
  67321. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67322. {
  67323. if (stateStack.getLast()->fillType.isColour())
  67324. {
  67325. writeClip();
  67326. Path p (path);
  67327. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67328. (float) stateStack.getLast()->yOffset));
  67329. writePath (p);
  67330. writeColour (stateStack.getLast()->fillType.colour);
  67331. out << "fill\n";
  67332. }
  67333. else if (stateStack.getLast()->fillType.isGradient())
  67334. {
  67335. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67336. // postscript can't do semi-transparent ones.
  67337. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67338. writeClip();
  67339. out << "gsave ";
  67340. {
  67341. Path p (path);
  67342. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67343. writePath (p);
  67344. out << "clip\n";
  67345. }
  67346. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67347. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67348. // time-being, this just fills it with the average colour..
  67349. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67350. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67351. out << "grestore\n";
  67352. }
  67353. }
  67354. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67355. const int sx, const int sy,
  67356. const int maxW, const int maxH) const
  67357. {
  67358. out << "{<\n";
  67359. const int w = jmin (maxW, im.getWidth());
  67360. const int h = jmin (maxH, im.getHeight());
  67361. int charsOnLine = 0;
  67362. const Image::BitmapData srcData (im, 0, 0, w, h);
  67363. Colour pixel;
  67364. for (int y = h; --y >= 0;)
  67365. {
  67366. for (int x = 0; x < w; ++x)
  67367. {
  67368. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67369. if (x >= sx && y >= sy)
  67370. {
  67371. if (im.isARGB())
  67372. {
  67373. PixelARGB p (*(const PixelARGB*) pixelData);
  67374. p.unpremultiply();
  67375. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67376. }
  67377. else if (im.isRGB())
  67378. {
  67379. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67380. }
  67381. else
  67382. {
  67383. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67384. }
  67385. }
  67386. else
  67387. {
  67388. pixel = Colours::transparentWhite;
  67389. }
  67390. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67391. out << String::toHexString (pixelValues, 3, 0);
  67392. charsOnLine += 3;
  67393. if (charsOnLine > 100)
  67394. {
  67395. out << '\n';
  67396. charsOnLine = 0;
  67397. }
  67398. }
  67399. }
  67400. out << "\n>}\n";
  67401. }
  67402. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67403. {
  67404. const int w = sourceImage.getWidth();
  67405. const int h = sourceImage.getHeight();
  67406. writeClip();
  67407. out << "gsave ";
  67408. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67409. .scaled (1.0f, -1.0f));
  67410. RectangleList imageClip;
  67411. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67412. out << "newpath ";
  67413. int itemsOnLine = 0;
  67414. for (RectangleList::Iterator i (imageClip); i.next();)
  67415. {
  67416. if (++itemsOnLine == 6)
  67417. {
  67418. out << '\n';
  67419. itemsOnLine = 0;
  67420. }
  67421. const Rectangle<int>& r = *i.getRectangle();
  67422. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67423. }
  67424. out << " clip newpath\n";
  67425. out << w << ' ' << h << " scale\n";
  67426. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67427. writeImage (sourceImage, 0, 0, w, h);
  67428. out << "false 3 colorimage grestore\n";
  67429. needToClip = true;
  67430. }
  67431. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67432. {
  67433. Path p;
  67434. p.addLineSegment (line, 1.0f);
  67435. fillPath (p, AffineTransform::identity);
  67436. }
  67437. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67438. {
  67439. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67440. }
  67441. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67442. {
  67443. drawLine (Line<float> (left, (float) y, right, (float) y));
  67444. }
  67445. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67446. {
  67447. stateStack.getLast()->font = newFont;
  67448. }
  67449. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67450. {
  67451. return stateStack.getLast()->font;
  67452. }
  67453. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67454. {
  67455. Path p;
  67456. Font& font = stateStack.getLast()->font;
  67457. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67458. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67459. }
  67460. END_JUCE_NAMESPACE
  67461. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67462. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67463. BEGIN_JUCE_NAMESPACE
  67464. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67465. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67466. #endif
  67467. #if JUCE_MSVC
  67468. #pragma warning (push)
  67469. #pragma warning (disable: 4127) // "expression is constant" warning
  67470. #if JUCE_DEBUG
  67471. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67472. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67473. #endif
  67474. #endif
  67475. namespace SoftwareRendererClasses
  67476. {
  67477. template <class PixelType, bool replaceExisting = false>
  67478. class SolidColourEdgeTableRenderer
  67479. {
  67480. public:
  67481. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67482. : data (data_),
  67483. sourceColour (colour)
  67484. {
  67485. if (sizeof (PixelType) == 3)
  67486. {
  67487. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67488. && sourceColour.getGreen() == sourceColour.getBlue();
  67489. filler[0].set (sourceColour);
  67490. filler[1].set (sourceColour);
  67491. filler[2].set (sourceColour);
  67492. filler[3].set (sourceColour);
  67493. }
  67494. }
  67495. forcedinline void setEdgeTableYPos (const int y) throw()
  67496. {
  67497. linePixels = (PixelType*) data.getLinePointer (y);
  67498. }
  67499. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67500. {
  67501. if (replaceExisting)
  67502. linePixels[x].set (sourceColour);
  67503. else
  67504. linePixels[x].blend (sourceColour, alphaLevel);
  67505. }
  67506. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67507. {
  67508. if (replaceExisting)
  67509. linePixels[x].set (sourceColour);
  67510. else
  67511. linePixels[x].blend (sourceColour);
  67512. }
  67513. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67514. {
  67515. PixelARGB p (sourceColour);
  67516. p.multiplyAlpha (alphaLevel);
  67517. PixelType* dest = linePixels + x;
  67518. if (replaceExisting || p.getAlpha() >= 0xff)
  67519. replaceLine (dest, p, width);
  67520. else
  67521. blendLine (dest, p, width);
  67522. }
  67523. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67524. {
  67525. PixelType* dest = linePixels + x;
  67526. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67527. replaceLine (dest, sourceColour, width);
  67528. else
  67529. blendLine (dest, sourceColour, width);
  67530. }
  67531. private:
  67532. const Image::BitmapData& data;
  67533. PixelType* linePixels;
  67534. PixelARGB sourceColour;
  67535. PixelRGB filler [4];
  67536. bool areRGBComponentsEqual;
  67537. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67538. {
  67539. do
  67540. {
  67541. dest->blend (colour);
  67542. ++dest;
  67543. } while (--width > 0);
  67544. }
  67545. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67546. {
  67547. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67548. {
  67549. memset (dest, colour.getRed(), width * 3);
  67550. }
  67551. else
  67552. {
  67553. if (width >> 5)
  67554. {
  67555. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67556. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67557. {
  67558. dest->set (colour);
  67559. ++dest;
  67560. --width;
  67561. }
  67562. while (width > 4)
  67563. {
  67564. int* d = reinterpret_cast<int*> (dest);
  67565. *d++ = intFiller[0];
  67566. *d++ = intFiller[1];
  67567. *d++ = intFiller[2];
  67568. dest = reinterpret_cast<PixelRGB*> (d);
  67569. width -= 4;
  67570. }
  67571. }
  67572. while (--width >= 0)
  67573. {
  67574. dest->set (colour);
  67575. ++dest;
  67576. }
  67577. }
  67578. }
  67579. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67580. {
  67581. memset (dest, colour.getAlpha(), width);
  67582. }
  67583. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67584. {
  67585. do
  67586. {
  67587. dest->set (colour);
  67588. ++dest;
  67589. } while (--width > 0);
  67590. }
  67591. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67592. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67593. };
  67594. class LinearGradientPixelGenerator
  67595. {
  67596. public:
  67597. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67598. : lookupTable (lookupTable_), numEntries (numEntries_)
  67599. {
  67600. jassert (numEntries_ >= 0);
  67601. Point<float> p1 (gradient.point1);
  67602. Point<float> p2 (gradient.point2);
  67603. if (! transform.isIdentity())
  67604. {
  67605. const Line<float> l (p2, p1);
  67606. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67607. p1.applyTransform (transform);
  67608. p2.applyTransform (transform);
  67609. p3.applyTransform (transform);
  67610. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67611. }
  67612. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67613. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67614. if (vertical)
  67615. {
  67616. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67617. start = roundToInt (p1.getY() * scale);
  67618. }
  67619. else if (horizontal)
  67620. {
  67621. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67622. start = roundToInt (p1.getX() * scale);
  67623. }
  67624. else
  67625. {
  67626. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67627. yTerm = p1.getY() - p1.getX() / grad;
  67628. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67629. grad *= scale;
  67630. }
  67631. }
  67632. forcedinline void setY (const int y) throw()
  67633. {
  67634. if (vertical)
  67635. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67636. else if (! horizontal)
  67637. start = roundToInt ((y - yTerm) * grad);
  67638. }
  67639. inline const PixelARGB getPixel (const int x) const throw()
  67640. {
  67641. return vertical ? linePix
  67642. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67643. }
  67644. private:
  67645. const PixelARGB* const lookupTable;
  67646. const int numEntries;
  67647. PixelARGB linePix;
  67648. int start, scale;
  67649. double grad, yTerm;
  67650. bool vertical, horizontal;
  67651. enum { numScaleBits = 12 };
  67652. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67653. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67654. };
  67655. class RadialGradientPixelGenerator
  67656. {
  67657. public:
  67658. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67659. const PixelARGB* const lookupTable_, const int numEntries_)
  67660. : lookupTable (lookupTable_),
  67661. numEntries (numEntries_),
  67662. gx1 (gradient.point1.getX()),
  67663. gy1 (gradient.point1.getY())
  67664. {
  67665. jassert (numEntries_ >= 0);
  67666. const Point<float> diff (gradient.point1 - gradient.point2);
  67667. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67668. invScale = numEntries / std::sqrt (maxDist);
  67669. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67670. }
  67671. forcedinline void setY (const int y) throw()
  67672. {
  67673. dy = y - gy1;
  67674. dy *= dy;
  67675. }
  67676. inline const PixelARGB getPixel (const int px) const throw()
  67677. {
  67678. double x = px - gx1;
  67679. x *= x;
  67680. x += dy;
  67681. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67682. }
  67683. protected:
  67684. const PixelARGB* const lookupTable;
  67685. const int numEntries;
  67686. const double gx1, gy1;
  67687. double maxDist, invScale, dy;
  67688. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67689. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67690. };
  67691. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67692. {
  67693. public:
  67694. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67695. const PixelARGB* const lookupTable_, const int numEntries_)
  67696. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67697. inverseTransform (transform.inverted())
  67698. {
  67699. tM10 = inverseTransform.mat10;
  67700. tM00 = inverseTransform.mat00;
  67701. }
  67702. forcedinline void setY (const int y) throw()
  67703. {
  67704. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67705. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67706. }
  67707. inline const PixelARGB getPixel (const int px) const throw()
  67708. {
  67709. double x = px;
  67710. const double y = tM10 * x + lineYM11;
  67711. x = tM00 * x + lineYM01;
  67712. x *= x;
  67713. x += y * y;
  67714. if (x >= maxDist)
  67715. return lookupTable [numEntries];
  67716. else
  67717. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67718. }
  67719. private:
  67720. double tM10, tM00, lineYM01, lineYM11;
  67721. const AffineTransform inverseTransform;
  67722. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67723. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67724. };
  67725. template <class PixelType, class GradientType>
  67726. class GradientEdgeTableRenderer : public GradientType
  67727. {
  67728. public:
  67729. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67730. const PixelARGB* const lookupTable_, const int numEntries_)
  67731. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67732. destData (destData_)
  67733. {
  67734. }
  67735. forcedinline void setEdgeTableYPos (const int y) throw()
  67736. {
  67737. linePixels = (PixelType*) destData.getLinePointer (y);
  67738. GradientType::setY (y);
  67739. }
  67740. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67741. {
  67742. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67743. }
  67744. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67745. {
  67746. linePixels[x].blend (GradientType::getPixel (x));
  67747. }
  67748. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67749. {
  67750. PixelType* dest = linePixels + x;
  67751. if (alphaLevel < 0xff)
  67752. {
  67753. do
  67754. {
  67755. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67756. } while (--width > 0);
  67757. }
  67758. else
  67759. {
  67760. do
  67761. {
  67762. (dest++)->blend (GradientType::getPixel (x++));
  67763. } while (--width > 0);
  67764. }
  67765. }
  67766. void handleEdgeTableLineFull (int x, int width) const throw()
  67767. {
  67768. PixelType* dest = linePixels + x;
  67769. do
  67770. {
  67771. (dest++)->blend (GradientType::getPixel (x++));
  67772. } while (--width > 0);
  67773. }
  67774. private:
  67775. const Image::BitmapData& destData;
  67776. PixelType* linePixels;
  67777. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67778. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67779. };
  67780. static forcedinline int safeModulo (int n, const int divisor) throw()
  67781. {
  67782. jassert (divisor > 0);
  67783. n %= divisor;
  67784. return (n < 0) ? (n + divisor) : n;
  67785. }
  67786. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67787. class ImageFillEdgeTableRenderer
  67788. {
  67789. public:
  67790. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67791. const Image::BitmapData& srcData_,
  67792. const int extraAlpha_,
  67793. const int x, const int y)
  67794. : destData (destData_),
  67795. srcData (srcData_),
  67796. extraAlpha (extraAlpha_ + 1),
  67797. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67798. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67799. {
  67800. }
  67801. forcedinline void setEdgeTableYPos (int y) throw()
  67802. {
  67803. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67804. y -= yOffset;
  67805. if (repeatPattern)
  67806. {
  67807. jassert (y >= 0);
  67808. y %= srcData.height;
  67809. }
  67810. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67811. }
  67812. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67813. {
  67814. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67815. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67816. }
  67817. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67818. {
  67819. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67820. }
  67821. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67822. {
  67823. DestPixelType* dest = linePixels + x;
  67824. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67825. x -= xOffset;
  67826. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67827. if (alphaLevel < 0xfe)
  67828. {
  67829. do
  67830. {
  67831. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67832. } while (--width > 0);
  67833. }
  67834. else
  67835. {
  67836. if (repeatPattern)
  67837. {
  67838. do
  67839. {
  67840. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67841. } while (--width > 0);
  67842. }
  67843. else
  67844. {
  67845. copyRow (dest, sourceLineStart + x, width);
  67846. }
  67847. }
  67848. }
  67849. void handleEdgeTableLineFull (int x, int width) const throw()
  67850. {
  67851. DestPixelType* dest = linePixels + x;
  67852. x -= xOffset;
  67853. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67854. if (extraAlpha < 0xfe)
  67855. {
  67856. do
  67857. {
  67858. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67859. } while (--width > 0);
  67860. }
  67861. else
  67862. {
  67863. if (repeatPattern)
  67864. {
  67865. do
  67866. {
  67867. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67868. } while (--width > 0);
  67869. }
  67870. else
  67871. {
  67872. copyRow (dest, sourceLineStart + x, width);
  67873. }
  67874. }
  67875. }
  67876. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67877. {
  67878. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67879. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67880. uint8* mask = (uint8*) (s + x - xOffset);
  67881. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67882. mask += PixelARGB::indexA;
  67883. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67884. }
  67885. private:
  67886. const Image::BitmapData& destData;
  67887. const Image::BitmapData& srcData;
  67888. const int extraAlpha, xOffset, yOffset;
  67889. DestPixelType* linePixels;
  67890. SrcPixelType* sourceLineStart;
  67891. template <class PixelType1, class PixelType2>
  67892. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67893. {
  67894. do
  67895. {
  67896. dest++ ->blend (*src++);
  67897. } while (--width > 0);
  67898. }
  67899. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67900. {
  67901. memcpy (dest, src, width * sizeof (PixelRGB));
  67902. }
  67903. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67904. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67905. };
  67906. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67907. class TransformedImageFillEdgeTableRenderer
  67908. {
  67909. public:
  67910. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67911. const Image::BitmapData& srcData_,
  67912. const AffineTransform& transform,
  67913. const int extraAlpha_,
  67914. const bool betterQuality_)
  67915. : interpolator (transform),
  67916. destData (destData_),
  67917. srcData (srcData_),
  67918. extraAlpha (extraAlpha_ + 1),
  67919. betterQuality (betterQuality_),
  67920. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67921. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67922. maxX (srcData_.width - 1),
  67923. maxY (srcData_.height - 1),
  67924. scratchSize (2048)
  67925. {
  67926. scratchBuffer.malloc (scratchSize);
  67927. }
  67928. ~TransformedImageFillEdgeTableRenderer()
  67929. {
  67930. }
  67931. forcedinline void setEdgeTableYPos (const int newY) throw()
  67932. {
  67933. y = newY;
  67934. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67935. }
  67936. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67937. {
  67938. alphaLevel *= extraAlpha;
  67939. alphaLevel >>= 8;
  67940. SrcPixelType p;
  67941. generate (&p, x, 1);
  67942. linePixels[x].blend (p, alphaLevel);
  67943. }
  67944. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67945. {
  67946. SrcPixelType p;
  67947. generate (&p, x, 1);
  67948. linePixels[x].blend (p, extraAlpha);
  67949. }
  67950. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67951. {
  67952. if (width > scratchSize)
  67953. {
  67954. scratchSize = width;
  67955. scratchBuffer.malloc (scratchSize);
  67956. }
  67957. SrcPixelType* span = scratchBuffer;
  67958. generate (span, x, width);
  67959. DestPixelType* dest = linePixels + x;
  67960. alphaLevel *= extraAlpha;
  67961. alphaLevel >>= 8;
  67962. if (alphaLevel < 0xfe)
  67963. {
  67964. do
  67965. {
  67966. dest++ ->blend (*span++, alphaLevel);
  67967. } while (--width > 0);
  67968. }
  67969. else
  67970. {
  67971. do
  67972. {
  67973. dest++ ->blend (*span++);
  67974. } while (--width > 0);
  67975. }
  67976. }
  67977. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67978. {
  67979. handleEdgeTableLine (x, width, 255);
  67980. }
  67981. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67982. {
  67983. if (width > scratchSize)
  67984. {
  67985. scratchSize = width;
  67986. scratchBuffer.malloc (scratchSize);
  67987. }
  67988. y = y_;
  67989. generate (scratchBuffer, x, width);
  67990. et.clipLineToMask (x, y_,
  67991. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67992. sizeof (SrcPixelType), width);
  67993. }
  67994. private:
  67995. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67996. {
  67997. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67998. do
  67999. {
  68000. int hiResX, hiResY;
  68001. this->interpolator.next (hiResX, hiResY);
  68002. hiResX += pixelOffsetInt;
  68003. hiResY += pixelOffsetInt;
  68004. int loResX = hiResX >> 8;
  68005. int loResY = hiResY >> 8;
  68006. if (repeatPattern)
  68007. {
  68008. loResX = safeModulo (loResX, srcData.width);
  68009. loResY = safeModulo (loResY, srcData.height);
  68010. }
  68011. if (betterQuality
  68012. && ((unsigned int) loResX) < (unsigned int) maxX
  68013. && ((unsigned int) loResY) < (unsigned int) maxY)
  68014. {
  68015. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  68016. hiResX &= 255;
  68017. hiResY &= 255;
  68018. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68019. uint32 weight = (256 - hiResX) * (256 - hiResY);
  68020. c[0] += weight * src[0];
  68021. c[1] += weight * src[1];
  68022. c[2] += weight * src[2];
  68023. c[3] += weight * src[3];
  68024. weight = hiResX * (256 - hiResY);
  68025. c[0] += weight * src[4];
  68026. c[1] += weight * src[5];
  68027. c[2] += weight * src[6];
  68028. c[3] += weight * src[7];
  68029. src += this->srcData.lineStride;
  68030. weight = (256 - hiResX) * hiResY;
  68031. c[0] += weight * src[0];
  68032. c[1] += weight * src[1];
  68033. c[2] += weight * src[2];
  68034. c[3] += weight * src[3];
  68035. weight = hiResX * hiResY;
  68036. c[0] += weight * src[4];
  68037. c[1] += weight * src[5];
  68038. c[2] += weight * src[6];
  68039. c[3] += weight * src[7];
  68040. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  68041. (uint8) (c[PixelARGB::indexR] >> 16),
  68042. (uint8) (c[PixelARGB::indexG] >> 16),
  68043. (uint8) (c[PixelARGB::indexB] >> 16));
  68044. }
  68045. else
  68046. {
  68047. if (! repeatPattern)
  68048. {
  68049. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68050. if (loResX < 0) loResX = 0;
  68051. if (loResY < 0) loResY = 0;
  68052. if (loResX > maxX) loResX = maxX;
  68053. if (loResY > maxY) loResY = maxY;
  68054. }
  68055. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  68056. }
  68057. ++dest;
  68058. } while (--numPixels > 0);
  68059. }
  68060. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  68061. {
  68062. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68063. do
  68064. {
  68065. int hiResX, hiResY;
  68066. this->interpolator.next (hiResX, hiResY);
  68067. hiResX += pixelOffsetInt;
  68068. hiResY += pixelOffsetInt;
  68069. int loResX = hiResX >> 8;
  68070. int loResY = hiResY >> 8;
  68071. if (repeatPattern)
  68072. {
  68073. loResX = safeModulo (loResX, srcData.width);
  68074. loResY = safeModulo (loResY, srcData.height);
  68075. }
  68076. if (betterQuality
  68077. && ((unsigned int) loResX) < (unsigned int) maxX
  68078. && ((unsigned int) loResY) < (unsigned int) maxY)
  68079. {
  68080. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68081. hiResX &= 255;
  68082. hiResY &= 255;
  68083. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68084. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68085. c[0] += weight * src[0];
  68086. c[1] += weight * src[1];
  68087. c[2] += weight * src[2];
  68088. weight = hiResX * (256 - hiResY);
  68089. c[0] += weight * src[3];
  68090. c[1] += weight * src[4];
  68091. c[2] += weight * src[5];
  68092. src += this->srcData.lineStride;
  68093. weight = (256 - hiResX) * hiResY;
  68094. c[0] += weight * src[0];
  68095. c[1] += weight * src[1];
  68096. c[2] += weight * src[2];
  68097. weight = hiResX * hiResY;
  68098. c[0] += weight * src[3];
  68099. c[1] += weight * src[4];
  68100. c[2] += weight * src[5];
  68101. dest->setARGB ((uint8) 255,
  68102. (uint8) (c[PixelRGB::indexR] >> 16),
  68103. (uint8) (c[PixelRGB::indexG] >> 16),
  68104. (uint8) (c[PixelRGB::indexB] >> 16));
  68105. }
  68106. else
  68107. {
  68108. if (! repeatPattern)
  68109. {
  68110. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68111. if (loResX < 0) loResX = 0;
  68112. if (loResY < 0) loResY = 0;
  68113. if (loResX > maxX) loResX = maxX;
  68114. if (loResY > maxY) loResY = maxY;
  68115. }
  68116. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68117. }
  68118. ++dest;
  68119. } while (--numPixels > 0);
  68120. }
  68121. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68122. {
  68123. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68124. do
  68125. {
  68126. int hiResX, hiResY;
  68127. this->interpolator.next (hiResX, hiResY);
  68128. hiResX += pixelOffsetInt;
  68129. hiResY += pixelOffsetInt;
  68130. int loResX = hiResX >> 8;
  68131. int loResY = hiResY >> 8;
  68132. if (repeatPattern)
  68133. {
  68134. loResX = safeModulo (loResX, srcData.width);
  68135. loResY = safeModulo (loResY, srcData.height);
  68136. }
  68137. if (betterQuality
  68138. && ((unsigned int) loResX) < (unsigned int) maxX
  68139. && ((unsigned int) loResY) < (unsigned int) maxY)
  68140. {
  68141. hiResX &= 255;
  68142. hiResY &= 255;
  68143. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68144. uint32 c = 256 * 128;
  68145. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68146. c += src[1] * (hiResX * (256 - hiResY));
  68147. src += this->srcData.lineStride;
  68148. c += src[0] * ((256 - hiResX) * hiResY);
  68149. c += src[1] * (hiResX * hiResY);
  68150. *((uint8*) dest) = (uint8) c;
  68151. }
  68152. else
  68153. {
  68154. if (! repeatPattern)
  68155. {
  68156. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68157. if (loResX < 0) loResX = 0;
  68158. if (loResY < 0) loResY = 0;
  68159. if (loResX > maxX) loResX = maxX;
  68160. if (loResY > maxY) loResY = maxY;
  68161. }
  68162. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68163. }
  68164. ++dest;
  68165. } while (--numPixels > 0);
  68166. }
  68167. class TransformedImageSpanInterpolator
  68168. {
  68169. public:
  68170. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68171. : inverseTransform (transform.inverted())
  68172. {}
  68173. void setStartOfLine (float x, float y, const int numPixels) throw()
  68174. {
  68175. float x1 = x, y1 = y;
  68176. x += numPixels;
  68177. inverseTransform.transformPoints (x1, y1, x, y);
  68178. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68179. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68180. }
  68181. void next (int& x, int& y) throw()
  68182. {
  68183. x = xBresenham.n;
  68184. xBresenham.stepToNext();
  68185. y = yBresenham.n;
  68186. yBresenham.stepToNext();
  68187. }
  68188. private:
  68189. class BresenhamInterpolator
  68190. {
  68191. public:
  68192. BresenhamInterpolator() throw() {}
  68193. void set (const int n1, const int n2, const int numSteps_) throw()
  68194. {
  68195. numSteps = jmax (1, numSteps_);
  68196. step = (n2 - n1) / numSteps;
  68197. remainder = modulo = (n2 - n1) % numSteps;
  68198. n = n1;
  68199. if (modulo <= 0)
  68200. {
  68201. modulo += numSteps;
  68202. remainder += numSteps;
  68203. --step;
  68204. }
  68205. modulo -= numSteps;
  68206. }
  68207. forcedinline void stepToNext() throw()
  68208. {
  68209. modulo += remainder;
  68210. n += step;
  68211. if (modulo > 0)
  68212. {
  68213. modulo -= numSteps;
  68214. ++n;
  68215. }
  68216. }
  68217. int n;
  68218. private:
  68219. int numSteps, step, modulo, remainder;
  68220. };
  68221. const AffineTransform inverseTransform;
  68222. BresenhamInterpolator xBresenham, yBresenham;
  68223. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68224. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68225. };
  68226. TransformedImageSpanInterpolator interpolator;
  68227. const Image::BitmapData& destData;
  68228. const Image::BitmapData& srcData;
  68229. const int extraAlpha;
  68230. const bool betterQuality;
  68231. const float pixelOffset;
  68232. const int pixelOffsetInt, maxX, maxY;
  68233. int y;
  68234. DestPixelType* linePixels;
  68235. HeapBlock <SrcPixelType> scratchBuffer;
  68236. int scratchSize;
  68237. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68238. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68239. };
  68240. class ClipRegionBase : public ReferenceCountedObject
  68241. {
  68242. public:
  68243. ClipRegionBase() {}
  68244. virtual ~ClipRegionBase() {}
  68245. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68246. virtual const Ptr clone() const = 0;
  68247. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68248. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68249. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68250. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68251. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68252. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68253. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68254. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68255. virtual const Rectangle<int> getClipBounds() const = 0;
  68256. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68257. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68258. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68259. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68260. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68261. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68262. protected:
  68263. template <class Iterator>
  68264. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68265. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68266. {
  68267. switch (destData.pixelFormat)
  68268. {
  68269. case Image::ARGB:
  68270. switch (srcData.pixelFormat)
  68271. {
  68272. case Image::ARGB:
  68273. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68274. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68275. break;
  68276. case Image::RGB:
  68277. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68278. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68279. break;
  68280. default:
  68281. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68282. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68283. break;
  68284. }
  68285. break;
  68286. case Image::RGB:
  68287. switch (srcData.pixelFormat)
  68288. {
  68289. case Image::ARGB:
  68290. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68291. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68292. break;
  68293. case Image::RGB:
  68294. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68295. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68296. break;
  68297. default:
  68298. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68299. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68300. break;
  68301. }
  68302. break;
  68303. default:
  68304. switch (srcData.pixelFormat)
  68305. {
  68306. case Image::ARGB:
  68307. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68308. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68309. break;
  68310. case Image::RGB:
  68311. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68312. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68313. break;
  68314. default:
  68315. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68316. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68317. break;
  68318. }
  68319. break;
  68320. }
  68321. }
  68322. template <class Iterator>
  68323. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68324. {
  68325. switch (destData.pixelFormat)
  68326. {
  68327. case Image::ARGB:
  68328. switch (srcData.pixelFormat)
  68329. {
  68330. case Image::ARGB:
  68331. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68332. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68333. break;
  68334. case Image::RGB:
  68335. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68336. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68337. break;
  68338. default:
  68339. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68340. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68341. break;
  68342. }
  68343. break;
  68344. case Image::RGB:
  68345. switch (srcData.pixelFormat)
  68346. {
  68347. case Image::ARGB:
  68348. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68349. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68350. break;
  68351. case Image::RGB:
  68352. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68353. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68354. break;
  68355. default:
  68356. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68357. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68358. break;
  68359. }
  68360. break;
  68361. default:
  68362. switch (srcData.pixelFormat)
  68363. {
  68364. case Image::ARGB:
  68365. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68366. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68367. break;
  68368. case Image::RGB:
  68369. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68370. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68371. break;
  68372. default:
  68373. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68374. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68375. break;
  68376. }
  68377. break;
  68378. }
  68379. }
  68380. template <class Iterator, class DestPixelType>
  68381. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68382. {
  68383. jassert (destData.pixelStride == sizeof (DestPixelType));
  68384. if (replaceContents)
  68385. {
  68386. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68387. iter.iterate (r);
  68388. }
  68389. else
  68390. {
  68391. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68392. iter.iterate (r);
  68393. }
  68394. }
  68395. template <class Iterator, class DestPixelType>
  68396. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68397. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68398. {
  68399. jassert (destData.pixelStride == sizeof (DestPixelType));
  68400. if (g.isRadial)
  68401. {
  68402. if (isIdentity)
  68403. {
  68404. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68405. iter.iterate (renderer);
  68406. }
  68407. else
  68408. {
  68409. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68410. iter.iterate (renderer);
  68411. }
  68412. }
  68413. else
  68414. {
  68415. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68416. iter.iterate (renderer);
  68417. }
  68418. }
  68419. };
  68420. class ClipRegion_EdgeTable : public ClipRegionBase
  68421. {
  68422. public:
  68423. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68424. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68425. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68426. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68427. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68428. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68429. ~ClipRegion_EdgeTable() {}
  68430. const Ptr clone() const
  68431. {
  68432. return new ClipRegion_EdgeTable (*this);
  68433. }
  68434. const Ptr applyClipTo (const Ptr& target) const
  68435. {
  68436. return target->clipToEdgeTable (edgeTable);
  68437. }
  68438. const Ptr clipToRectangle (const Rectangle<int>& r)
  68439. {
  68440. edgeTable.clipToRectangle (r);
  68441. return edgeTable.isEmpty() ? 0 : this;
  68442. }
  68443. const Ptr clipToRectangleList (const RectangleList& r)
  68444. {
  68445. RectangleList inverse (edgeTable.getMaximumBounds());
  68446. if (inverse.subtract (r))
  68447. for (RectangleList::Iterator iter (inverse); iter.next();)
  68448. edgeTable.excludeRectangle (*iter.getRectangle());
  68449. return edgeTable.isEmpty() ? 0 : this;
  68450. }
  68451. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68452. {
  68453. edgeTable.excludeRectangle (r);
  68454. return edgeTable.isEmpty() ? 0 : this;
  68455. }
  68456. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68457. {
  68458. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68459. edgeTable.clipToEdgeTable (et);
  68460. return edgeTable.isEmpty() ? 0 : this;
  68461. }
  68462. const Ptr clipToEdgeTable (const EdgeTable& et)
  68463. {
  68464. edgeTable.clipToEdgeTable (et);
  68465. return edgeTable.isEmpty() ? 0 : this;
  68466. }
  68467. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68468. {
  68469. const Image::BitmapData srcData (image, false);
  68470. if (transform.isOnlyTranslation())
  68471. {
  68472. // If our translation doesn't involve any distortion, just use a simple blit..
  68473. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68474. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68475. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68476. {
  68477. const int imageX = ((tx + 128) >> 8);
  68478. const int imageY = ((ty + 128) >> 8);
  68479. if (image.getFormat() == Image::ARGB)
  68480. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68481. else
  68482. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68483. return edgeTable.isEmpty() ? 0 : this;
  68484. }
  68485. }
  68486. if (transform.isSingularity())
  68487. return 0;
  68488. {
  68489. Path p;
  68490. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68491. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68492. edgeTable.clipToEdgeTable (et2);
  68493. }
  68494. if (! edgeTable.isEmpty())
  68495. {
  68496. if (image.getFormat() == Image::ARGB)
  68497. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68498. else
  68499. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68500. }
  68501. return edgeTable.isEmpty() ? 0 : this;
  68502. }
  68503. bool clipRegionIntersects (const Rectangle<int>& r) const
  68504. {
  68505. return edgeTable.getMaximumBounds().intersects (r);
  68506. }
  68507. const Rectangle<int> getClipBounds() const
  68508. {
  68509. return edgeTable.getMaximumBounds();
  68510. }
  68511. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68512. {
  68513. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68514. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68515. if (! clipped.isEmpty())
  68516. {
  68517. ClipRegion_EdgeTable et (clipped);
  68518. et.edgeTable.clipToEdgeTable (edgeTable);
  68519. et.fillAllWithColour (destData, colour, replaceContents);
  68520. }
  68521. }
  68522. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68523. {
  68524. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68525. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68526. if (! clipped.isEmpty())
  68527. {
  68528. ClipRegion_EdgeTable et (clipped);
  68529. et.edgeTable.clipToEdgeTable (edgeTable);
  68530. et.fillAllWithColour (destData, colour, false);
  68531. }
  68532. }
  68533. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68534. {
  68535. switch (destData.pixelFormat)
  68536. {
  68537. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68538. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68539. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68540. }
  68541. }
  68542. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68543. {
  68544. HeapBlock <PixelARGB> lookupTable;
  68545. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68546. jassert (numLookupEntries > 0);
  68547. switch (destData.pixelFormat)
  68548. {
  68549. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68550. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68551. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68552. }
  68553. }
  68554. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68555. {
  68556. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68557. }
  68558. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68559. {
  68560. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68561. }
  68562. EdgeTable edgeTable;
  68563. private:
  68564. template <class SrcPixelType>
  68565. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68566. {
  68567. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68568. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68569. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68570. edgeTable.getMaximumBounds().getWidth());
  68571. }
  68572. template <class SrcPixelType>
  68573. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68574. {
  68575. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68576. edgeTable.clipToRectangle (r);
  68577. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68578. for (int y = 0; y < r.getHeight(); ++y)
  68579. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68580. }
  68581. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68582. };
  68583. class ClipRegion_RectangleList : public ClipRegionBase
  68584. {
  68585. public:
  68586. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68587. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68588. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68589. ~ClipRegion_RectangleList() {}
  68590. const Ptr clone() const
  68591. {
  68592. return new ClipRegion_RectangleList (*this);
  68593. }
  68594. const Ptr applyClipTo (const Ptr& target) const
  68595. {
  68596. return target->clipToRectangleList (clip);
  68597. }
  68598. const Ptr clipToRectangle (const Rectangle<int>& r)
  68599. {
  68600. clip.clipTo (r);
  68601. return clip.isEmpty() ? 0 : this;
  68602. }
  68603. const Ptr clipToRectangleList (const RectangleList& r)
  68604. {
  68605. clip.clipTo (r);
  68606. return clip.isEmpty() ? 0 : this;
  68607. }
  68608. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68609. {
  68610. clip.subtract (r);
  68611. return clip.isEmpty() ? 0 : this;
  68612. }
  68613. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68614. {
  68615. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68616. }
  68617. const Ptr clipToEdgeTable (const EdgeTable& et)
  68618. {
  68619. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68620. }
  68621. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68622. {
  68623. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68624. }
  68625. bool clipRegionIntersects (const Rectangle<int>& r) const
  68626. {
  68627. return clip.intersects (r);
  68628. }
  68629. const Rectangle<int> getClipBounds() const
  68630. {
  68631. return clip.getBounds();
  68632. }
  68633. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68634. {
  68635. SubRectangleIterator iter (clip, area);
  68636. switch (destData.pixelFormat)
  68637. {
  68638. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68639. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68640. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68641. }
  68642. }
  68643. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68644. {
  68645. SubRectangleIteratorFloat iter (clip, area);
  68646. switch (destData.pixelFormat)
  68647. {
  68648. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68649. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68650. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68651. }
  68652. }
  68653. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68654. {
  68655. switch (destData.pixelFormat)
  68656. {
  68657. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68658. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68659. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68660. }
  68661. }
  68662. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68663. {
  68664. HeapBlock <PixelARGB> lookupTable;
  68665. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68666. jassert (numLookupEntries > 0);
  68667. switch (destData.pixelFormat)
  68668. {
  68669. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68670. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68671. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68672. }
  68673. }
  68674. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68675. {
  68676. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68677. }
  68678. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68679. {
  68680. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68681. }
  68682. RectangleList clip;
  68683. template <class Renderer>
  68684. void iterate (Renderer& r) const throw()
  68685. {
  68686. RectangleList::Iterator iter (clip);
  68687. while (iter.next())
  68688. {
  68689. const Rectangle<int> rect (*iter.getRectangle());
  68690. const int x = rect.getX();
  68691. const int w = rect.getWidth();
  68692. jassert (w > 0);
  68693. const int bottom = rect.getBottom();
  68694. for (int y = rect.getY(); y < bottom; ++y)
  68695. {
  68696. r.setEdgeTableYPos (y);
  68697. r.handleEdgeTableLineFull (x, w);
  68698. }
  68699. }
  68700. }
  68701. private:
  68702. class SubRectangleIterator
  68703. {
  68704. public:
  68705. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68706. : clip (clip_), area (area_)
  68707. {
  68708. }
  68709. template <class Renderer>
  68710. void iterate (Renderer& r) const throw()
  68711. {
  68712. RectangleList::Iterator iter (clip);
  68713. while (iter.next())
  68714. {
  68715. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68716. if (! rect.isEmpty())
  68717. {
  68718. const int x = rect.getX();
  68719. const int w = rect.getWidth();
  68720. const int bottom = rect.getBottom();
  68721. for (int y = rect.getY(); y < bottom; ++y)
  68722. {
  68723. r.setEdgeTableYPos (y);
  68724. r.handleEdgeTableLineFull (x, w);
  68725. }
  68726. }
  68727. }
  68728. }
  68729. private:
  68730. const RectangleList& clip;
  68731. const Rectangle<int> area;
  68732. SubRectangleIterator (const SubRectangleIterator&);
  68733. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68734. };
  68735. class SubRectangleIteratorFloat
  68736. {
  68737. public:
  68738. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68739. : clip (clip_), area (area_)
  68740. {
  68741. }
  68742. template <class Renderer>
  68743. void iterate (Renderer& r) const throw()
  68744. {
  68745. int left = roundToInt (area.getX() * 256.0f);
  68746. int top = roundToInt (area.getY() * 256.0f);
  68747. int right = roundToInt (area.getRight() * 256.0f);
  68748. int bottom = roundToInt (area.getBottom() * 256.0f);
  68749. int totalTop, totalLeft, totalBottom, totalRight;
  68750. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68751. if ((top >> 8) == (bottom >> 8))
  68752. {
  68753. topAlpha = bottom - top;
  68754. bottomAlpha = 0;
  68755. totalTop = top >> 8;
  68756. totalBottom = bottom = top = totalTop + 1;
  68757. }
  68758. else
  68759. {
  68760. if ((top & 255) == 0)
  68761. {
  68762. topAlpha = 0;
  68763. top = totalTop = (top >> 8);
  68764. }
  68765. else
  68766. {
  68767. topAlpha = 255 - (top & 255);
  68768. totalTop = (top >> 8);
  68769. top = totalTop + 1;
  68770. }
  68771. bottomAlpha = bottom & 255;
  68772. bottom >>= 8;
  68773. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68774. }
  68775. if ((left >> 8) == (right >> 8))
  68776. {
  68777. leftAlpha = right - left;
  68778. rightAlpha = 0;
  68779. totalLeft = (left >> 8);
  68780. totalRight = right = left = totalLeft + 1;
  68781. }
  68782. else
  68783. {
  68784. if ((left & 255) == 0)
  68785. {
  68786. leftAlpha = 0;
  68787. left = totalLeft = (left >> 8);
  68788. }
  68789. else
  68790. {
  68791. leftAlpha = 255 - (left & 255);
  68792. totalLeft = (left >> 8);
  68793. left = totalLeft + 1;
  68794. }
  68795. rightAlpha = right & 255;
  68796. right >>= 8;
  68797. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68798. }
  68799. RectangleList::Iterator iter (clip);
  68800. while (iter.next())
  68801. {
  68802. const int clipLeft = iter.getRectangle()->getX();
  68803. const int clipRight = iter.getRectangle()->getRight();
  68804. const int clipTop = iter.getRectangle()->getY();
  68805. const int clipBottom = iter.getRectangle()->getBottom();
  68806. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68807. {
  68808. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68809. {
  68810. if (topAlpha != 0 && totalTop >= clipTop)
  68811. {
  68812. r.setEdgeTableYPos (totalTop);
  68813. r.handleEdgeTablePixel (left, topAlpha);
  68814. }
  68815. const int endY = jmin (bottom, clipBottom);
  68816. for (int y = jmax (clipTop, top); y < endY; ++y)
  68817. {
  68818. r.setEdgeTableYPos (y);
  68819. r.handleEdgeTablePixelFull (left);
  68820. }
  68821. if (bottomAlpha != 0 && bottom < clipBottom)
  68822. {
  68823. r.setEdgeTableYPos (bottom);
  68824. r.handleEdgeTablePixel (left, bottomAlpha);
  68825. }
  68826. }
  68827. else
  68828. {
  68829. const int clippedLeft = jmax (left, clipLeft);
  68830. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68831. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68832. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68833. if (topAlpha != 0 && totalTop >= clipTop)
  68834. {
  68835. r.setEdgeTableYPos (totalTop);
  68836. if (doLeftAlpha)
  68837. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68838. if (clippedWidth > 0)
  68839. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68840. if (doRightAlpha)
  68841. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68842. }
  68843. const int endY = jmin (bottom, clipBottom);
  68844. for (int y = jmax (clipTop, top); y < endY; ++y)
  68845. {
  68846. r.setEdgeTableYPos (y);
  68847. if (doLeftAlpha)
  68848. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68849. if (clippedWidth > 0)
  68850. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68851. if (doRightAlpha)
  68852. r.handleEdgeTablePixel (right, rightAlpha);
  68853. }
  68854. if (bottomAlpha != 0 && bottom < clipBottom)
  68855. {
  68856. r.setEdgeTableYPos (bottom);
  68857. if (doLeftAlpha)
  68858. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68859. if (clippedWidth > 0)
  68860. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68861. if (doRightAlpha)
  68862. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68863. }
  68864. }
  68865. }
  68866. }
  68867. }
  68868. private:
  68869. const RectangleList& clip;
  68870. const Rectangle<float>& area;
  68871. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68872. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68873. };
  68874. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68875. };
  68876. }
  68877. class LowLevelGraphicsSoftwareRenderer::SavedState
  68878. {
  68879. public:
  68880. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68881. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68882. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68883. {
  68884. }
  68885. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68886. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68887. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68888. {
  68889. }
  68890. SavedState (const SavedState& other)
  68891. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68892. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68893. {
  68894. }
  68895. ~SavedState()
  68896. {
  68897. }
  68898. void setOrigin (const int x, const int y) throw()
  68899. {
  68900. xOffset += x;
  68901. yOffset += y;
  68902. }
  68903. bool clipToRectangle (const Rectangle<int>& r)
  68904. {
  68905. if (clip != 0)
  68906. {
  68907. cloneClipIfMultiplyReferenced();
  68908. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68909. }
  68910. return clip != 0;
  68911. }
  68912. bool clipToRectangleList (const RectangleList& r)
  68913. {
  68914. if (clip != 0)
  68915. {
  68916. cloneClipIfMultiplyReferenced();
  68917. RectangleList offsetList (r);
  68918. offsetList.offsetAll (xOffset, yOffset);
  68919. clip = clip->clipToRectangleList (offsetList);
  68920. }
  68921. return clip != 0;
  68922. }
  68923. bool excludeClipRectangle (const Rectangle<int>& r)
  68924. {
  68925. if (clip != 0)
  68926. {
  68927. cloneClipIfMultiplyReferenced();
  68928. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68929. }
  68930. return clip != 0;
  68931. }
  68932. void clipToPath (const Path& p, const AffineTransform& transform)
  68933. {
  68934. if (clip != 0)
  68935. {
  68936. cloneClipIfMultiplyReferenced();
  68937. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68938. }
  68939. }
  68940. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68941. {
  68942. if (clip != 0)
  68943. {
  68944. if (image.hasAlphaChannel())
  68945. {
  68946. cloneClipIfMultiplyReferenced();
  68947. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68948. interpolationQuality != Graphics::lowResamplingQuality);
  68949. }
  68950. else
  68951. {
  68952. Path p;
  68953. p.addRectangle (image.getBounds());
  68954. clipToPath (p, t);
  68955. }
  68956. }
  68957. }
  68958. bool clipRegionIntersects (const Rectangle<int>& r) const
  68959. {
  68960. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68961. }
  68962. const Rectangle<int> getClipBounds() const
  68963. {
  68964. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68965. }
  68966. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68967. {
  68968. if (clip != 0)
  68969. {
  68970. if (fillType.isColour())
  68971. {
  68972. Image::BitmapData destData (image, true);
  68973. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68974. }
  68975. else
  68976. {
  68977. const Rectangle<int> totalClip (clip->getClipBounds());
  68978. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68979. if (! clipped.isEmpty())
  68980. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68981. }
  68982. }
  68983. }
  68984. void fillRect (Image& image, const Rectangle<float>& r)
  68985. {
  68986. if (clip != 0)
  68987. {
  68988. if (fillType.isColour())
  68989. {
  68990. Image::BitmapData destData (image, true);
  68991. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68992. }
  68993. else
  68994. {
  68995. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68996. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68997. if (! clipped.isEmpty())
  68998. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68999. }
  69000. }
  69001. }
  69002. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  69003. {
  69004. if (clip != 0)
  69005. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  69006. }
  69007. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  69008. {
  69009. if (clip != 0)
  69010. {
  69011. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69012. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69013. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69014. fillShape (image, shapeToFill, false);
  69015. }
  69016. }
  69017. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69018. {
  69019. jassert (clip != 0);
  69020. shapeToFill = clip->applyClipTo (shapeToFill);
  69021. if (shapeToFill != 0)
  69022. {
  69023. Image::BitmapData destData (image, true);
  69024. if (fillType.isGradient())
  69025. {
  69026. jassert (! replaceContents); // that option is just for solid colours
  69027. ColourGradient g2 (*(fillType.gradient));
  69028. g2.multiplyOpacity (fillType.getOpacity());
  69029. g2.point1.addXY (-0.5f, -0.5f);
  69030. g2.point2.addXY (-0.5f, -0.5f);
  69031. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  69032. const bool isIdentity = transform.isOnlyTranslation();
  69033. if (isIdentity)
  69034. {
  69035. // If our translation doesn't involve any distortion, we can speed it up..
  69036. g2.point1.applyTransform (transform);
  69037. g2.point2.applyTransform (transform);
  69038. transform = AffineTransform::identity;
  69039. }
  69040. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69041. }
  69042. else if (fillType.isTiledImage())
  69043. {
  69044. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  69045. }
  69046. else
  69047. {
  69048. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69049. }
  69050. }
  69051. }
  69052. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69053. {
  69054. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  69055. const Image::BitmapData destData (destImage, true);
  69056. const Image::BitmapData srcData (sourceImage, false);
  69057. const int alpha = fillType.colour.getAlpha();
  69058. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69059. if (transform.isOnlyTranslation())
  69060. {
  69061. // If our translation doesn't involve any distortion, just use a simple blit..
  69062. int tx = (int) (transform.getTranslationX() * 256.0f);
  69063. int ty = (int) (transform.getTranslationY() * 256.0f);
  69064. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69065. {
  69066. tx = ((tx + 128) >> 8);
  69067. ty = ((ty + 128) >> 8);
  69068. if (tiledFillClipRegion != 0)
  69069. {
  69070. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69071. }
  69072. else
  69073. {
  69074. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  69075. c = clip->applyClipTo (c);
  69076. if (c != 0)
  69077. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69078. }
  69079. return;
  69080. }
  69081. }
  69082. if (transform.isSingularity())
  69083. return;
  69084. if (tiledFillClipRegion != 0)
  69085. {
  69086. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69087. }
  69088. else
  69089. {
  69090. Path p;
  69091. p.addRectangle (sourceImage.getBounds());
  69092. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69093. c = c->clipToPath (p, transform);
  69094. if (c != 0)
  69095. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69096. }
  69097. }
  69098. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69099. int xOffset, yOffset;
  69100. Font font;
  69101. FillType fillType;
  69102. Graphics::ResamplingQuality interpolationQuality;
  69103. private:
  69104. void cloneClipIfMultiplyReferenced()
  69105. {
  69106. if (clip->getReferenceCount() > 1)
  69107. clip = clip->clone();
  69108. }
  69109. SavedState& operator= (const SavedState&);
  69110. };
  69111. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69112. : image (image_)
  69113. {
  69114. currentState = new SavedState (image_.getBounds(), 0, 0);
  69115. }
  69116. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69117. const RectangleList& initialClip)
  69118. : image (image_)
  69119. {
  69120. currentState = new SavedState (initialClip, xOffset, yOffset);
  69121. }
  69122. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69123. {
  69124. }
  69125. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69126. {
  69127. return false;
  69128. }
  69129. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69130. {
  69131. currentState->setOrigin (x, y);
  69132. }
  69133. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69134. {
  69135. return currentState->clipToRectangle (r);
  69136. }
  69137. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69138. {
  69139. return currentState->clipToRectangleList (clipRegion);
  69140. }
  69141. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69142. {
  69143. currentState->excludeClipRectangle (r);
  69144. }
  69145. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69146. {
  69147. currentState->clipToPath (path, transform);
  69148. }
  69149. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69150. {
  69151. currentState->clipToImageAlpha (sourceImage, transform);
  69152. }
  69153. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69154. {
  69155. return currentState->clipRegionIntersects (r);
  69156. }
  69157. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69158. {
  69159. return currentState->getClipBounds();
  69160. }
  69161. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69162. {
  69163. return currentState->clip == 0;
  69164. }
  69165. void LowLevelGraphicsSoftwareRenderer::saveState()
  69166. {
  69167. stateStack.add (new SavedState (*currentState));
  69168. }
  69169. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69170. {
  69171. SavedState* const top = stateStack.getLast();
  69172. if (top != 0)
  69173. {
  69174. currentState = top;
  69175. stateStack.removeLast (1, false);
  69176. }
  69177. else
  69178. {
  69179. jassertfalse; // trying to pop with an empty stack!
  69180. }
  69181. }
  69182. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69183. {
  69184. currentState->fillType = fillType;
  69185. }
  69186. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69187. {
  69188. currentState->fillType.setOpacity (newOpacity);
  69189. }
  69190. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69191. {
  69192. currentState->interpolationQuality = quality;
  69193. }
  69194. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69195. {
  69196. currentState->fillRect (image, r, replaceExistingContents);
  69197. }
  69198. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69199. {
  69200. currentState->fillPath (image, path, transform);
  69201. }
  69202. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69203. {
  69204. currentState->renderImage (image, sourceImage, transform,
  69205. fillEntireClipAsTiles ? currentState->clip : 0);
  69206. }
  69207. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69208. {
  69209. Path p;
  69210. p.addLineSegment (line, 1.0f);
  69211. fillPath (p, AffineTransform::identity);
  69212. }
  69213. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69214. {
  69215. if (bottom > top)
  69216. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69217. }
  69218. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69219. {
  69220. if (right > left)
  69221. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69222. }
  69223. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69224. {
  69225. public:
  69226. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69227. ~CachedGlyph() {}
  69228. void draw (SavedState& state, Image& image, const float x, const float y) const
  69229. {
  69230. if (edgeTable != 0)
  69231. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69232. }
  69233. void generate (const Font& newFont, const int glyphNumber)
  69234. {
  69235. font = newFont;
  69236. glyph = glyphNumber;
  69237. edgeTable = 0;
  69238. Path glyphPath;
  69239. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69240. if (! glyphPath.isEmpty())
  69241. {
  69242. const float fontHeight = font.getHeight();
  69243. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69244. #if JUCE_MAC || JUCE_IOS
  69245. .translated (0.0f, -0.5f)
  69246. #endif
  69247. );
  69248. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69249. glyphPath, transform);
  69250. }
  69251. }
  69252. int glyph, lastAccessCount;
  69253. Font font;
  69254. juce_UseDebuggingNewOperator
  69255. private:
  69256. ScopedPointer <EdgeTable> edgeTable;
  69257. CachedGlyph (const CachedGlyph&);
  69258. CachedGlyph& operator= (const CachedGlyph&);
  69259. };
  69260. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69261. {
  69262. public:
  69263. GlyphCache()
  69264. : accessCounter (0), hits (0), misses (0)
  69265. {
  69266. for (int i = 120; --i >= 0;)
  69267. glyphs.add (new CachedGlyph());
  69268. }
  69269. ~GlyphCache()
  69270. {
  69271. clearSingletonInstance();
  69272. }
  69273. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69274. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69275. {
  69276. ++accessCounter;
  69277. int oldestCounter = std::numeric_limits<int>::max();
  69278. CachedGlyph* oldest = 0;
  69279. for (int i = glyphs.size(); --i >= 0;)
  69280. {
  69281. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69282. if (glyph->glyph == glyphNumber && glyph->font == font)
  69283. {
  69284. ++hits;
  69285. glyph->lastAccessCount = accessCounter;
  69286. glyph->draw (state, image, x, y);
  69287. return;
  69288. }
  69289. if (glyph->lastAccessCount <= oldestCounter)
  69290. {
  69291. oldestCounter = glyph->lastAccessCount;
  69292. oldest = glyph;
  69293. }
  69294. }
  69295. if (hits + ++misses > (glyphs.size() << 4))
  69296. {
  69297. if (misses * 2 > hits)
  69298. {
  69299. for (int i = 32; --i >= 0;)
  69300. glyphs.add (new CachedGlyph());
  69301. }
  69302. hits = misses = 0;
  69303. oldest = glyphs.getLast();
  69304. }
  69305. jassert (oldest != 0);
  69306. oldest->lastAccessCount = accessCounter;
  69307. oldest->generate (font, glyphNumber);
  69308. oldest->draw (state, image, x, y);
  69309. }
  69310. juce_UseDebuggingNewOperator
  69311. private:
  69312. friend class OwnedArray <CachedGlyph>;
  69313. OwnedArray <CachedGlyph> glyphs;
  69314. int accessCounter, hits, misses;
  69315. GlyphCache (const GlyphCache&);
  69316. GlyphCache& operator= (const GlyphCache&);
  69317. };
  69318. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69319. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69320. {
  69321. currentState->font = newFont;
  69322. }
  69323. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69324. {
  69325. return currentState->font;
  69326. }
  69327. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69328. {
  69329. Font& f = currentState->font;
  69330. if (transform.isOnlyTranslation())
  69331. {
  69332. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69333. transform.getTranslationX(),
  69334. transform.getTranslationY());
  69335. }
  69336. else
  69337. {
  69338. Path p;
  69339. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69340. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69341. }
  69342. }
  69343. #if JUCE_MSVC
  69344. #pragma warning (pop)
  69345. #if JUCE_DEBUG
  69346. #pragma optimize ("", on) // resets optimisations to the project defaults
  69347. #endif
  69348. #endif
  69349. END_JUCE_NAMESPACE
  69350. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69351. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69352. BEGIN_JUCE_NAMESPACE
  69353. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69354. : flags (other.flags)
  69355. {
  69356. }
  69357. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69358. {
  69359. flags = other.flags;
  69360. return *this;
  69361. }
  69362. void RectanglePlacement::applyTo (double& x, double& y,
  69363. double& w, double& h,
  69364. const double dx, const double dy,
  69365. const double dw, const double dh) const throw()
  69366. {
  69367. if (w == 0 || h == 0)
  69368. return;
  69369. if ((flags & stretchToFit) != 0)
  69370. {
  69371. x = dx;
  69372. y = dy;
  69373. w = dw;
  69374. h = dh;
  69375. }
  69376. else
  69377. {
  69378. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69379. : jmin (dw / w, dh / h);
  69380. if ((flags & onlyReduceInSize) != 0)
  69381. scale = jmin (scale, 1.0);
  69382. if ((flags & onlyIncreaseInSize) != 0)
  69383. scale = jmax (scale, 1.0);
  69384. w *= scale;
  69385. h *= scale;
  69386. if ((flags & xLeft) != 0)
  69387. x = dx;
  69388. else if ((flags & xRight) != 0)
  69389. x = dx + dw - w;
  69390. else
  69391. x = dx + (dw - w) * 0.5;
  69392. if ((flags & yTop) != 0)
  69393. y = dy;
  69394. else if ((flags & yBottom) != 0)
  69395. y = dy + dh - h;
  69396. else
  69397. y = dy + (dh - h) * 0.5;
  69398. }
  69399. }
  69400. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69401. {
  69402. if (source.isEmpty())
  69403. return AffineTransform::identity;
  69404. float w = source.getWidth();
  69405. float h = source.getHeight();
  69406. const float scaleX = destination.getWidth() / w;
  69407. const float scaleY = destination.getHeight() / h;
  69408. if ((flags & stretchToFit) != 0)
  69409. return AffineTransform::translation (-source.getX(), -source.getY())
  69410. .scaled (scaleX, scaleY)
  69411. .translated (destination.getX(), destination.getY());
  69412. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69413. : jmin (scaleX, scaleY);
  69414. if ((flags & onlyReduceInSize) != 0)
  69415. scale = jmin (scale, 1.0f);
  69416. if ((flags & onlyIncreaseInSize) != 0)
  69417. scale = jmax (scale, 1.0f);
  69418. w *= scale;
  69419. h *= scale;
  69420. float newX = destination.getX();
  69421. float newY = destination.getY();
  69422. if ((flags & xRight) != 0)
  69423. newX += destination.getWidth() - w; // right
  69424. else if ((flags & xLeft) == 0)
  69425. newX += (destination.getWidth() - w) / 2.0f; // centre
  69426. if ((flags & yBottom) != 0)
  69427. newY += destination.getHeight() - h; // bottom
  69428. else if ((flags & yTop) == 0)
  69429. newY += (destination.getHeight() - h) / 2.0f; // centre
  69430. return AffineTransform::translation (-source.getX(), -source.getY())
  69431. .scaled (scale, scale)
  69432. .translated (newX, newY);
  69433. }
  69434. END_JUCE_NAMESPACE
  69435. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69436. /*** Start of inlined file: juce_Drawable.cpp ***/
  69437. BEGIN_JUCE_NAMESPACE
  69438. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69439. const AffineTransform& transform_,
  69440. const float opacity_) throw()
  69441. : g (g_),
  69442. transform (transform_),
  69443. opacity (opacity_)
  69444. {
  69445. }
  69446. Drawable::Drawable()
  69447. : parent (0)
  69448. {
  69449. }
  69450. Drawable::~Drawable()
  69451. {
  69452. }
  69453. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69454. {
  69455. render (RenderingContext (g, transform, opacity));
  69456. }
  69457. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69458. {
  69459. draw (g, opacity, AffineTransform::translation (x, y));
  69460. }
  69461. void Drawable::drawWithin (Graphics& g,
  69462. const Rectangle<float>& destArea,
  69463. const RectanglePlacement& placement,
  69464. const float opacity) const
  69465. {
  69466. if (! destArea.isEmpty())
  69467. draw (g, opacity, placement.getTransformToFit (getBounds(), destArea));
  69468. }
  69469. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69470. {
  69471. Drawable* result = 0;
  69472. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69473. if (image.isValid())
  69474. {
  69475. DrawableImage* const di = new DrawableImage();
  69476. di->setImage (image);
  69477. result = di;
  69478. }
  69479. else
  69480. {
  69481. const String asString (String::createStringFromData (data, (int) numBytes));
  69482. XmlDocument doc (asString);
  69483. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69484. if (outer != 0 && outer->hasTagName ("svg"))
  69485. {
  69486. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69487. if (svg != 0)
  69488. result = Drawable::createFromSVG (*svg);
  69489. }
  69490. }
  69491. return result;
  69492. }
  69493. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69494. {
  69495. MemoryOutputStream mo;
  69496. mo.writeFromInputStream (dataSource, -1);
  69497. return createFromImageData (mo.getData(), mo.getDataSize());
  69498. }
  69499. Drawable* Drawable::createFromImageFile (const File& file)
  69500. {
  69501. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69502. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69503. }
  69504. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69505. {
  69506. return createChildFromValueTree (0, tree, imageProvider);
  69507. }
  69508. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69509. {
  69510. const Identifier type (tree.getType());
  69511. Drawable* d = 0;
  69512. if (type == DrawablePath::valueTreeType)
  69513. d = new DrawablePath();
  69514. else if (type == DrawableComposite::valueTreeType)
  69515. d = new DrawableComposite();
  69516. else if (type == DrawableRectangle::valueTreeType)
  69517. d = new DrawableRectangle();
  69518. else if (type == DrawableImage::valueTreeType)
  69519. d = new DrawableImage();
  69520. else if (type == DrawableText::valueTreeType)
  69521. d = new DrawableText();
  69522. if (d != 0)
  69523. {
  69524. d->parent = parent;
  69525. d->refreshFromValueTree (tree, imageProvider);
  69526. }
  69527. return d;
  69528. }
  69529. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69530. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69531. : state (state_)
  69532. {
  69533. }
  69534. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69535. {
  69536. }
  69537. const String Drawable::ValueTreeWrapperBase::getID() const
  69538. {
  69539. return state [idProperty];
  69540. }
  69541. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69542. {
  69543. if (newID.isEmpty())
  69544. state.removeProperty (idProperty, undoManager);
  69545. else
  69546. state.setProperty (idProperty, newID, undoManager);
  69547. }
  69548. END_JUCE_NAMESPACE
  69549. /*** End of inlined file: juce_Drawable.cpp ***/
  69550. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69551. BEGIN_JUCE_NAMESPACE
  69552. DrawableShape::DrawableShape()
  69553. : strokeType (0.0f),
  69554. mainFill (Colours::black),
  69555. strokeFill (Colours::black),
  69556. pathNeedsUpdating (true),
  69557. strokeNeedsUpdating (true)
  69558. {
  69559. }
  69560. DrawableShape::DrawableShape (const DrawableShape& other)
  69561. : strokeType (other.strokeType),
  69562. mainFill (other.mainFill),
  69563. strokeFill (other.strokeFill),
  69564. pathNeedsUpdating (true),
  69565. strokeNeedsUpdating (true)
  69566. {
  69567. }
  69568. DrawableShape::~DrawableShape()
  69569. {
  69570. }
  69571. void DrawableShape::setFill (const FillType& newFill)
  69572. {
  69573. mainFill = newFill;
  69574. }
  69575. void DrawableShape::setStrokeFill (const FillType& newFill)
  69576. {
  69577. strokeFill = newFill;
  69578. }
  69579. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69580. {
  69581. strokeType = newStrokeType;
  69582. strokeNeedsUpdating = true;
  69583. }
  69584. void DrawableShape::setStrokeThickness (const float newThickness)
  69585. {
  69586. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69587. }
  69588. bool DrawableShape::isStrokeVisible() const throw()
  69589. {
  69590. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69591. }
  69592. void DrawableShape::setBrush (const Drawable::RenderingContext& context, const FillType& type)
  69593. {
  69594. FillType f (type);
  69595. if (f.isGradient())
  69596. f.gradient->multiplyOpacity (context.opacity);
  69597. else
  69598. f.setOpacity (f.getOpacity() * context.opacity);
  69599. f.transform = f.transform.followedBy (context.transform);
  69600. context.g.setFillType (f);
  69601. }
  69602. bool DrawableShape::refreshFillTypes (const FillAndStrokeState& newState,
  69603. Expression::EvaluationContext* nameFinder,
  69604. ImageProvider* imageProvider)
  69605. {
  69606. bool hasChanged = false;
  69607. {
  69608. const FillType f (newState.getMainFill (parent, imageProvider));
  69609. if (mainFill != f)
  69610. {
  69611. hasChanged = true;
  69612. mainFill = f;
  69613. }
  69614. }
  69615. {
  69616. const FillType f (newState.getStrokeFill (parent, imageProvider));
  69617. if (strokeFill != f)
  69618. {
  69619. hasChanged = true;
  69620. strokeFill = f;
  69621. }
  69622. }
  69623. return hasChanged;
  69624. }
  69625. void DrawableShape::writeTo (FillAndStrokeState& state, ImageProvider* imageProvider, UndoManager* undoManager) const
  69626. {
  69627. state.setMainFill (mainFill, 0, 0, 0, imageProvider, undoManager);
  69628. state.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, undoManager);
  69629. state.setStrokeType (strokeType, undoManager);
  69630. }
  69631. void DrawableShape::render (const Drawable::RenderingContext& context) const
  69632. {
  69633. setBrush (context, mainFill);
  69634. context.g.fillPath (getCachedPath(), context.transform);
  69635. if (isStrokeVisible())
  69636. {
  69637. setBrush (context, strokeFill);
  69638. context.g.fillPath (getCachedStrokePath(), context.transform);
  69639. }
  69640. }
  69641. void DrawableShape::pathChanged()
  69642. {
  69643. pathNeedsUpdating = true;
  69644. }
  69645. void DrawableShape::strokeChanged()
  69646. {
  69647. strokeNeedsUpdating = true;
  69648. }
  69649. void DrawableShape::invalidatePoints()
  69650. {
  69651. pathNeedsUpdating = true;
  69652. strokeNeedsUpdating = true;
  69653. }
  69654. const Path& DrawableShape::getCachedPath() const
  69655. {
  69656. if (pathNeedsUpdating)
  69657. {
  69658. pathNeedsUpdating = false;
  69659. if (rebuildPath (cachedPath))
  69660. strokeNeedsUpdating = true;
  69661. }
  69662. return cachedPath;
  69663. }
  69664. const Path& DrawableShape::getCachedStrokePath() const
  69665. {
  69666. if (strokeNeedsUpdating)
  69667. {
  69668. cachedStroke.clear();
  69669. strokeType.createStrokedPath (cachedStroke, getCachedPath(), AffineTransform::identity, 4.0f);
  69670. strokeNeedsUpdating = false; // (must be called after getCachedPath)
  69671. }
  69672. return cachedStroke;
  69673. }
  69674. const Rectangle<float> DrawableShape::getBounds() const
  69675. {
  69676. if (isStrokeVisible())
  69677. return getCachedStrokePath().getBounds();
  69678. else
  69679. return getCachedPath().getBounds();
  69680. }
  69681. bool DrawableShape::hitTest (float x, float y) const
  69682. {
  69683. return getCachedPath().contains (x, y)
  69684. || (isStrokeVisible() && getCachedStrokePath().contains (x, y));
  69685. }
  69686. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69687. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69688. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69689. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69690. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69691. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69692. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69693. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69694. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69695. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69696. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69697. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69698. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69699. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69700. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69701. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69702. : Drawable::ValueTreeWrapperBase (state_)
  69703. {
  69704. }
  69705. const FillType DrawableShape::FillAndStrokeState::getMainFill (Expression::EvaluationContext* nameFinder,
  69706. ImageProvider* imageProvider) const
  69707. {
  69708. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69709. }
  69710. ValueTree DrawableShape::FillAndStrokeState::getMainFillState()
  69711. {
  69712. ValueTree v (state.getChildWithName (fill));
  69713. if (v.isValid())
  69714. return v;
  69715. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69716. return getMainFillState();
  69717. }
  69718. void DrawableShape::FillAndStrokeState::setMainFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69719. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69720. {
  69721. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69722. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69723. }
  69724. const FillType DrawableShape::FillAndStrokeState::getStrokeFill (Expression::EvaluationContext* nameFinder,
  69725. ImageProvider* imageProvider) const
  69726. {
  69727. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69728. }
  69729. ValueTree DrawableShape::FillAndStrokeState::getStrokeFillState()
  69730. {
  69731. ValueTree v (state.getChildWithName (stroke));
  69732. if (v.isValid())
  69733. return v;
  69734. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69735. return getStrokeFillState();
  69736. }
  69737. void DrawableShape::FillAndStrokeState::setStrokeFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69738. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69739. {
  69740. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69741. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69742. }
  69743. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69744. {
  69745. const String jointStyleString (state [jointStyle].toString());
  69746. const String capStyleString (state [capStyle].toString());
  69747. return PathStrokeType (state [strokeWidth],
  69748. jointStyleString == "curved" ? PathStrokeType::curved
  69749. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69750. : PathStrokeType::mitered),
  69751. capStyleString == "square" ? PathStrokeType::square
  69752. : (capStyleString == "round" ? PathStrokeType::rounded
  69753. : PathStrokeType::butt));
  69754. }
  69755. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69756. {
  69757. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69758. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69759. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69760. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69761. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69762. }
  69763. const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69764. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69765. {
  69766. const String newType (v[type].toString());
  69767. if (newType == "solid")
  69768. {
  69769. const String colourString (v [colour].toString());
  69770. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69771. : (uint32) colourString.getHexValue32()));
  69772. }
  69773. else if (newType == "gradient")
  69774. {
  69775. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69776. ColourGradient g;
  69777. if (gp1 != 0) *gp1 = p1;
  69778. if (gp2 != 0) *gp2 = p2;
  69779. if (gp3 != 0) *gp3 = p3;
  69780. g.point1 = p1.resolve (nameFinder);
  69781. g.point2 = p2.resolve (nameFinder);
  69782. g.isRadial = v[radial];
  69783. StringArray colourSteps;
  69784. colourSteps.addTokens (v[colours].toString(), false);
  69785. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69786. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69787. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69788. FillType fillType (g);
  69789. if (g.isRadial)
  69790. {
  69791. const Point<float> point3 (p3.resolve (nameFinder));
  69792. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69793. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69794. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69795. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69796. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69797. }
  69798. return fillType;
  69799. }
  69800. else if (newType == "image")
  69801. {
  69802. Image im;
  69803. if (imageProvider != 0)
  69804. im = imageProvider->getImageForIdentifier (v[imageId]);
  69805. FillType f (im, AffineTransform::identity);
  69806. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69807. return f;
  69808. }
  69809. jassert (! v.isValid());
  69810. return FillType();
  69811. }
  69812. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69813. {
  69814. const ColourGradient& g = *fillType.gradient;
  69815. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69816. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69817. return point3Source.transformedBy (fillType.transform);
  69818. }
  69819. void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType,
  69820. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69821. ImageProvider* imageProvider, UndoManager* const undoManager)
  69822. {
  69823. if (fillType.isColour())
  69824. {
  69825. v.setProperty (type, "solid", undoManager);
  69826. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69827. }
  69828. else if (fillType.isGradient())
  69829. {
  69830. v.setProperty (type, "gradient", undoManager);
  69831. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69832. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69833. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69834. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69835. String s;
  69836. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69837. s << ' ' << fillType.gradient->getColourPosition (i)
  69838. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69839. v.setProperty (colours, s.trimStart(), undoManager);
  69840. }
  69841. else if (fillType.isTiledImage())
  69842. {
  69843. v.setProperty (type, "image", undoManager);
  69844. if (imageProvider != 0)
  69845. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69846. if (fillType.getOpacity() < 1.0f)
  69847. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69848. else
  69849. v.removeProperty (imageOpacity, undoManager);
  69850. }
  69851. else
  69852. {
  69853. jassertfalse;
  69854. }
  69855. }
  69856. END_JUCE_NAMESPACE
  69857. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69858. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69859. BEGIN_JUCE_NAMESPACE
  69860. DrawableComposite::DrawableComposite()
  69861. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69862. {
  69863. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69864. RelativeCoordinate (100.0),
  69865. RelativeCoordinate (0.0),
  69866. RelativeCoordinate (100.0)));
  69867. }
  69868. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69869. {
  69870. bounds = other.bounds;
  69871. for (int i = 0; i < other.drawables.size(); ++i)
  69872. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69873. markersX.addCopiesOf (other.markersX);
  69874. markersY.addCopiesOf (other.markersY);
  69875. }
  69876. DrawableComposite::~DrawableComposite()
  69877. {
  69878. }
  69879. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69880. {
  69881. if (drawable != 0)
  69882. {
  69883. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69884. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69885. drawables.insert (index, drawable);
  69886. drawable->parent = this;
  69887. }
  69888. }
  69889. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69890. {
  69891. insertDrawable (drawable.createCopy(), index);
  69892. }
  69893. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69894. {
  69895. drawables.remove (index, deleteDrawable);
  69896. }
  69897. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69898. {
  69899. for (int i = drawables.size(); --i >= 0;)
  69900. if (drawables.getUnchecked(i)->getName() == name)
  69901. return drawables.getUnchecked(i);
  69902. return 0;
  69903. }
  69904. void DrawableComposite::bringToFront (const int index)
  69905. {
  69906. if (index >= 0 && index < drawables.size() - 1)
  69907. drawables.move (index, -1);
  69908. }
  69909. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69910. {
  69911. bounds = newBoundingBox;
  69912. }
  69913. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69914. : name (other.name), position (other.position)
  69915. {
  69916. }
  69917. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69918. : name (name_), position (position_)
  69919. {
  69920. }
  69921. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69922. {
  69923. return name != other.name || position != other.position;
  69924. }
  69925. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69926. const char* const DrawableComposite::contentRightMarkerName ("right");
  69927. const char* const DrawableComposite::contentTopMarkerName ("top");
  69928. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69929. const RelativeRectangle DrawableComposite::getContentArea() const
  69930. {
  69931. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69932. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69933. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69934. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69935. }
  69936. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69937. {
  69938. setMarker (contentLeftMarkerName, true, newArea.left);
  69939. setMarker (contentRightMarkerName, true, newArea.right);
  69940. setMarker (contentTopMarkerName, false, newArea.top);
  69941. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69942. }
  69943. void DrawableComposite::resetBoundingBoxToContentArea()
  69944. {
  69945. const RelativeRectangle content (getContentArea());
  69946. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69947. RelativePoint (content.right, content.top),
  69948. RelativePoint (content.left, content.bottom)));
  69949. }
  69950. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69951. {
  69952. const Rectangle<float> bounds (getUntransformedBounds (false));
  69953. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69954. RelativeCoordinate (bounds.getRight()),
  69955. RelativeCoordinate (bounds.getY()),
  69956. RelativeCoordinate (bounds.getBottom())));
  69957. resetBoundingBoxToContentArea();
  69958. }
  69959. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69960. {
  69961. return (xAxis ? markersX : markersY).size();
  69962. }
  69963. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69964. {
  69965. return (xAxis ? markersX : markersY) [index];
  69966. }
  69967. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69968. {
  69969. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69970. for (int i = 0; i < markers.size(); ++i)
  69971. {
  69972. Marker* const m = markers.getUnchecked(i);
  69973. if (m->name == name)
  69974. {
  69975. if (m->position != position)
  69976. {
  69977. m->position = position;
  69978. invalidatePoints();
  69979. }
  69980. return;
  69981. }
  69982. }
  69983. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69984. invalidatePoints();
  69985. }
  69986. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69987. {
  69988. jassert (index >= 2);
  69989. if (index >= 2)
  69990. (xAxis ? markersX : markersY).remove (index);
  69991. }
  69992. const AffineTransform DrawableComposite::calculateTransform() const
  69993. {
  69994. Point<float> resolved[3];
  69995. bounds.resolveThreePoints (resolved, parent);
  69996. const Rectangle<float> content (getContentArea().resolve (parent));
  69997. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69998. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69999. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  70000. }
  70001. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  70002. {
  70003. if (drawables.size() > 0 && context.opacity > 0)
  70004. {
  70005. if (context.opacity >= 1.0f || drawables.size() == 1)
  70006. {
  70007. Drawable::RenderingContext contextCopy (context);
  70008. contextCopy.transform = calculateTransform().followedBy (context.transform);
  70009. for (int i = 0; i < drawables.size(); ++i)
  70010. drawables.getUnchecked(i)->render (contextCopy);
  70011. }
  70012. else
  70013. {
  70014. // To correctly render a whole composite layer with an overall transparency,
  70015. // we need to render everything opaquely into a temp buffer, then blend that
  70016. // with the target opacity...
  70017. const Rectangle<int> clipBounds (context.g.getClipBounds());
  70018. if (! clipBounds.isEmpty())
  70019. {
  70020. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  70021. {
  70022. Graphics tempG (tempImage);
  70023. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  70024. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  70025. render (tempContext);
  70026. }
  70027. context.g.setOpacity (context.opacity);
  70028. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  70029. }
  70030. }
  70031. }
  70032. }
  70033. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  70034. {
  70035. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  70036. int i;
  70037. for (i = 0; i < markersX.size(); ++i)
  70038. {
  70039. Marker* const m = markersX.getUnchecked(i);
  70040. if (m->name == symbol)
  70041. return m->position.getExpression();
  70042. }
  70043. for (i = 0; i < markersY.size(); ++i)
  70044. {
  70045. Marker* const m = markersY.getUnchecked(i);
  70046. if (m->name == symbol)
  70047. return m->position.getExpression();
  70048. }
  70049. throw Expression::EvaluationError (symbol, member);
  70050. }
  70051. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  70052. {
  70053. Rectangle<float> bounds;
  70054. int i;
  70055. for (i = 0; i < drawables.size(); ++i)
  70056. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  70057. if (includeMarkers)
  70058. {
  70059. if (markersX.size() > 0)
  70060. {
  70061. float minX = std::numeric_limits<float>::max();
  70062. float maxX = std::numeric_limits<float>::min();
  70063. for (i = markersX.size(); --i >= 0;)
  70064. {
  70065. const Marker* m = markersX.getUnchecked(i);
  70066. const float pos = (float) m->position.resolve (this);
  70067. minX = jmin (minX, pos);
  70068. maxX = jmax (maxX, pos);
  70069. }
  70070. if (minX <= maxX)
  70071. {
  70072. if (bounds.getHeight() > 0)
  70073. {
  70074. minX = jmin (minX, bounds.getX());
  70075. maxX = jmax (maxX, bounds.getRight());
  70076. }
  70077. bounds.setLeft (minX);
  70078. bounds.setWidth (maxX - minX);
  70079. }
  70080. }
  70081. if (markersY.size() > 0)
  70082. {
  70083. float minY = std::numeric_limits<float>::max();
  70084. float maxY = std::numeric_limits<float>::min();
  70085. for (i = markersY.size(); --i >= 0;)
  70086. {
  70087. const Marker* m = markersY.getUnchecked(i);
  70088. const float pos = (float) m->position.resolve (this);
  70089. minY = jmin (minY, pos);
  70090. maxY = jmax (maxY, pos);
  70091. }
  70092. if (minY <= maxY)
  70093. {
  70094. if (bounds.getHeight() > 0)
  70095. {
  70096. minY = jmin (minY, bounds.getY());
  70097. maxY = jmax (maxY, bounds.getBottom());
  70098. }
  70099. bounds.setTop (minY);
  70100. bounds.setHeight (maxY - minY);
  70101. }
  70102. }
  70103. }
  70104. return bounds;
  70105. }
  70106. const Rectangle<float> DrawableComposite::getBounds() const
  70107. {
  70108. return getUntransformedBounds (true).transformed (calculateTransform());
  70109. }
  70110. bool DrawableComposite::hitTest (float x, float y) const
  70111. {
  70112. calculateTransform().inverted().transformPoint (x, y);
  70113. for (int i = 0; i < drawables.size(); ++i)
  70114. if (drawables.getUnchecked(i)->hitTest (x, y))
  70115. return true;
  70116. return false;
  70117. }
  70118. Drawable* DrawableComposite::createCopy() const
  70119. {
  70120. return new DrawableComposite (*this);
  70121. }
  70122. void DrawableComposite::invalidatePoints()
  70123. {
  70124. for (int i = 0; i < drawables.size(); ++i)
  70125. drawables.getUnchecked(i)->invalidatePoints();
  70126. }
  70127. const Identifier DrawableComposite::valueTreeType ("Group");
  70128. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70129. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70130. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70131. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70132. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70133. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70134. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  70135. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  70136. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  70137. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70138. : ValueTreeWrapperBase (state_)
  70139. {
  70140. jassert (state.hasType (valueTreeType));
  70141. }
  70142. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70143. {
  70144. return state.getChildWithName (childGroupTag);
  70145. }
  70146. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70147. {
  70148. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70149. }
  70150. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  70151. {
  70152. return getChildList().getNumChildren();
  70153. }
  70154. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  70155. {
  70156. return getChildList().getChild (index);
  70157. }
  70158. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  70159. {
  70160. if (getID() == objectId)
  70161. return state;
  70162. if (! recursive)
  70163. {
  70164. return getChildList().getChildWithProperty (idProperty, objectId);
  70165. }
  70166. else
  70167. {
  70168. const ValueTree childList (getChildList());
  70169. for (int i = getNumDrawables(); --i >= 0;)
  70170. {
  70171. const ValueTree& child = childList.getChild (i);
  70172. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  70173. return child;
  70174. if (child.hasType (DrawableComposite::valueTreeType))
  70175. {
  70176. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  70177. if (v.isValid())
  70178. return v;
  70179. }
  70180. }
  70181. return ValueTree::invalid;
  70182. }
  70183. }
  70184. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  70185. {
  70186. return getChildList().indexOf (item);
  70187. }
  70188. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  70189. {
  70190. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  70191. }
  70192. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  70193. {
  70194. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  70195. }
  70196. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  70197. {
  70198. getChildList().removeChild (child, undoManager);
  70199. }
  70200. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70201. {
  70202. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70203. state.getProperty (topRight, "100, 0"),
  70204. state.getProperty (bottomLeft, "0, 100"));
  70205. }
  70206. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70207. {
  70208. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70209. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70210. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70211. }
  70212. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70213. {
  70214. const RelativeRectangle content (getContentArea());
  70215. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70216. RelativePoint (content.right, content.top),
  70217. RelativePoint (content.left, content.bottom)), undoManager);
  70218. }
  70219. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70220. {
  70221. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  70222. getMarker (true, getMarkerState (true, 1)).position,
  70223. getMarker (false, getMarkerState (false, 0)).position,
  70224. getMarker (false, getMarkerState (false, 1)).position);
  70225. }
  70226. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70227. {
  70228. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70229. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70230. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70231. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70232. }
  70233. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70234. {
  70235. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70236. }
  70237. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70238. {
  70239. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70240. }
  70241. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70242. {
  70243. return getMarkerList (xAxis).getNumChildren();
  70244. }
  70245. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70246. {
  70247. return getMarkerList (xAxis).getChild (index);
  70248. }
  70249. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70250. {
  70251. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70252. }
  70253. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70254. {
  70255. return state.isAChildOf (getMarkerList (xAxis));
  70256. }
  70257. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70258. {
  70259. (void) xAxis;
  70260. jassert (containsMarker (xAxis, state));
  70261. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70262. }
  70263. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70264. {
  70265. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70266. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70267. if (marker.isValid())
  70268. {
  70269. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70270. }
  70271. else
  70272. {
  70273. marker = ValueTree (markerTag);
  70274. marker.setProperty (nameProperty, m.name, 0);
  70275. marker.setProperty (posProperty, m.position.toString(), 0);
  70276. markerList.addChild (marker, -1, undoManager);
  70277. }
  70278. }
  70279. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70280. {
  70281. if (state [nameProperty].toString() != contentLeftMarkerName
  70282. && state [nameProperty].toString() != contentRightMarkerName
  70283. && state [nameProperty].toString() != contentTopMarkerName
  70284. && state [nameProperty].toString() != contentBottomMarkerName)
  70285. return getMarkerList (xAxis).removeChild (state, undoManager);
  70286. }
  70287. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70288. {
  70289. const ValueTreeWrapper wrapper (tree);
  70290. setName (wrapper.getID());
  70291. Rectangle<float> damage;
  70292. bool redrawAll = false;
  70293. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70294. if (bounds != newBounds)
  70295. {
  70296. redrawAll = true;
  70297. damage = getBounds();
  70298. bounds = newBounds;
  70299. }
  70300. const int numMarkersX = wrapper.getNumMarkers (true);
  70301. const int numMarkersY = wrapper.getNumMarkers (false);
  70302. // Remove deleted markers...
  70303. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70304. {
  70305. if (! redrawAll)
  70306. {
  70307. redrawAll = true;
  70308. damage = getBounds();
  70309. }
  70310. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70311. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70312. }
  70313. // Update markers and add new ones..
  70314. int i;
  70315. for (i = 0; i < numMarkersX; ++i)
  70316. {
  70317. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70318. Marker* m = markersX[i];
  70319. if (m == 0 || newMarker != *m)
  70320. {
  70321. if (! redrawAll)
  70322. {
  70323. redrawAll = true;
  70324. damage = getBounds();
  70325. }
  70326. if (m == 0)
  70327. markersX.add (new Marker (newMarker));
  70328. else
  70329. *m = newMarker;
  70330. }
  70331. }
  70332. for (i = 0; i < numMarkersY; ++i)
  70333. {
  70334. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70335. Marker* m = markersY[i];
  70336. if (m == 0 || newMarker != *m)
  70337. {
  70338. if (! redrawAll)
  70339. {
  70340. redrawAll = true;
  70341. damage = getBounds();
  70342. }
  70343. if (m == 0)
  70344. markersY.add (new Marker (newMarker));
  70345. else
  70346. *m = newMarker;
  70347. }
  70348. }
  70349. // Remove deleted drawables..
  70350. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70351. {
  70352. Drawable* const d = drawables.getUnchecked(i);
  70353. if (! redrawAll)
  70354. damage = damage.getUnion (d->getBounds());
  70355. d->parent = 0;
  70356. drawables.remove (i);
  70357. }
  70358. // Update drawables and add new ones..
  70359. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70360. {
  70361. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70362. Drawable* d = drawables[i];
  70363. if (d != 0)
  70364. {
  70365. if (newDrawable.hasType (d->getValueTreeType()))
  70366. {
  70367. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70368. if (! redrawAll)
  70369. damage = damage.getUnion (area);
  70370. }
  70371. else
  70372. {
  70373. if (! redrawAll)
  70374. damage = damage.getUnion (d->getBounds());
  70375. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70376. drawables.set (i, d);
  70377. if (! redrawAll)
  70378. damage = damage.getUnion (d->getBounds());
  70379. }
  70380. }
  70381. else
  70382. {
  70383. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70384. drawables.set (i, d);
  70385. if (! redrawAll)
  70386. damage = damage.getUnion (d->getBounds());
  70387. }
  70388. }
  70389. if (redrawAll)
  70390. damage = damage.getUnion (getBounds());
  70391. else if (! damage.isEmpty())
  70392. damage = damage.transformed (calculateTransform());
  70393. return damage;
  70394. }
  70395. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70396. {
  70397. ValueTree tree (valueTreeType);
  70398. ValueTreeWrapper v (tree);
  70399. v.setID (getName(), 0);
  70400. v.setBoundingBox (bounds, 0);
  70401. int i;
  70402. for (i = 0; i < drawables.size(); ++i)
  70403. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70404. for (i = 0; i < markersX.size(); ++i)
  70405. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70406. for (i = 0; i < markersY.size(); ++i)
  70407. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70408. return tree;
  70409. }
  70410. END_JUCE_NAMESPACE
  70411. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70412. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70413. BEGIN_JUCE_NAMESPACE
  70414. DrawableImage::DrawableImage()
  70415. : image (0),
  70416. opacity (1.0f),
  70417. overlayColour (0x00000000)
  70418. {
  70419. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70420. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70421. }
  70422. DrawableImage::DrawableImage (const DrawableImage& other)
  70423. : image (other.image),
  70424. opacity (other.opacity),
  70425. overlayColour (other.overlayColour),
  70426. bounds (other.bounds)
  70427. {
  70428. }
  70429. DrawableImage::~DrawableImage()
  70430. {
  70431. }
  70432. void DrawableImage::setImage (const Image& imageToUse)
  70433. {
  70434. image = imageToUse;
  70435. if (image.isValid())
  70436. {
  70437. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70438. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70439. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70440. }
  70441. }
  70442. void DrawableImage::setOpacity (const float newOpacity)
  70443. {
  70444. opacity = newOpacity;
  70445. }
  70446. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70447. {
  70448. overlayColour = newOverlayColour;
  70449. }
  70450. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70451. {
  70452. bounds = newBounds;
  70453. }
  70454. const AffineTransform DrawableImage::calculateTransform() const
  70455. {
  70456. if (image.isNull())
  70457. return AffineTransform::identity;
  70458. Point<float> resolved[3];
  70459. bounds.resolveThreePoints (resolved, parent);
  70460. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70461. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70462. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70463. tr.getX(), tr.getY(),
  70464. bl.getX(), bl.getY());
  70465. }
  70466. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70467. {
  70468. if (image.isValid())
  70469. {
  70470. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70471. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70472. {
  70473. context.g.setOpacity (context.opacity * opacity);
  70474. context.g.drawImageTransformed (image, t, false);
  70475. }
  70476. if (! overlayColour.isTransparent())
  70477. {
  70478. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70479. context.g.drawImageTransformed (image, t, true);
  70480. }
  70481. }
  70482. }
  70483. const Rectangle<float> DrawableImage::getBounds() const
  70484. {
  70485. if (image.isNull())
  70486. return Rectangle<float>();
  70487. return bounds.getBounds (parent);
  70488. }
  70489. bool DrawableImage::hitTest (float x, float y) const
  70490. {
  70491. if (image.isNull())
  70492. return false;
  70493. calculateTransform().inverted().transformPoint (x, y);
  70494. const int ix = roundToInt (x);
  70495. const int iy = roundToInt (y);
  70496. return ix >= 0
  70497. && iy >= 0
  70498. && ix < image.getWidth()
  70499. && iy < image.getHeight()
  70500. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70501. }
  70502. Drawable* DrawableImage::createCopy() const
  70503. {
  70504. return new DrawableImage (*this);
  70505. }
  70506. void DrawableImage::invalidatePoints()
  70507. {
  70508. }
  70509. const Identifier DrawableImage::valueTreeType ("Image");
  70510. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70511. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70512. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70513. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70514. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70515. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70516. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70517. : ValueTreeWrapperBase (state_)
  70518. {
  70519. jassert (state.hasType (valueTreeType));
  70520. }
  70521. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70522. {
  70523. return state [image];
  70524. }
  70525. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70526. {
  70527. return state.getPropertyAsValue (image, undoManager);
  70528. }
  70529. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70530. {
  70531. state.setProperty (image, newIdentifier, undoManager);
  70532. }
  70533. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70534. {
  70535. return (float) state.getProperty (opacity, 1.0);
  70536. }
  70537. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70538. {
  70539. if (! state.hasProperty (opacity))
  70540. state.setProperty (opacity, 1.0, undoManager);
  70541. return state.getPropertyAsValue (opacity, undoManager);
  70542. }
  70543. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70544. {
  70545. state.setProperty (opacity, newOpacity, undoManager);
  70546. }
  70547. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70548. {
  70549. return Colour (state [overlay].toString().getHexValue32());
  70550. }
  70551. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70552. {
  70553. if (newColour.isTransparent())
  70554. state.removeProperty (overlay, undoManager);
  70555. else
  70556. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70557. }
  70558. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70559. {
  70560. return state.getPropertyAsValue (overlay, undoManager);
  70561. }
  70562. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70563. {
  70564. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70565. state.getProperty (topRight, "100, 0"),
  70566. state.getProperty (bottomLeft, "0, 100"));
  70567. }
  70568. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70569. {
  70570. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70571. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70572. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70573. }
  70574. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70575. {
  70576. const ValueTreeWrapper controller (tree);
  70577. setName (controller.getID());
  70578. const float newOpacity = controller.getOpacity();
  70579. const Colour newOverlayColour (controller.getOverlayColour());
  70580. Image newImage;
  70581. const var imageIdentifier (controller.getImageIdentifier());
  70582. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70583. if (imageProvider != 0)
  70584. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70585. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70586. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70587. {
  70588. const Rectangle<float> damage (getBounds());
  70589. opacity = newOpacity;
  70590. overlayColour = newOverlayColour;
  70591. bounds = newBounds;
  70592. image = newImage;
  70593. return damage.getUnion (getBounds());
  70594. }
  70595. return Rectangle<float>();
  70596. }
  70597. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70598. {
  70599. ValueTree tree (valueTreeType);
  70600. ValueTreeWrapper v (tree);
  70601. v.setID (getName(), 0);
  70602. v.setOpacity (opacity, 0);
  70603. v.setOverlayColour (overlayColour, 0);
  70604. v.setBoundingBox (bounds, 0);
  70605. if (image.isValid())
  70606. {
  70607. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70608. if (imageProvider != 0)
  70609. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70610. }
  70611. return tree;
  70612. }
  70613. END_JUCE_NAMESPACE
  70614. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70615. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70616. BEGIN_JUCE_NAMESPACE
  70617. DrawablePath::DrawablePath()
  70618. {
  70619. }
  70620. DrawablePath::DrawablePath (const DrawablePath& other)
  70621. : DrawableShape (other)
  70622. {
  70623. if (other.relativePath != 0)
  70624. relativePath = new RelativePointPath (*other.relativePath);
  70625. else
  70626. cachedPath = other.cachedPath;
  70627. }
  70628. DrawablePath::~DrawablePath()
  70629. {
  70630. }
  70631. Drawable* DrawablePath::createCopy() const
  70632. {
  70633. return new DrawablePath (*this);
  70634. }
  70635. void DrawablePath::setPath (const Path& newPath)
  70636. {
  70637. cachedPath = newPath;
  70638. strokeChanged();
  70639. }
  70640. const Path& DrawablePath::getPath() const
  70641. {
  70642. return getCachedPath();
  70643. }
  70644. const Path& DrawablePath::getStrokePath() const
  70645. {
  70646. return getCachedStrokePath();
  70647. }
  70648. bool DrawablePath::rebuildPath (Path& path) const
  70649. {
  70650. if (relativePath != 0)
  70651. {
  70652. path.clear();
  70653. relativePath->createPath (path, parent);
  70654. return true;
  70655. }
  70656. return false;
  70657. }
  70658. const Identifier DrawablePath::valueTreeType ("Path");
  70659. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70660. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70661. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70662. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70663. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70664. : FillAndStrokeState (state_)
  70665. {
  70666. jassert (state.hasType (valueTreeType));
  70667. }
  70668. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70669. {
  70670. return state.getOrCreateChildWithName (path, 0);
  70671. }
  70672. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70673. {
  70674. return state [nonZeroWinding];
  70675. }
  70676. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70677. {
  70678. state.setProperty (nonZeroWinding, b, undoManager);
  70679. }
  70680. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70681. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70682. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70683. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70684. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70685. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70686. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70687. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70688. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70689. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70690. : state (state_)
  70691. {
  70692. }
  70693. DrawablePath::ValueTreeWrapper::Element::~Element()
  70694. {
  70695. }
  70696. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70697. {
  70698. return ValueTreeWrapper (state.getParent().getParent());
  70699. }
  70700. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70701. {
  70702. return Element (state.getSibling (-1));
  70703. }
  70704. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70705. {
  70706. const Identifier i (state.getType());
  70707. if (i == startSubPathElement || i == lineToElement) return 1;
  70708. if (i == quadraticToElement) return 2;
  70709. if (i == cubicToElement) return 3;
  70710. return 0;
  70711. }
  70712. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70713. {
  70714. jassert (index >= 0 && index < getNumControlPoints());
  70715. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70716. }
  70717. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70718. {
  70719. jassert (index >= 0 && index < getNumControlPoints());
  70720. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70721. }
  70722. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70723. {
  70724. jassert (index >= 0 && index < getNumControlPoints());
  70725. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70726. }
  70727. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70728. {
  70729. const Identifier i (state.getType());
  70730. if (i == startSubPathElement)
  70731. return getControlPoint (0);
  70732. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70733. return getPreviousElement().getEndPoint();
  70734. }
  70735. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70736. {
  70737. const Identifier i (state.getType());
  70738. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70739. if (i == quadraticToElement) return getControlPoint (1);
  70740. if (i == cubicToElement) return getControlPoint (2);
  70741. jassert (i == closeSubPathElement);
  70742. return RelativePoint();
  70743. }
  70744. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70745. {
  70746. const Identifier i (state.getType());
  70747. if (i == lineToElement || i == closeSubPathElement)
  70748. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70749. if (i == cubicToElement)
  70750. {
  70751. Path p;
  70752. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70753. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70754. return p.getLength();
  70755. }
  70756. if (i == quadraticToElement)
  70757. {
  70758. Path p;
  70759. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70760. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70761. return p.getLength();
  70762. }
  70763. jassert (i == startSubPathElement);
  70764. return 0;
  70765. }
  70766. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70767. {
  70768. return state [mode].toString();
  70769. }
  70770. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70771. {
  70772. if (state.hasType (cubicToElement))
  70773. state.setProperty (mode, newMode, undoManager);
  70774. }
  70775. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70776. {
  70777. const Identifier i (state.getType());
  70778. if (i == quadraticToElement || i == cubicToElement)
  70779. {
  70780. ValueTree newState (lineToElement);
  70781. Element e (newState);
  70782. e.setControlPoint (0, getEndPoint(), undoManager);
  70783. state = newState;
  70784. }
  70785. }
  70786. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70787. {
  70788. const Identifier i (state.getType());
  70789. if (i == lineToElement || i == quadraticToElement)
  70790. {
  70791. ValueTree newState (cubicToElement);
  70792. Element e (newState);
  70793. const RelativePoint start (getStartPoint());
  70794. const RelativePoint end (getEndPoint());
  70795. const Point<float> startResolved (start.resolve (nameFinder));
  70796. const Point<float> endResolved (end.resolve (nameFinder));
  70797. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70798. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70799. e.setControlPoint (2, end, undoManager);
  70800. state = newState;
  70801. }
  70802. }
  70803. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70804. {
  70805. const Identifier i (state.getType());
  70806. if (i != startSubPathElement)
  70807. {
  70808. ValueTree newState (startSubPathElement);
  70809. Element e (newState);
  70810. e.setControlPoint (0, getEndPoint(), undoManager);
  70811. state = newState;
  70812. }
  70813. }
  70814. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70815. {
  70816. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70817. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70818. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70819. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70820. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70821. return newCp1 + (newCp2 - newCp1) * proportion;
  70822. }
  70823. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70824. {
  70825. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70826. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70827. return mid1 + (mid2 - mid1) * proportion;
  70828. }
  70829. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70830. {
  70831. const Identifier i (state.getType());
  70832. float bestProp = 0;
  70833. if (i == cubicToElement)
  70834. {
  70835. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70836. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70837. float bestDistance = std::numeric_limits<float>::max();
  70838. for (int i = 110; --i >= 0;)
  70839. {
  70840. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70841. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70842. const float distance = centre.getDistanceFrom (targetPoint);
  70843. if (distance < bestDistance)
  70844. {
  70845. bestProp = prop;
  70846. bestDistance = distance;
  70847. }
  70848. }
  70849. }
  70850. else if (i == quadraticToElement)
  70851. {
  70852. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70853. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70854. float bestDistance = std::numeric_limits<float>::max();
  70855. for (int i = 110; --i >= 0;)
  70856. {
  70857. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70858. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70859. const float distance = centre.getDistanceFrom (targetPoint);
  70860. if (distance < bestDistance)
  70861. {
  70862. bestProp = prop;
  70863. bestDistance = distance;
  70864. }
  70865. }
  70866. }
  70867. else if (i == lineToElement)
  70868. {
  70869. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70870. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70871. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70872. }
  70873. return bestProp;
  70874. }
  70875. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70876. {
  70877. ValueTree newTree;
  70878. const Identifier i (state.getType());
  70879. if (i == cubicToElement)
  70880. {
  70881. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70882. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70883. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70884. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70885. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70886. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70887. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70888. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70889. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70890. setControlPoint (0, mid1, undoManager);
  70891. setControlPoint (1, newCp1, undoManager);
  70892. setControlPoint (2, newCentre, undoManager);
  70893. setModeOfEndPoint (roundedMode, undoManager);
  70894. Element newElement (newTree = ValueTree (cubicToElement));
  70895. newElement.setControlPoint (0, newCp2, 0);
  70896. newElement.setControlPoint (1, mid3, 0);
  70897. newElement.setControlPoint (2, rp4, 0);
  70898. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70899. }
  70900. else if (i == quadraticToElement)
  70901. {
  70902. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70903. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70904. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70905. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70906. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70907. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70908. setControlPoint (0, mid1, undoManager);
  70909. setControlPoint (1, newCentre, undoManager);
  70910. setModeOfEndPoint (roundedMode, undoManager);
  70911. Element newElement (newTree = ValueTree (quadraticToElement));
  70912. newElement.setControlPoint (0, mid2, 0);
  70913. newElement.setControlPoint (1, rp3, 0);
  70914. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70915. }
  70916. else if (i == lineToElement)
  70917. {
  70918. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70919. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70920. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70921. setControlPoint (0, newPoint, undoManager);
  70922. Element newElement (newTree = ValueTree (lineToElement));
  70923. newElement.setControlPoint (0, rp2, 0);
  70924. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70925. }
  70926. else if (i == closeSubPathElement)
  70927. {
  70928. }
  70929. return newTree;
  70930. }
  70931. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70932. {
  70933. state.getParent().removeChild (state, undoManager);
  70934. }
  70935. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70936. {
  70937. Rectangle<float> damageRect;
  70938. ValueTreeWrapper v (tree);
  70939. setName (v.getID());
  70940. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  70941. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70942. Path newPath;
  70943. newRelativePath->createPath (newPath, parent);
  70944. if (! newRelativePath->containsAnyDynamicPoints())
  70945. newRelativePath = 0;
  70946. const PathStrokeType newStroke (v.getStrokeType());
  70947. if (strokeType != newStroke || cachedPath != newPath)
  70948. {
  70949. damageRect = getBounds();
  70950. cachedPath.swapWithPath (newPath);
  70951. strokeChanged();
  70952. strokeType = newStroke;
  70953. needsRedraw = true;
  70954. }
  70955. relativePath = newRelativePath;
  70956. if (needsRedraw)
  70957. damageRect = damageRect.getUnion (getBounds());
  70958. return damageRect;
  70959. }
  70960. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70961. {
  70962. ValueTree tree (valueTreeType);
  70963. ValueTreeWrapper v (tree);
  70964. v.setID (getName(), 0);
  70965. writeTo (v, imageProvider, 0);
  70966. if (relativePath != 0)
  70967. {
  70968. relativePath->writeTo (tree, 0);
  70969. }
  70970. else
  70971. {
  70972. RelativePointPath rp (getCachedPath());
  70973. rp.writeTo (tree, 0);
  70974. }
  70975. return tree;
  70976. }
  70977. END_JUCE_NAMESPACE
  70978. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70979. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70980. BEGIN_JUCE_NAMESPACE
  70981. DrawableRectangle::DrawableRectangle()
  70982. {
  70983. }
  70984. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70985. : DrawableShape (other)
  70986. {
  70987. }
  70988. DrawableRectangle::~DrawableRectangle()
  70989. {
  70990. }
  70991. Drawable* DrawableRectangle::createCopy() const
  70992. {
  70993. return new DrawableRectangle (*this);
  70994. }
  70995. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70996. {
  70997. bounds = newBounds;
  70998. pathChanged();
  70999. strokeChanged();
  71000. }
  71001. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  71002. {
  71003. cornerSize = newSize;
  71004. pathChanged();
  71005. strokeChanged();
  71006. }
  71007. bool DrawableRectangle::rebuildPath (Path& path) const
  71008. {
  71009. Point<float> points[3];
  71010. bounds.resolveThreePoints (points, parent);
  71011. const float w = Line<float> (points[0], points[1]).getLength();
  71012. const float h = Line<float> (points[0], points[2]).getLength();
  71013. const float cornerSizeX = cornerSize.x.resolve (parent);
  71014. const float cornerSizeY = cornerSize.y.resolve (parent);
  71015. path.clear();
  71016. if (cornerSizeX > 0 && cornerSizeY > 0)
  71017. path.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  71018. else
  71019. path.addRectangle (0, 0, w, h);
  71020. path.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71021. w, 0, points[1].getX(), points[1].getY(),
  71022. 0, h, points[2].getX(), points[2].getY()));
  71023. return true;
  71024. }
  71025. const AffineTransform DrawableRectangle::calculateTransform() const
  71026. {
  71027. Point<float> resolved[3];
  71028. bounds.resolveThreePoints (resolved, parent);
  71029. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  71030. resolved[1].getX(), resolved[1].getY(),
  71031. resolved[2].getX(), resolved[2].getY());
  71032. }
  71033. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  71034. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  71035. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  71036. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71037. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  71038. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71039. : FillAndStrokeState (state_)
  71040. {
  71041. jassert (state.hasType (valueTreeType));
  71042. }
  71043. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  71044. {
  71045. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  71046. state.getProperty (topRight, "100, 0"),
  71047. state.getProperty (bottomLeft, "0, 100"));
  71048. }
  71049. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71050. {
  71051. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71052. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71053. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71054. }
  71055. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  71056. {
  71057. state.setProperty (cornerSize, newSize.toString(), undoManager);
  71058. }
  71059. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  71060. {
  71061. return RelativePoint (state [cornerSize]);
  71062. }
  71063. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  71064. {
  71065. return state.getPropertyAsValue (cornerSize, undoManager);
  71066. }
  71067. const Rectangle<float> DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  71068. {
  71069. Rectangle<float> damageRect;
  71070. ValueTreeWrapper v (tree);
  71071. setName (v.getID());
  71072. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  71073. RelativeParallelogram newBounds (v.getRectangle());
  71074. const PathStrokeType newStroke (v.getStrokeType());
  71075. const RelativePoint newCornerSize (v.getCornerSize());
  71076. if (strokeType != newStroke || newBounds != bounds || newCornerSize != cornerSize)
  71077. {
  71078. damageRect = getBounds();
  71079. bounds = newBounds;
  71080. strokeType = newStroke;
  71081. cornerSize = newCornerSize;
  71082. pathChanged();
  71083. strokeChanged();
  71084. needsRedraw = true;
  71085. }
  71086. if (needsRedraw)
  71087. damageRect = damageRect.getUnion (getBounds());
  71088. return damageRect;
  71089. }
  71090. const ValueTree DrawableRectangle::createValueTree (ImageProvider* imageProvider) const
  71091. {
  71092. ValueTree tree (valueTreeType);
  71093. ValueTreeWrapper v (tree);
  71094. v.setID (getName(), 0);
  71095. writeTo (v, imageProvider, 0);
  71096. v.setRectangle (bounds, 0);
  71097. v.setCornerSize (cornerSize, 0);
  71098. return tree;
  71099. }
  71100. END_JUCE_NAMESPACE
  71101. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  71102. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71103. BEGIN_JUCE_NAMESPACE
  71104. DrawableText::DrawableText()
  71105. : colour (Colours::black),
  71106. justification (Justification::centredLeft)
  71107. {
  71108. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71109. RelativePoint (50.0f, 0.0f),
  71110. RelativePoint (0.0f, 20.0f)));
  71111. setFont (Font (15.0f), true);
  71112. }
  71113. DrawableText::DrawableText (const DrawableText& other)
  71114. : bounds (other.bounds),
  71115. fontSizeControlPoint (other.fontSizeControlPoint),
  71116. font (other.font),
  71117. text (other.text),
  71118. colour (other.colour),
  71119. justification (other.justification)
  71120. {
  71121. }
  71122. DrawableText::~DrawableText()
  71123. {
  71124. }
  71125. void DrawableText::setText (const String& newText)
  71126. {
  71127. text = newText;
  71128. }
  71129. void DrawableText::setColour (const Colour& newColour)
  71130. {
  71131. colour = newColour;
  71132. }
  71133. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71134. {
  71135. font = newFont;
  71136. if (applySizeAndScale)
  71137. {
  71138. Point<float> corners[3];
  71139. bounds.resolveThreePoints (corners, parent);
  71140. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  71141. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71142. }
  71143. }
  71144. void DrawableText::setJustification (const Justification& newJustification)
  71145. {
  71146. justification = newJustification;
  71147. }
  71148. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71149. {
  71150. bounds = newBounds;
  71151. }
  71152. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71153. {
  71154. fontSizeControlPoint = newPoint;
  71155. }
  71156. void DrawableText::render (const Drawable::RenderingContext& context) const
  71157. {
  71158. Point<float> points[3];
  71159. bounds.resolveThreePoints (points, parent);
  71160. const float w = Line<float> (points[0], points[1]).getLength();
  71161. const float h = Line<float> (points[0], points[2]).getLength();
  71162. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  71163. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71164. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71165. Font f (font);
  71166. f.setHeight (fontHeight);
  71167. f.setHorizontalScale (fontWidth / fontHeight);
  71168. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  71169. GlyphArrangement ga;
  71170. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  71171. ga.draw (context.g,
  71172. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71173. w, 0, points[1].getX(), points[1].getY(),
  71174. 0, h, points[2].getX(), points[2].getY())
  71175. .followedBy (context.transform));
  71176. }
  71177. const Rectangle<float> DrawableText::getBounds() const
  71178. {
  71179. return bounds.getBounds (parent);
  71180. }
  71181. bool DrawableText::hitTest (float x, float y) const
  71182. {
  71183. Path p;
  71184. bounds.getPath (p, parent);
  71185. return p.contains (x, y);
  71186. }
  71187. Drawable* DrawableText::createCopy() const
  71188. {
  71189. return new DrawableText (*this);
  71190. }
  71191. void DrawableText::invalidatePoints()
  71192. {
  71193. }
  71194. const Identifier DrawableText::valueTreeType ("Text");
  71195. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71196. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71197. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71198. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71199. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71200. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71201. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71202. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71203. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71204. : ValueTreeWrapperBase (state_)
  71205. {
  71206. jassert (state.hasType (valueTreeType));
  71207. }
  71208. const String DrawableText::ValueTreeWrapper::getText() const
  71209. {
  71210. return state [text].toString();
  71211. }
  71212. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71213. {
  71214. state.setProperty (text, newText, undoManager);
  71215. }
  71216. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71217. {
  71218. return state.getPropertyAsValue (text, undoManager);
  71219. }
  71220. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71221. {
  71222. return Colour::fromString (state [colour].toString());
  71223. }
  71224. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71225. {
  71226. state.setProperty (colour, newColour.toString(), undoManager);
  71227. }
  71228. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71229. {
  71230. return Justification ((int) state [justification]);
  71231. }
  71232. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71233. {
  71234. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71235. }
  71236. const Font DrawableText::ValueTreeWrapper::getFont() const
  71237. {
  71238. return Font::fromString (state [font]);
  71239. }
  71240. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71241. {
  71242. state.setProperty (font, newFont.toString(), undoManager);
  71243. }
  71244. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71245. {
  71246. return state.getPropertyAsValue (font, undoManager);
  71247. }
  71248. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71249. {
  71250. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71251. }
  71252. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71253. {
  71254. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71255. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71256. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71257. }
  71258. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71259. {
  71260. return state [fontSizeAnchor].toString();
  71261. }
  71262. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71263. {
  71264. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71265. }
  71266. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71267. {
  71268. ValueTreeWrapper v (tree);
  71269. setName (v.getID());
  71270. const RelativeParallelogram newBounds (v.getBoundingBox());
  71271. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71272. const Colour newColour (v.getColour());
  71273. const Justification newJustification (v.getJustification());
  71274. const String newText (v.getText());
  71275. const Font newFont (v.getFont());
  71276. if (text != newText || font != newFont || justification != newJustification
  71277. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71278. {
  71279. const Rectangle<float> damage (getBounds());
  71280. setBoundingBox (newBounds);
  71281. setFontSizeControlPoint (newFontPoint);
  71282. setColour (newColour);
  71283. setFont (newFont, false);
  71284. setJustification (newJustification);
  71285. setText (newText);
  71286. return damage.getUnion (getBounds());
  71287. }
  71288. return Rectangle<float>();
  71289. }
  71290. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71291. {
  71292. ValueTree tree (valueTreeType);
  71293. ValueTreeWrapper v (tree);
  71294. v.setID (getName(), 0);
  71295. v.setText (text, 0);
  71296. v.setFont (font, 0);
  71297. v.setJustification (justification, 0);
  71298. v.setColour (colour, 0);
  71299. v.setBoundingBox (bounds, 0);
  71300. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71301. return tree;
  71302. }
  71303. END_JUCE_NAMESPACE
  71304. /*** End of inlined file: juce_DrawableText.cpp ***/
  71305. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71306. BEGIN_JUCE_NAMESPACE
  71307. class SVGState
  71308. {
  71309. public:
  71310. SVGState (const XmlElement* const topLevel)
  71311. : topLevelXml (topLevel),
  71312. elementX (0), elementY (0),
  71313. width (512), height (512),
  71314. viewBoxW (0), viewBoxH (0)
  71315. {
  71316. }
  71317. ~SVGState()
  71318. {
  71319. }
  71320. Drawable* parseSVGElement (const XmlElement& xml)
  71321. {
  71322. if (! xml.hasTagName ("svg"))
  71323. return 0;
  71324. DrawableComposite* const drawable = new DrawableComposite();
  71325. drawable->setName (xml.getStringAttribute ("id"));
  71326. SVGState newState (*this);
  71327. if (xml.hasAttribute ("transform"))
  71328. newState.addTransform (xml);
  71329. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71330. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71331. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71332. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71333. if (xml.hasAttribute ("viewBox"))
  71334. {
  71335. const String viewParams (xml.getStringAttribute ("viewBox"));
  71336. int i = 0;
  71337. float vx, vy, vw, vh;
  71338. if (parseCoords (viewParams, vx, vy, i, true)
  71339. && parseCoords (viewParams, vw, vh, i, true)
  71340. && vw > 0
  71341. && vh > 0)
  71342. {
  71343. newState.viewBoxW = vw;
  71344. newState.viewBoxH = vh;
  71345. int placementFlags = 0;
  71346. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71347. if (aspect.containsIgnoreCase ("none"))
  71348. {
  71349. placementFlags = RectanglePlacement::stretchToFit;
  71350. }
  71351. else
  71352. {
  71353. if (aspect.containsIgnoreCase ("slice"))
  71354. placementFlags |= RectanglePlacement::fillDestination;
  71355. if (aspect.containsIgnoreCase ("xMin"))
  71356. placementFlags |= RectanglePlacement::xLeft;
  71357. else if (aspect.containsIgnoreCase ("xMax"))
  71358. placementFlags |= RectanglePlacement::xRight;
  71359. else
  71360. placementFlags |= RectanglePlacement::xMid;
  71361. if (aspect.containsIgnoreCase ("yMin"))
  71362. placementFlags |= RectanglePlacement::yTop;
  71363. else if (aspect.containsIgnoreCase ("yMax"))
  71364. placementFlags |= RectanglePlacement::yBottom;
  71365. else
  71366. placementFlags |= RectanglePlacement::yMid;
  71367. }
  71368. const RectanglePlacement placement (placementFlags);
  71369. newState.transform
  71370. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71371. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71372. .followedBy (newState.transform);
  71373. }
  71374. }
  71375. else
  71376. {
  71377. if (viewBoxW == 0)
  71378. newState.viewBoxW = newState.width;
  71379. if (viewBoxH == 0)
  71380. newState.viewBoxH = newState.height;
  71381. }
  71382. newState.parseSubElements (xml, drawable);
  71383. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71384. return drawable;
  71385. }
  71386. private:
  71387. const XmlElement* const topLevelXml;
  71388. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71389. AffineTransform transform;
  71390. String cssStyleText;
  71391. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71392. {
  71393. forEachXmlChildElement (xml, e)
  71394. {
  71395. Drawable* d = 0;
  71396. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71397. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71398. else if (e->hasTagName ("path")) d = parsePath (*e);
  71399. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71400. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71401. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71402. else if (e->hasTagName ("line")) d = parseLine (*e);
  71403. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71404. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71405. else if (e->hasTagName ("text")) d = parseText (*e);
  71406. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71407. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71408. parentDrawable->insertDrawable (d);
  71409. }
  71410. }
  71411. DrawableComposite* parseSwitch (const XmlElement& xml)
  71412. {
  71413. const XmlElement* const group = xml.getChildByName ("g");
  71414. if (group != 0)
  71415. return parseGroupElement (*group);
  71416. return 0;
  71417. }
  71418. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71419. {
  71420. DrawableComposite* const drawable = new DrawableComposite();
  71421. drawable->setName (xml.getStringAttribute ("id"));
  71422. if (xml.hasAttribute ("transform"))
  71423. {
  71424. SVGState newState (*this);
  71425. newState.addTransform (xml);
  71426. newState.parseSubElements (xml, drawable);
  71427. }
  71428. else
  71429. {
  71430. parseSubElements (xml, drawable);
  71431. }
  71432. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71433. return drawable;
  71434. }
  71435. Drawable* parsePath (const XmlElement& xml) const
  71436. {
  71437. const String d (xml.getStringAttribute ("d").trimStart());
  71438. Path path;
  71439. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71440. path.setUsingNonZeroWinding (false);
  71441. int index = 0;
  71442. float lastX = 0, lastY = 0;
  71443. float lastX2 = 0, lastY2 = 0;
  71444. juce_wchar lastCommandChar = 0;
  71445. bool isRelative = true;
  71446. bool carryOn = true;
  71447. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71448. while (d[index] != 0)
  71449. {
  71450. float x, y, x2, y2, x3, y3;
  71451. if (validCommandChars.containsChar (d[index]))
  71452. {
  71453. lastCommandChar = d [index++];
  71454. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71455. }
  71456. switch (lastCommandChar)
  71457. {
  71458. case 'M':
  71459. case 'm':
  71460. case 'L':
  71461. case 'l':
  71462. if (parseCoords (d, x, y, index, false))
  71463. {
  71464. if (isRelative)
  71465. {
  71466. x += lastX;
  71467. y += lastY;
  71468. }
  71469. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71470. {
  71471. path.startNewSubPath (x, y);
  71472. lastCommandChar = 'l';
  71473. }
  71474. else
  71475. path.lineTo (x, y);
  71476. lastX2 = lastX;
  71477. lastY2 = lastY;
  71478. lastX = x;
  71479. lastY = y;
  71480. }
  71481. else
  71482. {
  71483. ++index;
  71484. }
  71485. break;
  71486. case 'H':
  71487. case 'h':
  71488. if (parseCoord (d, x, index, false, true))
  71489. {
  71490. if (isRelative)
  71491. x += lastX;
  71492. path.lineTo (x, lastY);
  71493. lastX2 = lastX;
  71494. lastX = x;
  71495. }
  71496. else
  71497. {
  71498. ++index;
  71499. }
  71500. break;
  71501. case 'V':
  71502. case 'v':
  71503. if (parseCoord (d, y, index, false, false))
  71504. {
  71505. if (isRelative)
  71506. y += lastY;
  71507. path.lineTo (lastX, y);
  71508. lastY2 = lastY;
  71509. lastY = y;
  71510. }
  71511. else
  71512. {
  71513. ++index;
  71514. }
  71515. break;
  71516. case 'C':
  71517. case 'c':
  71518. if (parseCoords (d, x, y, index, false)
  71519. && parseCoords (d, x2, y2, index, false)
  71520. && parseCoords (d, x3, y3, index, false))
  71521. {
  71522. if (isRelative)
  71523. {
  71524. x += lastX;
  71525. y += lastY;
  71526. x2 += lastX;
  71527. y2 += lastY;
  71528. x3 += lastX;
  71529. y3 += lastY;
  71530. }
  71531. path.cubicTo (x, y, x2, y2, x3, y3);
  71532. lastX2 = x2;
  71533. lastY2 = y2;
  71534. lastX = x3;
  71535. lastY = y3;
  71536. }
  71537. else
  71538. {
  71539. ++index;
  71540. }
  71541. break;
  71542. case 'S':
  71543. case 's':
  71544. if (parseCoords (d, x, y, index, false)
  71545. && parseCoords (d, x3, y3, index, false))
  71546. {
  71547. if (isRelative)
  71548. {
  71549. x += lastX;
  71550. y += lastY;
  71551. x3 += lastX;
  71552. y3 += lastY;
  71553. }
  71554. x2 = lastX + (lastX - lastX2);
  71555. y2 = lastY + (lastY - lastY2);
  71556. path.cubicTo (x2, y2, x, y, x3, y3);
  71557. lastX2 = x;
  71558. lastY2 = y;
  71559. lastX = x3;
  71560. lastY = y3;
  71561. }
  71562. else
  71563. {
  71564. ++index;
  71565. }
  71566. break;
  71567. case 'Q':
  71568. case 'q':
  71569. if (parseCoords (d, x, y, index, false)
  71570. && parseCoords (d, x2, y2, index, false))
  71571. {
  71572. if (isRelative)
  71573. {
  71574. x += lastX;
  71575. y += lastY;
  71576. x2 += lastX;
  71577. y2 += lastY;
  71578. }
  71579. path.quadraticTo (x, y, x2, y2);
  71580. lastX2 = x;
  71581. lastY2 = y;
  71582. lastX = x2;
  71583. lastY = y2;
  71584. }
  71585. else
  71586. {
  71587. ++index;
  71588. }
  71589. break;
  71590. case 'T':
  71591. case 't':
  71592. if (parseCoords (d, x, y, index, false))
  71593. {
  71594. if (isRelative)
  71595. {
  71596. x += lastX;
  71597. y += lastY;
  71598. }
  71599. x2 = lastX + (lastX - lastX2);
  71600. y2 = lastY + (lastY - lastY2);
  71601. path.quadraticTo (x2, y2, x, y);
  71602. lastX2 = x2;
  71603. lastY2 = y2;
  71604. lastX = x;
  71605. lastY = y;
  71606. }
  71607. else
  71608. {
  71609. ++index;
  71610. }
  71611. break;
  71612. case 'A':
  71613. case 'a':
  71614. if (parseCoords (d, x, y, index, false))
  71615. {
  71616. String num;
  71617. if (parseNextNumber (d, num, index, false))
  71618. {
  71619. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71620. if (parseNextNumber (d, num, index, false))
  71621. {
  71622. const bool largeArc = num.getIntValue() != 0;
  71623. if (parseNextNumber (d, num, index, false))
  71624. {
  71625. const bool sweep = num.getIntValue() != 0;
  71626. if (parseCoords (d, x2, y2, index, false))
  71627. {
  71628. if (isRelative)
  71629. {
  71630. x2 += lastX;
  71631. y2 += lastY;
  71632. }
  71633. if (lastX != x2 || lastY != y2)
  71634. {
  71635. double centreX, centreY, startAngle, deltaAngle;
  71636. double rx = x, ry = y;
  71637. endpointToCentreParameters (lastX, lastY, x2, y2,
  71638. angle, largeArc, sweep,
  71639. rx, ry, centreX, centreY,
  71640. startAngle, deltaAngle);
  71641. path.addCentredArc ((float) centreX, (float) centreY,
  71642. (float) rx, (float) ry,
  71643. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71644. false);
  71645. path.lineTo (x2, y2);
  71646. }
  71647. lastX2 = lastX;
  71648. lastY2 = lastY;
  71649. lastX = x2;
  71650. lastY = y2;
  71651. }
  71652. }
  71653. }
  71654. }
  71655. }
  71656. else
  71657. {
  71658. ++index;
  71659. }
  71660. break;
  71661. case 'Z':
  71662. case 'z':
  71663. path.closeSubPath();
  71664. while (CharacterFunctions::isWhitespace (d [index]))
  71665. ++index;
  71666. break;
  71667. default:
  71668. carryOn = false;
  71669. break;
  71670. }
  71671. if (! carryOn)
  71672. break;
  71673. }
  71674. return parseShape (xml, path);
  71675. }
  71676. Drawable* parseRect (const XmlElement& xml) const
  71677. {
  71678. Path rect;
  71679. const bool hasRX = xml.hasAttribute ("rx");
  71680. const bool hasRY = xml.hasAttribute ("ry");
  71681. if (hasRX || hasRY)
  71682. {
  71683. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71684. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71685. if (! hasRX)
  71686. rx = ry;
  71687. else if (! hasRY)
  71688. ry = rx;
  71689. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71690. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71691. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71692. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71693. rx, ry);
  71694. }
  71695. else
  71696. {
  71697. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71698. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71699. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71700. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71701. }
  71702. return parseShape (xml, rect);
  71703. }
  71704. Drawable* parseCircle (const XmlElement& xml) const
  71705. {
  71706. Path circle;
  71707. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71708. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71709. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71710. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71711. return parseShape (xml, circle);
  71712. }
  71713. Drawable* parseEllipse (const XmlElement& xml) const
  71714. {
  71715. Path ellipse;
  71716. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71717. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71718. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71719. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71720. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71721. return parseShape (xml, ellipse);
  71722. }
  71723. Drawable* parseLine (const XmlElement& xml) const
  71724. {
  71725. Path line;
  71726. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71727. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71728. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71729. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71730. line.startNewSubPath (x1, y1);
  71731. line.lineTo (x2, y2);
  71732. return parseShape (xml, line);
  71733. }
  71734. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71735. {
  71736. const String points (xml.getStringAttribute ("points"));
  71737. Path path;
  71738. int index = 0;
  71739. float x, y;
  71740. if (parseCoords (points, x, y, index, true))
  71741. {
  71742. float firstX = x;
  71743. float firstY = y;
  71744. float lastX = 0, lastY = 0;
  71745. path.startNewSubPath (x, y);
  71746. while (parseCoords (points, x, y, index, true))
  71747. {
  71748. lastX = x;
  71749. lastY = y;
  71750. path.lineTo (x, y);
  71751. }
  71752. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71753. path.closeSubPath();
  71754. }
  71755. return parseShape (xml, path);
  71756. }
  71757. Drawable* parseShape (const XmlElement& xml, Path& path,
  71758. const bool shouldParseTransform = true) const
  71759. {
  71760. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71761. {
  71762. SVGState newState (*this);
  71763. newState.addTransform (xml);
  71764. return newState.parseShape (xml, path, false);
  71765. }
  71766. DrawablePath* dp = new DrawablePath();
  71767. dp->setName (xml.getStringAttribute ("id"));
  71768. dp->setFill (Colours::transparentBlack);
  71769. path.applyTransform (transform);
  71770. dp->setPath (path);
  71771. Path::Iterator iter (path);
  71772. bool containsClosedSubPath = false;
  71773. while (iter.next())
  71774. {
  71775. if (iter.elementType == Path::Iterator::closePath)
  71776. {
  71777. containsClosedSubPath = true;
  71778. break;
  71779. }
  71780. }
  71781. dp->setFill (getPathFillType (path,
  71782. getStyleAttribute (&xml, "fill"),
  71783. getStyleAttribute (&xml, "fill-opacity"),
  71784. getStyleAttribute (&xml, "opacity"),
  71785. containsClosedSubPath ? Colours::black
  71786. : Colours::transparentBlack));
  71787. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71788. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71789. {
  71790. dp->setStrokeFill (getPathFillType (path, strokeType,
  71791. getStyleAttribute (&xml, "stroke-opacity"),
  71792. getStyleAttribute (&xml, "opacity"),
  71793. Colours::transparentBlack));
  71794. dp->setStrokeType (getStrokeFor (&xml));
  71795. }
  71796. return dp;
  71797. }
  71798. const XmlElement* findLinkedElement (const XmlElement* e) const
  71799. {
  71800. const String id (e->getStringAttribute ("xlink:href"));
  71801. if (! id.startsWithChar ('#'))
  71802. return 0;
  71803. return findElementForId (topLevelXml, id.substring (1));
  71804. }
  71805. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71806. {
  71807. if (fillXml == 0)
  71808. return;
  71809. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71810. {
  71811. int index = 0;
  71812. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71813. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71814. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71815. double offset = e->getDoubleAttribute ("offset");
  71816. if (e->getStringAttribute ("offset").containsChar ('%'))
  71817. offset *= 0.01;
  71818. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71819. }
  71820. }
  71821. const FillType getPathFillType (const Path& path,
  71822. const String& fill,
  71823. const String& fillOpacity,
  71824. const String& overallOpacity,
  71825. const Colour& defaultColour) const
  71826. {
  71827. float opacity = 1.0f;
  71828. if (overallOpacity.isNotEmpty())
  71829. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71830. if (fillOpacity.isNotEmpty())
  71831. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71832. if (fill.startsWithIgnoreCase ("url"))
  71833. {
  71834. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71835. .upToLastOccurrenceOf (")", false, false).trim());
  71836. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71837. if (fillXml != 0
  71838. && (fillXml->hasTagName ("linearGradient")
  71839. || fillXml->hasTagName ("radialGradient")))
  71840. {
  71841. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71842. ColourGradient gradient;
  71843. addGradientStopsIn (gradient, inheritedFrom);
  71844. addGradientStopsIn (gradient, fillXml);
  71845. if (gradient.getNumColours() > 0)
  71846. {
  71847. gradient.addColour (0.0, gradient.getColour (0));
  71848. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71849. }
  71850. else
  71851. {
  71852. gradient.addColour (0.0, Colours::black);
  71853. gradient.addColour (1.0, Colours::black);
  71854. }
  71855. if (overallOpacity.isNotEmpty())
  71856. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71857. jassert (gradient.getNumColours() > 0);
  71858. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71859. float gradientWidth = viewBoxW;
  71860. float gradientHeight = viewBoxH;
  71861. float dx = 0.0f;
  71862. float dy = 0.0f;
  71863. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71864. if (! userSpace)
  71865. {
  71866. const Rectangle<float> bounds (path.getBounds());
  71867. dx = bounds.getX();
  71868. dy = bounds.getY();
  71869. gradientWidth = bounds.getWidth();
  71870. gradientHeight = bounds.getHeight();
  71871. }
  71872. if (gradient.isRadial)
  71873. {
  71874. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71875. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71876. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71877. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71878. //xxx (the fx, fy focal point isn't handled properly here..)
  71879. }
  71880. else
  71881. {
  71882. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71883. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71884. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71885. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71886. if (gradient.point1 == gradient.point2)
  71887. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71888. }
  71889. FillType type (gradient);
  71890. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71891. .followedBy (transform);
  71892. return type;
  71893. }
  71894. }
  71895. if (fill.equalsIgnoreCase ("none"))
  71896. return Colours::transparentBlack;
  71897. int i = 0;
  71898. const Colour colour (parseColour (fill, i, defaultColour));
  71899. return colour.withMultipliedAlpha (opacity);
  71900. }
  71901. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71902. {
  71903. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71904. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71905. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71906. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71907. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71908. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71909. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71910. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71911. if (join.equalsIgnoreCase ("round"))
  71912. joinStyle = PathStrokeType::curved;
  71913. else if (join.equalsIgnoreCase ("bevel"))
  71914. joinStyle = PathStrokeType::beveled;
  71915. if (cap.equalsIgnoreCase ("round"))
  71916. capStyle = PathStrokeType::rounded;
  71917. else if (cap.equalsIgnoreCase ("square"))
  71918. capStyle = PathStrokeType::square;
  71919. float ox = 0.0f, oy = 0.0f;
  71920. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71921. transform.transformPoints (ox, oy, x, y);
  71922. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71923. joinStyle, capStyle);
  71924. }
  71925. Drawable* parseText (const XmlElement& xml)
  71926. {
  71927. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71928. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71929. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71930. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71931. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71932. //xxx not done text yet!
  71933. forEachXmlChildElement (xml, e)
  71934. {
  71935. if (e->isTextElement())
  71936. {
  71937. const String text (e->getText());
  71938. Path path;
  71939. Drawable* s = parseShape (*e, path);
  71940. delete s; // xxx not finished!
  71941. }
  71942. else if (e->hasTagName ("tspan"))
  71943. {
  71944. Drawable* s = parseText (*e);
  71945. delete s; // xxx not finished!
  71946. }
  71947. }
  71948. return 0;
  71949. }
  71950. void addTransform (const XmlElement& xml)
  71951. {
  71952. transform = parseTransform (xml.getStringAttribute ("transform"))
  71953. .followedBy (transform);
  71954. }
  71955. bool parseCoord (const String& s, float& value, int& index,
  71956. const bool allowUnits, const bool isX) const
  71957. {
  71958. String number;
  71959. if (! parseNextNumber (s, number, index, allowUnits))
  71960. {
  71961. value = 0;
  71962. return false;
  71963. }
  71964. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71965. return true;
  71966. }
  71967. bool parseCoords (const String& s, float& x, float& y,
  71968. int& index, const bool allowUnits) const
  71969. {
  71970. return parseCoord (s, x, index, allowUnits, true)
  71971. && parseCoord (s, y, index, allowUnits, false);
  71972. }
  71973. float getCoordLength (const String& s, const float sizeForProportions) const
  71974. {
  71975. float n = s.getFloatValue();
  71976. const int len = s.length();
  71977. if (len > 2)
  71978. {
  71979. const float dpi = 96.0f;
  71980. const juce_wchar n1 = s [len - 2];
  71981. const juce_wchar n2 = s [len - 1];
  71982. if (n1 == 'i' && n2 == 'n')
  71983. n *= dpi;
  71984. else if (n1 == 'm' && n2 == 'm')
  71985. n *= dpi / 25.4f;
  71986. else if (n1 == 'c' && n2 == 'm')
  71987. n *= dpi / 2.54f;
  71988. else if (n1 == 'p' && n2 == 'c')
  71989. n *= 15.0f;
  71990. else if (n2 == '%')
  71991. n *= 0.01f * sizeForProportions;
  71992. }
  71993. return n;
  71994. }
  71995. void getCoordList (Array <float>& coords, const String& list,
  71996. const bool allowUnits, const bool isX) const
  71997. {
  71998. int index = 0;
  71999. float value;
  72000. while (parseCoord (list, value, index, allowUnits, isX))
  72001. coords.add (value);
  72002. }
  72003. void parseCSSStyle (const XmlElement& xml)
  72004. {
  72005. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  72006. }
  72007. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  72008. const String& defaultValue = String::empty) const
  72009. {
  72010. if (xml->hasAttribute (attributeName))
  72011. return xml->getStringAttribute (attributeName, defaultValue);
  72012. const String styleAtt (xml->getStringAttribute ("style"));
  72013. if (styleAtt.isNotEmpty())
  72014. {
  72015. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  72016. if (value.isNotEmpty())
  72017. return value;
  72018. }
  72019. else if (xml->hasAttribute ("class"))
  72020. {
  72021. const String className ("." + xml->getStringAttribute ("class"));
  72022. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  72023. if (index < 0)
  72024. index = cssStyleText.indexOfIgnoreCase (className + "{");
  72025. if (index >= 0)
  72026. {
  72027. const int openBracket = cssStyleText.indexOfChar (index, '{');
  72028. if (openBracket > index)
  72029. {
  72030. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  72031. if (closeBracket > openBracket)
  72032. {
  72033. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  72034. if (value.isNotEmpty())
  72035. return value;
  72036. }
  72037. }
  72038. }
  72039. }
  72040. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72041. if (xml != 0)
  72042. return getStyleAttribute (xml, attributeName, defaultValue);
  72043. return defaultValue;
  72044. }
  72045. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72046. {
  72047. if (xml->hasAttribute (attributeName))
  72048. return xml->getStringAttribute (attributeName);
  72049. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72050. if (xml != 0)
  72051. return getInheritedAttribute (xml, attributeName);
  72052. return String::empty;
  72053. }
  72054. static bool isIdentifierChar (const juce_wchar c)
  72055. {
  72056. return CharacterFunctions::isLetter (c) || c == '-';
  72057. }
  72058. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72059. {
  72060. int i = 0;
  72061. for (;;)
  72062. {
  72063. i = list.indexOf (i, attributeName);
  72064. if (i < 0)
  72065. break;
  72066. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72067. && ! isIdentifierChar (list [i + attributeName.length()]))
  72068. {
  72069. i = list.indexOfChar (i, ':');
  72070. if (i < 0)
  72071. break;
  72072. int end = list.indexOfChar (i, ';');
  72073. if (end < 0)
  72074. end = 0x7ffff;
  72075. return list.substring (i + 1, end).trim();
  72076. }
  72077. ++i;
  72078. }
  72079. return defaultValue;
  72080. }
  72081. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  72082. {
  72083. const juce_wchar* const s = source;
  72084. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72085. ++index;
  72086. int start = index;
  72087. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  72088. ++index;
  72089. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  72090. ++index;
  72091. if ((s[index] == 'e' || s[index] == 'E')
  72092. && (CharacterFunctions::isDigit (s[index + 1])
  72093. || s[index + 1] == '-'
  72094. || s[index + 1] == '+'))
  72095. {
  72096. index += 2;
  72097. while (CharacterFunctions::isDigit (s[index]))
  72098. ++index;
  72099. }
  72100. if (allowUnits)
  72101. {
  72102. while (CharacterFunctions::isLetter (s[index]))
  72103. ++index;
  72104. }
  72105. if (index == start)
  72106. return false;
  72107. value = String (s + start, index - start);
  72108. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72109. ++index;
  72110. return true;
  72111. }
  72112. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72113. {
  72114. if (s [index] == '#')
  72115. {
  72116. uint32 hex [6];
  72117. zeromem (hex, sizeof (hex));
  72118. int numChars = 0;
  72119. for (int i = 6; --i >= 0;)
  72120. {
  72121. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72122. if (hexValue >= 0)
  72123. hex [numChars++] = hexValue;
  72124. else
  72125. break;
  72126. }
  72127. if (numChars <= 3)
  72128. return Colour ((uint8) (hex [0] * 0x11),
  72129. (uint8) (hex [1] * 0x11),
  72130. (uint8) (hex [2] * 0x11));
  72131. else
  72132. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72133. (uint8) ((hex [2] << 4) + hex [3]),
  72134. (uint8) ((hex [4] << 4) + hex [5]));
  72135. }
  72136. else if (s [index] == 'r'
  72137. && s [index + 1] == 'g'
  72138. && s [index + 2] == 'b')
  72139. {
  72140. const int openBracket = s.indexOfChar (index, '(');
  72141. const int closeBracket = s.indexOfChar (openBracket, ')');
  72142. if (openBracket >= 3 && closeBracket > openBracket)
  72143. {
  72144. index = closeBracket;
  72145. StringArray tokens;
  72146. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72147. tokens.trim();
  72148. tokens.removeEmptyStrings();
  72149. if (tokens[0].containsChar ('%'))
  72150. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72151. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72152. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72153. else
  72154. return Colour ((uint8) tokens[0].getIntValue(),
  72155. (uint8) tokens[1].getIntValue(),
  72156. (uint8) tokens[2].getIntValue());
  72157. }
  72158. }
  72159. return Colours::findColourForName (s, defaultColour);
  72160. }
  72161. static const AffineTransform parseTransform (String t)
  72162. {
  72163. AffineTransform result;
  72164. while (t.isNotEmpty())
  72165. {
  72166. StringArray tokens;
  72167. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72168. .upToFirstOccurrenceOf (")", false, false),
  72169. ", ", String::empty);
  72170. tokens.removeEmptyStrings (true);
  72171. float numbers [6];
  72172. for (int i = 0; i < 6; ++i)
  72173. numbers[i] = tokens[i].getFloatValue();
  72174. AffineTransform trans;
  72175. if (t.startsWithIgnoreCase ("matrix"))
  72176. {
  72177. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72178. numbers[1], numbers[3], numbers[5]);
  72179. }
  72180. else if (t.startsWithIgnoreCase ("translate"))
  72181. {
  72182. jassert (tokens.size() == 2);
  72183. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72184. }
  72185. else if (t.startsWithIgnoreCase ("scale"))
  72186. {
  72187. if (tokens.size() == 1)
  72188. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72189. else
  72190. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72191. }
  72192. else if (t.startsWithIgnoreCase ("rotate"))
  72193. {
  72194. if (tokens.size() != 3)
  72195. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72196. else
  72197. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72198. numbers[1], numbers[2]);
  72199. }
  72200. else if (t.startsWithIgnoreCase ("skewX"))
  72201. {
  72202. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72203. 0.0f, 1.0f, 0.0f);
  72204. }
  72205. else if (t.startsWithIgnoreCase ("skewY"))
  72206. {
  72207. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72208. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72209. }
  72210. result = trans.followedBy (result);
  72211. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72212. }
  72213. return result;
  72214. }
  72215. static void endpointToCentreParameters (const double x1, const double y1,
  72216. const double x2, const double y2,
  72217. const double angle,
  72218. const bool largeArc, const bool sweep,
  72219. double& rx, double& ry,
  72220. double& centreX, double& centreY,
  72221. double& startAngle, double& deltaAngle)
  72222. {
  72223. const double midX = (x1 - x2) * 0.5;
  72224. const double midY = (y1 - y2) * 0.5;
  72225. const double cosAngle = cos (angle);
  72226. const double sinAngle = sin (angle);
  72227. const double xp = cosAngle * midX + sinAngle * midY;
  72228. const double yp = cosAngle * midY - sinAngle * midX;
  72229. const double xp2 = xp * xp;
  72230. const double yp2 = yp * yp;
  72231. double rx2 = rx * rx;
  72232. double ry2 = ry * ry;
  72233. const double s = (xp2 / rx2) + (yp2 / ry2);
  72234. double c;
  72235. if (s <= 1.0)
  72236. {
  72237. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72238. / (( rx2 * yp2) + (ry2 * xp2))));
  72239. if (largeArc == sweep)
  72240. c = -c;
  72241. }
  72242. else
  72243. {
  72244. const double s2 = std::sqrt (s);
  72245. rx *= s2;
  72246. ry *= s2;
  72247. rx2 = rx * rx;
  72248. ry2 = ry * ry;
  72249. c = 0;
  72250. }
  72251. const double cpx = ((rx * yp) / ry) * c;
  72252. const double cpy = ((-ry * xp) / rx) * c;
  72253. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72254. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72255. const double ux = (xp - cpx) / rx;
  72256. const double uy = (yp - cpy) / ry;
  72257. const double vx = (-xp - cpx) / rx;
  72258. const double vy = (-yp - cpy) / ry;
  72259. const double length = juce_hypot (ux, uy);
  72260. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72261. if (uy < 0)
  72262. startAngle = -startAngle;
  72263. startAngle += double_Pi * 0.5;
  72264. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72265. / (length * juce_hypot (vx, vy))));
  72266. if ((ux * vy) - (uy * vx) < 0)
  72267. deltaAngle = -deltaAngle;
  72268. if (sweep)
  72269. {
  72270. if (deltaAngle < 0)
  72271. deltaAngle += double_Pi * 2.0;
  72272. }
  72273. else
  72274. {
  72275. if (deltaAngle > 0)
  72276. deltaAngle -= double_Pi * 2.0;
  72277. }
  72278. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72279. }
  72280. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72281. {
  72282. forEachXmlChildElement (*parent, e)
  72283. {
  72284. if (e->compareAttribute ("id", id))
  72285. return e;
  72286. const XmlElement* const found = findElementForId (e, id);
  72287. if (found != 0)
  72288. return found;
  72289. }
  72290. return 0;
  72291. }
  72292. SVGState& operator= (const SVGState&);
  72293. };
  72294. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72295. {
  72296. SVGState state (&svgDocument);
  72297. return state.parseSVGElement (svgDocument);
  72298. }
  72299. END_JUCE_NAMESPACE
  72300. /*** End of inlined file: juce_SVGParser.cpp ***/
  72301. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72302. BEGIN_JUCE_NAMESPACE
  72303. #if JUCE_MSVC && JUCE_DEBUG
  72304. #pragma optimize ("t", on)
  72305. #endif
  72306. DropShadowEffect::DropShadowEffect()
  72307. : offsetX (0),
  72308. offsetY (0),
  72309. radius (4),
  72310. opacity (0.6f)
  72311. {
  72312. }
  72313. DropShadowEffect::~DropShadowEffect()
  72314. {
  72315. }
  72316. void DropShadowEffect::setShadowProperties (const float newRadius,
  72317. const float newOpacity,
  72318. const int newShadowOffsetX,
  72319. const int newShadowOffsetY)
  72320. {
  72321. radius = jmax (1.1f, newRadius);
  72322. offsetX = newShadowOffsetX;
  72323. offsetY = newShadowOffsetY;
  72324. opacity = newOpacity;
  72325. }
  72326. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72327. {
  72328. const int w = image.getWidth();
  72329. const int h = image.getHeight();
  72330. Image shadowImage (Image::SingleChannel, w, h, false);
  72331. const Image::BitmapData srcData (image, false);
  72332. const Image::BitmapData destData (shadowImage, true);
  72333. const int filter = roundToInt (63.0f / radius);
  72334. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72335. for (int x = w; --x >= 0;)
  72336. {
  72337. int shadowAlpha = 0;
  72338. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72339. uint8* shadowPix = destData.data + x;
  72340. for (int y = h; --y >= 0;)
  72341. {
  72342. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72343. *shadowPix = (uint8) shadowAlpha;
  72344. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72345. shadowPix += destData.lineStride;
  72346. }
  72347. }
  72348. for (int y = h; --y >= 0;)
  72349. {
  72350. int shadowAlpha = 0;
  72351. uint8* shadowPix = destData.getLinePointer (y);
  72352. for (int x = w; --x >= 0;)
  72353. {
  72354. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72355. *shadowPix++ = (uint8) shadowAlpha;
  72356. }
  72357. }
  72358. g.setColour (Colours::black.withAlpha (opacity));
  72359. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72360. g.setOpacity (1.0f);
  72361. g.drawImageAt (image, 0, 0);
  72362. }
  72363. #if JUCE_MSVC && JUCE_DEBUG
  72364. #pragma optimize ("", on) // resets optimisations to the project defaults
  72365. #endif
  72366. END_JUCE_NAMESPACE
  72367. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72368. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72369. BEGIN_JUCE_NAMESPACE
  72370. GlowEffect::GlowEffect()
  72371. : radius (2.0f),
  72372. colour (Colours::white)
  72373. {
  72374. }
  72375. GlowEffect::~GlowEffect()
  72376. {
  72377. }
  72378. void GlowEffect::setGlowProperties (const float newRadius,
  72379. const Colour& newColour)
  72380. {
  72381. radius = newRadius;
  72382. colour = newColour;
  72383. }
  72384. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72385. {
  72386. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72387. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72388. blurKernel.createGaussianBlur (radius);
  72389. blurKernel.rescaleAllValues (radius);
  72390. blurKernel.applyToImage (temp, image, image.getBounds());
  72391. g.setColour (colour);
  72392. g.drawImageAt (temp, 0, 0, true);
  72393. g.setOpacity (1.0f);
  72394. g.drawImageAt (image, 0, 0, false);
  72395. }
  72396. END_JUCE_NAMESPACE
  72397. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72398. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72399. BEGIN_JUCE_NAMESPACE
  72400. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72401. : opacity (opacity_)
  72402. {
  72403. }
  72404. ReduceOpacityEffect::~ReduceOpacityEffect()
  72405. {
  72406. }
  72407. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72408. {
  72409. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72410. }
  72411. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72412. {
  72413. g.setOpacity (opacity);
  72414. g.drawImageAt (image, 0, 0);
  72415. }
  72416. END_JUCE_NAMESPACE
  72417. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72418. /*** Start of inlined file: juce_Font.cpp ***/
  72419. BEGIN_JUCE_NAMESPACE
  72420. namespace FontValues
  72421. {
  72422. static float limitFontHeight (const float height) throw()
  72423. {
  72424. return jlimit (0.1f, 10000.0f, height);
  72425. }
  72426. static const float defaultFontHeight = 14.0f;
  72427. static String fallbackFont;
  72428. }
  72429. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72430. const float kerning_, const float ascent_, const int styleFlags_,
  72431. Typeface* const typeface_) throw()
  72432. : typefaceName (typefaceName_),
  72433. height (height_),
  72434. horizontalScale (horizontalScale_),
  72435. kerning (kerning_),
  72436. ascent (ascent_),
  72437. styleFlags (styleFlags_),
  72438. typeface (typeface_)
  72439. {
  72440. }
  72441. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72442. : typefaceName (other.typefaceName),
  72443. height (other.height),
  72444. horizontalScale (other.horizontalScale),
  72445. kerning (other.kerning),
  72446. ascent (other.ascent),
  72447. styleFlags (other.styleFlags),
  72448. typeface (other.typeface)
  72449. {
  72450. }
  72451. Font::Font()
  72452. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72453. 1.0f, 0, 0, Font::plain, 0))
  72454. {
  72455. }
  72456. Font::Font (const float fontHeight, const int styleFlags_)
  72457. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72458. 1.0f, 0, 0, styleFlags_, 0))
  72459. {
  72460. }
  72461. Font::Font (const String& typefaceName_,
  72462. const float fontHeight,
  72463. const int styleFlags_)
  72464. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72465. 1.0f, 0, 0, styleFlags_, 0))
  72466. {
  72467. }
  72468. Font::Font (const Font& other) throw()
  72469. : font (other.font)
  72470. {
  72471. }
  72472. Font& Font::operator= (const Font& other) throw()
  72473. {
  72474. font = other.font;
  72475. return *this;
  72476. }
  72477. Font::~Font() throw()
  72478. {
  72479. }
  72480. Font::Font (const Typeface::Ptr& typeface)
  72481. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72482. 1.0f, 0, 0, Font::plain, typeface))
  72483. {
  72484. }
  72485. bool Font::operator== (const Font& other) const throw()
  72486. {
  72487. return font == other.font
  72488. || (font->height == other.font->height
  72489. && font->styleFlags == other.font->styleFlags
  72490. && font->horizontalScale == other.font->horizontalScale
  72491. && font->kerning == other.font->kerning
  72492. && font->typefaceName == other.font->typefaceName);
  72493. }
  72494. bool Font::operator!= (const Font& other) const throw()
  72495. {
  72496. return ! operator== (other);
  72497. }
  72498. void Font::dupeInternalIfShared()
  72499. {
  72500. if (font->getReferenceCount() > 1)
  72501. font = new SharedFontInternal (*font);
  72502. }
  72503. const String Font::getDefaultSansSerifFontName()
  72504. {
  72505. static const String name ("<Sans-Serif>");
  72506. return name;
  72507. }
  72508. const String Font::getDefaultSerifFontName()
  72509. {
  72510. static const String name ("<Serif>");
  72511. return name;
  72512. }
  72513. const String Font::getDefaultMonospacedFontName()
  72514. {
  72515. static const String name ("<Monospaced>");
  72516. return name;
  72517. }
  72518. void Font::setTypefaceName (const String& faceName)
  72519. {
  72520. if (faceName != font->typefaceName)
  72521. {
  72522. dupeInternalIfShared();
  72523. font->typefaceName = faceName;
  72524. font->typeface = 0;
  72525. font->ascent = 0;
  72526. }
  72527. }
  72528. const String Font::getFallbackFontName()
  72529. {
  72530. return FontValues::fallbackFont;
  72531. }
  72532. void Font::setFallbackFontName (const String& name)
  72533. {
  72534. FontValues::fallbackFont = name;
  72535. }
  72536. void Font::setHeight (float newHeight)
  72537. {
  72538. newHeight = FontValues::limitFontHeight (newHeight);
  72539. if (font->height != newHeight)
  72540. {
  72541. dupeInternalIfShared();
  72542. font->height = newHeight;
  72543. }
  72544. }
  72545. void Font::setHeightWithoutChangingWidth (float newHeight)
  72546. {
  72547. newHeight = FontValues::limitFontHeight (newHeight);
  72548. if (font->height != newHeight)
  72549. {
  72550. dupeInternalIfShared();
  72551. font->horizontalScale *= (font->height / newHeight);
  72552. font->height = newHeight;
  72553. }
  72554. }
  72555. void Font::setStyleFlags (const int newFlags)
  72556. {
  72557. if (font->styleFlags != newFlags)
  72558. {
  72559. dupeInternalIfShared();
  72560. font->styleFlags = newFlags;
  72561. font->typeface = 0;
  72562. font->ascent = 0;
  72563. }
  72564. }
  72565. void Font::setSizeAndStyle (float newHeight,
  72566. const int newStyleFlags,
  72567. const float newHorizontalScale,
  72568. const float newKerningAmount)
  72569. {
  72570. newHeight = FontValues::limitFontHeight (newHeight);
  72571. if (font->height != newHeight
  72572. || font->horizontalScale != newHorizontalScale
  72573. || font->kerning != newKerningAmount)
  72574. {
  72575. dupeInternalIfShared();
  72576. font->height = newHeight;
  72577. font->horizontalScale = newHorizontalScale;
  72578. font->kerning = newKerningAmount;
  72579. }
  72580. setStyleFlags (newStyleFlags);
  72581. }
  72582. void Font::setHorizontalScale (const float scaleFactor)
  72583. {
  72584. dupeInternalIfShared();
  72585. font->horizontalScale = scaleFactor;
  72586. }
  72587. void Font::setExtraKerningFactor (const float extraKerning)
  72588. {
  72589. dupeInternalIfShared();
  72590. font->kerning = extraKerning;
  72591. }
  72592. void Font::setBold (const bool shouldBeBold)
  72593. {
  72594. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72595. : (font->styleFlags & ~bold));
  72596. }
  72597. const Font Font::boldened() const
  72598. {
  72599. Font f (*this);
  72600. f.setBold (true);
  72601. return f;
  72602. }
  72603. bool Font::isBold() const throw()
  72604. {
  72605. return (font->styleFlags & bold) != 0;
  72606. }
  72607. void Font::setItalic (const bool shouldBeItalic)
  72608. {
  72609. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72610. : (font->styleFlags & ~italic));
  72611. }
  72612. const Font Font::italicised() const
  72613. {
  72614. Font f (*this);
  72615. f.setItalic (true);
  72616. return f;
  72617. }
  72618. bool Font::isItalic() const throw()
  72619. {
  72620. return (font->styleFlags & italic) != 0;
  72621. }
  72622. void Font::setUnderline (const bool shouldBeUnderlined)
  72623. {
  72624. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72625. : (font->styleFlags & ~underlined));
  72626. }
  72627. bool Font::isUnderlined() const throw()
  72628. {
  72629. return (font->styleFlags & underlined) != 0;
  72630. }
  72631. float Font::getAscent() const
  72632. {
  72633. if (font->ascent == 0)
  72634. font->ascent = getTypeface()->getAscent();
  72635. return font->height * font->ascent;
  72636. }
  72637. float Font::getDescent() const
  72638. {
  72639. return font->height - getAscent();
  72640. }
  72641. int Font::getStringWidth (const String& text) const
  72642. {
  72643. return roundToInt (getStringWidthFloat (text));
  72644. }
  72645. float Font::getStringWidthFloat (const String& text) const
  72646. {
  72647. float w = getTypeface()->getStringWidth (text);
  72648. if (font->kerning != 0)
  72649. w += font->kerning * text.length();
  72650. return w * font->height * font->horizontalScale;
  72651. }
  72652. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72653. {
  72654. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72655. const float scale = font->height * font->horizontalScale;
  72656. const int num = xOffsets.size();
  72657. if (num > 0)
  72658. {
  72659. float* const x = &(xOffsets.getReference(0));
  72660. if (font->kerning != 0)
  72661. {
  72662. for (int i = 0; i < num; ++i)
  72663. x[i] = (x[i] + i * font->kerning) * scale;
  72664. }
  72665. else
  72666. {
  72667. for (int i = 0; i < num; ++i)
  72668. x[i] *= scale;
  72669. }
  72670. }
  72671. }
  72672. void Font::findFonts (Array<Font>& destArray)
  72673. {
  72674. const StringArray names (findAllTypefaceNames());
  72675. for (int i = 0; i < names.size(); ++i)
  72676. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72677. }
  72678. const String Font::toString() const
  72679. {
  72680. String s (getTypefaceName());
  72681. if (s == getDefaultSansSerifFontName())
  72682. s = String::empty;
  72683. else
  72684. s += "; ";
  72685. s += String (getHeight(), 1);
  72686. if (isBold())
  72687. s += " bold";
  72688. if (isItalic())
  72689. s += " italic";
  72690. return s;
  72691. }
  72692. const Font Font::fromString (const String& fontDescription)
  72693. {
  72694. String name;
  72695. const int separator = fontDescription.indexOfChar (';');
  72696. if (separator > 0)
  72697. name = fontDescription.substring (0, separator).trim();
  72698. if (name.isEmpty())
  72699. name = getDefaultSansSerifFontName();
  72700. String sizeAndStyle (fontDescription.substring (separator + 1));
  72701. float height = sizeAndStyle.getFloatValue();
  72702. if (height <= 0)
  72703. height = 10.0f;
  72704. int flags = Font::plain;
  72705. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72706. flags |= Font::bold;
  72707. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72708. flags |= Font::italic;
  72709. return Font (name, height, flags);
  72710. }
  72711. class TypefaceCache : public DeletedAtShutdown
  72712. {
  72713. public:
  72714. TypefaceCache (int numToCache = 10)
  72715. : counter (1)
  72716. {
  72717. while (--numToCache >= 0)
  72718. faces.add (new CachedFace());
  72719. }
  72720. ~TypefaceCache()
  72721. {
  72722. clearSingletonInstance();
  72723. }
  72724. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72725. const Typeface::Ptr findTypefaceFor (const Font& font)
  72726. {
  72727. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72728. const String faceName (font.getTypefaceName());
  72729. int i;
  72730. for (i = faces.size(); --i >= 0;)
  72731. {
  72732. CachedFace* const face = faces.getUnchecked(i);
  72733. if (face->flags == flags
  72734. && face->typefaceName == faceName)
  72735. {
  72736. face->lastUsageCount = ++counter;
  72737. return face->typeFace;
  72738. }
  72739. }
  72740. int replaceIndex = 0;
  72741. int bestLastUsageCount = std::numeric_limits<int>::max();
  72742. for (i = faces.size(); --i >= 0;)
  72743. {
  72744. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72745. if (bestLastUsageCount > lu)
  72746. {
  72747. bestLastUsageCount = lu;
  72748. replaceIndex = i;
  72749. }
  72750. }
  72751. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72752. face->typefaceName = faceName;
  72753. face->flags = flags;
  72754. face->lastUsageCount = ++counter;
  72755. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72756. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72757. return face->typeFace;
  72758. }
  72759. juce_UseDebuggingNewOperator
  72760. private:
  72761. struct CachedFace
  72762. {
  72763. CachedFace() throw()
  72764. : lastUsageCount (0), flags (-1)
  72765. {
  72766. }
  72767. String typefaceName;
  72768. int lastUsageCount;
  72769. int flags;
  72770. Typeface::Ptr typeFace;
  72771. };
  72772. int counter;
  72773. OwnedArray <CachedFace> faces;
  72774. TypefaceCache (const TypefaceCache&);
  72775. TypefaceCache& operator= (const TypefaceCache&);
  72776. };
  72777. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72778. Typeface* Font::getTypeface() const
  72779. {
  72780. if (font->typeface == 0)
  72781. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72782. return font->typeface;
  72783. }
  72784. END_JUCE_NAMESPACE
  72785. /*** End of inlined file: juce_Font.cpp ***/
  72786. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72787. BEGIN_JUCE_NAMESPACE
  72788. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72789. const juce_wchar character_, const int glyph_)
  72790. : x (x_),
  72791. y (y_),
  72792. w (w_),
  72793. font (font_),
  72794. character (character_),
  72795. glyph (glyph_)
  72796. {
  72797. }
  72798. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72799. : x (other.x),
  72800. y (other.y),
  72801. w (other.w),
  72802. font (other.font),
  72803. character (other.character),
  72804. glyph (other.glyph)
  72805. {
  72806. }
  72807. void PositionedGlyph::draw (const Graphics& g) const
  72808. {
  72809. if (! isWhitespace())
  72810. {
  72811. g.getInternalContext()->setFont (font);
  72812. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72813. }
  72814. }
  72815. void PositionedGlyph::draw (const Graphics& g,
  72816. const AffineTransform& transform) const
  72817. {
  72818. if (! isWhitespace())
  72819. {
  72820. g.getInternalContext()->setFont (font);
  72821. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72822. .followedBy (transform));
  72823. }
  72824. }
  72825. void PositionedGlyph::createPath (Path& path) const
  72826. {
  72827. if (! isWhitespace())
  72828. {
  72829. Typeface* const t = font.getTypeface();
  72830. if (t != 0)
  72831. {
  72832. Path p;
  72833. t->getOutlineForGlyph (glyph, p);
  72834. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72835. .translated (x, y));
  72836. }
  72837. }
  72838. }
  72839. bool PositionedGlyph::hitTest (float px, float py) const
  72840. {
  72841. if (getBounds().contains (px, py) && ! isWhitespace())
  72842. {
  72843. Typeface* const t = font.getTypeface();
  72844. if (t != 0)
  72845. {
  72846. Path p;
  72847. t->getOutlineForGlyph (glyph, p);
  72848. AffineTransform::translation (-x, -y)
  72849. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72850. .transformPoint (px, py);
  72851. return p.contains (px, py);
  72852. }
  72853. }
  72854. return false;
  72855. }
  72856. void PositionedGlyph::moveBy (const float deltaX,
  72857. const float deltaY)
  72858. {
  72859. x += deltaX;
  72860. y += deltaY;
  72861. }
  72862. GlyphArrangement::GlyphArrangement()
  72863. {
  72864. glyphs.ensureStorageAllocated (128);
  72865. }
  72866. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72867. {
  72868. addGlyphArrangement (other);
  72869. }
  72870. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72871. {
  72872. if (this != &other)
  72873. {
  72874. clear();
  72875. addGlyphArrangement (other);
  72876. }
  72877. return *this;
  72878. }
  72879. GlyphArrangement::~GlyphArrangement()
  72880. {
  72881. }
  72882. void GlyphArrangement::clear()
  72883. {
  72884. glyphs.clear();
  72885. }
  72886. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72887. {
  72888. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72889. return *glyphs [index];
  72890. }
  72891. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72892. {
  72893. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72894. glyphs.addCopiesOf (other.glyphs);
  72895. }
  72896. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72897. {
  72898. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72899. }
  72900. void GlyphArrangement::addLineOfText (const Font& font,
  72901. const String& text,
  72902. const float xOffset,
  72903. const float yOffset)
  72904. {
  72905. addCurtailedLineOfText (font, text,
  72906. xOffset, yOffset,
  72907. 1.0e10f, false);
  72908. }
  72909. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72910. const String& text,
  72911. float xOffset,
  72912. const float yOffset,
  72913. const float maxWidthPixels,
  72914. const bool useEllipsis)
  72915. {
  72916. if (text.isNotEmpty())
  72917. {
  72918. Array <int> newGlyphs;
  72919. Array <float> xOffsets;
  72920. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72921. const int textLen = newGlyphs.size();
  72922. const juce_wchar* const unicodeText = text;
  72923. for (int i = 0; i < textLen; ++i)
  72924. {
  72925. const float thisX = xOffsets.getUnchecked (i);
  72926. const float nextX = xOffsets.getUnchecked (i + 1);
  72927. if (nextX > maxWidthPixels + 1.0f)
  72928. {
  72929. // curtail the string if it's too wide..
  72930. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72931. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72932. break;
  72933. }
  72934. else
  72935. {
  72936. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72937. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72938. }
  72939. }
  72940. }
  72941. }
  72942. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72943. const int startIndex, int endIndex)
  72944. {
  72945. int numDeleted = 0;
  72946. if (glyphs.size() > 0)
  72947. {
  72948. Array<int> dotGlyphs;
  72949. Array<float> dotXs;
  72950. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72951. const float dx = dotXs[1];
  72952. float xOffset = 0.0f, yOffset = 0.0f;
  72953. while (endIndex > startIndex)
  72954. {
  72955. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72956. xOffset = pg->x;
  72957. yOffset = pg->y;
  72958. glyphs.remove (endIndex);
  72959. ++numDeleted;
  72960. if (xOffset + dx * 3 <= maxXPos)
  72961. break;
  72962. }
  72963. for (int i = 3; --i >= 0;)
  72964. {
  72965. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72966. font, '.', dotGlyphs.getFirst()));
  72967. --numDeleted;
  72968. xOffset += dx;
  72969. if (xOffset > maxXPos)
  72970. break;
  72971. }
  72972. }
  72973. return numDeleted;
  72974. }
  72975. void GlyphArrangement::addJustifiedText (const Font& font,
  72976. const String& text,
  72977. float x, float y,
  72978. const float maxLineWidth,
  72979. const Justification& horizontalLayout)
  72980. {
  72981. int lineStartIndex = glyphs.size();
  72982. addLineOfText (font, text, x, y);
  72983. const float originalY = y;
  72984. while (lineStartIndex < glyphs.size())
  72985. {
  72986. int i = lineStartIndex;
  72987. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72988. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72989. ++i;
  72990. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72991. int lastWordBreakIndex = -1;
  72992. while (i < glyphs.size())
  72993. {
  72994. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72995. const juce_wchar c = pg->getCharacter();
  72996. if (c == '\r' || c == '\n')
  72997. {
  72998. ++i;
  72999. if (c == '\r' && i < glyphs.size()
  73000. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  73001. ++i;
  73002. break;
  73003. }
  73004. else if (pg->isWhitespace())
  73005. {
  73006. lastWordBreakIndex = i + 1;
  73007. }
  73008. else if (pg->getRight() - 0.0001f >= lineMaxX)
  73009. {
  73010. if (lastWordBreakIndex >= 0)
  73011. i = lastWordBreakIndex;
  73012. break;
  73013. }
  73014. ++i;
  73015. }
  73016. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  73017. float currentLineEndX = currentLineStartX;
  73018. for (int j = i; --j >= lineStartIndex;)
  73019. {
  73020. if (! glyphs.getUnchecked (j)->isWhitespace())
  73021. {
  73022. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73023. break;
  73024. }
  73025. }
  73026. float deltaX = 0.0f;
  73027. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73028. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73029. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73030. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73031. else if (horizontalLayout.testFlags (Justification::right))
  73032. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73033. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73034. x + deltaX - currentLineStartX, y - originalY);
  73035. lineStartIndex = i;
  73036. y += font.getHeight();
  73037. }
  73038. }
  73039. void GlyphArrangement::addFittedText (const Font& f,
  73040. const String& text,
  73041. const float x, const float y,
  73042. const float width, const float height,
  73043. const Justification& layout,
  73044. int maximumLines,
  73045. const float minimumHorizontalScale)
  73046. {
  73047. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73048. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73049. if (text.containsAnyOf ("\r\n"))
  73050. {
  73051. GlyphArrangement ga;
  73052. ga.addJustifiedText (f, text, x, y, width, layout);
  73053. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73054. float dy = y - bb.getY();
  73055. if (layout.testFlags (Justification::verticallyCentred))
  73056. dy += (height - bb.getHeight()) * 0.5f;
  73057. else if (layout.testFlags (Justification::bottom))
  73058. dy += height - bb.getHeight();
  73059. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73060. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73061. for (int i = 0; i < ga.glyphs.size(); ++i)
  73062. glyphs.add (ga.glyphs.getUnchecked (i));
  73063. ga.glyphs.clear (false);
  73064. return;
  73065. }
  73066. int startIndex = glyphs.size();
  73067. addLineOfText (f, text.trim(), x, y);
  73068. if (glyphs.size() > startIndex)
  73069. {
  73070. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73071. - glyphs.getUnchecked (startIndex)->getLeft();
  73072. if (lineWidth <= 0)
  73073. return;
  73074. if (lineWidth * minimumHorizontalScale < width)
  73075. {
  73076. if (lineWidth > width)
  73077. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73078. width / lineWidth);
  73079. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73080. x, y, width, height, layout);
  73081. }
  73082. else if (maximumLines <= 1)
  73083. {
  73084. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73085. x, y, width, height, f, layout, minimumHorizontalScale);
  73086. }
  73087. else
  73088. {
  73089. Font font (f);
  73090. String txt (text.trim());
  73091. const int length = txt.length();
  73092. const int originalStartIndex = startIndex;
  73093. int numLines = 1;
  73094. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73095. maximumLines = 1;
  73096. maximumLines = jmin (maximumLines, length);
  73097. while (numLines < maximumLines)
  73098. {
  73099. ++numLines;
  73100. const float newFontHeight = height / (float) numLines;
  73101. if (newFontHeight < font.getHeight())
  73102. {
  73103. font.setHeight (jmax (8.0f, newFontHeight));
  73104. removeRangeOfGlyphs (startIndex, -1);
  73105. addLineOfText (font, txt, x, y);
  73106. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73107. - glyphs.getUnchecked (startIndex)->getLeft();
  73108. }
  73109. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73110. break;
  73111. }
  73112. if (numLines < 1)
  73113. numLines = 1;
  73114. float lineY = y;
  73115. float widthPerLine = lineWidth / numLines;
  73116. int lastLineStartIndex = 0;
  73117. for (int line = 0; line < numLines; ++line)
  73118. {
  73119. int i = startIndex;
  73120. lastLineStartIndex = i;
  73121. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73122. if (line == numLines - 1)
  73123. {
  73124. widthPerLine = width;
  73125. i = glyphs.size();
  73126. }
  73127. else
  73128. {
  73129. while (i < glyphs.size())
  73130. {
  73131. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73132. if (lineWidth > widthPerLine)
  73133. {
  73134. // got to a point where the line's too long, so skip forward to find a
  73135. // good place to break it..
  73136. const int searchStartIndex = i;
  73137. while (i < glyphs.size())
  73138. {
  73139. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73140. {
  73141. if (glyphs.getUnchecked (i)->isWhitespace()
  73142. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73143. {
  73144. ++i;
  73145. break;
  73146. }
  73147. }
  73148. else
  73149. {
  73150. // can't find a suitable break, so try looking backwards..
  73151. i = searchStartIndex;
  73152. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73153. {
  73154. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73155. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73156. {
  73157. i -= back - 1;
  73158. break;
  73159. }
  73160. }
  73161. break;
  73162. }
  73163. ++i;
  73164. }
  73165. break;
  73166. }
  73167. ++i;
  73168. }
  73169. int wsStart = i;
  73170. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73171. --wsStart;
  73172. int wsEnd = i;
  73173. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73174. ++wsEnd;
  73175. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73176. i = jmax (wsStart, startIndex + 1);
  73177. }
  73178. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73179. x, lineY, width, font.getHeight(), font,
  73180. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73181. minimumHorizontalScale);
  73182. startIndex = i;
  73183. lineY += font.getHeight();
  73184. if (startIndex >= glyphs.size())
  73185. break;
  73186. }
  73187. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73188. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73189. }
  73190. }
  73191. }
  73192. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73193. const float dx, const float dy)
  73194. {
  73195. jassert (startIndex >= 0);
  73196. if (dx != 0.0f || dy != 0.0f)
  73197. {
  73198. if (num < 0 || startIndex + num > glyphs.size())
  73199. num = glyphs.size() - startIndex;
  73200. while (--num >= 0)
  73201. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73202. }
  73203. }
  73204. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73205. const Justification& justification, float minimumHorizontalScale)
  73206. {
  73207. int numDeleted = 0;
  73208. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73209. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73210. if (lineWidth > w)
  73211. {
  73212. if (minimumHorizontalScale < 1.0f)
  73213. {
  73214. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73215. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73216. }
  73217. if (lineWidth > w)
  73218. {
  73219. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73220. numGlyphs -= numDeleted;
  73221. }
  73222. }
  73223. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73224. return numDeleted;
  73225. }
  73226. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73227. const float horizontalScaleFactor)
  73228. {
  73229. jassert (startIndex >= 0);
  73230. if (num < 0 || startIndex + num > glyphs.size())
  73231. num = glyphs.size() - startIndex;
  73232. if (num > 0)
  73233. {
  73234. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73235. while (--num >= 0)
  73236. {
  73237. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73238. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73239. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73240. pg->w *= horizontalScaleFactor;
  73241. }
  73242. }
  73243. }
  73244. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73245. {
  73246. jassert (startIndex >= 0);
  73247. if (num < 0 || startIndex + num > glyphs.size())
  73248. num = glyphs.size() - startIndex;
  73249. Rectangle<float> result;
  73250. while (--num >= 0)
  73251. {
  73252. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73253. if (includeWhitespace || ! pg->isWhitespace())
  73254. result = result.getUnion (pg->getBounds());
  73255. }
  73256. return result;
  73257. }
  73258. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73259. const float x, const float y, const float width, const float height,
  73260. const Justification& justification)
  73261. {
  73262. jassert (num >= 0 && startIndex >= 0);
  73263. if (glyphs.size() > 0 && num > 0)
  73264. {
  73265. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73266. | Justification::horizontallyCentred)));
  73267. float deltaX = 0.0f;
  73268. if (justification.testFlags (Justification::horizontallyJustified))
  73269. deltaX = x - bb.getX();
  73270. else if (justification.testFlags (Justification::horizontallyCentred))
  73271. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73272. else if (justification.testFlags (Justification::right))
  73273. deltaX = (x + width) - bb.getRight();
  73274. else
  73275. deltaX = x - bb.getX();
  73276. float deltaY = 0.0f;
  73277. if (justification.testFlags (Justification::top))
  73278. deltaY = y - bb.getY();
  73279. else if (justification.testFlags (Justification::bottom))
  73280. deltaY = (y + height) - bb.getBottom();
  73281. else
  73282. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73283. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73284. if (justification.testFlags (Justification::horizontallyJustified))
  73285. {
  73286. int lineStart = 0;
  73287. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73288. int i;
  73289. for (i = 0; i < num; ++i)
  73290. {
  73291. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73292. if (glyphY != baseY)
  73293. {
  73294. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73295. lineStart = i;
  73296. baseY = glyphY;
  73297. }
  73298. }
  73299. if (i > lineStart)
  73300. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73301. }
  73302. }
  73303. }
  73304. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73305. {
  73306. if (start + num < glyphs.size()
  73307. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73308. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73309. {
  73310. int numSpaces = 0;
  73311. int spacesAtEnd = 0;
  73312. for (int i = 0; i < num; ++i)
  73313. {
  73314. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73315. {
  73316. ++spacesAtEnd;
  73317. ++numSpaces;
  73318. }
  73319. else
  73320. {
  73321. spacesAtEnd = 0;
  73322. }
  73323. }
  73324. numSpaces -= spacesAtEnd;
  73325. if (numSpaces > 0)
  73326. {
  73327. const float startX = glyphs.getUnchecked (start)->getLeft();
  73328. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73329. const float extraPaddingBetweenWords
  73330. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73331. float deltaX = 0.0f;
  73332. for (int i = 0; i < num; ++i)
  73333. {
  73334. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73335. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73336. deltaX += extraPaddingBetweenWords;
  73337. }
  73338. }
  73339. }
  73340. }
  73341. void GlyphArrangement::draw (const Graphics& g) const
  73342. {
  73343. for (int i = 0; i < glyphs.size(); ++i)
  73344. {
  73345. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73346. if (pg->font.isUnderlined())
  73347. {
  73348. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73349. float nextX = pg->x + pg->w;
  73350. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73351. nextX = glyphs.getUnchecked (i + 1)->x;
  73352. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73353. nextX - pg->x, lineThickness);
  73354. }
  73355. pg->draw (g);
  73356. }
  73357. }
  73358. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73359. {
  73360. for (int i = 0; i < glyphs.size(); ++i)
  73361. {
  73362. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73363. if (pg->font.isUnderlined())
  73364. {
  73365. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73366. float nextX = pg->x + pg->w;
  73367. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73368. nextX = glyphs.getUnchecked (i + 1)->x;
  73369. Path p;
  73370. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73371. nextX, pg->y + lineThickness * 2.0f),
  73372. lineThickness);
  73373. g.fillPath (p, transform);
  73374. }
  73375. pg->draw (g, transform);
  73376. }
  73377. }
  73378. void GlyphArrangement::createPath (Path& path) const
  73379. {
  73380. for (int i = 0; i < glyphs.size(); ++i)
  73381. glyphs.getUnchecked (i)->createPath (path);
  73382. }
  73383. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73384. {
  73385. for (int i = 0; i < glyphs.size(); ++i)
  73386. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73387. return i;
  73388. return -1;
  73389. }
  73390. END_JUCE_NAMESPACE
  73391. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73392. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73393. BEGIN_JUCE_NAMESPACE
  73394. class TextLayout::Token
  73395. {
  73396. public:
  73397. String text;
  73398. Font font;
  73399. int x, y, w, h;
  73400. int line, lineHeight;
  73401. bool isWhitespace, isNewLine;
  73402. Token (const String& t,
  73403. const Font& f,
  73404. const bool isWhitespace_)
  73405. : text (t),
  73406. font (f),
  73407. x(0),
  73408. y(0),
  73409. isWhitespace (isWhitespace_)
  73410. {
  73411. w = font.getStringWidth (t);
  73412. h = roundToInt (f.getHeight());
  73413. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73414. }
  73415. Token (const Token& other)
  73416. : text (other.text),
  73417. font (other.font),
  73418. x (other.x),
  73419. y (other.y),
  73420. w (other.w),
  73421. h (other.h),
  73422. line (other.line),
  73423. lineHeight (other.lineHeight),
  73424. isWhitespace (other.isWhitespace),
  73425. isNewLine (other.isNewLine)
  73426. {
  73427. }
  73428. ~Token()
  73429. {
  73430. }
  73431. void draw (Graphics& g,
  73432. const int xOffset,
  73433. const int yOffset)
  73434. {
  73435. if (! isWhitespace)
  73436. {
  73437. g.setFont (font);
  73438. g.drawSingleLineText (text.trimEnd(),
  73439. xOffset + x,
  73440. yOffset + y + (lineHeight - h)
  73441. + roundToInt (font.getAscent()));
  73442. }
  73443. }
  73444. juce_UseDebuggingNewOperator
  73445. };
  73446. TextLayout::TextLayout()
  73447. : totalLines (0)
  73448. {
  73449. tokens.ensureStorageAllocated (64);
  73450. }
  73451. TextLayout::TextLayout (const String& text, const Font& font)
  73452. : totalLines (0)
  73453. {
  73454. tokens.ensureStorageAllocated (64);
  73455. appendText (text, font);
  73456. }
  73457. TextLayout::TextLayout (const TextLayout& other)
  73458. : totalLines (0)
  73459. {
  73460. *this = other;
  73461. }
  73462. TextLayout& TextLayout::operator= (const TextLayout& other)
  73463. {
  73464. if (this != &other)
  73465. {
  73466. clear();
  73467. totalLines = other.totalLines;
  73468. tokens.addCopiesOf (other.tokens);
  73469. }
  73470. return *this;
  73471. }
  73472. TextLayout::~TextLayout()
  73473. {
  73474. clear();
  73475. }
  73476. void TextLayout::clear()
  73477. {
  73478. tokens.clear();
  73479. totalLines = 0;
  73480. }
  73481. bool TextLayout::isEmpty() const
  73482. {
  73483. return tokens.size() == 0;
  73484. }
  73485. void TextLayout::appendText (const String& text, const Font& font)
  73486. {
  73487. const juce_wchar* t = text;
  73488. String currentString;
  73489. int lastCharType = 0;
  73490. for (;;)
  73491. {
  73492. const juce_wchar c = *t++;
  73493. if (c == 0)
  73494. break;
  73495. int charType;
  73496. if (c == '\r' || c == '\n')
  73497. {
  73498. charType = 0;
  73499. }
  73500. else if (CharacterFunctions::isWhitespace (c))
  73501. {
  73502. charType = 2;
  73503. }
  73504. else
  73505. {
  73506. charType = 1;
  73507. }
  73508. if (charType == 0 || charType != lastCharType)
  73509. {
  73510. if (currentString.isNotEmpty())
  73511. {
  73512. tokens.add (new Token (currentString, font,
  73513. lastCharType == 2 || lastCharType == 0));
  73514. }
  73515. currentString = String::charToString (c);
  73516. if (c == '\r' && *t == '\n')
  73517. currentString += *t++;
  73518. }
  73519. else
  73520. {
  73521. currentString += c;
  73522. }
  73523. lastCharType = charType;
  73524. }
  73525. if (currentString.isNotEmpty())
  73526. tokens.add (new Token (currentString, font, lastCharType == 2));
  73527. }
  73528. void TextLayout::setText (const String& text, const Font& font)
  73529. {
  73530. clear();
  73531. appendText (text, font);
  73532. }
  73533. void TextLayout::layout (int maxWidth,
  73534. const Justification& justification,
  73535. const bool attemptToBalanceLineLengths)
  73536. {
  73537. if (attemptToBalanceLineLengths)
  73538. {
  73539. const int originalW = maxWidth;
  73540. int bestWidth = maxWidth;
  73541. float bestLineProportion = 0.0f;
  73542. while (maxWidth > originalW / 2)
  73543. {
  73544. layout (maxWidth, justification, false);
  73545. if (getNumLines() <= 1)
  73546. return;
  73547. const int lastLineW = getLineWidth (getNumLines() - 1);
  73548. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73549. const float prop = lastLineW / (float) lastButOneLineW;
  73550. if (prop > 0.9f)
  73551. return;
  73552. if (prop > bestLineProportion)
  73553. {
  73554. bestLineProportion = prop;
  73555. bestWidth = maxWidth;
  73556. }
  73557. maxWidth -= 10;
  73558. }
  73559. layout (bestWidth, justification, false);
  73560. }
  73561. else
  73562. {
  73563. int x = 0;
  73564. int y = 0;
  73565. int h = 0;
  73566. totalLines = 0;
  73567. int i;
  73568. for (i = 0; i < tokens.size(); ++i)
  73569. {
  73570. Token* const t = tokens.getUnchecked(i);
  73571. t->x = x;
  73572. t->y = y;
  73573. t->line = totalLines;
  73574. x += t->w;
  73575. h = jmax (h, t->h);
  73576. const Token* nextTok = tokens [i + 1];
  73577. if (nextTok == 0)
  73578. break;
  73579. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73580. {
  73581. // finished a line, so go back and update the heights of the things on it
  73582. for (int j = i; j >= 0; --j)
  73583. {
  73584. Token* const tok = tokens.getUnchecked(j);
  73585. if (tok->line == totalLines)
  73586. tok->lineHeight = h;
  73587. else
  73588. break;
  73589. }
  73590. x = 0;
  73591. y += h;
  73592. h = 0;
  73593. ++totalLines;
  73594. }
  73595. }
  73596. // finished a line, so go back and update the heights of the things on it
  73597. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73598. {
  73599. Token* const t = tokens.getUnchecked(j);
  73600. if (t->line == totalLines)
  73601. t->lineHeight = h;
  73602. else
  73603. break;
  73604. }
  73605. ++totalLines;
  73606. if (! justification.testFlags (Justification::left))
  73607. {
  73608. int totalW = getWidth();
  73609. for (i = totalLines; --i >= 0;)
  73610. {
  73611. const int lineW = getLineWidth (i);
  73612. int dx = 0;
  73613. if (justification.testFlags (Justification::horizontallyCentred))
  73614. dx = (totalW - lineW) / 2;
  73615. else if (justification.testFlags (Justification::right))
  73616. dx = totalW - lineW;
  73617. for (int j = tokens.size(); --j >= 0;)
  73618. {
  73619. Token* const t = tokens.getUnchecked(j);
  73620. if (t->line == i)
  73621. t->x += dx;
  73622. }
  73623. }
  73624. }
  73625. }
  73626. }
  73627. int TextLayout::getLineWidth (const int lineNumber) const
  73628. {
  73629. int maxW = 0;
  73630. for (int i = tokens.size(); --i >= 0;)
  73631. {
  73632. const Token* const t = tokens.getUnchecked(i);
  73633. if (t->line == lineNumber && ! t->isWhitespace)
  73634. maxW = jmax (maxW, t->x + t->w);
  73635. }
  73636. return maxW;
  73637. }
  73638. int TextLayout::getWidth() const
  73639. {
  73640. int maxW = 0;
  73641. for (int i = tokens.size(); --i >= 0;)
  73642. {
  73643. const Token* const t = tokens.getUnchecked(i);
  73644. if (! t->isWhitespace)
  73645. maxW = jmax (maxW, t->x + t->w);
  73646. }
  73647. return maxW;
  73648. }
  73649. int TextLayout::getHeight() const
  73650. {
  73651. int maxH = 0;
  73652. for (int i = tokens.size(); --i >= 0;)
  73653. {
  73654. const Token* const t = tokens.getUnchecked(i);
  73655. if (! t->isWhitespace)
  73656. maxH = jmax (maxH, t->y + t->h);
  73657. }
  73658. return maxH;
  73659. }
  73660. void TextLayout::draw (Graphics& g,
  73661. const int xOffset,
  73662. const int yOffset) const
  73663. {
  73664. for (int i = tokens.size(); --i >= 0;)
  73665. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73666. }
  73667. void TextLayout::drawWithin (Graphics& g,
  73668. int x, int y, int w, int h,
  73669. const Justification& justification) const
  73670. {
  73671. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73672. x, y, w, h);
  73673. draw (g, x, y);
  73674. }
  73675. END_JUCE_NAMESPACE
  73676. /*** End of inlined file: juce_TextLayout.cpp ***/
  73677. /*** Start of inlined file: juce_Typeface.cpp ***/
  73678. BEGIN_JUCE_NAMESPACE
  73679. Typeface::Typeface (const String& name_) throw()
  73680. : name (name_)
  73681. {
  73682. }
  73683. Typeface::~Typeface()
  73684. {
  73685. }
  73686. class CustomTypeface::GlyphInfo
  73687. {
  73688. public:
  73689. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73690. : character (character_), path (path_), width (width_)
  73691. {
  73692. }
  73693. ~GlyphInfo() throw()
  73694. {
  73695. }
  73696. struct KerningPair
  73697. {
  73698. juce_wchar character2;
  73699. float kerningAmount;
  73700. };
  73701. void addKerningPair (const juce_wchar subsequentCharacter,
  73702. const float extraKerningAmount) throw()
  73703. {
  73704. KerningPair kp;
  73705. kp.character2 = subsequentCharacter;
  73706. kp.kerningAmount = extraKerningAmount;
  73707. kerningPairs.add (kp);
  73708. }
  73709. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73710. {
  73711. if (subsequentCharacter != 0)
  73712. {
  73713. for (int i = kerningPairs.size(); --i >= 0;)
  73714. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73715. return width + kerningPairs.getReference(i).kerningAmount;
  73716. }
  73717. return width;
  73718. }
  73719. const juce_wchar character;
  73720. const Path path;
  73721. float width;
  73722. Array <KerningPair> kerningPairs;
  73723. juce_UseDebuggingNewOperator
  73724. private:
  73725. GlyphInfo (const GlyphInfo&);
  73726. GlyphInfo& operator= (const GlyphInfo&);
  73727. };
  73728. CustomTypeface::CustomTypeface()
  73729. : Typeface (String::empty)
  73730. {
  73731. clear();
  73732. }
  73733. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73734. : Typeface (String::empty)
  73735. {
  73736. clear();
  73737. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73738. BufferedInputStream in (&gzin, 32768, false);
  73739. name = in.readString();
  73740. isBold = in.readBool();
  73741. isItalic = in.readBool();
  73742. ascent = in.readFloat();
  73743. defaultCharacter = (juce_wchar) in.readShort();
  73744. int i, numChars = in.readInt();
  73745. for (i = 0; i < numChars; ++i)
  73746. {
  73747. const juce_wchar c = (juce_wchar) in.readShort();
  73748. const float width = in.readFloat();
  73749. Path p;
  73750. p.loadPathFromStream (in);
  73751. addGlyph (c, p, width);
  73752. }
  73753. const int numKerningPairs = in.readInt();
  73754. for (i = 0; i < numKerningPairs; ++i)
  73755. {
  73756. const juce_wchar char1 = (juce_wchar) in.readShort();
  73757. const juce_wchar char2 = (juce_wchar) in.readShort();
  73758. addKerningPair (char1, char2, in.readFloat());
  73759. }
  73760. }
  73761. CustomTypeface::~CustomTypeface()
  73762. {
  73763. }
  73764. void CustomTypeface::clear()
  73765. {
  73766. defaultCharacter = 0;
  73767. ascent = 1.0f;
  73768. isBold = isItalic = false;
  73769. zeromem (lookupTable, sizeof (lookupTable));
  73770. glyphs.clear();
  73771. }
  73772. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73773. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73774. {
  73775. name = name_;
  73776. defaultCharacter = defaultCharacter_;
  73777. ascent = ascent_;
  73778. isBold = isBold_;
  73779. isItalic = isItalic_;
  73780. }
  73781. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73782. {
  73783. // Check that you're not trying to add the same character twice..
  73784. jassert (findGlyph (character, false) == 0);
  73785. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73786. lookupTable [character] = (short) glyphs.size();
  73787. glyphs.add (new GlyphInfo (character, path, width));
  73788. }
  73789. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73790. {
  73791. if (extraAmount != 0)
  73792. {
  73793. GlyphInfo* const g = findGlyph (char1, true);
  73794. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73795. if (g != 0)
  73796. g->addKerningPair (char2, extraAmount);
  73797. }
  73798. }
  73799. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73800. {
  73801. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73802. return glyphs [(int) lookupTable [(int) character]];
  73803. for (int i = 0; i < glyphs.size(); ++i)
  73804. {
  73805. GlyphInfo* const g = glyphs.getUnchecked(i);
  73806. if (g->character == character)
  73807. return g;
  73808. }
  73809. if (loadIfNeeded && loadGlyphIfPossible (character))
  73810. return findGlyph (character, false);
  73811. return 0;
  73812. }
  73813. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73814. {
  73815. GlyphInfo* glyph = findGlyph (character, true);
  73816. if (glyph == 0)
  73817. {
  73818. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73819. glyph = findGlyph (L' ', true);
  73820. if (glyph == 0)
  73821. {
  73822. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73823. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73824. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73825. {
  73826. //xxx
  73827. }
  73828. if (glyph == 0)
  73829. glyph = findGlyph (defaultCharacter, true);
  73830. }
  73831. }
  73832. return glyph;
  73833. }
  73834. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73835. {
  73836. return false;
  73837. }
  73838. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73839. {
  73840. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73841. for (int i = 0; i < numCharacters; ++i)
  73842. {
  73843. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73844. Array <int> glyphIndexes;
  73845. Array <float> offsets;
  73846. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73847. const int glyphIndex = glyphIndexes.getFirst();
  73848. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73849. {
  73850. const float glyphWidth = offsets[1];
  73851. Path p;
  73852. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73853. addGlyph (c, p, glyphWidth);
  73854. for (int j = glyphs.size() - 1; --j >= 0;)
  73855. {
  73856. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73857. glyphIndexes.clearQuick();
  73858. offsets.clearQuick();
  73859. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73860. if (offsets.size() > 1)
  73861. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73862. }
  73863. }
  73864. }
  73865. }
  73866. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73867. {
  73868. GZIPCompressorOutputStream out (&outputStream);
  73869. out.writeString (name);
  73870. out.writeBool (isBold);
  73871. out.writeBool (isItalic);
  73872. out.writeFloat (ascent);
  73873. out.writeShort ((short) (unsigned short) defaultCharacter);
  73874. out.writeInt (glyphs.size());
  73875. int i, numKerningPairs = 0;
  73876. for (i = 0; i < glyphs.size(); ++i)
  73877. {
  73878. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73879. out.writeShort ((short) (unsigned short) g->character);
  73880. out.writeFloat (g->width);
  73881. g->path.writePathToStream (out);
  73882. numKerningPairs += g->kerningPairs.size();
  73883. }
  73884. out.writeInt (numKerningPairs);
  73885. for (i = 0; i < glyphs.size(); ++i)
  73886. {
  73887. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73888. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73889. {
  73890. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73891. out.writeShort ((short) (unsigned short) g->character);
  73892. out.writeShort ((short) (unsigned short) p.character2);
  73893. out.writeFloat (p.kerningAmount);
  73894. }
  73895. }
  73896. return true;
  73897. }
  73898. float CustomTypeface::getAscent() const
  73899. {
  73900. return ascent;
  73901. }
  73902. float CustomTypeface::getDescent() const
  73903. {
  73904. return 1.0f - ascent;
  73905. }
  73906. float CustomTypeface::getStringWidth (const String& text)
  73907. {
  73908. float x = 0;
  73909. const juce_wchar* t = text;
  73910. while (*t != 0)
  73911. {
  73912. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73913. if (glyph != 0)
  73914. x += glyph->getHorizontalSpacing (*t);
  73915. }
  73916. return x;
  73917. }
  73918. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73919. {
  73920. xOffsets.add (0);
  73921. float x = 0;
  73922. const juce_wchar* t = text;
  73923. while (*t != 0)
  73924. {
  73925. const juce_wchar c = *t++;
  73926. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73927. if (glyph != 0)
  73928. {
  73929. x += glyph->getHorizontalSpacing (*t);
  73930. resultGlyphs.add ((int) glyph->character);
  73931. xOffsets.add (x);
  73932. }
  73933. }
  73934. }
  73935. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73936. {
  73937. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73938. if (glyph != 0)
  73939. {
  73940. path = glyph->path;
  73941. return true;
  73942. }
  73943. return false;
  73944. }
  73945. END_JUCE_NAMESPACE
  73946. /*** End of inlined file: juce_Typeface.cpp ***/
  73947. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73948. BEGIN_JUCE_NAMESPACE
  73949. AffineTransform::AffineTransform() throw()
  73950. : mat00 (1.0f),
  73951. mat01 (0),
  73952. mat02 (0),
  73953. mat10 (0),
  73954. mat11 (1.0f),
  73955. mat12 (0)
  73956. {
  73957. }
  73958. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73959. : mat00 (other.mat00),
  73960. mat01 (other.mat01),
  73961. mat02 (other.mat02),
  73962. mat10 (other.mat10),
  73963. mat11 (other.mat11),
  73964. mat12 (other.mat12)
  73965. {
  73966. }
  73967. AffineTransform::AffineTransform (const float mat00_,
  73968. const float mat01_,
  73969. const float mat02_,
  73970. const float mat10_,
  73971. const float mat11_,
  73972. const float mat12_) throw()
  73973. : mat00 (mat00_),
  73974. mat01 (mat01_),
  73975. mat02 (mat02_),
  73976. mat10 (mat10_),
  73977. mat11 (mat11_),
  73978. mat12 (mat12_)
  73979. {
  73980. }
  73981. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73982. {
  73983. mat00 = other.mat00;
  73984. mat01 = other.mat01;
  73985. mat02 = other.mat02;
  73986. mat10 = other.mat10;
  73987. mat11 = other.mat11;
  73988. mat12 = other.mat12;
  73989. return *this;
  73990. }
  73991. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73992. {
  73993. return mat00 == other.mat00
  73994. && mat01 == other.mat01
  73995. && mat02 == other.mat02
  73996. && mat10 == other.mat10
  73997. && mat11 == other.mat11
  73998. && mat12 == other.mat12;
  73999. }
  74000. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  74001. {
  74002. return ! operator== (other);
  74003. }
  74004. bool AffineTransform::isIdentity() const throw()
  74005. {
  74006. return (mat01 == 0)
  74007. && (mat02 == 0)
  74008. && (mat10 == 0)
  74009. && (mat12 == 0)
  74010. && (mat00 == 1.0f)
  74011. && (mat11 == 1.0f);
  74012. }
  74013. const AffineTransform AffineTransform::identity;
  74014. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74015. {
  74016. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74017. other.mat00 * mat01 + other.mat01 * mat11,
  74018. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74019. other.mat10 * mat00 + other.mat11 * mat10,
  74020. other.mat10 * mat01 + other.mat11 * mat11,
  74021. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74022. }
  74023. const AffineTransform AffineTransform::followedBy (const float omat00,
  74024. const float omat01,
  74025. const float omat02,
  74026. const float omat10,
  74027. const float omat11,
  74028. const float omat12) const throw()
  74029. {
  74030. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  74031. omat00 * mat01 + omat01 * mat11,
  74032. omat00 * mat02 + omat01 * mat12 + omat02,
  74033. omat10 * mat00 + omat11 * mat10,
  74034. omat10 * mat01 + omat11 * mat11,
  74035. omat10 * mat02 + omat11 * mat12 + omat12);
  74036. }
  74037. const AffineTransform AffineTransform::translated (const float dx,
  74038. const float dy) const throw()
  74039. {
  74040. return AffineTransform (mat00, mat01, mat02 + dx,
  74041. mat10, mat11, mat12 + dy);
  74042. }
  74043. const AffineTransform AffineTransform::translation (const float dx,
  74044. const float dy) throw()
  74045. {
  74046. return AffineTransform (1.0f, 0, dx,
  74047. 0, 1.0f, dy);
  74048. }
  74049. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74050. {
  74051. const float cosRad = std::cos (rad);
  74052. const float sinRad = std::sin (rad);
  74053. return followedBy (cosRad, -sinRad, 0,
  74054. sinRad, cosRad, 0);
  74055. }
  74056. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74057. {
  74058. const float cosRad = std::cos (rad);
  74059. const float sinRad = std::sin (rad);
  74060. return AffineTransform (cosRad, -sinRad, 0,
  74061. sinRad, cosRad, 0);
  74062. }
  74063. const AffineTransform AffineTransform::rotated (const float angle,
  74064. const float pivotX,
  74065. const float pivotY) const throw()
  74066. {
  74067. return translated (-pivotX, -pivotY)
  74068. .rotated (angle)
  74069. .translated (pivotX, pivotY);
  74070. }
  74071. const AffineTransform AffineTransform::rotation (const float angle,
  74072. const float pivotX,
  74073. const float pivotY) throw()
  74074. {
  74075. return translation (-pivotX, -pivotY)
  74076. .rotated (angle)
  74077. .translated (pivotX, pivotY);
  74078. }
  74079. const AffineTransform AffineTransform::scaled (const float factorX,
  74080. const float factorY) const throw()
  74081. {
  74082. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74083. factorY * mat10, factorY * mat11, factorY * mat12);
  74084. }
  74085. const AffineTransform AffineTransform::scale (const float factorX,
  74086. const float factorY) throw()
  74087. {
  74088. return AffineTransform (factorX, 0, 0,
  74089. 0, factorY, 0);
  74090. }
  74091. const AffineTransform AffineTransform::sheared (const float shearX,
  74092. const float shearY) const throw()
  74093. {
  74094. return followedBy (1.0f, shearX, 0,
  74095. shearY, 1.0f, 0);
  74096. }
  74097. const AffineTransform AffineTransform::inverted() const throw()
  74098. {
  74099. double determinant = (mat00 * mat11 - mat10 * mat01);
  74100. if (determinant != 0.0)
  74101. {
  74102. determinant = 1.0 / determinant;
  74103. const float dst00 = (float) (mat11 * determinant);
  74104. const float dst10 = (float) (-mat10 * determinant);
  74105. const float dst01 = (float) (-mat01 * determinant);
  74106. const float dst11 = (float) (mat00 * determinant);
  74107. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74108. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74109. }
  74110. else
  74111. {
  74112. // singularity..
  74113. return *this;
  74114. }
  74115. }
  74116. bool AffineTransform::isSingularity() const throw()
  74117. {
  74118. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  74119. }
  74120. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74121. const float x10, const float y10,
  74122. const float x01, const float y01) throw()
  74123. {
  74124. return AffineTransform (x10 - x00, x01 - x00, x00,
  74125. y10 - y00, y01 - y00, y00);
  74126. }
  74127. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74128. const float sx2, const float sy2, const float tx2, const float ty2,
  74129. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74130. {
  74131. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74132. .inverted()
  74133. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74134. }
  74135. bool AffineTransform::isOnlyTranslation() const throw()
  74136. {
  74137. return (mat01 == 0)
  74138. && (mat10 == 0)
  74139. && (mat00 == 1.0f)
  74140. && (mat11 == 1.0f);
  74141. }
  74142. END_JUCE_NAMESPACE
  74143. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74144. /*** Start of inlined file: juce_BorderSize.cpp ***/
  74145. BEGIN_JUCE_NAMESPACE
  74146. BorderSize::BorderSize() throw()
  74147. : top (0),
  74148. left (0),
  74149. bottom (0),
  74150. right (0)
  74151. {
  74152. }
  74153. BorderSize::BorderSize (const BorderSize& other) throw()
  74154. : top (other.top),
  74155. left (other.left),
  74156. bottom (other.bottom),
  74157. right (other.right)
  74158. {
  74159. }
  74160. BorderSize::BorderSize (const int topGap,
  74161. const int leftGap,
  74162. const int bottomGap,
  74163. const int rightGap) throw()
  74164. : top (topGap),
  74165. left (leftGap),
  74166. bottom (bottomGap),
  74167. right (rightGap)
  74168. {
  74169. }
  74170. BorderSize::BorderSize (const int allGaps) throw()
  74171. : top (allGaps),
  74172. left (allGaps),
  74173. bottom (allGaps),
  74174. right (allGaps)
  74175. {
  74176. }
  74177. BorderSize::~BorderSize() throw()
  74178. {
  74179. }
  74180. void BorderSize::setTop (const int newTopGap) throw()
  74181. {
  74182. top = newTopGap;
  74183. }
  74184. void BorderSize::setLeft (const int newLeftGap) throw()
  74185. {
  74186. left = newLeftGap;
  74187. }
  74188. void BorderSize::setBottom (const int newBottomGap) throw()
  74189. {
  74190. bottom = newBottomGap;
  74191. }
  74192. void BorderSize::setRight (const int newRightGap) throw()
  74193. {
  74194. right = newRightGap;
  74195. }
  74196. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74197. {
  74198. return Rectangle<int> (r.getX() + left,
  74199. r.getY() + top,
  74200. r.getWidth() - (left + right),
  74201. r.getHeight() - (top + bottom));
  74202. }
  74203. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74204. {
  74205. r.setBounds (r.getX() + left,
  74206. r.getY() + top,
  74207. r.getWidth() - (left + right),
  74208. r.getHeight() - (top + bottom));
  74209. }
  74210. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74211. {
  74212. return Rectangle<int> (r.getX() - left,
  74213. r.getY() - top,
  74214. r.getWidth() + (left + right),
  74215. r.getHeight() + (top + bottom));
  74216. }
  74217. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74218. {
  74219. r.setBounds (r.getX() - left,
  74220. r.getY() - top,
  74221. r.getWidth() + (left + right),
  74222. r.getHeight() + (top + bottom));
  74223. }
  74224. bool BorderSize::operator== (const BorderSize& other) const throw()
  74225. {
  74226. return top == other.top
  74227. && left == other.left
  74228. && bottom == other.bottom
  74229. && right == other.right;
  74230. }
  74231. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74232. {
  74233. return ! operator== (other);
  74234. }
  74235. END_JUCE_NAMESPACE
  74236. /*** End of inlined file: juce_BorderSize.cpp ***/
  74237. /*** Start of inlined file: juce_Path.cpp ***/
  74238. BEGIN_JUCE_NAMESPACE
  74239. // tests that some co-ords aren't NaNs
  74240. #define CHECK_COORDS_ARE_VALID(x, y) \
  74241. jassert (x == x && y == y);
  74242. namespace PathHelpers
  74243. {
  74244. static const float ellipseAngularIncrement = 0.05f;
  74245. static const String nextToken (const juce_wchar*& t)
  74246. {
  74247. while (CharacterFunctions::isWhitespace (*t))
  74248. ++t;
  74249. const juce_wchar* const start = t;
  74250. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74251. ++t;
  74252. return String (start, (int) (t - start));
  74253. }
  74254. }
  74255. const float Path::lineMarker = 100001.0f;
  74256. const float Path::moveMarker = 100002.0f;
  74257. const float Path::quadMarker = 100003.0f;
  74258. const float Path::cubicMarker = 100004.0f;
  74259. const float Path::closeSubPathMarker = 100005.0f;
  74260. Path::Path()
  74261. : numElements (0),
  74262. pathXMin (0),
  74263. pathXMax (0),
  74264. pathYMin (0),
  74265. pathYMax (0),
  74266. useNonZeroWinding (true)
  74267. {
  74268. }
  74269. Path::~Path()
  74270. {
  74271. }
  74272. Path::Path (const Path& other)
  74273. : numElements (other.numElements),
  74274. pathXMin (other.pathXMin),
  74275. pathXMax (other.pathXMax),
  74276. pathYMin (other.pathYMin),
  74277. pathYMax (other.pathYMax),
  74278. useNonZeroWinding (other.useNonZeroWinding)
  74279. {
  74280. if (numElements > 0)
  74281. {
  74282. data.setAllocatedSize ((int) numElements);
  74283. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74284. }
  74285. }
  74286. Path& Path::operator= (const Path& other)
  74287. {
  74288. if (this != &other)
  74289. {
  74290. data.ensureAllocatedSize ((int) other.numElements);
  74291. numElements = other.numElements;
  74292. pathXMin = other.pathXMin;
  74293. pathXMax = other.pathXMax;
  74294. pathYMin = other.pathYMin;
  74295. pathYMax = other.pathYMax;
  74296. useNonZeroWinding = other.useNonZeroWinding;
  74297. if (numElements > 0)
  74298. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74299. }
  74300. return *this;
  74301. }
  74302. bool Path::operator== (const Path& other) const throw()
  74303. {
  74304. return ! operator!= (other);
  74305. }
  74306. bool Path::operator!= (const Path& other) const throw()
  74307. {
  74308. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74309. return true;
  74310. for (size_t i = 0; i < numElements; ++i)
  74311. if (data.elements[i] != other.data.elements[i])
  74312. return true;
  74313. return false;
  74314. }
  74315. void Path::clear() throw()
  74316. {
  74317. numElements = 0;
  74318. pathXMin = 0;
  74319. pathYMin = 0;
  74320. pathYMax = 0;
  74321. pathXMax = 0;
  74322. }
  74323. void Path::swapWithPath (Path& other) throw()
  74324. {
  74325. data.swapWith (other.data);
  74326. swapVariables <size_t> (numElements, other.numElements);
  74327. swapVariables <float> (pathXMin, other.pathXMin);
  74328. swapVariables <float> (pathXMax, other.pathXMax);
  74329. swapVariables <float> (pathYMin, other.pathYMin);
  74330. swapVariables <float> (pathYMax, other.pathYMax);
  74331. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74332. }
  74333. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74334. {
  74335. useNonZeroWinding = isNonZero;
  74336. }
  74337. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74338. const bool preserveProportions) throw()
  74339. {
  74340. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74341. }
  74342. bool Path::isEmpty() const throw()
  74343. {
  74344. size_t i = 0;
  74345. while (i < numElements)
  74346. {
  74347. const float type = data.elements [i++];
  74348. if (type == moveMarker)
  74349. {
  74350. i += 2;
  74351. }
  74352. else if (type == lineMarker
  74353. || type == quadMarker
  74354. || type == cubicMarker)
  74355. {
  74356. return false;
  74357. }
  74358. }
  74359. return true;
  74360. }
  74361. const Rectangle<float> Path::getBounds() const throw()
  74362. {
  74363. return Rectangle<float> (pathXMin, pathYMin,
  74364. pathXMax - pathXMin,
  74365. pathYMax - pathYMin);
  74366. }
  74367. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74368. {
  74369. return getBounds().transformed (transform);
  74370. }
  74371. void Path::startNewSubPath (const float x, const float y)
  74372. {
  74373. CHECK_COORDS_ARE_VALID (x, y);
  74374. if (numElements == 0)
  74375. {
  74376. pathXMin = pathXMax = x;
  74377. pathYMin = pathYMax = y;
  74378. }
  74379. else
  74380. {
  74381. pathXMin = jmin (pathXMin, x);
  74382. pathXMax = jmax (pathXMax, x);
  74383. pathYMin = jmin (pathYMin, y);
  74384. pathYMax = jmax (pathYMax, y);
  74385. }
  74386. data.ensureAllocatedSize ((int) numElements + 3);
  74387. data.elements [numElements++] = moveMarker;
  74388. data.elements [numElements++] = x;
  74389. data.elements [numElements++] = y;
  74390. }
  74391. void Path::startNewSubPath (const Point<float>& start)
  74392. {
  74393. startNewSubPath (start.getX(), start.getY());
  74394. }
  74395. void Path::lineTo (const float x, const float y)
  74396. {
  74397. CHECK_COORDS_ARE_VALID (x, y);
  74398. if (numElements == 0)
  74399. startNewSubPath (0, 0);
  74400. data.ensureAllocatedSize ((int) numElements + 3);
  74401. data.elements [numElements++] = lineMarker;
  74402. data.elements [numElements++] = x;
  74403. data.elements [numElements++] = y;
  74404. pathXMin = jmin (pathXMin, x);
  74405. pathXMax = jmax (pathXMax, x);
  74406. pathYMin = jmin (pathYMin, y);
  74407. pathYMax = jmax (pathYMax, y);
  74408. }
  74409. void Path::lineTo (const Point<float>& end)
  74410. {
  74411. lineTo (end.getX(), end.getY());
  74412. }
  74413. void Path::quadraticTo (const float x1, const float y1,
  74414. const float x2, const float y2)
  74415. {
  74416. CHECK_COORDS_ARE_VALID (x1, y1);
  74417. CHECK_COORDS_ARE_VALID (x2, y2);
  74418. if (numElements == 0)
  74419. startNewSubPath (0, 0);
  74420. data.ensureAllocatedSize ((int) numElements + 5);
  74421. data.elements [numElements++] = quadMarker;
  74422. data.elements [numElements++] = x1;
  74423. data.elements [numElements++] = y1;
  74424. data.elements [numElements++] = x2;
  74425. data.elements [numElements++] = y2;
  74426. pathXMin = jmin (pathXMin, x1, x2);
  74427. pathXMax = jmax (pathXMax, x1, x2);
  74428. pathYMin = jmin (pathYMin, y1, y2);
  74429. pathYMax = jmax (pathYMax, y1, y2);
  74430. }
  74431. void Path::quadraticTo (const Point<float>& controlPoint,
  74432. const Point<float>& endPoint)
  74433. {
  74434. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74435. endPoint.getX(), endPoint.getY());
  74436. }
  74437. void Path::cubicTo (const float x1, const float y1,
  74438. const float x2, const float y2,
  74439. const float x3, const float y3)
  74440. {
  74441. CHECK_COORDS_ARE_VALID (x1, y1);
  74442. CHECK_COORDS_ARE_VALID (x2, y2);
  74443. CHECK_COORDS_ARE_VALID (x3, y3);
  74444. if (numElements == 0)
  74445. startNewSubPath (0, 0);
  74446. data.ensureAllocatedSize ((int) numElements + 7);
  74447. data.elements [numElements++] = cubicMarker;
  74448. data.elements [numElements++] = x1;
  74449. data.elements [numElements++] = y1;
  74450. data.elements [numElements++] = x2;
  74451. data.elements [numElements++] = y2;
  74452. data.elements [numElements++] = x3;
  74453. data.elements [numElements++] = y3;
  74454. pathXMin = jmin (pathXMin, x1, x2, x3);
  74455. pathXMax = jmax (pathXMax, x1, x2, x3);
  74456. pathYMin = jmin (pathYMin, y1, y2, y3);
  74457. pathYMax = jmax (pathYMax, y1, y2, y3);
  74458. }
  74459. void Path::cubicTo (const Point<float>& controlPoint1,
  74460. const Point<float>& controlPoint2,
  74461. const Point<float>& endPoint)
  74462. {
  74463. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74464. controlPoint2.getX(), controlPoint2.getY(),
  74465. endPoint.getX(), endPoint.getY());
  74466. }
  74467. void Path::closeSubPath()
  74468. {
  74469. if (numElements > 0
  74470. && data.elements [numElements - 1] != closeSubPathMarker)
  74471. {
  74472. data.ensureAllocatedSize ((int) numElements + 1);
  74473. data.elements [numElements++] = closeSubPathMarker;
  74474. }
  74475. }
  74476. const Point<float> Path::getCurrentPosition() const
  74477. {
  74478. size_t i = numElements - 1;
  74479. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74480. {
  74481. while (i >= 0)
  74482. {
  74483. if (data.elements[i] == moveMarker)
  74484. {
  74485. i += 2;
  74486. break;
  74487. }
  74488. --i;
  74489. }
  74490. }
  74491. if (i > 0)
  74492. return Point<float> (data.elements [i - 1], data.elements [i]);
  74493. return Point<float>();
  74494. }
  74495. void Path::addRectangle (const float x, const float y,
  74496. const float w, const float h)
  74497. {
  74498. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74499. if (w < 0)
  74500. swapVariables (x1, x2);
  74501. if (h < 0)
  74502. swapVariables (y1, y2);
  74503. data.ensureAllocatedSize ((int) numElements + 13);
  74504. if (numElements == 0)
  74505. {
  74506. pathXMin = x1;
  74507. pathXMax = x2;
  74508. pathYMin = y1;
  74509. pathYMax = y2;
  74510. }
  74511. else
  74512. {
  74513. pathXMin = jmin (pathXMin, x1);
  74514. pathXMax = jmax (pathXMax, x2);
  74515. pathYMin = jmin (pathYMin, y1);
  74516. pathYMax = jmax (pathYMax, y2);
  74517. }
  74518. data.elements [numElements++] = moveMarker;
  74519. data.elements [numElements++] = x1;
  74520. data.elements [numElements++] = y2;
  74521. data.elements [numElements++] = lineMarker;
  74522. data.elements [numElements++] = x1;
  74523. data.elements [numElements++] = y1;
  74524. data.elements [numElements++] = lineMarker;
  74525. data.elements [numElements++] = x2;
  74526. data.elements [numElements++] = y1;
  74527. data.elements [numElements++] = lineMarker;
  74528. data.elements [numElements++] = x2;
  74529. data.elements [numElements++] = y2;
  74530. data.elements [numElements++] = closeSubPathMarker;
  74531. }
  74532. void Path::addRoundedRectangle (const float x, const float y,
  74533. const float w, const float h,
  74534. float csx,
  74535. float csy)
  74536. {
  74537. csx = jmin (csx, w * 0.5f);
  74538. csy = jmin (csy, h * 0.5f);
  74539. const float cs45x = csx * 0.45f;
  74540. const float cs45y = csy * 0.45f;
  74541. const float x2 = x + w;
  74542. const float y2 = y + h;
  74543. startNewSubPath (x + csx, y);
  74544. lineTo (x2 - csx, y);
  74545. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74546. lineTo (x2, y2 - csy);
  74547. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74548. lineTo (x + csx, y2);
  74549. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74550. lineTo (x, y + csy);
  74551. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74552. closeSubPath();
  74553. }
  74554. void Path::addRoundedRectangle (const float x, const float y,
  74555. const float w, const float h,
  74556. float cs)
  74557. {
  74558. addRoundedRectangle (x, y, w, h, cs, cs);
  74559. }
  74560. void Path::addTriangle (const float x1, const float y1,
  74561. const float x2, const float y2,
  74562. const float x3, const float y3)
  74563. {
  74564. startNewSubPath (x1, y1);
  74565. lineTo (x2, y2);
  74566. lineTo (x3, y3);
  74567. closeSubPath();
  74568. }
  74569. void Path::addQuadrilateral (const float x1, const float y1,
  74570. const float x2, const float y2,
  74571. const float x3, const float y3,
  74572. const float x4, const float y4)
  74573. {
  74574. startNewSubPath (x1, y1);
  74575. lineTo (x2, y2);
  74576. lineTo (x3, y3);
  74577. lineTo (x4, y4);
  74578. closeSubPath();
  74579. }
  74580. void Path::addEllipse (const float x, const float y,
  74581. const float w, const float h)
  74582. {
  74583. const float hw = w * 0.5f;
  74584. const float hw55 = hw * 0.55f;
  74585. const float hh = h * 0.5f;
  74586. const float hh55 = hh * 0.55f;
  74587. const float cx = x + hw;
  74588. const float cy = y + hh;
  74589. startNewSubPath (cx, cy - hh);
  74590. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74591. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74592. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74593. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74594. closeSubPath();
  74595. }
  74596. void Path::addArc (const float x, const float y,
  74597. const float w, const float h,
  74598. const float fromRadians,
  74599. const float toRadians,
  74600. const bool startAsNewSubPath)
  74601. {
  74602. const float radiusX = w / 2.0f;
  74603. const float radiusY = h / 2.0f;
  74604. addCentredArc (x + radiusX,
  74605. y + radiusY,
  74606. radiusX, radiusY,
  74607. 0.0f,
  74608. fromRadians, toRadians,
  74609. startAsNewSubPath);
  74610. }
  74611. void Path::addCentredArc (const float centreX, const float centreY,
  74612. const float radiusX, const float radiusY,
  74613. const float rotationOfEllipse,
  74614. const float fromRadians,
  74615. const float toRadians,
  74616. const bool startAsNewSubPath)
  74617. {
  74618. if (radiusX > 0.0f && radiusY > 0.0f)
  74619. {
  74620. const Point<float> centre (centreX, centreY);
  74621. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74622. float angle = fromRadians;
  74623. if (startAsNewSubPath)
  74624. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74625. if (fromRadians < toRadians)
  74626. {
  74627. if (startAsNewSubPath)
  74628. angle += PathHelpers::ellipseAngularIncrement;
  74629. while (angle < toRadians)
  74630. {
  74631. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74632. angle += PathHelpers::ellipseAngularIncrement;
  74633. }
  74634. }
  74635. else
  74636. {
  74637. if (startAsNewSubPath)
  74638. angle -= PathHelpers::ellipseAngularIncrement;
  74639. while (angle > toRadians)
  74640. {
  74641. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74642. angle -= PathHelpers::ellipseAngularIncrement;
  74643. }
  74644. }
  74645. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74646. }
  74647. }
  74648. void Path::addPieSegment (const float x, const float y,
  74649. const float width, const float height,
  74650. const float fromRadians,
  74651. const float toRadians,
  74652. const float innerCircleProportionalSize)
  74653. {
  74654. float radiusX = width * 0.5f;
  74655. float radiusY = height * 0.5f;
  74656. const Point<float> centre (x + radiusX, y + radiusY);
  74657. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74658. addArc (x, y, width, height, fromRadians, toRadians);
  74659. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74660. {
  74661. closeSubPath();
  74662. if (innerCircleProportionalSize > 0)
  74663. {
  74664. radiusX *= innerCircleProportionalSize;
  74665. radiusY *= innerCircleProportionalSize;
  74666. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74667. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74668. }
  74669. }
  74670. else
  74671. {
  74672. if (innerCircleProportionalSize > 0)
  74673. {
  74674. radiusX *= innerCircleProportionalSize;
  74675. radiusY *= innerCircleProportionalSize;
  74676. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74677. }
  74678. else
  74679. {
  74680. lineTo (centre);
  74681. }
  74682. }
  74683. closeSubPath();
  74684. }
  74685. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74686. {
  74687. const Line<float> reversed (line.reversed());
  74688. lineThickness *= 0.5f;
  74689. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74690. lineTo (line.getPointAlongLine (0, -lineThickness));
  74691. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74692. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74693. closeSubPath();
  74694. }
  74695. void Path::addArrow (const Line<float>& line, float lineThickness,
  74696. float arrowheadWidth, float arrowheadLength)
  74697. {
  74698. const Line<float> reversed (line.reversed());
  74699. lineThickness *= 0.5f;
  74700. arrowheadWidth *= 0.5f;
  74701. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74702. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74703. lineTo (line.getPointAlongLine (0, -lineThickness));
  74704. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74705. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74706. lineTo (line.getEnd());
  74707. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74708. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74709. closeSubPath();
  74710. }
  74711. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74712. const float radius, const float startAngle)
  74713. {
  74714. jassert (numberOfSides > 1); // this would be silly.
  74715. if (numberOfSides > 1)
  74716. {
  74717. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74718. for (int i = 0; i < numberOfSides; ++i)
  74719. {
  74720. const float angle = startAngle + i * angleBetweenPoints;
  74721. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74722. if (i == 0)
  74723. startNewSubPath (p);
  74724. else
  74725. lineTo (p);
  74726. }
  74727. closeSubPath();
  74728. }
  74729. }
  74730. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74731. const float innerRadius, const float outerRadius, const float startAngle)
  74732. {
  74733. jassert (numberOfPoints > 1); // this would be silly.
  74734. if (numberOfPoints > 1)
  74735. {
  74736. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74737. for (int i = 0; i < numberOfPoints; ++i)
  74738. {
  74739. const float angle = startAngle + i * angleBetweenPoints;
  74740. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74741. if (i == 0)
  74742. startNewSubPath (p);
  74743. else
  74744. lineTo (p);
  74745. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74746. }
  74747. closeSubPath();
  74748. }
  74749. }
  74750. void Path::addBubble (float x, float y,
  74751. float w, float h,
  74752. float cs,
  74753. float tipX,
  74754. float tipY,
  74755. int whichSide,
  74756. float arrowPos,
  74757. float arrowWidth)
  74758. {
  74759. if (w > 1.0f && h > 1.0f)
  74760. {
  74761. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74762. const float cs2 = 2.0f * cs;
  74763. startNewSubPath (x + cs, y);
  74764. if (whichSide == 0)
  74765. {
  74766. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74767. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74768. lineTo (arrowX1, y);
  74769. lineTo (tipX, tipY);
  74770. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74771. }
  74772. lineTo (x + w - cs, y);
  74773. if (cs > 0.0f)
  74774. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74775. if (whichSide == 3)
  74776. {
  74777. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74778. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74779. lineTo (x + w, arrowY1);
  74780. lineTo (tipX, tipY);
  74781. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74782. }
  74783. lineTo (x + w, y + h - cs);
  74784. if (cs > 0.0f)
  74785. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74786. if (whichSide == 2)
  74787. {
  74788. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74789. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74790. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74791. lineTo (tipX, tipY);
  74792. lineTo (arrowX1, y + h);
  74793. }
  74794. lineTo (x + cs, y + h);
  74795. if (cs > 0.0f)
  74796. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74797. if (whichSide == 1)
  74798. {
  74799. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74800. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74801. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74802. lineTo (tipX, tipY);
  74803. lineTo (x, arrowY1);
  74804. }
  74805. lineTo (x, y + cs);
  74806. if (cs > 0.0f)
  74807. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74808. closeSubPath();
  74809. }
  74810. }
  74811. void Path::addPath (const Path& other)
  74812. {
  74813. size_t i = 0;
  74814. while (i < other.numElements)
  74815. {
  74816. const float type = other.data.elements [i++];
  74817. if (type == moveMarker)
  74818. {
  74819. startNewSubPath (other.data.elements [i],
  74820. other.data.elements [i + 1]);
  74821. i += 2;
  74822. }
  74823. else if (type == lineMarker)
  74824. {
  74825. lineTo (other.data.elements [i],
  74826. other.data.elements [i + 1]);
  74827. i += 2;
  74828. }
  74829. else if (type == quadMarker)
  74830. {
  74831. quadraticTo (other.data.elements [i],
  74832. other.data.elements [i + 1],
  74833. other.data.elements [i + 2],
  74834. other.data.elements [i + 3]);
  74835. i += 4;
  74836. }
  74837. else if (type == cubicMarker)
  74838. {
  74839. cubicTo (other.data.elements [i],
  74840. other.data.elements [i + 1],
  74841. other.data.elements [i + 2],
  74842. other.data.elements [i + 3],
  74843. other.data.elements [i + 4],
  74844. other.data.elements [i + 5]);
  74845. i += 6;
  74846. }
  74847. else if (type == closeSubPathMarker)
  74848. {
  74849. closeSubPath();
  74850. }
  74851. else
  74852. {
  74853. // something's gone wrong with the element list!
  74854. jassertfalse;
  74855. }
  74856. }
  74857. }
  74858. void Path::addPath (const Path& other,
  74859. const AffineTransform& transformToApply)
  74860. {
  74861. size_t i = 0;
  74862. while (i < other.numElements)
  74863. {
  74864. const float type = other.data.elements [i++];
  74865. if (type == closeSubPathMarker)
  74866. {
  74867. closeSubPath();
  74868. }
  74869. else
  74870. {
  74871. float x = other.data.elements [i++];
  74872. float y = other.data.elements [i++];
  74873. transformToApply.transformPoint (x, y);
  74874. if (type == moveMarker)
  74875. {
  74876. startNewSubPath (x, y);
  74877. }
  74878. else if (type == lineMarker)
  74879. {
  74880. lineTo (x, y);
  74881. }
  74882. else if (type == quadMarker)
  74883. {
  74884. float x2 = other.data.elements [i++];
  74885. float y2 = other.data.elements [i++];
  74886. transformToApply.transformPoint (x2, y2);
  74887. quadraticTo (x, y, x2, y2);
  74888. }
  74889. else if (type == cubicMarker)
  74890. {
  74891. float x2 = other.data.elements [i++];
  74892. float y2 = other.data.elements [i++];
  74893. float x3 = other.data.elements [i++];
  74894. float y3 = other.data.elements [i++];
  74895. transformToApply.transformPoints (x2, y2, x3, y3);
  74896. cubicTo (x, y, x2, y2, x3, y3);
  74897. }
  74898. else
  74899. {
  74900. // something's gone wrong with the element list!
  74901. jassertfalse;
  74902. }
  74903. }
  74904. }
  74905. }
  74906. void Path::applyTransform (const AffineTransform& transform) throw()
  74907. {
  74908. size_t i = 0;
  74909. pathYMin = pathXMin = 0;
  74910. pathYMax = pathXMax = 0;
  74911. bool setMaxMin = false;
  74912. while (i < numElements)
  74913. {
  74914. const float type = data.elements [i++];
  74915. if (type == moveMarker)
  74916. {
  74917. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74918. if (setMaxMin)
  74919. {
  74920. pathXMin = jmin (pathXMin, data.elements [i]);
  74921. pathXMax = jmax (pathXMax, data.elements [i]);
  74922. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74923. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74924. }
  74925. else
  74926. {
  74927. pathXMin = pathXMax = data.elements [i];
  74928. pathYMin = pathYMax = data.elements [i + 1];
  74929. setMaxMin = true;
  74930. }
  74931. i += 2;
  74932. }
  74933. else if (type == lineMarker)
  74934. {
  74935. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74936. pathXMin = jmin (pathXMin, data.elements [i]);
  74937. pathXMax = jmax (pathXMax, data.elements [i]);
  74938. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74939. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74940. i += 2;
  74941. }
  74942. else if (type == quadMarker)
  74943. {
  74944. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74945. data.elements [i + 2], data.elements [i + 3]);
  74946. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74947. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74948. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74949. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74950. i += 4;
  74951. }
  74952. else if (type == cubicMarker)
  74953. {
  74954. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74955. data.elements [i + 2], data.elements [i + 3],
  74956. data.elements [i + 4], data.elements [i + 5]);
  74957. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74958. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74959. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74960. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74961. i += 6;
  74962. }
  74963. }
  74964. }
  74965. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74966. const float w, const float h,
  74967. const bool preserveProportions,
  74968. const Justification& justification) const
  74969. {
  74970. Rectangle<float> bounds (getBounds());
  74971. if (preserveProportions)
  74972. {
  74973. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74974. return AffineTransform::identity;
  74975. float newW, newH;
  74976. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74977. if (srcRatio > h / w)
  74978. {
  74979. newW = h / srcRatio;
  74980. newH = h;
  74981. }
  74982. else
  74983. {
  74984. newW = w;
  74985. newH = w * srcRatio;
  74986. }
  74987. float newXCentre = x;
  74988. float newYCentre = y;
  74989. if (justification.testFlags (Justification::left))
  74990. newXCentre += newW * 0.5f;
  74991. else if (justification.testFlags (Justification::right))
  74992. newXCentre += w - newW * 0.5f;
  74993. else
  74994. newXCentre += w * 0.5f;
  74995. if (justification.testFlags (Justification::top))
  74996. newYCentre += newH * 0.5f;
  74997. else if (justification.testFlags (Justification::bottom))
  74998. newYCentre += h - newH * 0.5f;
  74999. else
  75000. newYCentre += h * 0.5f;
  75001. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  75002. bounds.getHeight() * -0.5f - bounds.getY())
  75003. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  75004. .translated (newXCentre, newYCentre);
  75005. }
  75006. else
  75007. {
  75008. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  75009. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  75010. .translated (x, y);
  75011. }
  75012. }
  75013. bool Path::contains (const float x, const float y, const float tolerence) const
  75014. {
  75015. if (x <= pathXMin || x >= pathXMax
  75016. || y <= pathYMin || y >= pathYMax)
  75017. return false;
  75018. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  75019. int positiveCrossings = 0;
  75020. int negativeCrossings = 0;
  75021. while (i.next())
  75022. {
  75023. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  75024. {
  75025. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  75026. if (intersectX <= x)
  75027. {
  75028. if (i.y1 < i.y2)
  75029. ++positiveCrossings;
  75030. else
  75031. ++negativeCrossings;
  75032. }
  75033. }
  75034. }
  75035. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  75036. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  75037. }
  75038. bool Path::contains (const Point<float>& point, const float tolerence) const
  75039. {
  75040. return contains (point.getX(), point.getY(), tolerence);
  75041. }
  75042. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  75043. {
  75044. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  75045. Point<float> intersection;
  75046. while (i.next())
  75047. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75048. return true;
  75049. return false;
  75050. }
  75051. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75052. {
  75053. Line<float> result (line);
  75054. const bool startInside = contains (line.getStart());
  75055. const bool endInside = contains (line.getEnd());
  75056. if (startInside == endInside)
  75057. {
  75058. if (keepSectionOutsidePath == startInside)
  75059. result = Line<float>();
  75060. }
  75061. else
  75062. {
  75063. PathFlatteningIterator i (*this, AffineTransform::identity);
  75064. Point<float> intersection;
  75065. while (i.next())
  75066. {
  75067. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75068. {
  75069. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75070. result.setStart (intersection);
  75071. else
  75072. result.setEnd (intersection);
  75073. }
  75074. }
  75075. }
  75076. return result;
  75077. }
  75078. float Path::getLength (const AffineTransform& transform) const
  75079. {
  75080. float length = 0;
  75081. PathFlatteningIterator i (*this, transform);
  75082. while (i.next())
  75083. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75084. return length;
  75085. }
  75086. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75087. {
  75088. PathFlatteningIterator i (*this, transform);
  75089. while (i.next())
  75090. {
  75091. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75092. const float lineLength = line.getLength();
  75093. if (distanceFromStart <= lineLength)
  75094. return line.getPointAlongLine (distanceFromStart);
  75095. distanceFromStart -= lineLength;
  75096. }
  75097. return Point<float> (i.x2, i.y2);
  75098. }
  75099. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75100. const AffineTransform& transform) const
  75101. {
  75102. PathFlatteningIterator i (*this, transform);
  75103. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75104. float length = 0;
  75105. Point<float> pointOnLine;
  75106. while (i.next())
  75107. {
  75108. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75109. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75110. if (distance < bestDistance)
  75111. {
  75112. bestDistance = distance;
  75113. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75114. pointOnPath = pointOnLine;
  75115. }
  75116. length += line.getLength();
  75117. }
  75118. return bestPosition;
  75119. }
  75120. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75121. {
  75122. if (cornerRadius <= 0.01f)
  75123. return *this;
  75124. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75125. size_t n = 0;
  75126. bool lastWasLine = false, firstWasLine = false;
  75127. Path p;
  75128. while (n < numElements)
  75129. {
  75130. const float type = data.elements [n++];
  75131. if (type == moveMarker)
  75132. {
  75133. indexOfPathStart = p.numElements;
  75134. indexOfPathStartThis = n - 1;
  75135. const float x = data.elements [n++];
  75136. const float y = data.elements [n++];
  75137. p.startNewSubPath (x, y);
  75138. lastWasLine = false;
  75139. firstWasLine = (data.elements [n] == lineMarker);
  75140. }
  75141. else if (type == lineMarker || type == closeSubPathMarker)
  75142. {
  75143. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75144. if (type == lineMarker)
  75145. {
  75146. endX = data.elements [n++];
  75147. endY = data.elements [n++];
  75148. if (n > 8)
  75149. {
  75150. startX = data.elements [n - 8];
  75151. startY = data.elements [n - 7];
  75152. joinX = data.elements [n - 5];
  75153. joinY = data.elements [n - 4];
  75154. }
  75155. }
  75156. else
  75157. {
  75158. endX = data.elements [indexOfPathStartThis + 1];
  75159. endY = data.elements [indexOfPathStartThis + 2];
  75160. if (n > 6)
  75161. {
  75162. startX = data.elements [n - 6];
  75163. startY = data.elements [n - 5];
  75164. joinX = data.elements [n - 3];
  75165. joinY = data.elements [n - 2];
  75166. }
  75167. }
  75168. if (lastWasLine)
  75169. {
  75170. const double len1 = juce_hypot (startX - joinX,
  75171. startY - joinY);
  75172. if (len1 > 0)
  75173. {
  75174. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75175. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75176. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75177. }
  75178. const double len2 = juce_hypot (endX - joinX,
  75179. endY - joinY);
  75180. if (len2 > 0)
  75181. {
  75182. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75183. p.quadraticTo (joinX, joinY,
  75184. (float) (joinX + (endX - joinX) * propNeeded),
  75185. (float) (joinY + (endY - joinY) * propNeeded));
  75186. }
  75187. p.lineTo (endX, endY);
  75188. }
  75189. else if (type == lineMarker)
  75190. {
  75191. p.lineTo (endX, endY);
  75192. lastWasLine = true;
  75193. }
  75194. if (type == closeSubPathMarker)
  75195. {
  75196. if (firstWasLine)
  75197. {
  75198. startX = data.elements [n - 3];
  75199. startY = data.elements [n - 2];
  75200. joinX = endX;
  75201. joinY = endY;
  75202. endX = data.elements [indexOfPathStartThis + 4];
  75203. endY = data.elements [indexOfPathStartThis + 5];
  75204. const double len1 = juce_hypot (startX - joinX,
  75205. startY - joinY);
  75206. if (len1 > 0)
  75207. {
  75208. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75209. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75210. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75211. }
  75212. const double len2 = juce_hypot (endX - joinX,
  75213. endY - joinY);
  75214. if (len2 > 0)
  75215. {
  75216. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75217. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75218. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75219. p.quadraticTo (joinX, joinY, endX, endY);
  75220. p.data.elements [indexOfPathStart + 1] = endX;
  75221. p.data.elements [indexOfPathStart + 2] = endY;
  75222. }
  75223. }
  75224. p.closeSubPath();
  75225. }
  75226. }
  75227. else if (type == quadMarker)
  75228. {
  75229. lastWasLine = false;
  75230. const float x1 = data.elements [n++];
  75231. const float y1 = data.elements [n++];
  75232. const float x2 = data.elements [n++];
  75233. const float y2 = data.elements [n++];
  75234. p.quadraticTo (x1, y1, x2, y2);
  75235. }
  75236. else if (type == cubicMarker)
  75237. {
  75238. lastWasLine = false;
  75239. const float x1 = data.elements [n++];
  75240. const float y1 = data.elements [n++];
  75241. const float x2 = data.elements [n++];
  75242. const float y2 = data.elements [n++];
  75243. const float x3 = data.elements [n++];
  75244. const float y3 = data.elements [n++];
  75245. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75246. }
  75247. }
  75248. return p;
  75249. }
  75250. void Path::loadPathFromStream (InputStream& source)
  75251. {
  75252. while (! source.isExhausted())
  75253. {
  75254. switch (source.readByte())
  75255. {
  75256. case 'm':
  75257. {
  75258. const float x = source.readFloat();
  75259. const float y = source.readFloat();
  75260. startNewSubPath (x, y);
  75261. break;
  75262. }
  75263. case 'l':
  75264. {
  75265. const float x = source.readFloat();
  75266. const float y = source.readFloat();
  75267. lineTo (x, y);
  75268. break;
  75269. }
  75270. case 'q':
  75271. {
  75272. const float x1 = source.readFloat();
  75273. const float y1 = source.readFloat();
  75274. const float x2 = source.readFloat();
  75275. const float y2 = source.readFloat();
  75276. quadraticTo (x1, y1, x2, y2);
  75277. break;
  75278. }
  75279. case 'b':
  75280. {
  75281. const float x1 = source.readFloat();
  75282. const float y1 = source.readFloat();
  75283. const float x2 = source.readFloat();
  75284. const float y2 = source.readFloat();
  75285. const float x3 = source.readFloat();
  75286. const float y3 = source.readFloat();
  75287. cubicTo (x1, y1, x2, y2, x3, y3);
  75288. break;
  75289. }
  75290. case 'c':
  75291. closeSubPath();
  75292. break;
  75293. case 'n':
  75294. useNonZeroWinding = true;
  75295. break;
  75296. case 'z':
  75297. useNonZeroWinding = false;
  75298. break;
  75299. case 'e':
  75300. return; // end of path marker
  75301. default:
  75302. jassertfalse; // illegal char in the stream
  75303. break;
  75304. }
  75305. }
  75306. }
  75307. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75308. {
  75309. MemoryInputStream in (pathData, numberOfBytes, false);
  75310. loadPathFromStream (in);
  75311. }
  75312. void Path::writePathToStream (OutputStream& dest) const
  75313. {
  75314. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75315. size_t i = 0;
  75316. while (i < numElements)
  75317. {
  75318. const float type = data.elements [i++];
  75319. if (type == moveMarker)
  75320. {
  75321. dest.writeByte ('m');
  75322. dest.writeFloat (data.elements [i++]);
  75323. dest.writeFloat (data.elements [i++]);
  75324. }
  75325. else if (type == lineMarker)
  75326. {
  75327. dest.writeByte ('l');
  75328. dest.writeFloat (data.elements [i++]);
  75329. dest.writeFloat (data.elements [i++]);
  75330. }
  75331. else if (type == quadMarker)
  75332. {
  75333. dest.writeByte ('q');
  75334. dest.writeFloat (data.elements [i++]);
  75335. dest.writeFloat (data.elements [i++]);
  75336. dest.writeFloat (data.elements [i++]);
  75337. dest.writeFloat (data.elements [i++]);
  75338. }
  75339. else if (type == cubicMarker)
  75340. {
  75341. dest.writeByte ('b');
  75342. dest.writeFloat (data.elements [i++]);
  75343. dest.writeFloat (data.elements [i++]);
  75344. dest.writeFloat (data.elements [i++]);
  75345. dest.writeFloat (data.elements [i++]);
  75346. dest.writeFloat (data.elements [i++]);
  75347. dest.writeFloat (data.elements [i++]);
  75348. }
  75349. else if (type == closeSubPathMarker)
  75350. {
  75351. dest.writeByte ('c');
  75352. }
  75353. }
  75354. dest.writeByte ('e'); // marks the end-of-path
  75355. }
  75356. const String Path::toString() const
  75357. {
  75358. MemoryOutputStream s (2048);
  75359. if (! useNonZeroWinding)
  75360. s << 'a';
  75361. size_t i = 0;
  75362. float lastMarker = 0.0f;
  75363. while (i < numElements)
  75364. {
  75365. const float marker = data.elements [i++];
  75366. char markerChar = 0;
  75367. int numCoords = 0;
  75368. if (marker == moveMarker)
  75369. {
  75370. markerChar = 'm';
  75371. numCoords = 2;
  75372. }
  75373. else if (marker == lineMarker)
  75374. {
  75375. markerChar = 'l';
  75376. numCoords = 2;
  75377. }
  75378. else if (marker == quadMarker)
  75379. {
  75380. markerChar = 'q';
  75381. numCoords = 4;
  75382. }
  75383. else if (marker == cubicMarker)
  75384. {
  75385. markerChar = 'c';
  75386. numCoords = 6;
  75387. }
  75388. else
  75389. {
  75390. jassert (marker == closeSubPathMarker);
  75391. markerChar = 'z';
  75392. }
  75393. if (marker != lastMarker)
  75394. {
  75395. if (s.getDataSize() != 0)
  75396. s << ' ';
  75397. s << markerChar;
  75398. lastMarker = marker;
  75399. }
  75400. while (--numCoords >= 0 && i < numElements)
  75401. {
  75402. String coord (data.elements [i++], 3);
  75403. while (coord.endsWithChar ('0') && coord != "0")
  75404. coord = coord.dropLastCharacters (1);
  75405. if (coord.endsWithChar ('.'))
  75406. coord = coord.dropLastCharacters (1);
  75407. if (s.getDataSize() != 0)
  75408. s << ' ';
  75409. s << coord;
  75410. }
  75411. }
  75412. return s.toUTF8();
  75413. }
  75414. void Path::restoreFromString (const String& stringVersion)
  75415. {
  75416. clear();
  75417. setUsingNonZeroWinding (true);
  75418. const juce_wchar* t = stringVersion;
  75419. juce_wchar marker = 'm';
  75420. int numValues = 2;
  75421. float values [6];
  75422. for (;;)
  75423. {
  75424. const String token (PathHelpers::nextToken (t));
  75425. const juce_wchar firstChar = token[0];
  75426. int startNum = 0;
  75427. if (firstChar == 0)
  75428. break;
  75429. if (firstChar == 'm' || firstChar == 'l')
  75430. {
  75431. marker = firstChar;
  75432. numValues = 2;
  75433. }
  75434. else if (firstChar == 'q')
  75435. {
  75436. marker = firstChar;
  75437. numValues = 4;
  75438. }
  75439. else if (firstChar == 'c')
  75440. {
  75441. marker = firstChar;
  75442. numValues = 6;
  75443. }
  75444. else if (firstChar == 'z')
  75445. {
  75446. marker = firstChar;
  75447. numValues = 0;
  75448. }
  75449. else if (firstChar == 'a')
  75450. {
  75451. setUsingNonZeroWinding (false);
  75452. continue;
  75453. }
  75454. else
  75455. {
  75456. ++startNum;
  75457. values [0] = token.getFloatValue();
  75458. }
  75459. for (int i = startNum; i < numValues; ++i)
  75460. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75461. switch (marker)
  75462. {
  75463. case 'm': startNewSubPath (values[0], values[1]); break;
  75464. case 'l': lineTo (values[0], values[1]); break;
  75465. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75466. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75467. case 'z': closeSubPath(); break;
  75468. default: jassertfalse; break; // illegal string format?
  75469. }
  75470. }
  75471. }
  75472. Path::Iterator::Iterator (const Path& path_)
  75473. : path (path_),
  75474. index (0)
  75475. {
  75476. }
  75477. Path::Iterator::~Iterator()
  75478. {
  75479. }
  75480. bool Path::Iterator::next()
  75481. {
  75482. const float* const elements = path.data.elements;
  75483. if (index < path.numElements)
  75484. {
  75485. const float type = elements [index++];
  75486. if (type == moveMarker)
  75487. {
  75488. elementType = startNewSubPath;
  75489. x1 = elements [index++];
  75490. y1 = elements [index++];
  75491. }
  75492. else if (type == lineMarker)
  75493. {
  75494. elementType = lineTo;
  75495. x1 = elements [index++];
  75496. y1 = elements [index++];
  75497. }
  75498. else if (type == quadMarker)
  75499. {
  75500. elementType = quadraticTo;
  75501. x1 = elements [index++];
  75502. y1 = elements [index++];
  75503. x2 = elements [index++];
  75504. y2 = elements [index++];
  75505. }
  75506. else if (type == cubicMarker)
  75507. {
  75508. elementType = cubicTo;
  75509. x1 = elements [index++];
  75510. y1 = elements [index++];
  75511. x2 = elements [index++];
  75512. y2 = elements [index++];
  75513. x3 = elements [index++];
  75514. y3 = elements [index++];
  75515. }
  75516. else if (type == closeSubPathMarker)
  75517. {
  75518. elementType = closePath;
  75519. }
  75520. return true;
  75521. }
  75522. return false;
  75523. }
  75524. END_JUCE_NAMESPACE
  75525. /*** End of inlined file: juce_Path.cpp ***/
  75526. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75527. BEGIN_JUCE_NAMESPACE
  75528. #if JUCE_MSVC && JUCE_DEBUG
  75529. #pragma optimize ("t", on)
  75530. #endif
  75531. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75532. const AffineTransform& transform_,
  75533. float tolerence_)
  75534. : x2 (0),
  75535. y2 (0),
  75536. closesSubPath (false),
  75537. subPathIndex (-1),
  75538. path (path_),
  75539. transform (transform_),
  75540. points (path_.data.elements),
  75541. tolerence (tolerence_ * tolerence_),
  75542. subPathCloseX (0),
  75543. subPathCloseY (0),
  75544. isIdentityTransform (transform_.isIdentity()),
  75545. stackBase (32),
  75546. index (0),
  75547. stackSize (32)
  75548. {
  75549. stackPos = stackBase;
  75550. }
  75551. PathFlatteningIterator::~PathFlatteningIterator()
  75552. {
  75553. }
  75554. bool PathFlatteningIterator::next()
  75555. {
  75556. x1 = x2;
  75557. y1 = y2;
  75558. float x3 = 0;
  75559. float y3 = 0;
  75560. float x4 = 0;
  75561. float y4 = 0;
  75562. float type;
  75563. for (;;)
  75564. {
  75565. if (stackPos == stackBase)
  75566. {
  75567. if (index >= path.numElements)
  75568. {
  75569. return false;
  75570. }
  75571. else
  75572. {
  75573. type = points [index++];
  75574. if (type != Path::closeSubPathMarker)
  75575. {
  75576. x2 = points [index++];
  75577. y2 = points [index++];
  75578. if (type == Path::quadMarker)
  75579. {
  75580. x3 = points [index++];
  75581. y3 = points [index++];
  75582. if (! isIdentityTransform)
  75583. transform.transformPoints (x2, y2, x3, y3);
  75584. }
  75585. else if (type == Path::cubicMarker)
  75586. {
  75587. x3 = points [index++];
  75588. y3 = points [index++];
  75589. x4 = points [index++];
  75590. y4 = points [index++];
  75591. if (! isIdentityTransform)
  75592. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75593. }
  75594. else
  75595. {
  75596. if (! isIdentityTransform)
  75597. transform.transformPoint (x2, y2);
  75598. }
  75599. }
  75600. }
  75601. }
  75602. else
  75603. {
  75604. type = *--stackPos;
  75605. if (type != Path::closeSubPathMarker)
  75606. {
  75607. x2 = *--stackPos;
  75608. y2 = *--stackPos;
  75609. if (type == Path::quadMarker)
  75610. {
  75611. x3 = *--stackPos;
  75612. y3 = *--stackPos;
  75613. }
  75614. else if (type == Path::cubicMarker)
  75615. {
  75616. x3 = *--stackPos;
  75617. y3 = *--stackPos;
  75618. x4 = *--stackPos;
  75619. y4 = *--stackPos;
  75620. }
  75621. }
  75622. }
  75623. if (type == Path::lineMarker)
  75624. {
  75625. ++subPathIndex;
  75626. closesSubPath = (stackPos == stackBase)
  75627. && (index < path.numElements)
  75628. && (points [index] == Path::closeSubPathMarker)
  75629. && x2 == subPathCloseX
  75630. && y2 == subPathCloseY;
  75631. return true;
  75632. }
  75633. else if (type == Path::quadMarker)
  75634. {
  75635. const size_t offset = (size_t) (stackPos - stackBase);
  75636. if (offset >= stackSize - 10)
  75637. {
  75638. stackSize <<= 1;
  75639. stackBase.realloc (stackSize);
  75640. stackPos = stackBase + offset;
  75641. }
  75642. const float dx1 = x1 - x2;
  75643. const float dy1 = y1 - y2;
  75644. const float dx2 = x2 - x3;
  75645. const float dy2 = y2 - y3;
  75646. const float m1x = (x1 + x2) * 0.5f;
  75647. const float m1y = (y1 + y2) * 0.5f;
  75648. const float m2x = (x2 + x3) * 0.5f;
  75649. const float m2y = (y2 + y3) * 0.5f;
  75650. const float m3x = (m1x + m2x) * 0.5f;
  75651. const float m3y = (m1y + m2y) * 0.5f;
  75652. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75653. {
  75654. *stackPos++ = y3;
  75655. *stackPos++ = x3;
  75656. *stackPos++ = m2y;
  75657. *stackPos++ = m2x;
  75658. *stackPos++ = Path::quadMarker;
  75659. *stackPos++ = m3y;
  75660. *stackPos++ = m3x;
  75661. *stackPos++ = m1y;
  75662. *stackPos++ = m1x;
  75663. *stackPos++ = Path::quadMarker;
  75664. }
  75665. else
  75666. {
  75667. *stackPos++ = y3;
  75668. *stackPos++ = x3;
  75669. *stackPos++ = Path::lineMarker;
  75670. *stackPos++ = m3y;
  75671. *stackPos++ = m3x;
  75672. *stackPos++ = Path::lineMarker;
  75673. }
  75674. jassert (stackPos < stackBase + stackSize);
  75675. }
  75676. else if (type == Path::cubicMarker)
  75677. {
  75678. const size_t offset = (size_t) (stackPos - stackBase);
  75679. if (offset >= stackSize - 16)
  75680. {
  75681. stackSize <<= 1;
  75682. stackBase.realloc (stackSize);
  75683. stackPos = stackBase + offset;
  75684. }
  75685. const float dx1 = x1 - x2;
  75686. const float dy1 = y1 - y2;
  75687. const float dx2 = x2 - x3;
  75688. const float dy2 = y2 - y3;
  75689. const float dx3 = x3 - x4;
  75690. const float dy3 = y3 - y4;
  75691. const float m1x = (x1 + x2) * 0.5f;
  75692. const float m1y = (y1 + y2) * 0.5f;
  75693. const float m2x = (x3 + x2) * 0.5f;
  75694. const float m2y = (y3 + y2) * 0.5f;
  75695. const float m3x = (x3 + x4) * 0.5f;
  75696. const float m3y = (y3 + y4) * 0.5f;
  75697. const float m4x = (m1x + m2x) * 0.5f;
  75698. const float m4y = (m1y + m2y) * 0.5f;
  75699. const float m5x = (m3x + m2x) * 0.5f;
  75700. const float m5y = (m3y + m2y) * 0.5f;
  75701. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75702. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75703. {
  75704. *stackPos++ = y4;
  75705. *stackPos++ = x4;
  75706. *stackPos++ = m3y;
  75707. *stackPos++ = m3x;
  75708. *stackPos++ = m5y;
  75709. *stackPos++ = m5x;
  75710. *stackPos++ = Path::cubicMarker;
  75711. *stackPos++ = (m4y + m5y) * 0.5f;
  75712. *stackPos++ = (m4x + m5x) * 0.5f;
  75713. *stackPos++ = m4y;
  75714. *stackPos++ = m4x;
  75715. *stackPos++ = m1y;
  75716. *stackPos++ = m1x;
  75717. *stackPos++ = Path::cubicMarker;
  75718. }
  75719. else
  75720. {
  75721. *stackPos++ = y4;
  75722. *stackPos++ = x4;
  75723. *stackPos++ = Path::lineMarker;
  75724. *stackPos++ = m5y;
  75725. *stackPos++ = m5x;
  75726. *stackPos++ = Path::lineMarker;
  75727. *stackPos++ = m4y;
  75728. *stackPos++ = m4x;
  75729. *stackPos++ = Path::lineMarker;
  75730. }
  75731. }
  75732. else if (type == Path::closeSubPathMarker)
  75733. {
  75734. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75735. {
  75736. x1 = x2;
  75737. y1 = y2;
  75738. x2 = subPathCloseX;
  75739. y2 = subPathCloseY;
  75740. closesSubPath = true;
  75741. return true;
  75742. }
  75743. }
  75744. else
  75745. {
  75746. jassert (type == Path::moveMarker);
  75747. subPathIndex = -1;
  75748. subPathCloseX = x1 = x2;
  75749. subPathCloseY = y1 = y2;
  75750. }
  75751. }
  75752. }
  75753. #if JUCE_MSVC && JUCE_DEBUG
  75754. #pragma optimize ("", on) // resets optimisations to the project defaults
  75755. #endif
  75756. END_JUCE_NAMESPACE
  75757. /*** End of inlined file: juce_PathIterator.cpp ***/
  75758. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75759. BEGIN_JUCE_NAMESPACE
  75760. PathStrokeType::PathStrokeType (const float strokeThickness,
  75761. const JointStyle jointStyle_,
  75762. const EndCapStyle endStyle_) throw()
  75763. : thickness (strokeThickness),
  75764. jointStyle (jointStyle_),
  75765. endStyle (endStyle_)
  75766. {
  75767. }
  75768. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75769. : thickness (other.thickness),
  75770. jointStyle (other.jointStyle),
  75771. endStyle (other.endStyle)
  75772. {
  75773. }
  75774. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75775. {
  75776. thickness = other.thickness;
  75777. jointStyle = other.jointStyle;
  75778. endStyle = other.endStyle;
  75779. return *this;
  75780. }
  75781. PathStrokeType::~PathStrokeType() throw()
  75782. {
  75783. }
  75784. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75785. {
  75786. return thickness == other.thickness
  75787. && jointStyle == other.jointStyle
  75788. && endStyle == other.endStyle;
  75789. }
  75790. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75791. {
  75792. return ! operator== (other);
  75793. }
  75794. namespace PathStrokeHelpers
  75795. {
  75796. static bool lineIntersection (const float x1, const float y1,
  75797. const float x2, const float y2,
  75798. const float x3, const float y3,
  75799. const float x4, const float y4,
  75800. float& intersectionX,
  75801. float& intersectionY,
  75802. float& distanceBeyondLine1EndSquared) throw()
  75803. {
  75804. if (x2 != x3 || y2 != y3)
  75805. {
  75806. const float dx1 = x2 - x1;
  75807. const float dy1 = y2 - y1;
  75808. const float dx2 = x4 - x3;
  75809. const float dy2 = y4 - y3;
  75810. const float divisor = dx1 * dy2 - dx2 * dy1;
  75811. if (divisor == 0)
  75812. {
  75813. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75814. {
  75815. if (dy1 == 0 && dy2 != 0)
  75816. {
  75817. const float along = (y1 - y3) / dy2;
  75818. intersectionX = x3 + along * dx2;
  75819. intersectionY = y1;
  75820. distanceBeyondLine1EndSquared = intersectionX - x2;
  75821. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75822. if ((x2 > x1) == (intersectionX < x2))
  75823. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75824. return along >= 0 && along <= 1.0f;
  75825. }
  75826. else if (dy2 == 0 && dy1 != 0)
  75827. {
  75828. const float along = (y3 - y1) / dy1;
  75829. intersectionX = x1 + along * dx1;
  75830. intersectionY = y3;
  75831. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75832. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75833. if (along < 1.0f)
  75834. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75835. return along >= 0 && along <= 1.0f;
  75836. }
  75837. else if (dx1 == 0 && dx2 != 0)
  75838. {
  75839. const float along = (x1 - x3) / dx2;
  75840. intersectionX = x1;
  75841. intersectionY = y3 + along * dy2;
  75842. distanceBeyondLine1EndSquared = intersectionY - y2;
  75843. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75844. if ((y2 > y1) == (intersectionY < y2))
  75845. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75846. return along >= 0 && along <= 1.0f;
  75847. }
  75848. else if (dx2 == 0 && dx1 != 0)
  75849. {
  75850. const float along = (x3 - x1) / dx1;
  75851. intersectionX = x3;
  75852. intersectionY = y1 + along * dy1;
  75853. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75854. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75855. if (along < 1.0f)
  75856. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75857. return along >= 0 && along <= 1.0f;
  75858. }
  75859. }
  75860. intersectionX = 0.5f * (x2 + x3);
  75861. intersectionY = 0.5f * (y2 + y3);
  75862. distanceBeyondLine1EndSquared = 0.0f;
  75863. return false;
  75864. }
  75865. else
  75866. {
  75867. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75868. intersectionX = x1 + along1 * dx1;
  75869. intersectionY = y1 + along1 * dy1;
  75870. if (along1 >= 0 && along1 <= 1.0f)
  75871. {
  75872. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75873. if (along2 >= 0 && along2 <= divisor)
  75874. {
  75875. distanceBeyondLine1EndSquared = 0.0f;
  75876. return true;
  75877. }
  75878. }
  75879. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75880. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75881. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75882. if (along1 < 1.0f)
  75883. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75884. return false;
  75885. }
  75886. }
  75887. intersectionX = x2;
  75888. intersectionY = y2;
  75889. distanceBeyondLine1EndSquared = 0.0f;
  75890. return true;
  75891. }
  75892. static void addEdgeAndJoint (Path& destPath,
  75893. const PathStrokeType::JointStyle style,
  75894. const float maxMiterExtensionSquared, const float width,
  75895. const float x1, const float y1,
  75896. const float x2, const float y2,
  75897. const float x3, const float y3,
  75898. const float x4, const float y4,
  75899. const float midX, const float midY)
  75900. {
  75901. if (style == PathStrokeType::beveled
  75902. || (x3 == x4 && y3 == y4)
  75903. || (x1 == x2 && y1 == y2))
  75904. {
  75905. destPath.lineTo (x2, y2);
  75906. destPath.lineTo (x3, y3);
  75907. }
  75908. else
  75909. {
  75910. float jx, jy, distanceBeyondLine1EndSquared;
  75911. // if they intersect, use this point..
  75912. if (lineIntersection (x1, y1, x2, y2,
  75913. x3, y3, x4, y4,
  75914. jx, jy, distanceBeyondLine1EndSquared))
  75915. {
  75916. destPath.lineTo (jx, jy);
  75917. }
  75918. else
  75919. {
  75920. if (style == PathStrokeType::mitered)
  75921. {
  75922. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75923. && distanceBeyondLine1EndSquared > 0.0f)
  75924. {
  75925. destPath.lineTo (jx, jy);
  75926. }
  75927. else
  75928. {
  75929. // the end sticks out too far, so just use a blunt joint
  75930. destPath.lineTo (x2, y2);
  75931. destPath.lineTo (x3, y3);
  75932. }
  75933. }
  75934. else
  75935. {
  75936. // curved joints
  75937. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75938. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75939. const float angleIncrement = 0.1f;
  75940. destPath.lineTo (x2, y2);
  75941. if (std::abs (angle1 - angle2) > angleIncrement)
  75942. {
  75943. if (angle2 > angle1 + float_Pi
  75944. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75945. {
  75946. if (angle2 > angle1)
  75947. angle2 -= float_Pi * 2.0f;
  75948. jassert (angle1 <= angle2 + float_Pi);
  75949. angle1 -= angleIncrement;
  75950. while (angle1 > angle2)
  75951. {
  75952. destPath.lineTo (midX + width * std::sin (angle1),
  75953. midY + width * std::cos (angle1));
  75954. angle1 -= angleIncrement;
  75955. }
  75956. }
  75957. else
  75958. {
  75959. if (angle1 > angle2)
  75960. angle1 -= float_Pi * 2.0f;
  75961. jassert (angle1 >= angle2 - float_Pi);
  75962. angle1 += angleIncrement;
  75963. while (angle1 < angle2)
  75964. {
  75965. destPath.lineTo (midX + width * std::sin (angle1),
  75966. midY + width * std::cos (angle1));
  75967. angle1 += angleIncrement;
  75968. }
  75969. }
  75970. }
  75971. destPath.lineTo (x3, y3);
  75972. }
  75973. }
  75974. }
  75975. }
  75976. static void addLineEnd (Path& destPath,
  75977. const PathStrokeType::EndCapStyle style,
  75978. const float x1, const float y1,
  75979. const float x2, const float y2,
  75980. const float width)
  75981. {
  75982. if (style == PathStrokeType::butt)
  75983. {
  75984. destPath.lineTo (x2, y2);
  75985. }
  75986. else
  75987. {
  75988. float offx1, offy1, offx2, offy2;
  75989. float dx = x2 - x1;
  75990. float dy = y2 - y1;
  75991. const float len = juce_hypotf (dx, dy);
  75992. if (len == 0)
  75993. {
  75994. offx1 = offx2 = x1;
  75995. offy1 = offy2 = y1;
  75996. }
  75997. else
  75998. {
  75999. const float offset = width / len;
  76000. dx *= offset;
  76001. dy *= offset;
  76002. offx1 = x1 + dy;
  76003. offy1 = y1 - dx;
  76004. offx2 = x2 + dy;
  76005. offy2 = y2 - dx;
  76006. }
  76007. if (style == PathStrokeType::square)
  76008. {
  76009. // sqaure ends
  76010. destPath.lineTo (offx1, offy1);
  76011. destPath.lineTo (offx2, offy2);
  76012. destPath.lineTo (x2, y2);
  76013. }
  76014. else
  76015. {
  76016. // rounded ends
  76017. const float midx = (offx1 + offx2) * 0.5f;
  76018. const float midy = (offy1 + offy2) * 0.5f;
  76019. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  76020. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  76021. midx, midy);
  76022. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  76023. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  76024. x2, y2);
  76025. }
  76026. }
  76027. }
  76028. struct Arrowhead
  76029. {
  76030. float startWidth, startLength;
  76031. float endWidth, endLength;
  76032. };
  76033. static void addArrowhead (Path& destPath,
  76034. const float x1, const float y1,
  76035. const float x2, const float y2,
  76036. const float tipX, const float tipY,
  76037. const float width,
  76038. const float arrowheadWidth)
  76039. {
  76040. Line<float> line (x1, y1, x2, y2);
  76041. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76042. destPath.lineTo (tipX, tipY);
  76043. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76044. destPath.lineTo (x2, y2);
  76045. }
  76046. struct LineSection
  76047. {
  76048. float x1, y1, x2, y2; // original line
  76049. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76050. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76051. };
  76052. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76053. {
  76054. while (amountAtEnd > 0 && subPath.size() > 0)
  76055. {
  76056. LineSection& l = subPath.getReference (subPath.size() - 1);
  76057. float dx = l.rx2 - l.rx1;
  76058. float dy = l.ry2 - l.ry1;
  76059. const float len = juce_hypotf (dx, dy);
  76060. if (len <= amountAtEnd && subPath.size() > 1)
  76061. {
  76062. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76063. prev.x2 = l.x2;
  76064. prev.y2 = l.y2;
  76065. subPath.removeLast();
  76066. amountAtEnd -= len;
  76067. }
  76068. else
  76069. {
  76070. const float prop = jmin (0.9999f, amountAtEnd / len);
  76071. dx *= prop;
  76072. dy *= prop;
  76073. l.rx1 += dx;
  76074. l.ry1 += dy;
  76075. l.lx2 += dx;
  76076. l.ly2 += dy;
  76077. break;
  76078. }
  76079. }
  76080. while (amountAtStart > 0 && subPath.size() > 0)
  76081. {
  76082. LineSection& l = subPath.getReference (0);
  76083. float dx = l.rx2 - l.rx1;
  76084. float dy = l.ry2 - l.ry1;
  76085. const float len = juce_hypotf (dx, dy);
  76086. if (len <= amountAtStart && subPath.size() > 1)
  76087. {
  76088. LineSection& next = subPath.getReference (1);
  76089. next.x1 = l.x1;
  76090. next.y1 = l.y1;
  76091. subPath.remove (0);
  76092. amountAtStart -= len;
  76093. }
  76094. else
  76095. {
  76096. const float prop = jmin (0.9999f, amountAtStart / len);
  76097. dx *= prop;
  76098. dy *= prop;
  76099. l.rx2 -= dx;
  76100. l.ry2 -= dy;
  76101. l.lx1 -= dx;
  76102. l.ly1 -= dy;
  76103. break;
  76104. }
  76105. }
  76106. }
  76107. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76108. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76109. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76110. const Arrowhead* const arrowhead)
  76111. {
  76112. jassert (subPath.size() > 0);
  76113. if (arrowhead != 0)
  76114. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76115. const LineSection& firstLine = subPath.getReference (0);
  76116. float lastX1 = firstLine.lx1;
  76117. float lastY1 = firstLine.ly1;
  76118. float lastX2 = firstLine.lx2;
  76119. float lastY2 = firstLine.ly2;
  76120. if (isClosed)
  76121. {
  76122. destPath.startNewSubPath (lastX1, lastY1);
  76123. }
  76124. else
  76125. {
  76126. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76127. if (arrowhead != 0)
  76128. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76129. width, arrowhead->startWidth);
  76130. else
  76131. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76132. }
  76133. int i;
  76134. for (i = 1; i < subPath.size(); ++i)
  76135. {
  76136. const LineSection& l = subPath.getReference (i);
  76137. addEdgeAndJoint (destPath, jointStyle,
  76138. maxMiterExtensionSquared, width,
  76139. lastX1, lastY1, lastX2, lastY2,
  76140. l.lx1, l.ly1, l.lx2, l.ly2,
  76141. l.x1, l.y1);
  76142. lastX1 = l.lx1;
  76143. lastY1 = l.ly1;
  76144. lastX2 = l.lx2;
  76145. lastY2 = l.ly2;
  76146. }
  76147. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76148. if (isClosed)
  76149. {
  76150. const LineSection& l = subPath.getReference (0);
  76151. addEdgeAndJoint (destPath, jointStyle,
  76152. maxMiterExtensionSquared, width,
  76153. lastX1, lastY1, lastX2, lastY2,
  76154. l.lx1, l.ly1, l.lx2, l.ly2,
  76155. l.x1, l.y1);
  76156. destPath.closeSubPath();
  76157. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76158. }
  76159. else
  76160. {
  76161. destPath.lineTo (lastX2, lastY2);
  76162. if (arrowhead != 0)
  76163. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76164. width, arrowhead->endWidth);
  76165. else
  76166. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76167. }
  76168. lastX1 = lastLine.rx1;
  76169. lastY1 = lastLine.ry1;
  76170. lastX2 = lastLine.rx2;
  76171. lastY2 = lastLine.ry2;
  76172. for (i = subPath.size() - 1; --i >= 0;)
  76173. {
  76174. const LineSection& l = subPath.getReference (i);
  76175. addEdgeAndJoint (destPath, jointStyle,
  76176. maxMiterExtensionSquared, width,
  76177. lastX1, lastY1, lastX2, lastY2,
  76178. l.rx1, l.ry1, l.rx2, l.ry2,
  76179. l.x2, l.y2);
  76180. lastX1 = l.rx1;
  76181. lastY1 = l.ry1;
  76182. lastX2 = l.rx2;
  76183. lastY2 = l.ry2;
  76184. }
  76185. if (isClosed)
  76186. {
  76187. addEdgeAndJoint (destPath, jointStyle,
  76188. maxMiterExtensionSquared, width,
  76189. lastX1, lastY1, lastX2, lastY2,
  76190. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76191. lastLine.x2, lastLine.y2);
  76192. }
  76193. else
  76194. {
  76195. // do the last line
  76196. destPath.lineTo (lastX2, lastY2);
  76197. }
  76198. destPath.closeSubPath();
  76199. }
  76200. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76201. const PathStrokeType::EndCapStyle endStyle,
  76202. Path& destPath, const Path& source,
  76203. const AffineTransform& transform,
  76204. const float extraAccuracy, const Arrowhead* const arrowhead)
  76205. {
  76206. if (thickness <= 0)
  76207. {
  76208. destPath.clear();
  76209. return;
  76210. }
  76211. const Path* sourcePath = &source;
  76212. Path temp;
  76213. if (sourcePath == &destPath)
  76214. {
  76215. destPath.swapWithPath (temp);
  76216. sourcePath = &temp;
  76217. }
  76218. else
  76219. {
  76220. destPath.clear();
  76221. }
  76222. destPath.setUsingNonZeroWinding (true);
  76223. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76224. const float width = 0.5f * thickness;
  76225. // Iterate the path, creating a list of the
  76226. // left/right-hand lines along either side of it...
  76227. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76228. Array <LineSection> subPath;
  76229. subPath.ensureStorageAllocated (512);
  76230. LineSection l;
  76231. l.x1 = 0;
  76232. l.y1 = 0;
  76233. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76234. while (it.next())
  76235. {
  76236. if (it.subPathIndex == 0)
  76237. {
  76238. if (subPath.size() > 0)
  76239. {
  76240. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76241. subPath.clearQuick();
  76242. }
  76243. l.x1 = it.x1;
  76244. l.y1 = it.y1;
  76245. }
  76246. l.x2 = it.x2;
  76247. l.y2 = it.y2;
  76248. float dx = l.x2 - l.x1;
  76249. float dy = l.y2 - l.y1;
  76250. const float hypotSquared = dx*dx + dy*dy;
  76251. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76252. {
  76253. const float len = std::sqrt (hypotSquared);
  76254. if (len == 0)
  76255. {
  76256. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76257. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76258. }
  76259. else
  76260. {
  76261. const float offset = width / len;
  76262. dx *= offset;
  76263. dy *= offset;
  76264. l.rx2 = l.x1 - dy;
  76265. l.ry2 = l.y1 + dx;
  76266. l.lx1 = l.x1 + dy;
  76267. l.ly1 = l.y1 - dx;
  76268. l.lx2 = l.x2 + dy;
  76269. l.ly2 = l.y2 - dx;
  76270. l.rx1 = l.x2 - dy;
  76271. l.ry1 = l.y2 + dx;
  76272. }
  76273. subPath.add (l);
  76274. if (it.closesSubPath)
  76275. {
  76276. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76277. subPath.clearQuick();
  76278. }
  76279. else
  76280. {
  76281. l.x1 = it.x2;
  76282. l.y1 = it.y2;
  76283. }
  76284. }
  76285. }
  76286. if (subPath.size() > 0)
  76287. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76288. }
  76289. }
  76290. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76291. const AffineTransform& transform, const float extraAccuracy) const
  76292. {
  76293. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76294. transform, extraAccuracy, 0);
  76295. }
  76296. void PathStrokeType::createDashedStroke (Path& destPath,
  76297. const Path& sourcePath,
  76298. const float* dashLengths,
  76299. int numDashLengths,
  76300. const AffineTransform& transform,
  76301. const float extraAccuracy) const
  76302. {
  76303. if (thickness <= 0)
  76304. return;
  76305. // this should really be an even number..
  76306. jassert ((numDashLengths & 1) == 0);
  76307. Path newDestPath;
  76308. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76309. bool first = true;
  76310. int dashNum = 0;
  76311. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76312. float dx = 0.0f, dy = 0.0f;
  76313. for (;;)
  76314. {
  76315. const bool isSolid = ((dashNum & 1) == 0);
  76316. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76317. jassert (dashLen > 0); // must be a positive increment!
  76318. if (dashLen <= 0)
  76319. break;
  76320. pos += dashLen;
  76321. while (pos > lineEndPos)
  76322. {
  76323. if (! it.next())
  76324. {
  76325. if (isSolid && ! first)
  76326. newDestPath.lineTo (it.x2, it.y2);
  76327. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76328. return;
  76329. }
  76330. if (isSolid && ! first)
  76331. newDestPath.lineTo (it.x1, it.y1);
  76332. else
  76333. newDestPath.startNewSubPath (it.x1, it.y1);
  76334. dx = it.x2 - it.x1;
  76335. dy = it.y2 - it.y1;
  76336. lineLen = juce_hypotf (dx, dy);
  76337. lineEndPos += lineLen;
  76338. first = it.closesSubPath;
  76339. }
  76340. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76341. if (isSolid)
  76342. newDestPath.lineTo (it.x1 + dx * alpha,
  76343. it.y1 + dy * alpha);
  76344. else
  76345. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76346. it.y1 + dy * alpha);
  76347. }
  76348. }
  76349. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76350. const Path& sourcePath,
  76351. const float arrowheadStartWidth, const float arrowheadStartLength,
  76352. const float arrowheadEndWidth, const float arrowheadEndLength,
  76353. const AffineTransform& transform,
  76354. const float extraAccuracy) const
  76355. {
  76356. PathStrokeHelpers::Arrowhead head;
  76357. head.startWidth = arrowheadStartWidth;
  76358. head.startLength = arrowheadStartLength;
  76359. head.endWidth = arrowheadEndWidth;
  76360. head.endLength = arrowheadEndLength;
  76361. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76362. destPath, sourcePath, transform, extraAccuracy, &head);
  76363. }
  76364. END_JUCE_NAMESPACE
  76365. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76366. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76367. BEGIN_JUCE_NAMESPACE
  76368. PositionedRectangle::PositionedRectangle() throw()
  76369. : x (0.0),
  76370. y (0.0),
  76371. w (0.0),
  76372. h (0.0),
  76373. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76374. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76375. wMode (absoluteSize),
  76376. hMode (absoluteSize)
  76377. {
  76378. }
  76379. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76380. : x (other.x),
  76381. y (other.y),
  76382. w (other.w),
  76383. h (other.h),
  76384. xMode (other.xMode),
  76385. yMode (other.yMode),
  76386. wMode (other.wMode),
  76387. hMode (other.hMode)
  76388. {
  76389. }
  76390. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76391. {
  76392. x = other.x;
  76393. y = other.y;
  76394. w = other.w;
  76395. h = other.h;
  76396. xMode = other.xMode;
  76397. yMode = other.yMode;
  76398. wMode = other.wMode;
  76399. hMode = other.hMode;
  76400. return *this;
  76401. }
  76402. PositionedRectangle::~PositionedRectangle() throw()
  76403. {
  76404. }
  76405. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76406. {
  76407. return x == other.x
  76408. && y == other.y
  76409. && w == other.w
  76410. && h == other.h
  76411. && xMode == other.xMode
  76412. && yMode == other.yMode
  76413. && wMode == other.wMode
  76414. && hMode == other.hMode;
  76415. }
  76416. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76417. {
  76418. return ! operator== (other);
  76419. }
  76420. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76421. {
  76422. StringArray tokens;
  76423. tokens.addTokens (stringVersion, false);
  76424. decodePosString (tokens [0], xMode, x);
  76425. decodePosString (tokens [1], yMode, y);
  76426. decodeSizeString (tokens [2], wMode, w);
  76427. decodeSizeString (tokens [3], hMode, h);
  76428. }
  76429. const String PositionedRectangle::toString() const throw()
  76430. {
  76431. String s;
  76432. s.preallocateStorage (12);
  76433. addPosDescription (s, xMode, x);
  76434. s << ' ';
  76435. addPosDescription (s, yMode, y);
  76436. s << ' ';
  76437. addSizeDescription (s, wMode, w);
  76438. s << ' ';
  76439. addSizeDescription (s, hMode, h);
  76440. return s;
  76441. }
  76442. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76443. {
  76444. jassert (! target.isEmpty());
  76445. double x_, y_, w_, h_;
  76446. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76447. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76448. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76449. roundToInt (w_), roundToInt (h_));
  76450. }
  76451. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76452. double& x_, double& y_,
  76453. double& w_, double& h_) const throw()
  76454. {
  76455. jassert (! target.isEmpty());
  76456. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76457. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76458. }
  76459. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76460. {
  76461. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76462. }
  76463. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76464. const Rectangle<int>& target) throw()
  76465. {
  76466. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76467. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76468. }
  76469. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76470. const double newW, const double newH,
  76471. const Rectangle<int>& target) throw()
  76472. {
  76473. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76474. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76475. }
  76476. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76477. {
  76478. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76479. updateFrom (comp.getBounds(), Rectangle<int>());
  76480. else
  76481. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76482. }
  76483. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76484. {
  76485. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76486. }
  76487. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76488. {
  76489. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76490. | absoluteFromParentBottomRight
  76491. | absoluteFromParentCentre
  76492. | proportionOfParentSize));
  76493. }
  76494. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76495. {
  76496. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76497. }
  76498. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76499. {
  76500. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76501. | absoluteFromParentBottomRight
  76502. | absoluteFromParentCentre
  76503. | proportionOfParentSize));
  76504. }
  76505. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76506. {
  76507. return (SizeMode) wMode;
  76508. }
  76509. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76510. {
  76511. return (SizeMode) hMode;
  76512. }
  76513. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76514. const PositionMode xMode_,
  76515. const AnchorPoint yAnchor,
  76516. const PositionMode yMode_,
  76517. const SizeMode widthMode,
  76518. const SizeMode heightMode,
  76519. const Rectangle<int>& target) throw()
  76520. {
  76521. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76522. {
  76523. double tx, tw;
  76524. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76525. xMode = (uint8) (xAnchor | xMode_);
  76526. wMode = (uint8) widthMode;
  76527. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76528. }
  76529. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76530. {
  76531. double ty, th;
  76532. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76533. yMode = (uint8) (yAnchor | yMode_);
  76534. hMode = (uint8) heightMode;
  76535. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76536. }
  76537. }
  76538. bool PositionedRectangle::isPositionAbsolute() const throw()
  76539. {
  76540. return xMode == absoluteFromParentTopLeft
  76541. && yMode == absoluteFromParentTopLeft
  76542. && wMode == absoluteSize
  76543. && hMode == absoluteSize;
  76544. }
  76545. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76546. {
  76547. if ((mode & proportionOfParentSize) != 0)
  76548. {
  76549. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76550. }
  76551. else
  76552. {
  76553. s << (roundToInt (value * 100.0) / 100.0);
  76554. if ((mode & absoluteFromParentBottomRight) != 0)
  76555. s << 'R';
  76556. else if ((mode & absoluteFromParentCentre) != 0)
  76557. s << 'C';
  76558. }
  76559. if ((mode & anchorAtRightOrBottom) != 0)
  76560. s << 'r';
  76561. else if ((mode & anchorAtCentre) != 0)
  76562. s << 'c';
  76563. }
  76564. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76565. {
  76566. if (mode == proportionalSize)
  76567. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76568. else if (mode == parentSizeMinusAbsolute)
  76569. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76570. else
  76571. s << (roundToInt (value * 100.0) / 100.0);
  76572. }
  76573. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76574. {
  76575. if (s.containsChar ('r'))
  76576. mode = anchorAtRightOrBottom;
  76577. else if (s.containsChar ('c'))
  76578. mode = anchorAtCentre;
  76579. else
  76580. mode = anchorAtLeftOrTop;
  76581. if (s.containsChar ('%'))
  76582. {
  76583. mode |= proportionOfParentSize;
  76584. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76585. }
  76586. else
  76587. {
  76588. if (s.containsChar ('R'))
  76589. mode |= absoluteFromParentBottomRight;
  76590. else if (s.containsChar ('C'))
  76591. mode |= absoluteFromParentCentre;
  76592. else
  76593. mode |= absoluteFromParentTopLeft;
  76594. value = s.removeCharacters ("rcRC").getDoubleValue();
  76595. }
  76596. }
  76597. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76598. {
  76599. if (s.containsChar ('%'))
  76600. {
  76601. mode = proportionalSize;
  76602. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76603. }
  76604. else if (s.containsChar ('M'))
  76605. {
  76606. mode = parentSizeMinusAbsolute;
  76607. value = s.getDoubleValue();
  76608. }
  76609. else
  76610. {
  76611. mode = absoluteSize;
  76612. value = s.getDoubleValue();
  76613. }
  76614. }
  76615. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76616. const double x_, const double w_,
  76617. const uint8 xMode_, const uint8 wMode_,
  76618. const int parentPos,
  76619. const int parentSize) const throw()
  76620. {
  76621. if (wMode_ == proportionalSize)
  76622. wOut = roundToInt (w_ * parentSize);
  76623. else if (wMode_ == parentSizeMinusAbsolute)
  76624. wOut = jmax (0, parentSize - roundToInt (w_));
  76625. else
  76626. wOut = roundToInt (w_);
  76627. if ((xMode_ & proportionOfParentSize) != 0)
  76628. xOut = parentPos + x_ * parentSize;
  76629. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76630. xOut = (parentPos + parentSize) - x_;
  76631. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76632. xOut = x_ + (parentPos + parentSize / 2);
  76633. else
  76634. xOut = x_ + parentPos;
  76635. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76636. xOut -= wOut;
  76637. else if ((xMode_ & anchorAtCentre) != 0)
  76638. xOut -= wOut / 2;
  76639. }
  76640. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76641. double x_, const double w_,
  76642. const uint8 xMode_, const uint8 wMode_,
  76643. const int parentPos,
  76644. const int parentSize) const throw()
  76645. {
  76646. if (wMode_ == proportionalSize)
  76647. {
  76648. if (parentSize > 0)
  76649. wOut = w_ / parentSize;
  76650. }
  76651. else if (wMode_ == parentSizeMinusAbsolute)
  76652. wOut = parentSize - w_;
  76653. else
  76654. wOut = w_;
  76655. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76656. x_ += w_;
  76657. else if ((xMode_ & anchorAtCentre) != 0)
  76658. x_ += w_ / 2;
  76659. if ((xMode_ & proportionOfParentSize) != 0)
  76660. {
  76661. if (parentSize > 0)
  76662. xOut = (x_ - parentPos) / parentSize;
  76663. }
  76664. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76665. xOut = (parentPos + parentSize) - x_;
  76666. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76667. xOut = x_ - (parentPos + parentSize / 2);
  76668. else
  76669. xOut = x_ - parentPos;
  76670. }
  76671. END_JUCE_NAMESPACE
  76672. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76673. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76674. BEGIN_JUCE_NAMESPACE
  76675. RectangleList::RectangleList() throw()
  76676. {
  76677. }
  76678. RectangleList::RectangleList (const Rectangle<int>& rect)
  76679. {
  76680. if (! rect.isEmpty())
  76681. rects.add (rect);
  76682. }
  76683. RectangleList::RectangleList (const RectangleList& other)
  76684. : rects (other.rects)
  76685. {
  76686. }
  76687. RectangleList& RectangleList::operator= (const RectangleList& other)
  76688. {
  76689. rects = other.rects;
  76690. return *this;
  76691. }
  76692. RectangleList::~RectangleList()
  76693. {
  76694. }
  76695. void RectangleList::clear()
  76696. {
  76697. rects.clearQuick();
  76698. }
  76699. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76700. {
  76701. if (((unsigned int) index) < (unsigned int) rects.size())
  76702. return rects.getReference (index);
  76703. return Rectangle<int>();
  76704. }
  76705. bool RectangleList::isEmpty() const throw()
  76706. {
  76707. return rects.size() == 0;
  76708. }
  76709. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76710. : current (0),
  76711. owner (list),
  76712. index (list.rects.size())
  76713. {
  76714. }
  76715. RectangleList::Iterator::~Iterator()
  76716. {
  76717. }
  76718. bool RectangleList::Iterator::next() throw()
  76719. {
  76720. if (--index >= 0)
  76721. {
  76722. current = & (owner.rects.getReference (index));
  76723. return true;
  76724. }
  76725. return false;
  76726. }
  76727. void RectangleList::add (const Rectangle<int>& rect)
  76728. {
  76729. if (! rect.isEmpty())
  76730. {
  76731. if (rects.size() == 0)
  76732. {
  76733. rects.add (rect);
  76734. }
  76735. else
  76736. {
  76737. bool anyOverlaps = false;
  76738. int i;
  76739. for (i = rects.size(); --i >= 0;)
  76740. {
  76741. Rectangle<int>& ourRect = rects.getReference (i);
  76742. if (rect.intersects (ourRect))
  76743. {
  76744. if (rect.contains (ourRect))
  76745. rects.remove (i);
  76746. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76747. anyOverlaps = true;
  76748. }
  76749. }
  76750. if (anyOverlaps && rects.size() > 0)
  76751. {
  76752. RectangleList r (rect);
  76753. for (i = rects.size(); --i >= 0;)
  76754. {
  76755. const Rectangle<int>& ourRect = rects.getReference (i);
  76756. if (rect.intersects (ourRect))
  76757. {
  76758. r.subtract (ourRect);
  76759. if (r.rects.size() == 0)
  76760. return;
  76761. }
  76762. }
  76763. for (i = r.getNumRectangles(); --i >= 0;)
  76764. rects.add (r.rects.getReference (i));
  76765. }
  76766. else
  76767. {
  76768. rects.add (rect);
  76769. }
  76770. }
  76771. }
  76772. }
  76773. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76774. {
  76775. if (! rect.isEmpty())
  76776. rects.add (rect);
  76777. }
  76778. void RectangleList::add (const int x, const int y, const int w, const int h)
  76779. {
  76780. if (rects.size() == 0)
  76781. {
  76782. if (w > 0 && h > 0)
  76783. rects.add (Rectangle<int> (x, y, w, h));
  76784. }
  76785. else
  76786. {
  76787. add (Rectangle<int> (x, y, w, h));
  76788. }
  76789. }
  76790. void RectangleList::add (const RectangleList& other)
  76791. {
  76792. for (int i = 0; i < other.rects.size(); ++i)
  76793. add (other.rects.getReference (i));
  76794. }
  76795. void RectangleList::subtract (const Rectangle<int>& rect)
  76796. {
  76797. const int originalNumRects = rects.size();
  76798. if (originalNumRects > 0)
  76799. {
  76800. const int x1 = rect.x;
  76801. const int y1 = rect.y;
  76802. const int x2 = x1 + rect.w;
  76803. const int y2 = y1 + rect.h;
  76804. for (int i = getNumRectangles(); --i >= 0;)
  76805. {
  76806. Rectangle<int>& r = rects.getReference (i);
  76807. const int rx1 = r.x;
  76808. const int ry1 = r.y;
  76809. const int rx2 = rx1 + r.w;
  76810. const int ry2 = ry1 + r.h;
  76811. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76812. {
  76813. if (x1 > rx1 && x1 < rx2)
  76814. {
  76815. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76816. {
  76817. r.w = x1 - rx1;
  76818. }
  76819. else
  76820. {
  76821. r.x = x1;
  76822. r.w = rx2 - x1;
  76823. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76824. i += 2;
  76825. }
  76826. }
  76827. else if (x2 > rx1 && x2 < rx2)
  76828. {
  76829. r.x = x2;
  76830. r.w = rx2 - x2;
  76831. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76832. {
  76833. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76834. i += 2;
  76835. }
  76836. }
  76837. else if (y1 > ry1 && y1 < ry2)
  76838. {
  76839. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76840. {
  76841. r.h = y1 - ry1;
  76842. }
  76843. else
  76844. {
  76845. r.y = y1;
  76846. r.h = ry2 - y1;
  76847. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76848. i += 2;
  76849. }
  76850. }
  76851. else if (y2 > ry1 && y2 < ry2)
  76852. {
  76853. r.y = y2;
  76854. r.h = ry2 - y2;
  76855. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76856. {
  76857. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76858. i += 2;
  76859. }
  76860. }
  76861. else
  76862. {
  76863. rects.remove (i);
  76864. }
  76865. }
  76866. }
  76867. }
  76868. }
  76869. bool RectangleList::subtract (const RectangleList& otherList)
  76870. {
  76871. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76872. subtract (otherList.rects.getReference (i));
  76873. return rects.size() > 0;
  76874. }
  76875. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76876. {
  76877. bool notEmpty = false;
  76878. if (rect.isEmpty())
  76879. {
  76880. clear();
  76881. }
  76882. else
  76883. {
  76884. for (int i = rects.size(); --i >= 0;)
  76885. {
  76886. Rectangle<int>& r = rects.getReference (i);
  76887. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76888. rects.remove (i);
  76889. else
  76890. notEmpty = true;
  76891. }
  76892. }
  76893. return notEmpty;
  76894. }
  76895. bool RectangleList::clipTo (const RectangleList& other)
  76896. {
  76897. if (rects.size() == 0)
  76898. return false;
  76899. RectangleList result;
  76900. for (int j = 0; j < rects.size(); ++j)
  76901. {
  76902. const Rectangle<int>& rect = rects.getReference (j);
  76903. for (int i = other.rects.size(); --i >= 0;)
  76904. {
  76905. Rectangle<int> r (other.rects.getReference (i));
  76906. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76907. result.rects.add (r);
  76908. }
  76909. }
  76910. swapWith (result);
  76911. return ! isEmpty();
  76912. }
  76913. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76914. {
  76915. destRegion.clear();
  76916. if (! rect.isEmpty())
  76917. {
  76918. for (int i = rects.size(); --i >= 0;)
  76919. {
  76920. Rectangle<int> r (rects.getReference (i));
  76921. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76922. destRegion.rects.add (r);
  76923. }
  76924. }
  76925. return destRegion.rects.size() > 0;
  76926. }
  76927. void RectangleList::swapWith (RectangleList& otherList) throw()
  76928. {
  76929. rects.swapWithArray (otherList.rects);
  76930. }
  76931. void RectangleList::consolidate()
  76932. {
  76933. int i;
  76934. for (i = 0; i < getNumRectangles() - 1; ++i)
  76935. {
  76936. Rectangle<int>& r = rects.getReference (i);
  76937. const int rx1 = r.x;
  76938. const int ry1 = r.y;
  76939. const int rx2 = rx1 + r.w;
  76940. const int ry2 = ry1 + r.h;
  76941. for (int j = rects.size(); --j > i;)
  76942. {
  76943. Rectangle<int>& r2 = rects.getReference (j);
  76944. const int jrx1 = r2.x;
  76945. const int jry1 = r2.y;
  76946. const int jrx2 = jrx1 + r2.w;
  76947. const int jry2 = jry1 + r2.h;
  76948. // if the vertical edges of any blocks are touching and their horizontals don't
  76949. // line up, split them horizontally..
  76950. if (jrx1 == rx2 || jrx2 == rx1)
  76951. {
  76952. if (jry1 > ry1 && jry1 < ry2)
  76953. {
  76954. r.h = jry1 - ry1;
  76955. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76956. i = -1;
  76957. break;
  76958. }
  76959. if (jry2 > ry1 && jry2 < ry2)
  76960. {
  76961. r.h = jry2 - ry1;
  76962. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76963. i = -1;
  76964. break;
  76965. }
  76966. else if (ry1 > jry1 && ry1 < jry2)
  76967. {
  76968. r2.h = ry1 - jry1;
  76969. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76970. i = -1;
  76971. break;
  76972. }
  76973. else if (ry2 > jry1 && ry2 < jry2)
  76974. {
  76975. r2.h = ry2 - jry1;
  76976. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76977. i = -1;
  76978. break;
  76979. }
  76980. }
  76981. }
  76982. }
  76983. for (i = 0; i < rects.size() - 1; ++i)
  76984. {
  76985. Rectangle<int>& r = rects.getReference (i);
  76986. for (int j = rects.size(); --j > i;)
  76987. {
  76988. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76989. {
  76990. rects.remove (j);
  76991. i = -1;
  76992. break;
  76993. }
  76994. }
  76995. }
  76996. }
  76997. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76998. {
  76999. for (int i = getNumRectangles(); --i >= 0;)
  77000. if (rects.getReference (i).contains (x, y))
  77001. return true;
  77002. return false;
  77003. }
  77004. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  77005. {
  77006. if (rects.size() > 1)
  77007. {
  77008. RectangleList r (rectangleToCheck);
  77009. for (int i = rects.size(); --i >= 0;)
  77010. {
  77011. r.subtract (rects.getReference (i));
  77012. if (r.rects.size() == 0)
  77013. return true;
  77014. }
  77015. }
  77016. else if (rects.size() > 0)
  77017. {
  77018. return rects.getReference (0).contains (rectangleToCheck);
  77019. }
  77020. return false;
  77021. }
  77022. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  77023. {
  77024. for (int i = rects.size(); --i >= 0;)
  77025. if (rects.getReference (i).intersects (rectangleToCheck))
  77026. return true;
  77027. return false;
  77028. }
  77029. bool RectangleList::intersects (const RectangleList& other) const throw()
  77030. {
  77031. for (int i = rects.size(); --i >= 0;)
  77032. if (other.intersectsRectangle (rects.getReference (i)))
  77033. return true;
  77034. return false;
  77035. }
  77036. const Rectangle<int> RectangleList::getBounds() const throw()
  77037. {
  77038. if (rects.size() <= 1)
  77039. {
  77040. if (rects.size() == 0)
  77041. return Rectangle<int>();
  77042. else
  77043. return rects.getReference (0);
  77044. }
  77045. else
  77046. {
  77047. const Rectangle<int>& r = rects.getReference (0);
  77048. int minX = r.x;
  77049. int minY = r.y;
  77050. int maxX = minX + r.w;
  77051. int maxY = minY + r.h;
  77052. for (int i = rects.size(); --i > 0;)
  77053. {
  77054. const Rectangle<int>& r2 = rects.getReference (i);
  77055. minX = jmin (minX, r2.x);
  77056. minY = jmin (minY, r2.y);
  77057. maxX = jmax (maxX, r2.getRight());
  77058. maxY = jmax (maxY, r2.getBottom());
  77059. }
  77060. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77061. }
  77062. }
  77063. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77064. {
  77065. for (int i = rects.size(); --i >= 0;)
  77066. {
  77067. Rectangle<int>& r = rects.getReference (i);
  77068. r.x += dx;
  77069. r.y += dy;
  77070. }
  77071. }
  77072. const Path RectangleList::toPath() const
  77073. {
  77074. Path p;
  77075. for (int i = rects.size(); --i >= 0;)
  77076. {
  77077. const Rectangle<int>& r = rects.getReference (i);
  77078. p.addRectangle ((float) r.x,
  77079. (float) r.y,
  77080. (float) r.w,
  77081. (float) r.h);
  77082. }
  77083. return p;
  77084. }
  77085. END_JUCE_NAMESPACE
  77086. /*** End of inlined file: juce_RectangleList.cpp ***/
  77087. /*** Start of inlined file: juce_Image.cpp ***/
  77088. BEGIN_JUCE_NAMESPACE
  77089. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77090. : format (format_), width (width_), height (height_)
  77091. {
  77092. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77093. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77094. }
  77095. Image::SharedImage::~SharedImage()
  77096. {
  77097. }
  77098. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  77099. {
  77100. return imageData + lineStride * y + pixelStride * x;
  77101. }
  77102. class SoftwareSharedImage : public Image::SharedImage
  77103. {
  77104. public:
  77105. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77106. : Image::SharedImage (format_, width_, height_)
  77107. {
  77108. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  77109. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  77110. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  77111. imageData = imageDataAllocated;
  77112. }
  77113. ~SoftwareSharedImage()
  77114. {
  77115. }
  77116. Image::ImageType getType() const
  77117. {
  77118. return Image::SoftwareImage;
  77119. }
  77120. LowLevelGraphicsContext* createLowLevelContext()
  77121. {
  77122. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77123. }
  77124. SharedImage* clone()
  77125. {
  77126. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77127. memcpy (s->imageData, imageData, lineStride * height);
  77128. return s;
  77129. }
  77130. private:
  77131. HeapBlock<uint8> imageDataAllocated;
  77132. };
  77133. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77134. {
  77135. return new SoftwareSharedImage (format, width, height, clearImage);
  77136. }
  77137. class SubsectionSharedImage : public Image::SharedImage
  77138. {
  77139. public:
  77140. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77141. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77142. image (image_), area (area_)
  77143. {
  77144. pixelStride = image_->getPixelStride();
  77145. lineStride = image_->getLineStride();
  77146. imageData = image_->getPixelData (area_.getX(), area_.getY());
  77147. }
  77148. ~SubsectionSharedImage() {}
  77149. Image::ImageType getType() const
  77150. {
  77151. return Image::SoftwareImage;
  77152. }
  77153. LowLevelGraphicsContext* createLowLevelContext()
  77154. {
  77155. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77156. g->clipToRectangle (area);
  77157. g->setOrigin (area.getX(), area.getY());
  77158. return g;
  77159. }
  77160. SharedImage* clone()
  77161. {
  77162. return new SubsectionSharedImage (image->clone(), area);
  77163. }
  77164. private:
  77165. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77166. const Rectangle<int> area;
  77167. SubsectionSharedImage (const SubsectionSharedImage&);
  77168. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  77169. };
  77170. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77171. {
  77172. if (area.contains (getBounds()))
  77173. return *this;
  77174. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77175. if (validArea.isEmpty())
  77176. return Image::null;
  77177. return Image (new SubsectionSharedImage (image, validArea));
  77178. }
  77179. Image::Image()
  77180. {
  77181. }
  77182. Image::Image (SharedImage* const instance)
  77183. : image (instance)
  77184. {
  77185. }
  77186. Image::Image (const PixelFormat format,
  77187. const int width, const int height,
  77188. const bool clearImage, const ImageType type)
  77189. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77190. : new SoftwareSharedImage (format, width, height, clearImage))
  77191. {
  77192. }
  77193. Image::Image (const Image& other)
  77194. : image (other.image)
  77195. {
  77196. }
  77197. Image& Image::operator= (const Image& other)
  77198. {
  77199. image = other.image;
  77200. return *this;
  77201. }
  77202. Image::~Image()
  77203. {
  77204. }
  77205. const Image Image::null;
  77206. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77207. {
  77208. return image == 0 ? 0 : image->createLowLevelContext();
  77209. }
  77210. void Image::duplicateIfShared()
  77211. {
  77212. if (image != 0 && image->getReferenceCount() > 1)
  77213. image = image->clone();
  77214. }
  77215. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77216. {
  77217. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77218. return *this;
  77219. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77220. Graphics g (newImage);
  77221. g.setImageResamplingQuality (quality);
  77222. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77223. return newImage;
  77224. }
  77225. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77226. {
  77227. if (image == 0 || newFormat == image->format)
  77228. return *this;
  77229. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77230. if (newFormat == SingleChannel)
  77231. {
  77232. if (! hasAlphaChannel())
  77233. {
  77234. newImage.clear (getBounds(), Colours::black);
  77235. }
  77236. else
  77237. {
  77238. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77239. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77240. for (int y = 0; y < image->height; ++y)
  77241. {
  77242. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77243. uint8* dst = destData.getLinePointer (y);
  77244. for (int x = image->width; --x >= 0;)
  77245. {
  77246. *dst++ = src->getAlpha();
  77247. ++src;
  77248. }
  77249. }
  77250. }
  77251. }
  77252. else
  77253. {
  77254. if (hasAlphaChannel())
  77255. newImage.clear (getBounds());
  77256. Graphics g (newImage);
  77257. g.drawImageAt (*this, 0, 0);
  77258. }
  77259. return newImage;
  77260. }
  77261. const var Image::getTag() const
  77262. {
  77263. return image == 0 ? var::null : image->userTag;
  77264. }
  77265. void Image::setTag (const var& newTag)
  77266. {
  77267. if (image != 0)
  77268. image->userTag = newTag;
  77269. }
  77270. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77271. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77272. pixelFormat (image.getFormat()),
  77273. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77274. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77275. width (w),
  77276. height (h)
  77277. {
  77278. jassert (data != 0);
  77279. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77280. }
  77281. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77282. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77283. pixelFormat (image.getFormat()),
  77284. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77285. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77286. width (w),
  77287. height (h)
  77288. {
  77289. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77290. }
  77291. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77292. : data (image.image == 0 ? 0 : image.image->imageData),
  77293. pixelFormat (image.getFormat()),
  77294. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77295. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77296. width (image.getWidth()),
  77297. height (image.getHeight())
  77298. {
  77299. }
  77300. Image::BitmapData::~BitmapData()
  77301. {
  77302. }
  77303. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77304. {
  77305. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77306. const uint8* const pixel = getPixelPointer (x, y);
  77307. switch (pixelFormat)
  77308. {
  77309. case Image::ARGB:
  77310. {
  77311. PixelARGB p (*(const PixelARGB*) pixel);
  77312. p.unpremultiply();
  77313. return Colour (p.getARGB());
  77314. }
  77315. case Image::RGB:
  77316. return Colour (((const PixelRGB*) pixel)->getARGB());
  77317. case Image::SingleChannel:
  77318. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77319. default:
  77320. jassertfalse;
  77321. break;
  77322. }
  77323. return Colour();
  77324. }
  77325. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77326. {
  77327. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77328. uint8* const pixel = getPixelPointer (x, y);
  77329. const PixelARGB col (colour.getPixelARGB());
  77330. switch (pixelFormat)
  77331. {
  77332. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77333. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77334. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77335. default: jassertfalse; break;
  77336. }
  77337. }
  77338. void Image::setPixelData (int x, int y, int w, int h,
  77339. const uint8* const sourcePixelData, const int sourceLineStride)
  77340. {
  77341. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77342. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77343. {
  77344. const BitmapData dest (*this, x, y, w, h, true);
  77345. for (int i = 0; i < h; ++i)
  77346. {
  77347. memcpy (dest.getLinePointer(i),
  77348. sourcePixelData + sourceLineStride * i,
  77349. w * dest.pixelStride);
  77350. }
  77351. }
  77352. }
  77353. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77354. {
  77355. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77356. if (! clipped.isEmpty())
  77357. {
  77358. const PixelARGB col (colourToClearTo.getPixelARGB());
  77359. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77360. uint8* dest = destData.data;
  77361. int dh = clipped.getHeight();
  77362. while (--dh >= 0)
  77363. {
  77364. uint8* line = dest;
  77365. dest += destData.lineStride;
  77366. if (isARGB())
  77367. {
  77368. for (int x = clipped.getWidth(); --x >= 0;)
  77369. {
  77370. ((PixelARGB*) line)->set (col);
  77371. line += destData.pixelStride;
  77372. }
  77373. }
  77374. else if (isRGB())
  77375. {
  77376. for (int x = clipped.getWidth(); --x >= 0;)
  77377. {
  77378. ((PixelRGB*) line)->set (col);
  77379. line += destData.pixelStride;
  77380. }
  77381. }
  77382. else
  77383. {
  77384. for (int x = clipped.getWidth(); --x >= 0;)
  77385. {
  77386. *line = col.getAlpha();
  77387. line += destData.pixelStride;
  77388. }
  77389. }
  77390. }
  77391. }
  77392. }
  77393. const Colour Image::getPixelAt (const int x, const int y) const
  77394. {
  77395. if (((unsigned int) x) < (unsigned int) getWidth()
  77396. && ((unsigned int) y) < (unsigned int) getHeight())
  77397. {
  77398. const BitmapData srcData (*this, x, y, 1, 1);
  77399. return srcData.getPixelColour (0, 0);
  77400. }
  77401. return Colour();
  77402. }
  77403. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77404. {
  77405. if (((unsigned int) x) < (unsigned int) getWidth()
  77406. && ((unsigned int) y) < (unsigned int) getHeight())
  77407. {
  77408. const BitmapData destData (*this, x, y, 1, 1, true);
  77409. destData.setPixelColour (0, 0, colour);
  77410. }
  77411. }
  77412. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77413. {
  77414. if (((unsigned int) x) < (unsigned int) getWidth()
  77415. && ((unsigned int) y) < (unsigned int) getHeight()
  77416. && hasAlphaChannel())
  77417. {
  77418. const BitmapData destData (*this, x, y, 1, 1, true);
  77419. if (isARGB())
  77420. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77421. else
  77422. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77423. }
  77424. }
  77425. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77426. {
  77427. if (hasAlphaChannel())
  77428. {
  77429. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77430. if (isARGB())
  77431. {
  77432. for (int y = 0; y < destData.height; ++y)
  77433. {
  77434. uint8* p = destData.getLinePointer (y);
  77435. for (int x = 0; x < destData.width; ++x)
  77436. {
  77437. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77438. p += destData.pixelStride;
  77439. }
  77440. }
  77441. }
  77442. else
  77443. {
  77444. for (int y = 0; y < destData.height; ++y)
  77445. {
  77446. uint8* p = destData.getLinePointer (y);
  77447. for (int x = 0; x < destData.width; ++x)
  77448. {
  77449. *p = (uint8) (*p * amountToMultiplyBy);
  77450. p += destData.pixelStride;
  77451. }
  77452. }
  77453. }
  77454. }
  77455. else
  77456. {
  77457. jassertfalse; // can't do this without an alpha-channel!
  77458. }
  77459. }
  77460. void Image::desaturate()
  77461. {
  77462. if (isARGB() || isRGB())
  77463. {
  77464. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77465. if (isARGB())
  77466. {
  77467. for (int y = 0; y < destData.height; ++y)
  77468. {
  77469. uint8* p = destData.getLinePointer (y);
  77470. for (int x = 0; x < destData.width; ++x)
  77471. {
  77472. ((PixelARGB*) p)->desaturate();
  77473. p += destData.pixelStride;
  77474. }
  77475. }
  77476. }
  77477. else
  77478. {
  77479. for (int y = 0; y < destData.height; ++y)
  77480. {
  77481. uint8* p = destData.getLinePointer (y);
  77482. for (int x = 0; x < destData.width; ++x)
  77483. {
  77484. ((PixelRGB*) p)->desaturate();
  77485. p += destData.pixelStride;
  77486. }
  77487. }
  77488. }
  77489. }
  77490. }
  77491. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77492. {
  77493. if (hasAlphaChannel())
  77494. {
  77495. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77496. SparseSet<int> pixelsOnRow;
  77497. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77498. for (int y = 0; y < srcData.height; ++y)
  77499. {
  77500. pixelsOnRow.clear();
  77501. const uint8* lineData = srcData.getLinePointer (y);
  77502. if (isARGB())
  77503. {
  77504. for (int x = 0; x < srcData.width; ++x)
  77505. {
  77506. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77507. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77508. lineData += srcData.pixelStride;
  77509. }
  77510. }
  77511. else
  77512. {
  77513. for (int x = 0; x < srcData.width; ++x)
  77514. {
  77515. if (*lineData >= threshold)
  77516. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77517. lineData += srcData.pixelStride;
  77518. }
  77519. }
  77520. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77521. {
  77522. const Range<int> range (pixelsOnRow.getRange (i));
  77523. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77524. }
  77525. result.consolidate();
  77526. }
  77527. }
  77528. else
  77529. {
  77530. result.add (0, 0, getWidth(), getHeight());
  77531. }
  77532. }
  77533. void Image::moveImageSection (int dx, int dy,
  77534. int sx, int sy,
  77535. int w, int h)
  77536. {
  77537. if (dx < 0)
  77538. {
  77539. w += dx;
  77540. sx -= dx;
  77541. dx = 0;
  77542. }
  77543. if (dy < 0)
  77544. {
  77545. h += dy;
  77546. sy -= dy;
  77547. dy = 0;
  77548. }
  77549. if (sx < 0)
  77550. {
  77551. w += sx;
  77552. dx -= sx;
  77553. sx = 0;
  77554. }
  77555. if (sy < 0)
  77556. {
  77557. h += sy;
  77558. dy -= sy;
  77559. sy = 0;
  77560. }
  77561. const int minX = jmin (dx, sx);
  77562. const int minY = jmin (dy, sy);
  77563. w = jmin (w, getWidth() - jmax (sx, dx));
  77564. h = jmin (h, getHeight() - jmax (sy, dy));
  77565. if (w > 0 && h > 0)
  77566. {
  77567. const int maxX = jmax (dx, sx) + w;
  77568. const int maxY = jmax (dy, sy) + h;
  77569. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77570. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77571. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77572. const int lineSize = destData.pixelStride * w;
  77573. if (dy > sy)
  77574. {
  77575. while (--h >= 0)
  77576. {
  77577. const int offset = h * destData.lineStride;
  77578. memmove (dst + offset, src + offset, lineSize);
  77579. }
  77580. }
  77581. else if (dst != src)
  77582. {
  77583. while (--h >= 0)
  77584. {
  77585. memmove (dst, src, lineSize);
  77586. dst += destData.lineStride;
  77587. src += destData.lineStride;
  77588. }
  77589. }
  77590. }
  77591. }
  77592. END_JUCE_NAMESPACE
  77593. /*** End of inlined file: juce_Image.cpp ***/
  77594. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77595. BEGIN_JUCE_NAMESPACE
  77596. class ImageCache::Pimpl : public Timer,
  77597. public DeletedAtShutdown
  77598. {
  77599. public:
  77600. Pimpl()
  77601. : cacheTimeout (5000)
  77602. {
  77603. }
  77604. ~Pimpl()
  77605. {
  77606. clearSingletonInstance();
  77607. }
  77608. const Image getFromHashCode (const int64 hashCode)
  77609. {
  77610. const ScopedLock sl (lock);
  77611. for (int i = images.size(); --i >= 0;)
  77612. {
  77613. Item* const item = images.getUnchecked(i);
  77614. if (item->hashCode == hashCode)
  77615. return item->image;
  77616. }
  77617. return Image::null;
  77618. }
  77619. void addImageToCache (const Image& image, const int64 hashCode)
  77620. {
  77621. if (image.isValid())
  77622. {
  77623. if (! isTimerRunning())
  77624. startTimer (2000);
  77625. Item* const item = new Item();
  77626. item->hashCode = hashCode;
  77627. item->image = image;
  77628. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77629. const ScopedLock sl (lock);
  77630. images.add (item);
  77631. }
  77632. }
  77633. void timerCallback()
  77634. {
  77635. const uint32 now = Time::getApproximateMillisecondCounter();
  77636. const ScopedLock sl (lock);
  77637. for (int i = images.size(); --i >= 0;)
  77638. {
  77639. Item* const item = images.getUnchecked(i);
  77640. if (item->image.getReferenceCount() <= 1)
  77641. {
  77642. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77643. images.remove (i);
  77644. }
  77645. else
  77646. {
  77647. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77648. }
  77649. }
  77650. if (images.size() == 0)
  77651. stopTimer();
  77652. }
  77653. struct Item
  77654. {
  77655. Image image;
  77656. int64 hashCode;
  77657. uint32 lastUseTime;
  77658. };
  77659. int cacheTimeout;
  77660. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77661. private:
  77662. OwnedArray<Item> images;
  77663. CriticalSection lock;
  77664. Pimpl (const Pimpl&);
  77665. Pimpl& operator= (const Pimpl&);
  77666. };
  77667. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77668. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77669. {
  77670. if (Pimpl::getInstanceWithoutCreating() != 0)
  77671. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77672. return Image::null;
  77673. }
  77674. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77675. {
  77676. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77677. }
  77678. const Image ImageCache::getFromFile (const File& file)
  77679. {
  77680. const int64 hashCode = file.hashCode64();
  77681. Image image (getFromHashCode (hashCode));
  77682. if (image.isNull())
  77683. {
  77684. image = ImageFileFormat::loadFrom (file);
  77685. addImageToCache (image, hashCode);
  77686. }
  77687. return image;
  77688. }
  77689. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77690. {
  77691. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77692. Image image (getFromHashCode (hashCode));
  77693. if (image.isNull())
  77694. {
  77695. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77696. addImageToCache (image, hashCode);
  77697. }
  77698. return image;
  77699. }
  77700. void ImageCache::setCacheTimeout (const int millisecs)
  77701. {
  77702. Pimpl::getInstance()->cacheTimeout = millisecs;
  77703. }
  77704. END_JUCE_NAMESPACE
  77705. /*** End of inlined file: juce_ImageCache.cpp ***/
  77706. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77707. BEGIN_JUCE_NAMESPACE
  77708. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77709. : values (size_ * size_),
  77710. size (size_)
  77711. {
  77712. clear();
  77713. }
  77714. ImageConvolutionKernel::~ImageConvolutionKernel()
  77715. {
  77716. }
  77717. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77718. {
  77719. if (((unsigned int) x) < (unsigned int) size
  77720. && ((unsigned int) y) < (unsigned int) size)
  77721. {
  77722. return values [x + y * size];
  77723. }
  77724. else
  77725. {
  77726. jassertfalse;
  77727. return 0;
  77728. }
  77729. }
  77730. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77731. {
  77732. if (((unsigned int) x) < (unsigned int) size
  77733. && ((unsigned int) y) < (unsigned int) size)
  77734. {
  77735. values [x + y * size] = value;
  77736. }
  77737. else
  77738. {
  77739. jassertfalse;
  77740. }
  77741. }
  77742. void ImageConvolutionKernel::clear()
  77743. {
  77744. for (int i = size * size; --i >= 0;)
  77745. values[i] = 0;
  77746. }
  77747. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77748. {
  77749. double currentTotal = 0.0;
  77750. for (int i = size * size; --i >= 0;)
  77751. currentTotal += values[i];
  77752. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77753. }
  77754. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77755. {
  77756. for (int i = size * size; --i >= 0;)
  77757. values[i] *= multiplier;
  77758. }
  77759. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77760. {
  77761. const double radiusFactor = -1.0 / (radius * radius * 2);
  77762. const int centre = size >> 1;
  77763. for (int y = size; --y >= 0;)
  77764. {
  77765. for (int x = size; --x >= 0;)
  77766. {
  77767. const int cx = x - centre;
  77768. const int cy = y - centre;
  77769. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77770. }
  77771. }
  77772. setOverallSum (1.0f);
  77773. }
  77774. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77775. const Image& sourceImage,
  77776. const Rectangle<int>& destinationArea) const
  77777. {
  77778. if (sourceImage == destImage)
  77779. {
  77780. destImage.duplicateIfShared();
  77781. }
  77782. else
  77783. {
  77784. if (sourceImage.getWidth() != destImage.getWidth()
  77785. || sourceImage.getHeight() != destImage.getHeight()
  77786. || sourceImage.getFormat() != destImage.getFormat())
  77787. {
  77788. jassertfalse;
  77789. return;
  77790. }
  77791. }
  77792. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77793. if (area.isEmpty())
  77794. return;
  77795. const int right = area.getRight();
  77796. const int bottom = area.getBottom();
  77797. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77798. uint8* line = destData.data;
  77799. const Image::BitmapData srcData (sourceImage, false);
  77800. if (destData.pixelStride == 4)
  77801. {
  77802. for (int y = area.getY(); y < bottom; ++y)
  77803. {
  77804. uint8* dest = line;
  77805. line += destData.lineStride;
  77806. for (int x = area.getX(); x < right; ++x)
  77807. {
  77808. float c1 = 0;
  77809. float c2 = 0;
  77810. float c3 = 0;
  77811. float c4 = 0;
  77812. for (int yy = 0; yy < size; ++yy)
  77813. {
  77814. const int sy = y + yy - (size >> 1);
  77815. if (sy >= srcData.height)
  77816. break;
  77817. if (sy >= 0)
  77818. {
  77819. int sx = x - (size >> 1);
  77820. const uint8* src = srcData.getPixelPointer (sx, sy);
  77821. for (int xx = 0; xx < size; ++xx)
  77822. {
  77823. if (sx >= srcData.width)
  77824. break;
  77825. if (sx >= 0)
  77826. {
  77827. const float kernelMult = values [xx + yy * size];
  77828. c1 += kernelMult * *src++;
  77829. c2 += kernelMult * *src++;
  77830. c3 += kernelMult * *src++;
  77831. c4 += kernelMult * *src++;
  77832. }
  77833. else
  77834. {
  77835. src += 4;
  77836. }
  77837. ++sx;
  77838. }
  77839. }
  77840. }
  77841. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77842. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77843. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77844. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77845. }
  77846. }
  77847. }
  77848. else if (destData.pixelStride == 3)
  77849. {
  77850. for (int y = area.getY(); y < bottom; ++y)
  77851. {
  77852. uint8* dest = line;
  77853. line += destData.lineStride;
  77854. for (int x = area.getX(); x < right; ++x)
  77855. {
  77856. float c1 = 0;
  77857. float c2 = 0;
  77858. float c3 = 0;
  77859. for (int yy = 0; yy < size; ++yy)
  77860. {
  77861. const int sy = y + yy - (size >> 1);
  77862. if (sy >= srcData.height)
  77863. break;
  77864. if (sy >= 0)
  77865. {
  77866. int sx = x - (size >> 1);
  77867. const uint8* src = srcData.getPixelPointer (sx, sy);
  77868. for (int xx = 0; xx < size; ++xx)
  77869. {
  77870. if (sx >= srcData.width)
  77871. break;
  77872. if (sx >= 0)
  77873. {
  77874. const float kernelMult = values [xx + yy * size];
  77875. c1 += kernelMult * *src++;
  77876. c2 += kernelMult * *src++;
  77877. c3 += kernelMult * *src++;
  77878. }
  77879. else
  77880. {
  77881. src += 3;
  77882. }
  77883. ++sx;
  77884. }
  77885. }
  77886. }
  77887. *dest++ = (uint8) roundToInt (c1);
  77888. *dest++ = (uint8) roundToInt (c2);
  77889. *dest++ = (uint8) roundToInt (c3);
  77890. }
  77891. }
  77892. }
  77893. }
  77894. END_JUCE_NAMESPACE
  77895. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77896. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77897. BEGIN_JUCE_NAMESPACE
  77898. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77899. {
  77900. static PNGImageFormat png;
  77901. static JPEGImageFormat jpg;
  77902. static GIFImageFormat gif;
  77903. ImageFileFormat* formats[4];
  77904. int numFormats = 0;
  77905. formats [numFormats++] = &png;
  77906. formats [numFormats++] = &jpg;
  77907. formats [numFormats++] = &gif;
  77908. const int64 streamPos = input.getPosition();
  77909. for (int i = 0; i < numFormats; ++i)
  77910. {
  77911. const bool found = formats[i]->canUnderstand (input);
  77912. input.setPosition (streamPos);
  77913. if (found)
  77914. return formats[i];
  77915. }
  77916. return 0;
  77917. }
  77918. const Image ImageFileFormat::loadFrom (InputStream& input)
  77919. {
  77920. ImageFileFormat* const format = findImageFormatForStream (input);
  77921. if (format != 0)
  77922. return format->decodeImage (input);
  77923. return Image::null;
  77924. }
  77925. const Image ImageFileFormat::loadFrom (const File& file)
  77926. {
  77927. InputStream* const in = file.createInputStream();
  77928. if (in != 0)
  77929. {
  77930. BufferedInputStream b (in, 8192, true);
  77931. return loadFrom (b);
  77932. }
  77933. return Image::null;
  77934. }
  77935. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77936. {
  77937. if (rawData != 0 && numBytes > 4)
  77938. {
  77939. MemoryInputStream stream (rawData, numBytes, false);
  77940. return loadFrom (stream);
  77941. }
  77942. return Image::null;
  77943. }
  77944. END_JUCE_NAMESPACE
  77945. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77946. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77947. BEGIN_JUCE_NAMESPACE
  77948. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77949. const Image juce_loadWithCoreImage (InputStream& input);
  77950. #else
  77951. class GIFLoader
  77952. {
  77953. public:
  77954. GIFLoader (InputStream& in)
  77955. : input (in),
  77956. dataBlockIsZero (false),
  77957. fresh (false),
  77958. finished (false)
  77959. {
  77960. currentBit = lastBit = lastByteIndex = 0;
  77961. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77962. firstcode = oldcode = 0;
  77963. clearCode = end_code = 0;
  77964. int imageWidth, imageHeight;
  77965. int transparent = -1;
  77966. if (! getSizeFromHeader (imageWidth, imageHeight))
  77967. return;
  77968. if ((imageWidth <= 0) || (imageHeight <= 0))
  77969. return;
  77970. unsigned char buf [16];
  77971. if (in.read (buf, 3) != 3)
  77972. return;
  77973. int numColours = 2 << (buf[0] & 7);
  77974. if ((buf[0] & 0x80) != 0)
  77975. readPalette (numColours);
  77976. for (;;)
  77977. {
  77978. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77979. break;
  77980. if (buf[0] == '!')
  77981. {
  77982. if (input.read (buf, 1) != 1)
  77983. break;
  77984. if (processExtension (buf[0], transparent) < 0)
  77985. break;
  77986. continue;
  77987. }
  77988. if (buf[0] != ',')
  77989. continue;
  77990. if (input.read (buf, 9) != 9)
  77991. break;
  77992. imageWidth = makeWord (buf[4], buf[5]);
  77993. imageHeight = makeWord (buf[6], buf[7]);
  77994. numColours = 2 << (buf[8] & 7);
  77995. if ((buf[8] & 0x80) != 0)
  77996. if (! readPalette (numColours))
  77997. break;
  77998. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77999. imageWidth, imageHeight, (transparent >= 0));
  78000. readImage ((buf[8] & 0x40) != 0, transparent);
  78001. break;
  78002. }
  78003. }
  78004. ~GIFLoader() {}
  78005. Image image;
  78006. private:
  78007. InputStream& input;
  78008. uint8 buffer [300];
  78009. uint8 palette [256][4];
  78010. bool dataBlockIsZero, fresh, finished;
  78011. int currentBit, lastBit, lastByteIndex;
  78012. int codeSize, setCodeSize;
  78013. int maxCode, maxCodeSize;
  78014. int firstcode, oldcode;
  78015. int clearCode, end_code;
  78016. enum { maxGifCode = 1 << 12 };
  78017. int table [2] [maxGifCode];
  78018. int stack [2 * maxGifCode];
  78019. int *sp;
  78020. bool getSizeFromHeader (int& w, int& h)
  78021. {
  78022. char b[8];
  78023. if (input.read (b, 6) == 6)
  78024. {
  78025. if ((strncmp ("GIF87a", b, 6) == 0)
  78026. || (strncmp ("GIF89a", b, 6) == 0))
  78027. {
  78028. if (input.read (b, 4) == 4)
  78029. {
  78030. w = makeWord (b[0], b[1]);
  78031. h = makeWord (b[2], b[3]);
  78032. return true;
  78033. }
  78034. }
  78035. }
  78036. return false;
  78037. }
  78038. bool readPalette (const int numCols)
  78039. {
  78040. unsigned char rgb[4];
  78041. for (int i = 0; i < numCols; ++i)
  78042. {
  78043. input.read (rgb, 3);
  78044. palette [i][0] = rgb[0];
  78045. palette [i][1] = rgb[1];
  78046. palette [i][2] = rgb[2];
  78047. palette [i][3] = 0xff;
  78048. }
  78049. return true;
  78050. }
  78051. int readDataBlock (unsigned char* dest)
  78052. {
  78053. unsigned char n;
  78054. if (input.read (&n, 1) == 1)
  78055. {
  78056. dataBlockIsZero = (n == 0);
  78057. if (dataBlockIsZero || (input.read (dest, n) == n))
  78058. return n;
  78059. }
  78060. return -1;
  78061. }
  78062. int processExtension (const int type, int& transparent)
  78063. {
  78064. unsigned char b [300];
  78065. int n = 0;
  78066. if (type == 0xf9)
  78067. {
  78068. n = readDataBlock (b);
  78069. if (n < 0)
  78070. return 1;
  78071. if ((b[0] & 0x1) != 0)
  78072. transparent = b[3];
  78073. }
  78074. do
  78075. {
  78076. n = readDataBlock (b);
  78077. }
  78078. while (n > 0);
  78079. return n;
  78080. }
  78081. int readLZWByte (const bool initialise, const int inputCodeSize)
  78082. {
  78083. int code, incode, i;
  78084. if (initialise)
  78085. {
  78086. setCodeSize = inputCodeSize;
  78087. codeSize = setCodeSize + 1;
  78088. clearCode = 1 << setCodeSize;
  78089. end_code = clearCode + 1;
  78090. maxCodeSize = 2 * clearCode;
  78091. maxCode = clearCode + 2;
  78092. getCode (0, true);
  78093. fresh = true;
  78094. for (i = 0; i < clearCode; ++i)
  78095. {
  78096. table[0][i] = 0;
  78097. table[1][i] = i;
  78098. }
  78099. for (; i < maxGifCode; ++i)
  78100. {
  78101. table[0][i] = 0;
  78102. table[1][i] = 0;
  78103. }
  78104. sp = stack;
  78105. return 0;
  78106. }
  78107. else if (fresh)
  78108. {
  78109. fresh = false;
  78110. do
  78111. {
  78112. firstcode = oldcode
  78113. = getCode (codeSize, false);
  78114. }
  78115. while (firstcode == clearCode);
  78116. return firstcode;
  78117. }
  78118. if (sp > stack)
  78119. return *--sp;
  78120. while ((code = getCode (codeSize, false)) >= 0)
  78121. {
  78122. if (code == clearCode)
  78123. {
  78124. for (i = 0; i < clearCode; ++i)
  78125. {
  78126. table[0][i] = 0;
  78127. table[1][i] = i;
  78128. }
  78129. for (; i < maxGifCode; ++i)
  78130. {
  78131. table[0][i] = 0;
  78132. table[1][i] = 0;
  78133. }
  78134. codeSize = setCodeSize + 1;
  78135. maxCodeSize = 2 * clearCode;
  78136. maxCode = clearCode + 2;
  78137. sp = stack;
  78138. firstcode = oldcode = getCode (codeSize, false);
  78139. return firstcode;
  78140. }
  78141. else if (code == end_code)
  78142. {
  78143. if (dataBlockIsZero)
  78144. return -2;
  78145. unsigned char buf [260];
  78146. int n;
  78147. while ((n = readDataBlock (buf)) > 0)
  78148. {}
  78149. if (n != 0)
  78150. return -2;
  78151. }
  78152. incode = code;
  78153. if (code >= maxCode)
  78154. {
  78155. *sp++ = firstcode;
  78156. code = oldcode;
  78157. }
  78158. while (code >= clearCode)
  78159. {
  78160. *sp++ = table[1][code];
  78161. if (code == table[0][code])
  78162. return -2;
  78163. code = table[0][code];
  78164. }
  78165. *sp++ = firstcode = table[1][code];
  78166. if ((code = maxCode) < maxGifCode)
  78167. {
  78168. table[0][code] = oldcode;
  78169. table[1][code] = firstcode;
  78170. ++maxCode;
  78171. if ((maxCode >= maxCodeSize)
  78172. && (maxCodeSize < maxGifCode))
  78173. {
  78174. maxCodeSize <<= 1;
  78175. ++codeSize;
  78176. }
  78177. }
  78178. oldcode = incode;
  78179. if (sp > stack)
  78180. return *--sp;
  78181. }
  78182. return code;
  78183. }
  78184. int getCode (const int codeSize_, const bool initialise)
  78185. {
  78186. if (initialise)
  78187. {
  78188. currentBit = 0;
  78189. lastBit = 0;
  78190. finished = false;
  78191. return 0;
  78192. }
  78193. if ((currentBit + codeSize_) >= lastBit)
  78194. {
  78195. if (finished)
  78196. return -1;
  78197. buffer[0] = buffer [lastByteIndex - 2];
  78198. buffer[1] = buffer [lastByteIndex - 1];
  78199. const int n = readDataBlock (&buffer[2]);
  78200. if (n == 0)
  78201. finished = true;
  78202. lastByteIndex = 2 + n;
  78203. currentBit = (currentBit - lastBit) + 16;
  78204. lastBit = (2 + n) * 8 ;
  78205. }
  78206. int result = 0;
  78207. int i = currentBit;
  78208. for (int j = 0; j < codeSize_; ++j)
  78209. {
  78210. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78211. ++i;
  78212. }
  78213. currentBit += codeSize_;
  78214. return result;
  78215. }
  78216. bool readImage (const int interlace, const int transparent)
  78217. {
  78218. unsigned char c;
  78219. if (input.read (&c, 1) != 1
  78220. || readLZWByte (true, c) < 0)
  78221. return false;
  78222. if (transparent >= 0)
  78223. {
  78224. palette [transparent][0] = 0;
  78225. palette [transparent][1] = 0;
  78226. palette [transparent][2] = 0;
  78227. palette [transparent][3] = 0;
  78228. }
  78229. int index;
  78230. int xpos = 0, ypos = 0, pass = 0;
  78231. const Image::BitmapData destData (image, true);
  78232. uint8* p = destData.data;
  78233. const bool hasAlpha = image.hasAlphaChannel();
  78234. while ((index = readLZWByte (false, c)) >= 0)
  78235. {
  78236. const uint8* const paletteEntry = palette [index];
  78237. if (hasAlpha)
  78238. {
  78239. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78240. paletteEntry[0],
  78241. paletteEntry[1],
  78242. paletteEntry[2]);
  78243. ((PixelARGB*) p)->premultiply();
  78244. }
  78245. else
  78246. {
  78247. ((PixelRGB*) p)->setARGB (0,
  78248. paletteEntry[0],
  78249. paletteEntry[1],
  78250. paletteEntry[2]);
  78251. }
  78252. p += destData.pixelStride;
  78253. ++xpos;
  78254. if (xpos == destData.width)
  78255. {
  78256. xpos = 0;
  78257. if (interlace)
  78258. {
  78259. switch (pass)
  78260. {
  78261. case 0:
  78262. case 1: ypos += 8; break;
  78263. case 2: ypos += 4; break;
  78264. case 3: ypos += 2; break;
  78265. }
  78266. while (ypos >= destData.height)
  78267. {
  78268. ++pass;
  78269. switch (pass)
  78270. {
  78271. case 1: ypos = 4; break;
  78272. case 2: ypos = 2; break;
  78273. case 3: ypos = 1; break;
  78274. default: return true;
  78275. }
  78276. }
  78277. }
  78278. else
  78279. {
  78280. ++ypos;
  78281. }
  78282. p = destData.getPixelPointer (xpos, ypos);
  78283. }
  78284. if (ypos >= destData.height)
  78285. break;
  78286. }
  78287. return true;
  78288. }
  78289. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78290. GIFLoader (const GIFLoader&);
  78291. GIFLoader& operator= (const GIFLoader&);
  78292. };
  78293. #endif
  78294. GIFImageFormat::GIFImageFormat() {}
  78295. GIFImageFormat::~GIFImageFormat() {}
  78296. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78297. bool GIFImageFormat::canUnderstand (InputStream& in)
  78298. {
  78299. char header [4];
  78300. return (in.read (header, sizeof (header)) == sizeof (header))
  78301. && header[0] == 'G'
  78302. && header[1] == 'I'
  78303. && header[2] == 'F';
  78304. }
  78305. const Image GIFImageFormat::decodeImage (InputStream& in)
  78306. {
  78307. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78308. return juce_loadWithCoreImage (in);
  78309. #else
  78310. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78311. return loader->image;
  78312. #endif
  78313. }
  78314. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78315. {
  78316. jassertfalse; // writing isn't implemented for GIFs!
  78317. return false;
  78318. }
  78319. END_JUCE_NAMESPACE
  78320. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78321. #endif
  78322. //==============================================================================
  78323. // some files include lots of library code, so leave them to the end to avoid cluttering
  78324. // up the build for the clean files.
  78325. #if JUCE_BUILD_CORE
  78326. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78327. namespace zlibNamespace
  78328. {
  78329. #if JUCE_INCLUDE_ZLIB_CODE
  78330. #undef OS_CODE
  78331. #undef fdopen
  78332. /*** Start of inlined file: zlib.h ***/
  78333. #ifndef ZLIB_H
  78334. #define ZLIB_H
  78335. /*** Start of inlined file: zconf.h ***/
  78336. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78337. #ifndef ZCONF_H
  78338. #define ZCONF_H
  78339. // *** Just a few hacks here to make it compile nicely with Juce..
  78340. #define Z_PREFIX 1
  78341. #undef __MACTYPES__
  78342. #ifdef _MSC_VER
  78343. #pragma warning (disable : 4131 4127 4244 4267)
  78344. #endif
  78345. /*
  78346. * If you *really* need a unique prefix for all types and library functions,
  78347. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78348. */
  78349. #ifdef Z_PREFIX
  78350. # define deflateInit_ z_deflateInit_
  78351. # define deflate z_deflate
  78352. # define deflateEnd z_deflateEnd
  78353. # define inflateInit_ z_inflateInit_
  78354. # define inflate z_inflate
  78355. # define inflateEnd z_inflateEnd
  78356. # define inflatePrime z_inflatePrime
  78357. # define inflateGetHeader z_inflateGetHeader
  78358. # define adler32_combine z_adler32_combine
  78359. # define crc32_combine z_crc32_combine
  78360. # define deflateInit2_ z_deflateInit2_
  78361. # define deflateSetDictionary z_deflateSetDictionary
  78362. # define deflateCopy z_deflateCopy
  78363. # define deflateReset z_deflateReset
  78364. # define deflateParams z_deflateParams
  78365. # define deflateBound z_deflateBound
  78366. # define deflatePrime z_deflatePrime
  78367. # define inflateInit2_ z_inflateInit2_
  78368. # define inflateSetDictionary z_inflateSetDictionary
  78369. # define inflateSync z_inflateSync
  78370. # define inflateSyncPoint z_inflateSyncPoint
  78371. # define inflateCopy z_inflateCopy
  78372. # define inflateReset z_inflateReset
  78373. # define inflateBack z_inflateBack
  78374. # define inflateBackEnd z_inflateBackEnd
  78375. # define compress z_compress
  78376. # define compress2 z_compress2
  78377. # define compressBound z_compressBound
  78378. # define uncompress z_uncompress
  78379. # define adler32 z_adler32
  78380. # define crc32 z_crc32
  78381. # define get_crc_table z_get_crc_table
  78382. # define zError z_zError
  78383. # define alloc_func z_alloc_func
  78384. # define free_func z_free_func
  78385. # define in_func z_in_func
  78386. # define out_func z_out_func
  78387. # define Byte z_Byte
  78388. # define uInt z_uInt
  78389. # define uLong z_uLong
  78390. # define Bytef z_Bytef
  78391. # define charf z_charf
  78392. # define intf z_intf
  78393. # define uIntf z_uIntf
  78394. # define uLongf z_uLongf
  78395. # define voidpf z_voidpf
  78396. # define voidp z_voidp
  78397. #endif
  78398. #if defined(__MSDOS__) && !defined(MSDOS)
  78399. # define MSDOS
  78400. #endif
  78401. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78402. # define OS2
  78403. #endif
  78404. #if defined(_WINDOWS) && !defined(WINDOWS)
  78405. # define WINDOWS
  78406. #endif
  78407. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78408. # ifndef WIN32
  78409. # define WIN32
  78410. # endif
  78411. #endif
  78412. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78413. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78414. # ifndef SYS16BIT
  78415. # define SYS16BIT
  78416. # endif
  78417. # endif
  78418. #endif
  78419. /*
  78420. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78421. * than 64k bytes at a time (needed on systems with 16-bit int).
  78422. */
  78423. #ifdef SYS16BIT
  78424. # define MAXSEG_64K
  78425. #endif
  78426. #ifdef MSDOS
  78427. # define UNALIGNED_OK
  78428. #endif
  78429. #ifdef __STDC_VERSION__
  78430. # ifndef STDC
  78431. # define STDC
  78432. # endif
  78433. # if __STDC_VERSION__ >= 199901L
  78434. # ifndef STDC99
  78435. # define STDC99
  78436. # endif
  78437. # endif
  78438. #endif
  78439. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78440. # define STDC
  78441. #endif
  78442. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78443. # define STDC
  78444. #endif
  78445. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78446. # define STDC
  78447. #endif
  78448. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78449. # define STDC
  78450. #endif
  78451. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78452. # define STDC
  78453. #endif
  78454. #ifndef STDC
  78455. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78456. # define const /* note: need a more gentle solution here */
  78457. # endif
  78458. #endif
  78459. /* Some Mac compilers merge all .h files incorrectly: */
  78460. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78461. # define NO_DUMMY_DECL
  78462. #endif
  78463. /* Maximum value for memLevel in deflateInit2 */
  78464. #ifndef MAX_MEM_LEVEL
  78465. # ifdef MAXSEG_64K
  78466. # define MAX_MEM_LEVEL 8
  78467. # else
  78468. # define MAX_MEM_LEVEL 9
  78469. # endif
  78470. #endif
  78471. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78472. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78473. * created by gzip. (Files created by minigzip can still be extracted by
  78474. * gzip.)
  78475. */
  78476. #ifndef MAX_WBITS
  78477. # define MAX_WBITS 15 /* 32K LZ77 window */
  78478. #endif
  78479. /* The memory requirements for deflate are (in bytes):
  78480. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78481. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78482. plus a few kilobytes for small objects. For example, if you want to reduce
  78483. the default memory requirements from 256K to 128K, compile with
  78484. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78485. Of course this will generally degrade compression (there's no free lunch).
  78486. The memory requirements for inflate are (in bytes) 1 << windowBits
  78487. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78488. for small objects.
  78489. */
  78490. /* Type declarations */
  78491. #ifndef OF /* function prototypes */
  78492. # ifdef STDC
  78493. # define OF(args) args
  78494. # else
  78495. # define OF(args) ()
  78496. # endif
  78497. #endif
  78498. /* The following definitions for FAR are needed only for MSDOS mixed
  78499. * model programming (small or medium model with some far allocations).
  78500. * This was tested only with MSC; for other MSDOS compilers you may have
  78501. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78502. * just define FAR to be empty.
  78503. */
  78504. #ifdef SYS16BIT
  78505. # if defined(M_I86SM) || defined(M_I86MM)
  78506. /* MSC small or medium model */
  78507. # define SMALL_MEDIUM
  78508. # ifdef _MSC_VER
  78509. # define FAR _far
  78510. # else
  78511. # define FAR far
  78512. # endif
  78513. # endif
  78514. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78515. /* Turbo C small or medium model */
  78516. # define SMALL_MEDIUM
  78517. # ifdef __BORLANDC__
  78518. # define FAR _far
  78519. # else
  78520. # define FAR far
  78521. # endif
  78522. # endif
  78523. #endif
  78524. #if defined(WINDOWS) || defined(WIN32)
  78525. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78526. * This is not mandatory, but it offers a little performance increase.
  78527. */
  78528. # ifdef ZLIB_DLL
  78529. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78530. # ifdef ZLIB_INTERNAL
  78531. # define ZEXTERN extern __declspec(dllexport)
  78532. # else
  78533. # define ZEXTERN extern __declspec(dllimport)
  78534. # endif
  78535. # endif
  78536. # endif /* ZLIB_DLL */
  78537. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78538. * define ZLIB_WINAPI.
  78539. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78540. */
  78541. # ifdef ZLIB_WINAPI
  78542. # ifdef FAR
  78543. # undef FAR
  78544. # endif
  78545. # include <windows.h>
  78546. /* No need for _export, use ZLIB.DEF instead. */
  78547. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78548. # define ZEXPORT WINAPI
  78549. # ifdef WIN32
  78550. # define ZEXPORTVA WINAPIV
  78551. # else
  78552. # define ZEXPORTVA FAR CDECL
  78553. # endif
  78554. # endif
  78555. #endif
  78556. #if defined (__BEOS__)
  78557. # ifdef ZLIB_DLL
  78558. # ifdef ZLIB_INTERNAL
  78559. # define ZEXPORT __declspec(dllexport)
  78560. # define ZEXPORTVA __declspec(dllexport)
  78561. # else
  78562. # define ZEXPORT __declspec(dllimport)
  78563. # define ZEXPORTVA __declspec(dllimport)
  78564. # endif
  78565. # endif
  78566. #endif
  78567. #ifndef ZEXTERN
  78568. # define ZEXTERN extern
  78569. #endif
  78570. #ifndef ZEXPORT
  78571. # define ZEXPORT
  78572. #endif
  78573. #ifndef ZEXPORTVA
  78574. # define ZEXPORTVA
  78575. #endif
  78576. #ifndef FAR
  78577. # define FAR
  78578. #endif
  78579. #if !defined(__MACTYPES__)
  78580. typedef unsigned char Byte; /* 8 bits */
  78581. #endif
  78582. typedef unsigned int uInt; /* 16 bits or more */
  78583. typedef unsigned long uLong; /* 32 bits or more */
  78584. #ifdef SMALL_MEDIUM
  78585. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78586. # define Bytef Byte FAR
  78587. #else
  78588. typedef Byte FAR Bytef;
  78589. #endif
  78590. typedef char FAR charf;
  78591. typedef int FAR intf;
  78592. typedef uInt FAR uIntf;
  78593. typedef uLong FAR uLongf;
  78594. #ifdef STDC
  78595. typedef void const *voidpc;
  78596. typedef void FAR *voidpf;
  78597. typedef void *voidp;
  78598. #else
  78599. typedef Byte const *voidpc;
  78600. typedef Byte FAR *voidpf;
  78601. typedef Byte *voidp;
  78602. #endif
  78603. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78604. # include <sys/types.h> /* for off_t */
  78605. # include <unistd.h> /* for SEEK_* and off_t */
  78606. # ifdef VMS
  78607. # include <unixio.h> /* for off_t */
  78608. # endif
  78609. # define z_off_t off_t
  78610. #endif
  78611. #ifndef SEEK_SET
  78612. # define SEEK_SET 0 /* Seek from beginning of file. */
  78613. # define SEEK_CUR 1 /* Seek from current position. */
  78614. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78615. #endif
  78616. #ifndef z_off_t
  78617. # define z_off_t long
  78618. #endif
  78619. #if defined(__OS400__)
  78620. # define NO_vsnprintf
  78621. #endif
  78622. #if defined(__MVS__)
  78623. # define NO_vsnprintf
  78624. # ifdef FAR
  78625. # undef FAR
  78626. # endif
  78627. #endif
  78628. /* MVS linker does not support external names larger than 8 bytes */
  78629. #if defined(__MVS__)
  78630. # pragma map(deflateInit_,"DEIN")
  78631. # pragma map(deflateInit2_,"DEIN2")
  78632. # pragma map(deflateEnd,"DEEND")
  78633. # pragma map(deflateBound,"DEBND")
  78634. # pragma map(inflateInit_,"ININ")
  78635. # pragma map(inflateInit2_,"ININ2")
  78636. # pragma map(inflateEnd,"INEND")
  78637. # pragma map(inflateSync,"INSY")
  78638. # pragma map(inflateSetDictionary,"INSEDI")
  78639. # pragma map(compressBound,"CMBND")
  78640. # pragma map(inflate_table,"INTABL")
  78641. # pragma map(inflate_fast,"INFA")
  78642. # pragma map(inflate_copyright,"INCOPY")
  78643. #endif
  78644. #endif /* ZCONF_H */
  78645. /*** End of inlined file: zconf.h ***/
  78646. #ifdef __cplusplus
  78647. //extern "C" {
  78648. #endif
  78649. #define ZLIB_VERSION "1.2.3"
  78650. #define ZLIB_VERNUM 0x1230
  78651. /*
  78652. The 'zlib' compression library provides in-memory compression and
  78653. decompression functions, including integrity checks of the uncompressed
  78654. data. This version of the library supports only one compression method
  78655. (deflation) but other algorithms will be added later and will have the same
  78656. stream interface.
  78657. Compression can be done in a single step if the buffers are large
  78658. enough (for example if an input file is mmap'ed), or can be done by
  78659. repeated calls of the compression function. In the latter case, the
  78660. application must provide more input and/or consume the output
  78661. (providing more output space) before each call.
  78662. The compressed data format used by default by the in-memory functions is
  78663. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78664. around a deflate stream, which is itself documented in RFC 1951.
  78665. The library also supports reading and writing files in gzip (.gz) format
  78666. with an interface similar to that of stdio using the functions that start
  78667. with "gz". The gzip format is different from the zlib format. gzip is a
  78668. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78669. This library can optionally read and write gzip streams in memory as well.
  78670. The zlib format was designed to be compact and fast for use in memory
  78671. and on communications channels. The gzip format was designed for single-
  78672. file compression on file systems, has a larger header than zlib to maintain
  78673. directory information, and uses a different, slower check method than zlib.
  78674. The library does not install any signal handler. The decoder checks
  78675. the consistency of the compressed data, so the library should never
  78676. crash even in case of corrupted input.
  78677. */
  78678. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78679. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78680. struct internal_state;
  78681. typedef struct z_stream_s {
  78682. Bytef *next_in; /* next input byte */
  78683. uInt avail_in; /* number of bytes available at next_in */
  78684. uLong total_in; /* total nb of input bytes read so far */
  78685. Bytef *next_out; /* next output byte should be put there */
  78686. uInt avail_out; /* remaining free space at next_out */
  78687. uLong total_out; /* total nb of bytes output so far */
  78688. char *msg; /* last error message, NULL if no error */
  78689. struct internal_state FAR *state; /* not visible by applications */
  78690. alloc_func zalloc; /* used to allocate the internal state */
  78691. free_func zfree; /* used to free the internal state */
  78692. voidpf opaque; /* private data object passed to zalloc and zfree */
  78693. int data_type; /* best guess about the data type: binary or text */
  78694. uLong adler; /* adler32 value of the uncompressed data */
  78695. uLong reserved; /* reserved for future use */
  78696. } z_stream;
  78697. typedef z_stream FAR *z_streamp;
  78698. /*
  78699. gzip header information passed to and from zlib routines. See RFC 1952
  78700. for more details on the meanings of these fields.
  78701. */
  78702. typedef struct gz_header_s {
  78703. int text; /* true if compressed data believed to be text */
  78704. uLong time; /* modification time */
  78705. int xflags; /* extra flags (not used when writing a gzip file) */
  78706. int os; /* operating system */
  78707. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78708. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78709. uInt extra_max; /* space at extra (only when reading header) */
  78710. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78711. uInt name_max; /* space at name (only when reading header) */
  78712. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78713. uInt comm_max; /* space at comment (only when reading header) */
  78714. int hcrc; /* true if there was or will be a header crc */
  78715. int done; /* true when done reading gzip header (not used
  78716. when writing a gzip file) */
  78717. } gz_header;
  78718. typedef gz_header FAR *gz_headerp;
  78719. /*
  78720. The application must update next_in and avail_in when avail_in has
  78721. dropped to zero. It must update next_out and avail_out when avail_out
  78722. has dropped to zero. The application must initialize zalloc, zfree and
  78723. opaque before calling the init function. All other fields are set by the
  78724. compression library and must not be updated by the application.
  78725. The opaque value provided by the application will be passed as the first
  78726. parameter for calls of zalloc and zfree. This can be useful for custom
  78727. memory management. The compression library attaches no meaning to the
  78728. opaque value.
  78729. zalloc must return Z_NULL if there is not enough memory for the object.
  78730. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78731. thread safe.
  78732. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78733. exactly 65536 bytes, but will not be required to allocate more than this
  78734. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78735. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78736. have their offset normalized to zero. The default allocation function
  78737. provided by this library ensures this (see zutil.c). To reduce memory
  78738. requirements and avoid any allocation of 64K objects, at the expense of
  78739. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78740. The fields total_in and total_out can be used for statistics or
  78741. progress reports. After compression, total_in holds the total size of
  78742. the uncompressed data and may be saved for use in the decompressor
  78743. (particularly if the decompressor wants to decompress everything in
  78744. a single step).
  78745. */
  78746. /* constants */
  78747. #define Z_NO_FLUSH 0
  78748. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78749. #define Z_SYNC_FLUSH 2
  78750. #define Z_FULL_FLUSH 3
  78751. #define Z_FINISH 4
  78752. #define Z_BLOCK 5
  78753. /* Allowed flush values; see deflate() and inflate() below for details */
  78754. #define Z_OK 0
  78755. #define Z_STREAM_END 1
  78756. #define Z_NEED_DICT 2
  78757. #define Z_ERRNO (-1)
  78758. #define Z_STREAM_ERROR (-2)
  78759. #define Z_DATA_ERROR (-3)
  78760. #define Z_MEM_ERROR (-4)
  78761. #define Z_BUF_ERROR (-5)
  78762. #define Z_VERSION_ERROR (-6)
  78763. /* Return codes for the compression/decompression functions. Negative
  78764. * values are errors, positive values are used for special but normal events.
  78765. */
  78766. #define Z_NO_COMPRESSION 0
  78767. #define Z_BEST_SPEED 1
  78768. #define Z_BEST_COMPRESSION 9
  78769. #define Z_DEFAULT_COMPRESSION (-1)
  78770. /* compression levels */
  78771. #define Z_FILTERED 1
  78772. #define Z_HUFFMAN_ONLY 2
  78773. #define Z_RLE 3
  78774. #define Z_FIXED 4
  78775. #define Z_DEFAULT_STRATEGY 0
  78776. /* compression strategy; see deflateInit2() below for details */
  78777. #define Z_BINARY 0
  78778. #define Z_TEXT 1
  78779. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78780. #define Z_UNKNOWN 2
  78781. /* Possible values of the data_type field (though see inflate()) */
  78782. #define Z_DEFLATED 8
  78783. /* The deflate compression method (the only one supported in this version) */
  78784. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78785. #define zlib_version zlibVersion()
  78786. /* for compatibility with versions < 1.0.2 */
  78787. /* basic functions */
  78788. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78789. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78790. If the first character differs, the library code actually used is
  78791. not compatible with the zlib.h header file used by the application.
  78792. This check is automatically made by deflateInit and inflateInit.
  78793. */
  78794. /*
  78795. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78796. Initializes the internal stream state for compression. The fields
  78797. zalloc, zfree and opaque must be initialized before by the caller.
  78798. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78799. use default allocation functions.
  78800. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78801. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78802. all (the input data is simply copied a block at a time).
  78803. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78804. compression (currently equivalent to level 6).
  78805. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78806. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78807. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78808. with the version assumed by the caller (ZLIB_VERSION).
  78809. msg is set to null if there is no error message. deflateInit does not
  78810. perform any compression: this will be done by deflate().
  78811. */
  78812. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78813. /*
  78814. deflate compresses as much data as possible, and stops when the input
  78815. buffer becomes empty or the output buffer becomes full. It may introduce some
  78816. output latency (reading input without producing any output) except when
  78817. forced to flush.
  78818. The detailed semantics are as follows. deflate performs one or both of the
  78819. following actions:
  78820. - Compress more input starting at next_in and update next_in and avail_in
  78821. accordingly. If not all input can be processed (because there is not
  78822. enough room in the output buffer), next_in and avail_in are updated and
  78823. processing will resume at this point for the next call of deflate().
  78824. - Provide more output starting at next_out and update next_out and avail_out
  78825. accordingly. This action is forced if the parameter flush is non zero.
  78826. Forcing flush frequently degrades the compression ratio, so this parameter
  78827. should be set only when necessary (in interactive applications).
  78828. Some output may be provided even if flush is not set.
  78829. Before the call of deflate(), the application should ensure that at least
  78830. one of the actions is possible, by providing more input and/or consuming
  78831. more output, and updating avail_in or avail_out accordingly; avail_out
  78832. should never be zero before the call. The application can consume the
  78833. compressed output when it wants, for example when the output buffer is full
  78834. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78835. and with zero avail_out, it must be called again after making room in the
  78836. output buffer because there might be more output pending.
  78837. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78838. decide how much data to accumualte before producing output, in order to
  78839. maximize compression.
  78840. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78841. flushed to the output buffer and the output is aligned on a byte boundary, so
  78842. that the decompressor can get all input data available so far. (In particular
  78843. avail_in is zero after the call if enough output space has been provided
  78844. before the call.) Flushing may degrade compression for some compression
  78845. algorithms and so it should be used only when necessary.
  78846. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78847. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78848. restart from this point if previous compressed data has been damaged or if
  78849. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78850. compression.
  78851. If deflate returns with avail_out == 0, this function must be called again
  78852. with the same value of the flush parameter and more output space (updated
  78853. avail_out), until the flush is complete (deflate returns with non-zero
  78854. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78855. avail_out is greater than six to avoid repeated flush markers due to
  78856. avail_out == 0 on return.
  78857. If the parameter flush is set to Z_FINISH, pending input is processed,
  78858. pending output is flushed and deflate returns with Z_STREAM_END if there
  78859. was enough output space; if deflate returns with Z_OK, this function must be
  78860. called again with Z_FINISH and more output space (updated avail_out) but no
  78861. more input data, until it returns with Z_STREAM_END or an error. After
  78862. deflate has returned Z_STREAM_END, the only possible operations on the
  78863. stream are deflateReset or deflateEnd.
  78864. Z_FINISH can be used immediately after deflateInit if all the compression
  78865. is to be done in a single step. In this case, avail_out must be at least
  78866. the value returned by deflateBound (see below). If deflate does not return
  78867. Z_STREAM_END, then it must be called again as described above.
  78868. deflate() sets strm->adler to the adler32 checksum of all input read
  78869. so far (that is, total_in bytes).
  78870. deflate() may update strm->data_type if it can make a good guess about
  78871. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78872. binary. This field is only for information purposes and does not affect
  78873. the compression algorithm in any manner.
  78874. deflate() returns Z_OK if some progress has been made (more input
  78875. processed or more output produced), Z_STREAM_END if all input has been
  78876. consumed and all output has been produced (only when flush is set to
  78877. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78878. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78879. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78880. fatal, and deflate() can be called again with more input and more output
  78881. space to continue compressing.
  78882. */
  78883. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78884. /*
  78885. All dynamically allocated data structures for this stream are freed.
  78886. This function discards any unprocessed input and does not flush any
  78887. pending output.
  78888. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78889. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78890. prematurely (some input or output was discarded). In the error case,
  78891. msg may be set but then points to a static string (which must not be
  78892. deallocated).
  78893. */
  78894. /*
  78895. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78896. Initializes the internal stream state for decompression. The fields
  78897. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78898. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78899. value depends on the compression method), inflateInit determines the
  78900. compression method from the zlib header and allocates all data structures
  78901. accordingly; otherwise the allocation will be deferred to the first call of
  78902. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78903. use default allocation functions.
  78904. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78905. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78906. version assumed by the caller. msg is set to null if there is no error
  78907. message. inflateInit does not perform any decompression apart from reading
  78908. the zlib header if present: this will be done by inflate(). (So next_in and
  78909. avail_in may be modified, but next_out and avail_out are unchanged.)
  78910. */
  78911. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78912. /*
  78913. inflate decompresses as much data as possible, and stops when the input
  78914. buffer becomes empty or the output buffer becomes full. It may introduce
  78915. some output latency (reading input without producing any output) except when
  78916. forced to flush.
  78917. The detailed semantics are as follows. inflate performs one or both of the
  78918. following actions:
  78919. - Decompress more input starting at next_in and update next_in and avail_in
  78920. accordingly. If not all input can be processed (because there is not
  78921. enough room in the output buffer), next_in is updated and processing
  78922. will resume at this point for the next call of inflate().
  78923. - Provide more output starting at next_out and update next_out and avail_out
  78924. accordingly. inflate() provides as much output as possible, until there
  78925. is no more input data or no more space in the output buffer (see below
  78926. about the flush parameter).
  78927. Before the call of inflate(), the application should ensure that at least
  78928. one of the actions is possible, by providing more input and/or consuming
  78929. more output, and updating the next_* and avail_* values accordingly.
  78930. The application can consume the uncompressed output when it wants, for
  78931. example when the output buffer is full (avail_out == 0), or after each
  78932. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78933. must be called again after making room in the output buffer because there
  78934. might be more output pending.
  78935. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78936. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78937. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78938. if and when it gets to the next deflate block boundary. When decoding the
  78939. zlib or gzip format, this will cause inflate() to return immediately after
  78940. the header and before the first block. When doing a raw inflate, inflate()
  78941. will go ahead and process the first block, and will return when it gets to
  78942. the end of that block, or when it runs out of data.
  78943. The Z_BLOCK option assists in appending to or combining deflate streams.
  78944. Also to assist in this, on return inflate() will set strm->data_type to the
  78945. number of unused bits in the last byte taken from strm->next_in, plus 64
  78946. if inflate() is currently decoding the last block in the deflate stream,
  78947. plus 128 if inflate() returned immediately after decoding an end-of-block
  78948. code or decoding the complete header up to just before the first byte of the
  78949. deflate stream. The end-of-block will not be indicated until all of the
  78950. uncompressed data from that block has been written to strm->next_out. The
  78951. number of unused bits may in general be greater than seven, except when
  78952. bit 7 of data_type is set, in which case the number of unused bits will be
  78953. less than eight.
  78954. inflate() should normally be called until it returns Z_STREAM_END or an
  78955. error. However if all decompression is to be performed in a single step
  78956. (a single call of inflate), the parameter flush should be set to
  78957. Z_FINISH. In this case all pending input is processed and all pending
  78958. output is flushed; avail_out must be large enough to hold all the
  78959. uncompressed data. (The size of the uncompressed data may have been saved
  78960. by the compressor for this purpose.) The next operation on this stream must
  78961. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78962. is never required, but can be used to inform inflate that a faster approach
  78963. may be used for the single inflate() call.
  78964. In this implementation, inflate() always flushes as much output as
  78965. possible to the output buffer, and always uses the faster approach on the
  78966. first call. So the only effect of the flush parameter in this implementation
  78967. is on the return value of inflate(), as noted below, or when it returns early
  78968. because Z_BLOCK is used.
  78969. If a preset dictionary is needed after this call (see inflateSetDictionary
  78970. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78971. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78972. strm->adler to the adler32 checksum of all output produced so far (that is,
  78973. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78974. below. At the end of the stream, inflate() checks that its computed adler32
  78975. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78976. only if the checksum is correct.
  78977. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78978. deflate data. The header type is detected automatically. Any information
  78979. contained in the gzip header is not retained, so applications that need that
  78980. information should instead use raw inflate, see inflateInit2() below, or
  78981. inflateBack() and perform their own processing of the gzip header and
  78982. trailer.
  78983. inflate() returns Z_OK if some progress has been made (more input processed
  78984. or more output produced), Z_STREAM_END if the end of the compressed data has
  78985. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78986. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78987. corrupted (input stream not conforming to the zlib format or incorrect check
  78988. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78989. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78990. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78991. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78992. inflate() can be called again with more input and more output space to
  78993. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78994. call inflateSync() to look for a good compression block if a partial recovery
  78995. of the data is desired.
  78996. */
  78997. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78998. /*
  78999. All dynamically allocated data structures for this stream are freed.
  79000. This function discards any unprocessed input and does not flush any
  79001. pending output.
  79002. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  79003. was inconsistent. In the error case, msg may be set but then points to a
  79004. static string (which must not be deallocated).
  79005. */
  79006. /* Advanced functions */
  79007. /*
  79008. The following functions are needed only in some special applications.
  79009. */
  79010. /*
  79011. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  79012. int level,
  79013. int method,
  79014. int windowBits,
  79015. int memLevel,
  79016. int strategy));
  79017. This is another version of deflateInit with more compression options. The
  79018. fields next_in, zalloc, zfree and opaque must be initialized before by
  79019. the caller.
  79020. The method parameter is the compression method. It must be Z_DEFLATED in
  79021. this version of the library.
  79022. The windowBits parameter is the base two logarithm of the window size
  79023. (the size of the history buffer). It should be in the range 8..15 for this
  79024. version of the library. Larger values of this parameter result in better
  79025. compression at the expense of memory usage. The default value is 15 if
  79026. deflateInit is used instead.
  79027. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  79028. determines the window size. deflate() will then generate raw deflate data
  79029. with no zlib header or trailer, and will not compute an adler32 check value.
  79030. windowBits can also be greater than 15 for optional gzip encoding. Add
  79031. 16 to windowBits to write a simple gzip header and trailer around the
  79032. compressed data instead of a zlib wrapper. The gzip header will have no
  79033. file name, no extra data, no comment, no modification time (set to zero),
  79034. no header crc, and the operating system will be set to 255 (unknown). If a
  79035. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  79036. The memLevel parameter specifies how much memory should be allocated
  79037. for the internal compression state. memLevel=1 uses minimum memory but
  79038. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  79039. for optimal speed. The default value is 8. See zconf.h for total memory
  79040. usage as a function of windowBits and memLevel.
  79041. The strategy parameter is used to tune the compression algorithm. Use the
  79042. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  79043. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  79044. string match), or Z_RLE to limit match distances to one (run-length
  79045. encoding). Filtered data consists mostly of small values with a somewhat
  79046. random distribution. In this case, the compression algorithm is tuned to
  79047. compress them better. The effect of Z_FILTERED is to force more Huffman
  79048. coding and less string matching; it is somewhat intermediate between
  79049. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  79050. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  79051. parameter only affects the compression ratio but not the correctness of the
  79052. compressed output even if it is not set appropriately. Z_FIXED prevents the
  79053. use of dynamic Huffman codes, allowing for a simpler decoder for special
  79054. applications.
  79055. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79056. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79057. method). msg is set to null if there is no error message. deflateInit2 does
  79058. not perform any compression: this will be done by deflate().
  79059. */
  79060. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79061. const Bytef *dictionary,
  79062. uInt dictLength));
  79063. /*
  79064. Initializes the compression dictionary from the given byte sequence
  79065. without producing any compressed output. This function must be called
  79066. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79067. call of deflate. The compressor and decompressor must use exactly the same
  79068. dictionary (see inflateSetDictionary).
  79069. The dictionary should consist of strings (byte sequences) that are likely
  79070. to be encountered later in the data to be compressed, with the most commonly
  79071. used strings preferably put towards the end of the dictionary. Using a
  79072. dictionary is most useful when the data to be compressed is short and can be
  79073. predicted with good accuracy; the data can then be compressed better than
  79074. with the default empty dictionary.
  79075. Depending on the size of the compression data structures selected by
  79076. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79077. discarded, for example if the dictionary is larger than the window size in
  79078. deflate or deflate2. Thus the strings most likely to be useful should be
  79079. put at the end of the dictionary, not at the front. In addition, the
  79080. current implementation of deflate will use at most the window size minus
  79081. 262 bytes of the provided dictionary.
  79082. Upon return of this function, strm->adler is set to the adler32 value
  79083. of the dictionary; the decompressor may later use this value to determine
  79084. which dictionary has been used by the compressor. (The adler32 value
  79085. applies to the whole dictionary even if only a subset of the dictionary is
  79086. actually used by the compressor.) If a raw deflate was requested, then the
  79087. adler32 value is not computed and strm->adler is not set.
  79088. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79089. parameter is invalid (such as NULL dictionary) or the stream state is
  79090. inconsistent (for example if deflate has already been called for this stream
  79091. or if the compression method is bsort). deflateSetDictionary does not
  79092. perform any compression: this will be done by deflate().
  79093. */
  79094. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79095. z_streamp source));
  79096. /*
  79097. Sets the destination stream as a complete copy of the source stream.
  79098. This function can be useful when several compression strategies will be
  79099. tried, for example when there are several ways of pre-processing the input
  79100. data with a filter. The streams that will be discarded should then be freed
  79101. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79102. compression state which can be quite large, so this strategy is slow and
  79103. can consume lots of memory.
  79104. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79105. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79106. (such as zalloc being NULL). msg is left unchanged in both source and
  79107. destination.
  79108. */
  79109. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79110. /*
  79111. This function is equivalent to deflateEnd followed by deflateInit,
  79112. but does not free and reallocate all the internal compression state.
  79113. The stream will keep the same compression level and any other attributes
  79114. that may have been set by deflateInit2.
  79115. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79116. stream state was inconsistent (such as zalloc or state being NULL).
  79117. */
  79118. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79119. int level,
  79120. int strategy));
  79121. /*
  79122. Dynamically update the compression level and compression strategy. The
  79123. interpretation of level and strategy is as in deflateInit2. This can be
  79124. used to switch between compression and straight copy of the input data, or
  79125. to switch to a different kind of input data requiring a different
  79126. strategy. If the compression level is changed, the input available so far
  79127. is compressed with the old level (and may be flushed); the new level will
  79128. take effect only at the next call of deflate().
  79129. Before the call of deflateParams, the stream state must be set as for
  79130. a call of deflate(), since the currently available input may have to
  79131. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79132. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79133. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79134. if strm->avail_out was zero.
  79135. */
  79136. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79137. int good_length,
  79138. int max_lazy,
  79139. int nice_length,
  79140. int max_chain));
  79141. /*
  79142. Fine tune deflate's internal compression parameters. This should only be
  79143. used by someone who understands the algorithm used by zlib's deflate for
  79144. searching for the best matching string, and even then only by the most
  79145. fanatic optimizer trying to squeeze out the last compressed bit for their
  79146. specific input data. Read the deflate.c source code for the meaning of the
  79147. max_lazy, good_length, nice_length, and max_chain parameters.
  79148. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79149. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79150. */
  79151. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79152. uLong sourceLen));
  79153. /*
  79154. deflateBound() returns an upper bound on the compressed size after
  79155. deflation of sourceLen bytes. It must be called after deflateInit()
  79156. or deflateInit2(). This would be used to allocate an output buffer
  79157. for deflation in a single pass, and so would be called before deflate().
  79158. */
  79159. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79160. int bits,
  79161. int value));
  79162. /*
  79163. deflatePrime() inserts bits in the deflate output stream. The intent
  79164. is that this function is used to start off the deflate output with the
  79165. bits leftover from a previous deflate stream when appending to it. As such,
  79166. this function can only be used for raw deflate, and must be used before the
  79167. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79168. less than or equal to 16, and that many of the least significant bits of
  79169. value will be inserted in the output.
  79170. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79171. stream state was inconsistent.
  79172. */
  79173. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79174. gz_headerp head));
  79175. /*
  79176. deflateSetHeader() provides gzip header information for when a gzip
  79177. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79178. after deflateInit2() or deflateReset() and before the first call of
  79179. deflate(). The text, time, os, extra field, name, and comment information
  79180. in the provided gz_header structure are written to the gzip header (xflag is
  79181. ignored -- the extra flags are set according to the compression level). The
  79182. caller must assure that, if not Z_NULL, name and comment are terminated with
  79183. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79184. available there. If hcrc is true, a gzip header crc is included. Note that
  79185. the current versions of the command-line version of gzip (up through version
  79186. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79187. gzip file" and give up.
  79188. If deflateSetHeader is not used, the default gzip header has text false,
  79189. the time set to zero, and os set to 255, with no extra, name, or comment
  79190. fields. The gzip header is returned to the default state by deflateReset().
  79191. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79192. stream state was inconsistent.
  79193. */
  79194. /*
  79195. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79196. int windowBits));
  79197. This is another version of inflateInit with an extra parameter. The
  79198. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79199. before by the caller.
  79200. The windowBits parameter is the base two logarithm of the maximum window
  79201. size (the size of the history buffer). It should be in the range 8..15 for
  79202. this version of the library. The default value is 15 if inflateInit is used
  79203. instead. windowBits must be greater than or equal to the windowBits value
  79204. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79205. deflateInit2() was not used. If a compressed stream with a larger window
  79206. size is given as input, inflate() will return with the error code
  79207. Z_DATA_ERROR instead of trying to allocate a larger window.
  79208. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79209. determines the window size. inflate() will then process raw deflate data,
  79210. not looking for a zlib or gzip header, not generating a check value, and not
  79211. looking for any check values for comparison at the end of the stream. This
  79212. is for use with other formats that use the deflate compressed data format
  79213. such as zip. Those formats provide their own check values. If a custom
  79214. format is developed using the raw deflate format for compressed data, it is
  79215. recommended that a check value such as an adler32 or a crc32 be applied to
  79216. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79217. most applications, the zlib format should be used as is. Note that comments
  79218. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79219. windowBits can also be greater than 15 for optional gzip decoding. Add
  79220. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79221. detection, or add 16 to decode only the gzip format (the zlib format will
  79222. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79223. a crc32 instead of an adler32.
  79224. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79225. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79226. is set to null if there is no error message. inflateInit2 does not perform
  79227. any decompression apart from reading the zlib header if present: this will
  79228. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79229. and avail_out are unchanged.)
  79230. */
  79231. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79232. const Bytef *dictionary,
  79233. uInt dictLength));
  79234. /*
  79235. Initializes the decompression dictionary from the given uncompressed byte
  79236. sequence. This function must be called immediately after a call of inflate,
  79237. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79238. can be determined from the adler32 value returned by that call of inflate.
  79239. The compressor and decompressor must use exactly the same dictionary (see
  79240. deflateSetDictionary). For raw inflate, this function can be called
  79241. immediately after inflateInit2() or inflateReset() and before any call of
  79242. inflate() to set the dictionary. The application must insure that the
  79243. dictionary that was used for compression is provided.
  79244. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79245. parameter is invalid (such as NULL dictionary) or the stream state is
  79246. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79247. expected one (incorrect adler32 value). inflateSetDictionary does not
  79248. perform any decompression: this will be done by subsequent calls of
  79249. inflate().
  79250. */
  79251. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79252. /*
  79253. Skips invalid compressed data until a full flush point (see above the
  79254. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79255. available input is skipped. No output is provided.
  79256. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79257. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79258. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79259. case, the application may save the current current value of total_in which
  79260. indicates where valid compressed data was found. In the error case, the
  79261. application may repeatedly call inflateSync, providing more input each time,
  79262. until success or end of the input data.
  79263. */
  79264. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79265. z_streamp source));
  79266. /*
  79267. Sets the destination stream as a complete copy of the source stream.
  79268. This function can be useful when randomly accessing a large stream. The
  79269. first pass through the stream can periodically record the inflate state,
  79270. allowing restarting inflate at those points when randomly accessing the
  79271. stream.
  79272. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79273. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79274. (such as zalloc being NULL). msg is left unchanged in both source and
  79275. destination.
  79276. */
  79277. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79278. /*
  79279. This function is equivalent to inflateEnd followed by inflateInit,
  79280. but does not free and reallocate all the internal decompression state.
  79281. The stream will keep attributes that may have been set by inflateInit2.
  79282. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79283. stream state was inconsistent (such as zalloc or state being NULL).
  79284. */
  79285. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79286. int bits,
  79287. int value));
  79288. /*
  79289. This function inserts bits in the inflate input stream. The intent is
  79290. that this function is used to start inflating at a bit position in the
  79291. middle of a byte. The provided bits will be used before any bytes are used
  79292. from next_in. This function should only be used with raw inflate, and
  79293. should be used before the first inflate() call after inflateInit2() or
  79294. inflateReset(). bits must be less than or equal to 16, and that many of the
  79295. least significant bits of value will be inserted in the input.
  79296. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79297. stream state was inconsistent.
  79298. */
  79299. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79300. gz_headerp head));
  79301. /*
  79302. inflateGetHeader() requests that gzip header information be stored in the
  79303. provided gz_header structure. inflateGetHeader() may be called after
  79304. inflateInit2() or inflateReset(), and before the first call of inflate().
  79305. As inflate() processes the gzip stream, head->done is zero until the header
  79306. is completed, at which time head->done is set to one. If a zlib stream is
  79307. being decoded, then head->done is set to -1 to indicate that there will be
  79308. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79309. force inflate() to return immediately after header processing is complete
  79310. and before any actual data is decompressed.
  79311. The text, time, xflags, and os fields are filled in with the gzip header
  79312. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79313. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79314. contains the maximum number of bytes to write to extra. Once done is true,
  79315. extra_len contains the actual extra field length, and extra contains the
  79316. extra field, or that field truncated if extra_max is less than extra_len.
  79317. If name is not Z_NULL, then up to name_max characters are written there,
  79318. terminated with a zero unless the length is greater than name_max. If
  79319. comment is not Z_NULL, then up to comm_max characters are written there,
  79320. terminated with a zero unless the length is greater than comm_max. When
  79321. any of extra, name, or comment are not Z_NULL and the respective field is
  79322. not present in the header, then that field is set to Z_NULL to signal its
  79323. absence. This allows the use of deflateSetHeader() with the returned
  79324. structure to duplicate the header. However if those fields are set to
  79325. allocated memory, then the application will need to save those pointers
  79326. elsewhere so that they can be eventually freed.
  79327. If inflateGetHeader is not used, then the header information is simply
  79328. discarded. The header is always checked for validity, including the header
  79329. CRC if present. inflateReset() will reset the process to discard the header
  79330. information. The application would need to call inflateGetHeader() again to
  79331. retrieve the header from the next gzip stream.
  79332. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79333. stream state was inconsistent.
  79334. */
  79335. /*
  79336. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79337. unsigned char FAR *window));
  79338. Initialize the internal stream state for decompression using inflateBack()
  79339. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79340. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79341. derived memory allocation routines are used. windowBits is the base two
  79342. logarithm of the window size, in the range 8..15. window is a caller
  79343. supplied buffer of that size. Except for special applications where it is
  79344. assured that deflate was used with small window sizes, windowBits must be 15
  79345. and a 32K byte window must be supplied to be able to decompress general
  79346. deflate streams.
  79347. See inflateBack() for the usage of these routines.
  79348. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79349. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79350. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79351. match the version of the header file.
  79352. */
  79353. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79354. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79355. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79356. in_func in, void FAR *in_desc,
  79357. out_func out, void FAR *out_desc));
  79358. /*
  79359. inflateBack() does a raw inflate with a single call using a call-back
  79360. interface for input and output. This is more efficient than inflate() for
  79361. file i/o applications in that it avoids copying between the output and the
  79362. sliding window by simply making the window itself the output buffer. This
  79363. function trusts the application to not change the output buffer passed by
  79364. the output function, at least until inflateBack() returns.
  79365. inflateBackInit() must be called first to allocate the internal state
  79366. and to initialize the state with the user-provided window buffer.
  79367. inflateBack() may then be used multiple times to inflate a complete, raw
  79368. deflate stream with each call. inflateBackEnd() is then called to free
  79369. the allocated state.
  79370. A raw deflate stream is one with no zlib or gzip header or trailer.
  79371. This routine would normally be used in a utility that reads zip or gzip
  79372. files and writes out uncompressed files. The utility would decode the
  79373. header and process the trailer on its own, hence this routine expects
  79374. only the raw deflate stream to decompress. This is different from the
  79375. normal behavior of inflate(), which expects either a zlib or gzip header and
  79376. trailer around the deflate stream.
  79377. inflateBack() uses two subroutines supplied by the caller that are then
  79378. called by inflateBack() for input and output. inflateBack() calls those
  79379. routines until it reads a complete deflate stream and writes out all of the
  79380. uncompressed data, or until it encounters an error. The function's
  79381. parameters and return types are defined above in the in_func and out_func
  79382. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79383. number of bytes of provided input, and a pointer to that input in buf. If
  79384. there is no input available, in() must return zero--buf is ignored in that
  79385. case--and inflateBack() will return a buffer error. inflateBack() will call
  79386. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79387. should return zero on success, or non-zero on failure. If out() returns
  79388. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79389. are permitted to change the contents of the window provided to
  79390. inflateBackInit(), which is also the buffer that out() uses to write from.
  79391. The length written by out() will be at most the window size. Any non-zero
  79392. amount of input may be provided by in().
  79393. For convenience, inflateBack() can be provided input on the first call by
  79394. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79395. in() will be called. Therefore strm->next_in must be initialized before
  79396. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79397. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79398. must also be initialized, and then if strm->avail_in is not zero, input will
  79399. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79400. The in_desc and out_desc parameters of inflateBack() is passed as the
  79401. first parameter of in() and out() respectively when they are called. These
  79402. descriptors can be optionally used to pass any information that the caller-
  79403. supplied in() and out() functions need to do their job.
  79404. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79405. pass back any unused input that was provided by the last in() call. The
  79406. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79407. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79408. error in the deflate stream (in which case strm->msg is set to indicate the
  79409. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79410. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79411. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79412. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79413. out() returning non-zero. (in() will always be called before out(), so
  79414. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79415. that inflateBack() cannot return Z_OK.
  79416. */
  79417. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79418. /*
  79419. All memory allocated by inflateBackInit() is freed.
  79420. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79421. state was inconsistent.
  79422. */
  79423. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79424. /* Return flags indicating compile-time options.
  79425. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79426. 1.0: size of uInt
  79427. 3.2: size of uLong
  79428. 5.4: size of voidpf (pointer)
  79429. 7.6: size of z_off_t
  79430. Compiler, assembler, and debug options:
  79431. 8: DEBUG
  79432. 9: ASMV or ASMINF -- use ASM code
  79433. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79434. 11: 0 (reserved)
  79435. One-time table building (smaller code, but not thread-safe if true):
  79436. 12: BUILDFIXED -- build static block decoding tables when needed
  79437. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79438. 14,15: 0 (reserved)
  79439. Library content (indicates missing functionality):
  79440. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79441. deflate code when not needed)
  79442. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79443. and decode gzip streams (to avoid linking crc code)
  79444. 18-19: 0 (reserved)
  79445. Operation variations (changes in library functionality):
  79446. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79447. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79448. 22,23: 0 (reserved)
  79449. The sprintf variant used by gzprintf (zero is best):
  79450. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79451. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79452. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79453. Remainder:
  79454. 27-31: 0 (reserved)
  79455. */
  79456. /* utility functions */
  79457. /*
  79458. The following utility functions are implemented on top of the
  79459. basic stream-oriented functions. To simplify the interface, some
  79460. default options are assumed (compression level and memory usage,
  79461. standard memory allocation functions). The source code of these
  79462. utility functions can easily be modified if you need special options.
  79463. */
  79464. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79465. const Bytef *source, uLong sourceLen));
  79466. /*
  79467. Compresses the source buffer into the destination buffer. sourceLen is
  79468. the byte length of the source buffer. Upon entry, destLen is the total
  79469. size of the destination buffer, which must be at least the value returned
  79470. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79471. compressed buffer.
  79472. This function can be used to compress a whole file at once if the
  79473. input file is mmap'ed.
  79474. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79475. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79476. buffer.
  79477. */
  79478. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79479. const Bytef *source, uLong sourceLen,
  79480. int level));
  79481. /*
  79482. Compresses the source buffer into the destination buffer. The level
  79483. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79484. length of the source buffer. Upon entry, destLen is the total size of the
  79485. destination buffer, which must be at least the value returned by
  79486. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79487. compressed buffer.
  79488. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79489. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79490. Z_STREAM_ERROR if the level parameter is invalid.
  79491. */
  79492. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79493. /*
  79494. compressBound() returns an upper bound on the compressed size after
  79495. compress() or compress2() on sourceLen bytes. It would be used before
  79496. a compress() or compress2() call to allocate the destination buffer.
  79497. */
  79498. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79499. const Bytef *source, uLong sourceLen));
  79500. /*
  79501. Decompresses the source buffer into the destination buffer. sourceLen is
  79502. the byte length of the source buffer. Upon entry, destLen is the total
  79503. size of the destination buffer, which must be large enough to hold the
  79504. entire uncompressed data. (The size of the uncompressed data must have
  79505. been saved previously by the compressor and transmitted to the decompressor
  79506. by some mechanism outside the scope of this compression library.)
  79507. Upon exit, destLen is the actual size of the compressed buffer.
  79508. This function can be used to decompress a whole file at once if the
  79509. input file is mmap'ed.
  79510. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79511. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79512. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79513. */
  79514. typedef voidp gzFile;
  79515. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79516. /*
  79517. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79518. is as in fopen ("rb" or "wb") but can also include a compression level
  79519. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79520. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79521. as in "wb1R". (See the description of deflateInit2 for more information
  79522. about the strategy parameter.)
  79523. gzopen can be used to read a file which is not in gzip format; in this
  79524. case gzread will directly read from the file without decompression.
  79525. gzopen returns NULL if the file could not be opened or if there was
  79526. insufficient memory to allocate the (de)compression state; errno
  79527. can be checked to distinguish the two cases (if errno is zero, the
  79528. zlib error is Z_MEM_ERROR). */
  79529. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79530. /*
  79531. gzdopen() associates a gzFile with the file descriptor fd. File
  79532. descriptors are obtained from calls like open, dup, creat, pipe or
  79533. fileno (in the file has been previously opened with fopen).
  79534. The mode parameter is as in gzopen.
  79535. The next call of gzclose on the returned gzFile will also close the
  79536. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79537. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79538. gzdopen returns NULL if there was insufficient memory to allocate
  79539. the (de)compression state.
  79540. */
  79541. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79542. /*
  79543. Dynamically update the compression level or strategy. See the description
  79544. of deflateInit2 for the meaning of these parameters.
  79545. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79546. opened for writing.
  79547. */
  79548. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79549. /*
  79550. Reads the given number of uncompressed bytes from the compressed file.
  79551. If the input file was not in gzip format, gzread copies the given number
  79552. of bytes into the buffer.
  79553. gzread returns the number of uncompressed bytes actually read (0 for
  79554. end of file, -1 for error). */
  79555. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79556. voidpc buf, unsigned len));
  79557. /*
  79558. Writes the given number of uncompressed bytes into the compressed file.
  79559. gzwrite returns the number of uncompressed bytes actually written
  79560. (0 in case of error).
  79561. */
  79562. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79563. /*
  79564. Converts, formats, and writes the args to the compressed file under
  79565. control of the format string, as in fprintf. gzprintf returns the number of
  79566. uncompressed bytes actually written (0 in case of error). The number of
  79567. uncompressed bytes written is limited to 4095. The caller should assure that
  79568. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79569. return an error (0) with nothing written. In this case, there may also be a
  79570. buffer overflow with unpredictable consequences, which is possible only if
  79571. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79572. because the secure snprintf() or vsnprintf() functions were not available.
  79573. */
  79574. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79575. /*
  79576. Writes the given null-terminated string to the compressed file, excluding
  79577. the terminating null character.
  79578. gzputs returns the number of characters written, or -1 in case of error.
  79579. */
  79580. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79581. /*
  79582. Reads bytes from the compressed file until len-1 characters are read, or
  79583. a newline character is read and transferred to buf, or an end-of-file
  79584. condition is encountered. The string is then terminated with a null
  79585. character.
  79586. gzgets returns buf, or Z_NULL in case of error.
  79587. */
  79588. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79589. /*
  79590. Writes c, converted to an unsigned char, into the compressed file.
  79591. gzputc returns the value that was written, or -1 in case of error.
  79592. */
  79593. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79594. /*
  79595. Reads one byte from the compressed file. gzgetc returns this byte
  79596. or -1 in case of end of file or error.
  79597. */
  79598. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79599. /*
  79600. Push one character back onto the stream to be read again later.
  79601. Only one character of push-back is allowed. gzungetc() returns the
  79602. character pushed, or -1 on failure. gzungetc() will fail if a
  79603. character has been pushed but not read yet, or if c is -1. The pushed
  79604. character will be discarded if the stream is repositioned with gzseek()
  79605. or gzrewind().
  79606. */
  79607. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79608. /*
  79609. Flushes all pending output into the compressed file. The parameter
  79610. flush is as in the deflate() function. The return value is the zlib
  79611. error number (see function gzerror below). gzflush returns Z_OK if
  79612. the flush parameter is Z_FINISH and all output could be flushed.
  79613. gzflush should be called only when strictly necessary because it can
  79614. degrade compression.
  79615. */
  79616. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79617. z_off_t offset, int whence));
  79618. /*
  79619. Sets the starting position for the next gzread or gzwrite on the
  79620. given compressed file. The offset represents a number of bytes in the
  79621. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79622. the value SEEK_END is not supported.
  79623. If the file is opened for reading, this function is emulated but can be
  79624. extremely slow. If the file is opened for writing, only forward seeks are
  79625. supported; gzseek then compresses a sequence of zeroes up to the new
  79626. starting position.
  79627. gzseek returns the resulting offset location as measured in bytes from
  79628. the beginning of the uncompressed stream, or -1 in case of error, in
  79629. particular if the file is opened for writing and the new starting position
  79630. would be before the current position.
  79631. */
  79632. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79633. /*
  79634. Rewinds the given file. This function is supported only for reading.
  79635. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79636. */
  79637. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79638. /*
  79639. Returns the starting position for the next gzread or gzwrite on the
  79640. given compressed file. This position represents a number of bytes in the
  79641. uncompressed data stream.
  79642. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79643. */
  79644. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79645. /*
  79646. Returns 1 when EOF has previously been detected reading the given
  79647. input stream, otherwise zero.
  79648. */
  79649. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79650. /*
  79651. Returns 1 if file is being read directly without decompression, otherwise
  79652. zero.
  79653. */
  79654. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79655. /*
  79656. Flushes all pending output if necessary, closes the compressed file
  79657. and deallocates all the (de)compression state. The return value is the zlib
  79658. error number (see function gzerror below).
  79659. */
  79660. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79661. /*
  79662. Returns the error message for the last error which occurred on the
  79663. given compressed file. errnum is set to zlib error number. If an
  79664. error occurred in the file system and not in the compression library,
  79665. errnum is set to Z_ERRNO and the application may consult errno
  79666. to get the exact error code.
  79667. */
  79668. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79669. /*
  79670. Clears the error and end-of-file flags for file. This is analogous to the
  79671. clearerr() function in stdio. This is useful for continuing to read a gzip
  79672. file that is being written concurrently.
  79673. */
  79674. /* checksum functions */
  79675. /*
  79676. These functions are not related to compression but are exported
  79677. anyway because they might be useful in applications using the
  79678. compression library.
  79679. */
  79680. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79681. /*
  79682. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79683. return the updated checksum. If buf is NULL, this function returns
  79684. the required initial value for the checksum.
  79685. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79686. much faster. Usage example:
  79687. uLong adler = adler32(0L, Z_NULL, 0);
  79688. while (read_buffer(buffer, length) != EOF) {
  79689. adler = adler32(adler, buffer, length);
  79690. }
  79691. if (adler != original_adler) error();
  79692. */
  79693. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79694. z_off_t len2));
  79695. /*
  79696. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79697. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79698. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79699. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79700. */
  79701. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79702. /*
  79703. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79704. updated CRC-32. If buf is NULL, this function returns the required initial
  79705. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79706. performed within this function so it shouldn't be done by the application.
  79707. Usage example:
  79708. uLong crc = crc32(0L, Z_NULL, 0);
  79709. while (read_buffer(buffer, length) != EOF) {
  79710. crc = crc32(crc, buffer, length);
  79711. }
  79712. if (crc != original_crc) error();
  79713. */
  79714. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79715. /*
  79716. Combine two CRC-32 check values into one. For two sequences of bytes,
  79717. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79718. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79719. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79720. len2.
  79721. */
  79722. /* various hacks, don't look :) */
  79723. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79724. * and the compiler's view of z_stream:
  79725. */
  79726. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79727. const char *version, int stream_size));
  79728. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79729. const char *version, int stream_size));
  79730. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79731. int windowBits, int memLevel,
  79732. int strategy, const char *version,
  79733. int stream_size));
  79734. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79735. const char *version, int stream_size));
  79736. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79737. unsigned char FAR *window,
  79738. const char *version,
  79739. int stream_size));
  79740. #define deflateInit(strm, level) \
  79741. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79742. #define inflateInit(strm) \
  79743. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79744. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79745. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79746. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79747. #define inflateInit2(strm, windowBits) \
  79748. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79749. #define inflateBackInit(strm, windowBits, window) \
  79750. inflateBackInit_((strm), (windowBits), (window), \
  79751. ZLIB_VERSION, sizeof(z_stream))
  79752. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79753. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79754. #endif
  79755. ZEXTERN const char * ZEXPORT zError OF((int));
  79756. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79757. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79758. #ifdef __cplusplus
  79759. //}
  79760. #endif
  79761. #endif /* ZLIB_H */
  79762. /*** End of inlined file: zlib.h ***/
  79763. #undef OS_CODE
  79764. #else
  79765. #include <zlib.h>
  79766. #endif
  79767. }
  79768. BEGIN_JUCE_NAMESPACE
  79769. // internal helper object that holds the zlib structures so they don't have to be
  79770. // included publicly.
  79771. class GZIPCompressorHelper
  79772. {
  79773. public:
  79774. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79775. : data (0),
  79776. dataSize (0),
  79777. compLevel (compressionLevel),
  79778. strategy (0),
  79779. setParams (true),
  79780. streamIsValid (false),
  79781. finished (false),
  79782. shouldFinish (false)
  79783. {
  79784. using namespace zlibNamespace;
  79785. zerostruct (stream);
  79786. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79787. nowrap ? -MAX_WBITS : MAX_WBITS,
  79788. 8, strategy) == Z_OK);
  79789. }
  79790. ~GZIPCompressorHelper()
  79791. {
  79792. using namespace zlibNamespace;
  79793. if (streamIsValid)
  79794. deflateEnd (&stream);
  79795. }
  79796. bool needsInput() const throw()
  79797. {
  79798. return dataSize <= 0;
  79799. }
  79800. void setInput (const uint8* const newData, const int size) throw()
  79801. {
  79802. data = newData;
  79803. dataSize = size;
  79804. }
  79805. int doNextBlock (uint8* const dest, const int destSize) throw()
  79806. {
  79807. using namespace zlibNamespace;
  79808. if (streamIsValid)
  79809. {
  79810. stream.next_in = const_cast <uint8*> (data);
  79811. stream.next_out = dest;
  79812. stream.avail_in = dataSize;
  79813. stream.avail_out = destSize;
  79814. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79815. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79816. setParams = false;
  79817. switch (result)
  79818. {
  79819. case Z_STREAM_END:
  79820. finished = true;
  79821. // Deliberate fall-through..
  79822. case Z_OK:
  79823. data += dataSize - stream.avail_in;
  79824. dataSize = stream.avail_in;
  79825. return destSize - stream.avail_out;
  79826. default:
  79827. break;
  79828. }
  79829. }
  79830. return 0;
  79831. }
  79832. private:
  79833. zlibNamespace::z_stream stream;
  79834. const uint8* data;
  79835. int dataSize, compLevel, strategy;
  79836. bool setParams, streamIsValid;
  79837. public:
  79838. bool finished, shouldFinish;
  79839. };
  79840. const int gzipCompBufferSize = 32768;
  79841. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79842. int compressionLevel,
  79843. const bool deleteDestStream,
  79844. const bool noWrap)
  79845. : destStream (destStream_),
  79846. streamToDelete (deleteDestStream ? destStream_ : 0),
  79847. buffer (gzipCompBufferSize)
  79848. {
  79849. if (compressionLevel < 1 || compressionLevel > 9)
  79850. compressionLevel = -1;
  79851. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79852. }
  79853. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79854. {
  79855. flush();
  79856. }
  79857. void GZIPCompressorOutputStream::flush()
  79858. {
  79859. if (! helper->finished)
  79860. {
  79861. helper->shouldFinish = true;
  79862. while (! helper->finished)
  79863. doNextBlock();
  79864. }
  79865. destStream->flush();
  79866. }
  79867. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79868. {
  79869. if (! helper->finished)
  79870. {
  79871. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79872. while (! helper->needsInput())
  79873. {
  79874. if (! doNextBlock())
  79875. return false;
  79876. }
  79877. }
  79878. return true;
  79879. }
  79880. bool GZIPCompressorOutputStream::doNextBlock()
  79881. {
  79882. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79883. if (len > 0)
  79884. return destStream->write (buffer, len);
  79885. else
  79886. return true;
  79887. }
  79888. int64 GZIPCompressorOutputStream::getPosition()
  79889. {
  79890. return destStream->getPosition();
  79891. }
  79892. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79893. {
  79894. jassertfalse; // can't do it!
  79895. return false;
  79896. }
  79897. END_JUCE_NAMESPACE
  79898. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79899. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79900. #if JUCE_MSVC
  79901. #pragma warning (push)
  79902. #pragma warning (disable: 4309 4305)
  79903. #endif
  79904. namespace zlibNamespace
  79905. {
  79906. #if JUCE_INCLUDE_ZLIB_CODE
  79907. #undef OS_CODE
  79908. #undef fdopen
  79909. #define ZLIB_INTERNAL
  79910. #define NO_DUMMY_DECL
  79911. /*** Start of inlined file: adler32.c ***/
  79912. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79913. #define ZLIB_INTERNAL
  79914. #define BASE 65521UL /* largest prime smaller than 65536 */
  79915. #define NMAX 5552
  79916. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79917. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79918. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79919. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79920. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79921. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79922. /* use NO_DIVIDE if your processor does not do division in hardware */
  79923. #ifdef NO_DIVIDE
  79924. # define MOD(a) \
  79925. do { \
  79926. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79927. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79928. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79929. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79930. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79931. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79932. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79933. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79934. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79935. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79936. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79937. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79938. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79939. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79940. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79941. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79942. if (a >= BASE) a -= BASE; \
  79943. } while (0)
  79944. # define MOD4(a) \
  79945. do { \
  79946. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79947. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79948. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79949. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79950. if (a >= BASE) a -= BASE; \
  79951. } while (0)
  79952. #else
  79953. # define MOD(a) a %= BASE
  79954. # define MOD4(a) a %= BASE
  79955. #endif
  79956. /* ========================================================================= */
  79957. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79958. {
  79959. unsigned long sum2;
  79960. unsigned n;
  79961. /* split Adler-32 into component sums */
  79962. sum2 = (adler >> 16) & 0xffff;
  79963. adler &= 0xffff;
  79964. /* in case user likes doing a byte at a time, keep it fast */
  79965. if (len == 1) {
  79966. adler += buf[0];
  79967. if (adler >= BASE)
  79968. adler -= BASE;
  79969. sum2 += adler;
  79970. if (sum2 >= BASE)
  79971. sum2 -= BASE;
  79972. return adler | (sum2 << 16);
  79973. }
  79974. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79975. if (buf == Z_NULL)
  79976. return 1L;
  79977. /* in case short lengths are provided, keep it somewhat fast */
  79978. if (len < 16) {
  79979. while (len--) {
  79980. adler += *buf++;
  79981. sum2 += adler;
  79982. }
  79983. if (adler >= BASE)
  79984. adler -= BASE;
  79985. MOD4(sum2); /* only added so many BASE's */
  79986. return adler | (sum2 << 16);
  79987. }
  79988. /* do length NMAX blocks -- requires just one modulo operation */
  79989. while (len >= NMAX) {
  79990. len -= NMAX;
  79991. n = NMAX / 16; /* NMAX is divisible by 16 */
  79992. do {
  79993. DO16(buf); /* 16 sums unrolled */
  79994. buf += 16;
  79995. } while (--n);
  79996. MOD(adler);
  79997. MOD(sum2);
  79998. }
  79999. /* do remaining bytes (less than NMAX, still just one modulo) */
  80000. if (len) { /* avoid modulos if none remaining */
  80001. while (len >= 16) {
  80002. len -= 16;
  80003. DO16(buf);
  80004. buf += 16;
  80005. }
  80006. while (len--) {
  80007. adler += *buf++;
  80008. sum2 += adler;
  80009. }
  80010. MOD(adler);
  80011. MOD(sum2);
  80012. }
  80013. /* return recombined sums */
  80014. return adler | (sum2 << 16);
  80015. }
  80016. /* ========================================================================= */
  80017. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  80018. {
  80019. unsigned long sum1;
  80020. unsigned long sum2;
  80021. unsigned rem;
  80022. /* the derivation of this formula is left as an exercise for the reader */
  80023. rem = (unsigned)(len2 % BASE);
  80024. sum1 = adler1 & 0xffff;
  80025. sum2 = rem * sum1;
  80026. MOD(sum2);
  80027. sum1 += (adler2 & 0xffff) + BASE - 1;
  80028. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  80029. if (sum1 > BASE) sum1 -= BASE;
  80030. if (sum1 > BASE) sum1 -= BASE;
  80031. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  80032. if (sum2 > BASE) sum2 -= BASE;
  80033. return sum1 | (sum2 << 16);
  80034. }
  80035. /*** End of inlined file: adler32.c ***/
  80036. /*** Start of inlined file: compress.c ***/
  80037. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80038. #define ZLIB_INTERNAL
  80039. /* ===========================================================================
  80040. Compresses the source buffer into the destination buffer. The level
  80041. parameter has the same meaning as in deflateInit. sourceLen is the byte
  80042. length of the source buffer. Upon entry, destLen is the total size of the
  80043. destination buffer, which must be at least 0.1% larger than sourceLen plus
  80044. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  80045. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  80046. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  80047. Z_STREAM_ERROR if the level parameter is invalid.
  80048. */
  80049. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  80050. uLong sourceLen, int level)
  80051. {
  80052. z_stream stream;
  80053. int err;
  80054. stream.next_in = (Bytef*)source;
  80055. stream.avail_in = (uInt)sourceLen;
  80056. #ifdef MAXSEG_64K
  80057. /* Check for source > 64K on 16-bit machine: */
  80058. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80059. #endif
  80060. stream.next_out = dest;
  80061. stream.avail_out = (uInt)*destLen;
  80062. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80063. stream.zalloc = (alloc_func)0;
  80064. stream.zfree = (free_func)0;
  80065. stream.opaque = (voidpf)0;
  80066. err = deflateInit(&stream, level);
  80067. if (err != Z_OK) return err;
  80068. err = deflate(&stream, Z_FINISH);
  80069. if (err != Z_STREAM_END) {
  80070. deflateEnd(&stream);
  80071. return err == Z_OK ? Z_BUF_ERROR : err;
  80072. }
  80073. *destLen = stream.total_out;
  80074. err = deflateEnd(&stream);
  80075. return err;
  80076. }
  80077. /* ===========================================================================
  80078. */
  80079. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80080. {
  80081. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80082. }
  80083. /* ===========================================================================
  80084. If the default memLevel or windowBits for deflateInit() is changed, then
  80085. this function needs to be updated.
  80086. */
  80087. uLong ZEXPORT compressBound (uLong sourceLen)
  80088. {
  80089. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80090. }
  80091. /*** End of inlined file: compress.c ***/
  80092. #undef DO1
  80093. #undef DO8
  80094. /*** Start of inlined file: crc32.c ***/
  80095. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80096. /*
  80097. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80098. protection on the static variables used to control the first-use generation
  80099. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80100. first call get_crc_table() to initialize the tables before allowing more than
  80101. one thread to use crc32().
  80102. */
  80103. #ifdef MAKECRCH
  80104. # include <stdio.h>
  80105. # ifndef DYNAMIC_CRC_TABLE
  80106. # define DYNAMIC_CRC_TABLE
  80107. # endif /* !DYNAMIC_CRC_TABLE */
  80108. #endif /* MAKECRCH */
  80109. /*** Start of inlined file: zutil.h ***/
  80110. /* WARNING: this file should *not* be used by applications. It is
  80111. part of the implementation of the compression library and is
  80112. subject to change. Applications should only use zlib.h.
  80113. */
  80114. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80115. #ifndef ZUTIL_H
  80116. #define ZUTIL_H
  80117. #define ZLIB_INTERNAL
  80118. #ifdef STDC
  80119. # ifndef _WIN32_WCE
  80120. # include <stddef.h>
  80121. # endif
  80122. # include <string.h>
  80123. # include <stdlib.h>
  80124. #endif
  80125. #ifdef NO_ERRNO_H
  80126. # ifdef _WIN32_WCE
  80127. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80128. * errno. We define it as a global variable to simplify porting.
  80129. * Its value is always 0 and should not be used. We rename it to
  80130. * avoid conflict with other libraries that use the same workaround.
  80131. */
  80132. # define errno z_errno
  80133. # endif
  80134. extern int errno;
  80135. #else
  80136. # ifndef _WIN32_WCE
  80137. # include <errno.h>
  80138. # endif
  80139. #endif
  80140. #ifndef local
  80141. # define local static
  80142. #endif
  80143. /* compile with -Dlocal if your debugger can't find static symbols */
  80144. typedef unsigned char uch;
  80145. typedef uch FAR uchf;
  80146. typedef unsigned short ush;
  80147. typedef ush FAR ushf;
  80148. typedef unsigned long ulg;
  80149. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80150. /* (size given to avoid silly warnings with Visual C++) */
  80151. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80152. #define ERR_RETURN(strm,err) \
  80153. return (strm->msg = (char*)ERR_MSG(err), (err))
  80154. /* To be used only when the state is known to be valid */
  80155. /* common constants */
  80156. #ifndef DEF_WBITS
  80157. # define DEF_WBITS MAX_WBITS
  80158. #endif
  80159. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80160. #if MAX_MEM_LEVEL >= 8
  80161. # define DEF_MEM_LEVEL 8
  80162. #else
  80163. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80164. #endif
  80165. /* default memLevel */
  80166. #define STORED_BLOCK 0
  80167. #define STATIC_TREES 1
  80168. #define DYN_TREES 2
  80169. /* The three kinds of block type */
  80170. #define MIN_MATCH 3
  80171. #define MAX_MATCH 258
  80172. /* The minimum and maximum match lengths */
  80173. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80174. /* target dependencies */
  80175. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80176. # define OS_CODE 0x00
  80177. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80178. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80179. /* Allow compilation with ANSI keywords only enabled */
  80180. void _Cdecl farfree( void *block );
  80181. void *_Cdecl farmalloc( unsigned long nbytes );
  80182. # else
  80183. # include <alloc.h>
  80184. # endif
  80185. # else /* MSC or DJGPP */
  80186. # include <malloc.h>
  80187. # endif
  80188. #endif
  80189. #ifdef AMIGA
  80190. # define OS_CODE 0x01
  80191. #endif
  80192. #if defined(VAXC) || defined(VMS)
  80193. # define OS_CODE 0x02
  80194. # define F_OPEN(name, mode) \
  80195. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80196. #endif
  80197. #if defined(ATARI) || defined(atarist)
  80198. # define OS_CODE 0x05
  80199. #endif
  80200. #ifdef OS2
  80201. # define OS_CODE 0x06
  80202. # ifdef M_I86
  80203. #include <malloc.h>
  80204. # endif
  80205. #endif
  80206. #if defined(MACOS) || TARGET_OS_MAC
  80207. # define OS_CODE 0x07
  80208. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80209. # include <unix.h> /* for fdopen */
  80210. # else
  80211. # ifndef fdopen
  80212. # define fdopen(fd,mode) NULL /* No fdopen() */
  80213. # endif
  80214. # endif
  80215. #endif
  80216. #ifdef TOPS20
  80217. # define OS_CODE 0x0a
  80218. #endif
  80219. #ifdef WIN32
  80220. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80221. # define OS_CODE 0x0b
  80222. # endif
  80223. #endif
  80224. #ifdef __50SERIES /* Prime/PRIMOS */
  80225. # define OS_CODE 0x0f
  80226. #endif
  80227. #if defined(_BEOS_) || defined(RISCOS)
  80228. # define fdopen(fd,mode) NULL /* No fdopen() */
  80229. #endif
  80230. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80231. # if defined(_WIN32_WCE)
  80232. # define fdopen(fd,mode) NULL /* No fdopen() */
  80233. # ifndef _PTRDIFF_T_DEFINED
  80234. typedef int ptrdiff_t;
  80235. # define _PTRDIFF_T_DEFINED
  80236. # endif
  80237. # else
  80238. # define fdopen(fd,type) _fdopen(fd,type)
  80239. # endif
  80240. #endif
  80241. /* common defaults */
  80242. #ifndef OS_CODE
  80243. # define OS_CODE 0x03 /* assume Unix */
  80244. #endif
  80245. #ifndef F_OPEN
  80246. # define F_OPEN(name, mode) fopen((name), (mode))
  80247. #endif
  80248. /* functions */
  80249. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80250. # ifndef HAVE_VSNPRINTF
  80251. # define HAVE_VSNPRINTF
  80252. # endif
  80253. #endif
  80254. #if defined(__CYGWIN__)
  80255. # ifndef HAVE_VSNPRINTF
  80256. # define HAVE_VSNPRINTF
  80257. # endif
  80258. #endif
  80259. #ifndef HAVE_VSNPRINTF
  80260. # ifdef MSDOS
  80261. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80262. but for now we just assume it doesn't. */
  80263. # define NO_vsnprintf
  80264. # endif
  80265. # ifdef __TURBOC__
  80266. # define NO_vsnprintf
  80267. # endif
  80268. # ifdef WIN32
  80269. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80270. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80271. # define vsnprintf _vsnprintf
  80272. # endif
  80273. # endif
  80274. # ifdef __SASC
  80275. # define NO_vsnprintf
  80276. # endif
  80277. #endif
  80278. #ifdef VMS
  80279. # define NO_vsnprintf
  80280. #endif
  80281. #if defined(pyr)
  80282. # define NO_MEMCPY
  80283. #endif
  80284. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80285. /* Use our own functions for small and medium model with MSC <= 5.0.
  80286. * You may have to use the same strategy for Borland C (untested).
  80287. * The __SC__ check is for Symantec.
  80288. */
  80289. # define NO_MEMCPY
  80290. #endif
  80291. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80292. # define HAVE_MEMCPY
  80293. #endif
  80294. #ifdef HAVE_MEMCPY
  80295. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80296. # define zmemcpy _fmemcpy
  80297. # define zmemcmp _fmemcmp
  80298. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80299. # else
  80300. # define zmemcpy memcpy
  80301. # define zmemcmp memcmp
  80302. # define zmemzero(dest, len) memset(dest, 0, len)
  80303. # endif
  80304. #else
  80305. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80306. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80307. extern void zmemzero OF((Bytef* dest, uInt len));
  80308. #endif
  80309. /* Diagnostic functions */
  80310. #ifdef DEBUG
  80311. # include <stdio.h>
  80312. extern int z_verbose;
  80313. extern void z_error OF((const char *m));
  80314. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80315. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80316. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80317. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80318. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80319. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80320. #else
  80321. # define Assert(cond,msg)
  80322. # define Trace(x)
  80323. # define Tracev(x)
  80324. # define Tracevv(x)
  80325. # define Tracec(c,x)
  80326. # define Tracecv(c,x)
  80327. #endif
  80328. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80329. void zcfree OF((voidpf opaque, voidpf ptr));
  80330. #define ZALLOC(strm, items, size) \
  80331. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80332. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80333. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80334. #endif /* ZUTIL_H */
  80335. /*** End of inlined file: zutil.h ***/
  80336. /* for STDC and FAR definitions */
  80337. #define local static
  80338. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80339. #ifndef NOBYFOUR
  80340. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80341. # include <limits.h>
  80342. # define BYFOUR
  80343. # if (UINT_MAX == 0xffffffffUL)
  80344. typedef unsigned int u4;
  80345. # else
  80346. # if (ULONG_MAX == 0xffffffffUL)
  80347. typedef unsigned long u4;
  80348. # else
  80349. # if (USHRT_MAX == 0xffffffffUL)
  80350. typedef unsigned short u4;
  80351. # else
  80352. # undef BYFOUR /* can't find a four-byte integer type! */
  80353. # endif
  80354. # endif
  80355. # endif
  80356. # endif /* STDC */
  80357. #endif /* !NOBYFOUR */
  80358. /* Definitions for doing the crc four data bytes at a time. */
  80359. #ifdef BYFOUR
  80360. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80361. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80362. local unsigned long crc32_little OF((unsigned long,
  80363. const unsigned char FAR *, unsigned));
  80364. local unsigned long crc32_big OF((unsigned long,
  80365. const unsigned char FAR *, unsigned));
  80366. # define TBLS 8
  80367. #else
  80368. # define TBLS 1
  80369. #endif /* BYFOUR */
  80370. /* Local functions for crc concatenation */
  80371. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80372. unsigned long vec));
  80373. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80374. #ifdef DYNAMIC_CRC_TABLE
  80375. local volatile int crc_table_empty = 1;
  80376. local unsigned long FAR crc_table[TBLS][256];
  80377. local void make_crc_table OF((void));
  80378. #ifdef MAKECRCH
  80379. local void write_table OF((FILE *, const unsigned long FAR *));
  80380. #endif /* MAKECRCH */
  80381. /*
  80382. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80383. 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.
  80384. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80385. with the lowest powers in the most significant bit. Then adding polynomials
  80386. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80387. one. If we call the above polynomial p, and represent a byte as the
  80388. polynomial q, also with the lowest power in the most significant bit (so the
  80389. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80390. where a mod b means the remainder after dividing a by b.
  80391. This calculation is done using the shift-register method of multiplying and
  80392. taking the remainder. The register is initialized to zero, and for each
  80393. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80394. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80395. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80396. out is a one). We start with the highest power (least significant bit) of
  80397. q and repeat for all eight bits of q.
  80398. The first table is simply the CRC of all possible eight bit values. This is
  80399. all the information needed to generate CRCs on data a byte at a time for all
  80400. combinations of CRC register values and incoming bytes. The remaining tables
  80401. allow for word-at-a-time CRC calculation for both big-endian and little-
  80402. endian machines, where a word is four bytes.
  80403. */
  80404. local void make_crc_table()
  80405. {
  80406. unsigned long c;
  80407. int n, k;
  80408. unsigned long poly; /* polynomial exclusive-or pattern */
  80409. /* terms of polynomial defining this crc (except x^32): */
  80410. static volatile int first = 1; /* flag to limit concurrent making */
  80411. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80412. /* See if another task is already doing this (not thread-safe, but better
  80413. than nothing -- significantly reduces duration of vulnerability in
  80414. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80415. if (first) {
  80416. first = 0;
  80417. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80418. poly = 0UL;
  80419. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80420. poly |= 1UL << (31 - p[n]);
  80421. /* generate a crc for every 8-bit value */
  80422. for (n = 0; n < 256; n++) {
  80423. c = (unsigned long)n;
  80424. for (k = 0; k < 8; k++)
  80425. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80426. crc_table[0][n] = c;
  80427. }
  80428. #ifdef BYFOUR
  80429. /* generate crc for each value followed by one, two, and three zeros,
  80430. and then the byte reversal of those as well as the first table */
  80431. for (n = 0; n < 256; n++) {
  80432. c = crc_table[0][n];
  80433. crc_table[4][n] = REV(c);
  80434. for (k = 1; k < 4; k++) {
  80435. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80436. crc_table[k][n] = c;
  80437. crc_table[k + 4][n] = REV(c);
  80438. }
  80439. }
  80440. #endif /* BYFOUR */
  80441. crc_table_empty = 0;
  80442. }
  80443. else { /* not first */
  80444. /* wait for the other guy to finish (not efficient, but rare) */
  80445. while (crc_table_empty)
  80446. ;
  80447. }
  80448. #ifdef MAKECRCH
  80449. /* write out CRC tables to crc32.h */
  80450. {
  80451. FILE *out;
  80452. out = fopen("crc32.h", "w");
  80453. if (out == NULL) return;
  80454. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80455. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80456. fprintf(out, "local const unsigned long FAR ");
  80457. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80458. write_table(out, crc_table[0]);
  80459. # ifdef BYFOUR
  80460. fprintf(out, "#ifdef BYFOUR\n");
  80461. for (k = 1; k < 8; k++) {
  80462. fprintf(out, " },\n {\n");
  80463. write_table(out, crc_table[k]);
  80464. }
  80465. fprintf(out, "#endif\n");
  80466. # endif /* BYFOUR */
  80467. fprintf(out, " }\n};\n");
  80468. fclose(out);
  80469. }
  80470. #endif /* MAKECRCH */
  80471. }
  80472. #ifdef MAKECRCH
  80473. local void write_table(out, table)
  80474. FILE *out;
  80475. const unsigned long FAR *table;
  80476. {
  80477. int n;
  80478. for (n = 0; n < 256; n++)
  80479. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80480. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80481. }
  80482. #endif /* MAKECRCH */
  80483. #else /* !DYNAMIC_CRC_TABLE */
  80484. /* ========================================================================
  80485. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80486. */
  80487. /*** Start of inlined file: crc32.h ***/
  80488. local const unsigned long FAR crc_table[TBLS][256] =
  80489. {
  80490. {
  80491. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80492. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80493. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80494. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80495. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80496. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80497. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80498. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80499. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80500. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80501. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80502. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80503. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80504. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80505. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80506. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80507. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80508. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80509. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80510. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80511. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80512. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80513. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80514. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80515. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80516. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80517. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80518. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80519. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80520. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80521. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80522. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80523. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80524. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80525. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80526. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80527. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80528. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80529. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80530. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80531. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80532. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80533. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80534. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80535. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80536. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80537. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80538. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80539. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80540. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80541. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80542. 0x2d02ef8dUL
  80543. #ifdef BYFOUR
  80544. },
  80545. {
  80546. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80547. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80548. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80549. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80550. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80551. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80552. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80553. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80554. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80555. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80556. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80557. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80558. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80559. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80560. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80561. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80562. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80563. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80564. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80565. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80566. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80567. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80568. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80569. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80570. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80571. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80572. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80573. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80574. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80575. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80576. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80577. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80578. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80579. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80580. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80581. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80582. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80583. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80584. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80585. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80586. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80587. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80588. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80589. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80590. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80591. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80592. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80593. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80594. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80595. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80596. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80597. 0x9324fd72UL
  80598. },
  80599. {
  80600. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80601. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80602. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80603. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80604. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80605. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80606. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80607. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80608. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80609. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80610. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80611. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80612. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80613. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80614. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80615. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80616. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80617. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80618. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80619. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80620. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80621. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80622. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80623. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80624. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80625. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80626. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80627. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80628. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80629. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80630. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80631. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80632. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80633. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80634. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80635. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80636. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80637. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80638. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80639. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80640. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80641. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80642. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80643. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80644. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80645. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80646. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80647. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80648. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80649. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80650. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80651. 0xbe9834edUL
  80652. },
  80653. {
  80654. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80655. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80656. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80657. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80658. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80659. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80660. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80661. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80662. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80663. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80664. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80665. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80666. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80667. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80668. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80669. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80670. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80671. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80672. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80673. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80674. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80675. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80676. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80677. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80678. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80679. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80680. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80681. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80682. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80683. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80684. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80685. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80686. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80687. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80688. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80689. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80690. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80691. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80692. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80693. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80694. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80695. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80696. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80697. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80698. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80699. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80700. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80701. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80702. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80703. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80704. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80705. 0xde0506f1UL
  80706. },
  80707. {
  80708. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80709. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80710. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80711. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80712. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80713. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80714. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80715. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80716. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80717. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80718. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80719. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80720. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80721. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80722. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80723. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80724. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80725. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80726. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80727. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80728. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80729. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80730. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80731. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80732. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80733. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80734. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80735. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80736. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80737. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80738. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80739. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80740. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80741. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80742. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80743. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80744. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80745. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80746. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80747. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80748. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80749. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80750. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80751. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80752. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80753. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80754. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80755. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80756. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80757. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80758. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80759. 0x8def022dUL
  80760. },
  80761. {
  80762. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80763. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80764. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80765. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80766. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80767. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80768. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80769. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80770. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80771. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80772. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80773. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80774. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80775. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80776. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80777. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80778. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80779. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80780. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80781. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80782. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80783. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80784. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80785. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80786. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80787. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80788. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80789. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80790. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80791. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80792. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80793. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80794. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80795. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80796. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80797. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80798. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80799. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80800. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80801. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80802. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80803. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80804. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80805. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80806. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80807. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80808. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80809. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80810. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80811. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80812. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80813. 0x72fd2493UL
  80814. },
  80815. {
  80816. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80817. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80818. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80819. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80820. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80821. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80822. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80823. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80824. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80825. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80826. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80827. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80828. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80829. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80830. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80831. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80832. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80833. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80834. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80835. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80836. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80837. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80838. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80839. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80840. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80841. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80842. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80843. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80844. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80845. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80846. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80847. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80848. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80849. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80850. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80851. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80852. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80853. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80854. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80855. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80856. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80857. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80858. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80859. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80860. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80861. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80862. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80863. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80864. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80865. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80866. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80867. 0xed3498beUL
  80868. },
  80869. {
  80870. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80871. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80872. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80873. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80874. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80875. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80876. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80877. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80878. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80879. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80880. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80881. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80882. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80883. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80884. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80885. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80886. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80887. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80888. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80889. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80890. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80891. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80892. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80893. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80894. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80895. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80896. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80897. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80898. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80899. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80900. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80901. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80902. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80903. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80904. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80905. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80906. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80907. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80908. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80909. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80910. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80911. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80912. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80913. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80914. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80915. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80916. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80917. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80918. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80919. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80920. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80921. 0xf10605deUL
  80922. #endif
  80923. }
  80924. };
  80925. /*** End of inlined file: crc32.h ***/
  80926. #endif /* DYNAMIC_CRC_TABLE */
  80927. /* =========================================================================
  80928. * This function can be used by asm versions of crc32()
  80929. */
  80930. const unsigned long FAR * ZEXPORT get_crc_table()
  80931. {
  80932. #ifdef DYNAMIC_CRC_TABLE
  80933. if (crc_table_empty)
  80934. make_crc_table();
  80935. #endif /* DYNAMIC_CRC_TABLE */
  80936. return (const unsigned long FAR *)crc_table;
  80937. }
  80938. /* ========================================================================= */
  80939. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80940. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80941. /* ========================================================================= */
  80942. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80943. {
  80944. if (buf == Z_NULL) return 0UL;
  80945. #ifdef DYNAMIC_CRC_TABLE
  80946. if (crc_table_empty)
  80947. make_crc_table();
  80948. #endif /* DYNAMIC_CRC_TABLE */
  80949. #ifdef BYFOUR
  80950. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80951. u4 endian;
  80952. endian = 1;
  80953. if (*((unsigned char *)(&endian)))
  80954. return crc32_little(crc, buf, len);
  80955. else
  80956. return crc32_big(crc, buf, len);
  80957. }
  80958. #endif /* BYFOUR */
  80959. crc = crc ^ 0xffffffffUL;
  80960. while (len >= 8) {
  80961. DO8;
  80962. len -= 8;
  80963. }
  80964. if (len) do {
  80965. DO1;
  80966. } while (--len);
  80967. return crc ^ 0xffffffffUL;
  80968. }
  80969. #ifdef BYFOUR
  80970. /* ========================================================================= */
  80971. #define DOLIT4 c ^= *buf4++; \
  80972. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80973. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80974. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80975. /* ========================================================================= */
  80976. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80977. {
  80978. register u4 c;
  80979. register const u4 FAR *buf4;
  80980. c = (u4)crc;
  80981. c = ~c;
  80982. while (len && ((ptrdiff_t)buf & 3)) {
  80983. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80984. len--;
  80985. }
  80986. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80987. while (len >= 32) {
  80988. DOLIT32;
  80989. len -= 32;
  80990. }
  80991. while (len >= 4) {
  80992. DOLIT4;
  80993. len -= 4;
  80994. }
  80995. buf = (const unsigned char FAR *)buf4;
  80996. if (len) do {
  80997. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80998. } while (--len);
  80999. c = ~c;
  81000. return (unsigned long)c;
  81001. }
  81002. /* ========================================================================= */
  81003. #define DOBIG4 c ^= *++buf4; \
  81004. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  81005. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  81006. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  81007. /* ========================================================================= */
  81008. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  81009. {
  81010. register u4 c;
  81011. register const u4 FAR *buf4;
  81012. c = REV((u4)crc);
  81013. c = ~c;
  81014. while (len && ((ptrdiff_t)buf & 3)) {
  81015. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81016. len--;
  81017. }
  81018. buf4 = (const u4 FAR *)(const void FAR *)buf;
  81019. buf4--;
  81020. while (len >= 32) {
  81021. DOBIG32;
  81022. len -= 32;
  81023. }
  81024. while (len >= 4) {
  81025. DOBIG4;
  81026. len -= 4;
  81027. }
  81028. buf4++;
  81029. buf = (const unsigned char FAR *)buf4;
  81030. if (len) do {
  81031. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81032. } while (--len);
  81033. c = ~c;
  81034. return (unsigned long)(REV(c));
  81035. }
  81036. #endif /* BYFOUR */
  81037. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  81038. /* ========================================================================= */
  81039. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  81040. {
  81041. unsigned long sum;
  81042. sum = 0;
  81043. while (vec) {
  81044. if (vec & 1)
  81045. sum ^= *mat;
  81046. vec >>= 1;
  81047. mat++;
  81048. }
  81049. return sum;
  81050. }
  81051. /* ========================================================================= */
  81052. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  81053. {
  81054. int n;
  81055. for (n = 0; n < GF2_DIM; n++)
  81056. square[n] = gf2_matrix_times(mat, mat[n]);
  81057. }
  81058. /* ========================================================================= */
  81059. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  81060. {
  81061. int n;
  81062. unsigned long row;
  81063. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81064. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81065. /* degenerate case */
  81066. if (len2 == 0)
  81067. return crc1;
  81068. /* put operator for one zero bit in odd */
  81069. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81070. row = 1;
  81071. for (n = 1; n < GF2_DIM; n++) {
  81072. odd[n] = row;
  81073. row <<= 1;
  81074. }
  81075. /* put operator for two zero bits in even */
  81076. gf2_matrix_square(even, odd);
  81077. /* put operator for four zero bits in odd */
  81078. gf2_matrix_square(odd, even);
  81079. /* apply len2 zeros to crc1 (first square will put the operator for one
  81080. zero byte, eight zero bits, in even) */
  81081. do {
  81082. /* apply zeros operator for this bit of len2 */
  81083. gf2_matrix_square(even, odd);
  81084. if (len2 & 1)
  81085. crc1 = gf2_matrix_times(even, crc1);
  81086. len2 >>= 1;
  81087. /* if no more bits set, then done */
  81088. if (len2 == 0)
  81089. break;
  81090. /* another iteration of the loop with odd and even swapped */
  81091. gf2_matrix_square(odd, even);
  81092. if (len2 & 1)
  81093. crc1 = gf2_matrix_times(odd, crc1);
  81094. len2 >>= 1;
  81095. /* if no more bits set, then done */
  81096. } while (len2 != 0);
  81097. /* return combined crc */
  81098. crc1 ^= crc2;
  81099. return crc1;
  81100. }
  81101. /*** End of inlined file: crc32.c ***/
  81102. /*** Start of inlined file: deflate.c ***/
  81103. /*
  81104. * ALGORITHM
  81105. *
  81106. * The "deflation" process depends on being able to identify portions
  81107. * of the input text which are identical to earlier input (within a
  81108. * sliding window trailing behind the input currently being processed).
  81109. *
  81110. * The most straightforward technique turns out to be the fastest for
  81111. * most input files: try all possible matches and select the longest.
  81112. * The key feature of this algorithm is that insertions into the string
  81113. * dictionary are very simple and thus fast, and deletions are avoided
  81114. * completely. Insertions are performed at each input character, whereas
  81115. * string matches are performed only when the previous match ends. So it
  81116. * is preferable to spend more time in matches to allow very fast string
  81117. * insertions and avoid deletions. The matching algorithm for small
  81118. * strings is inspired from that of Rabin & Karp. A brute force approach
  81119. * is used to find longer strings when a small match has been found.
  81120. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81121. * (by Leonid Broukhis).
  81122. * A previous version of this file used a more sophisticated algorithm
  81123. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81124. * time, but has a larger average cost, uses more memory and is patented.
  81125. * However the F&G algorithm may be faster for some highly redundant
  81126. * files if the parameter max_chain_length (described below) is too large.
  81127. *
  81128. * ACKNOWLEDGEMENTS
  81129. *
  81130. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81131. * I found it in 'freeze' written by Leonid Broukhis.
  81132. * Thanks to many people for bug reports and testing.
  81133. *
  81134. * REFERENCES
  81135. *
  81136. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81137. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81138. *
  81139. * A description of the Rabin and Karp algorithm is given in the book
  81140. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81141. *
  81142. * Fiala,E.R., and Greene,D.H.
  81143. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81144. *
  81145. */
  81146. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81147. /*** Start of inlined file: deflate.h ***/
  81148. /* WARNING: this file should *not* be used by applications. It is
  81149. part of the implementation of the compression library and is
  81150. subject to change. Applications should only use zlib.h.
  81151. */
  81152. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81153. #ifndef DEFLATE_H
  81154. #define DEFLATE_H
  81155. /* define NO_GZIP when compiling if you want to disable gzip header and
  81156. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81157. the crc code when it is not needed. For shared libraries, gzip encoding
  81158. should be left enabled. */
  81159. #ifndef NO_GZIP
  81160. # define GZIP
  81161. #endif
  81162. #define NO_DUMMY_DECL
  81163. /* ===========================================================================
  81164. * Internal compression state.
  81165. */
  81166. #define LENGTH_CODES 29
  81167. /* number of length codes, not counting the special END_BLOCK code */
  81168. #define LITERALS 256
  81169. /* number of literal bytes 0..255 */
  81170. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81171. /* number of Literal or Length codes, including the END_BLOCK code */
  81172. #define D_CODES 30
  81173. /* number of distance codes */
  81174. #define BL_CODES 19
  81175. /* number of codes used to transfer the bit lengths */
  81176. #define HEAP_SIZE (2*L_CODES+1)
  81177. /* maximum heap size */
  81178. #define MAX_BITS 15
  81179. /* All codes must not exceed MAX_BITS bits */
  81180. #define INIT_STATE 42
  81181. #define EXTRA_STATE 69
  81182. #define NAME_STATE 73
  81183. #define COMMENT_STATE 91
  81184. #define HCRC_STATE 103
  81185. #define BUSY_STATE 113
  81186. #define FINISH_STATE 666
  81187. /* Stream status */
  81188. /* Data structure describing a single value and its code string. */
  81189. typedef struct ct_data_s {
  81190. union {
  81191. ush freq; /* frequency count */
  81192. ush code; /* bit string */
  81193. } fc;
  81194. union {
  81195. ush dad; /* father node in Huffman tree */
  81196. ush len; /* length of bit string */
  81197. } dl;
  81198. } FAR ct_data;
  81199. #define Freq fc.freq
  81200. #define Code fc.code
  81201. #define Dad dl.dad
  81202. #define Len dl.len
  81203. typedef struct static_tree_desc_s static_tree_desc;
  81204. typedef struct tree_desc_s {
  81205. ct_data *dyn_tree; /* the dynamic tree */
  81206. int max_code; /* largest code with non zero frequency */
  81207. static_tree_desc *stat_desc; /* the corresponding static tree */
  81208. } FAR tree_desc;
  81209. typedef ush Pos;
  81210. typedef Pos FAR Posf;
  81211. typedef unsigned IPos;
  81212. /* A Pos is an index in the character window. We use short instead of int to
  81213. * save space in the various tables. IPos is used only for parameter passing.
  81214. */
  81215. typedef struct internal_state {
  81216. z_streamp strm; /* pointer back to this zlib stream */
  81217. int status; /* as the name implies */
  81218. Bytef *pending_buf; /* output still pending */
  81219. ulg pending_buf_size; /* size of pending_buf */
  81220. Bytef *pending_out; /* next pending byte to output to the stream */
  81221. uInt pending; /* nb of bytes in the pending buffer */
  81222. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81223. gz_headerp gzhead; /* gzip header information to write */
  81224. uInt gzindex; /* where in extra, name, or comment */
  81225. Byte method; /* STORED (for zip only) or DEFLATED */
  81226. int last_flush; /* value of flush param for previous deflate call */
  81227. /* used by deflate.c: */
  81228. uInt w_size; /* LZ77 window size (32K by default) */
  81229. uInt w_bits; /* log2(w_size) (8..16) */
  81230. uInt w_mask; /* w_size - 1 */
  81231. Bytef *window;
  81232. /* Sliding window. Input bytes are read into the second half of the window,
  81233. * and move to the first half later to keep a dictionary of at least wSize
  81234. * bytes. With this organization, matches are limited to a distance of
  81235. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81236. * performed with a length multiple of the block size. Also, it limits
  81237. * the window size to 64K, which is quite useful on MSDOS.
  81238. * To do: use the user input buffer as sliding window.
  81239. */
  81240. ulg window_size;
  81241. /* Actual size of window: 2*wSize, except when the user input buffer
  81242. * is directly used as sliding window.
  81243. */
  81244. Posf *prev;
  81245. /* Link to older string with same hash index. To limit the size of this
  81246. * array to 64K, this link is maintained only for the last 32K strings.
  81247. * An index in this array is thus a window index modulo 32K.
  81248. */
  81249. Posf *head; /* Heads of the hash chains or NIL. */
  81250. uInt ins_h; /* hash index of string to be inserted */
  81251. uInt hash_size; /* number of elements in hash table */
  81252. uInt hash_bits; /* log2(hash_size) */
  81253. uInt hash_mask; /* hash_size-1 */
  81254. uInt hash_shift;
  81255. /* Number of bits by which ins_h must be shifted at each input
  81256. * step. It must be such that after MIN_MATCH steps, the oldest
  81257. * byte no longer takes part in the hash key, that is:
  81258. * hash_shift * MIN_MATCH >= hash_bits
  81259. */
  81260. long block_start;
  81261. /* Window position at the beginning of the current output block. Gets
  81262. * negative when the window is moved backwards.
  81263. */
  81264. uInt match_length; /* length of best match */
  81265. IPos prev_match; /* previous match */
  81266. int match_available; /* set if previous match exists */
  81267. uInt strstart; /* start of string to insert */
  81268. uInt match_start; /* start of matching string */
  81269. uInt lookahead; /* number of valid bytes ahead in window */
  81270. uInt prev_length;
  81271. /* Length of the best match at previous step. Matches not greater than this
  81272. * are discarded. This is used in the lazy match evaluation.
  81273. */
  81274. uInt max_chain_length;
  81275. /* To speed up deflation, hash chains are never searched beyond this
  81276. * length. A higher limit improves compression ratio but degrades the
  81277. * speed.
  81278. */
  81279. uInt max_lazy_match;
  81280. /* Attempt to find a better match only when the current match is strictly
  81281. * smaller than this value. This mechanism is used only for compression
  81282. * levels >= 4.
  81283. */
  81284. # define max_insert_length max_lazy_match
  81285. /* Insert new strings in the hash table only if the match length is not
  81286. * greater than this length. This saves time but degrades compression.
  81287. * max_insert_length is used only for compression levels <= 3.
  81288. */
  81289. int level; /* compression level (1..9) */
  81290. int strategy; /* favor or force Huffman coding*/
  81291. uInt good_match;
  81292. /* Use a faster search when the previous match is longer than this */
  81293. int nice_match; /* Stop searching when current match exceeds this */
  81294. /* used by trees.c: */
  81295. /* Didn't use ct_data typedef below to supress compiler warning */
  81296. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81297. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81298. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81299. struct tree_desc_s l_desc; /* desc. for literal tree */
  81300. struct tree_desc_s d_desc; /* desc. for distance tree */
  81301. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81302. ush bl_count[MAX_BITS+1];
  81303. /* number of codes at each bit length for an optimal tree */
  81304. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81305. int heap_len; /* number of elements in the heap */
  81306. int heap_max; /* element of largest frequency */
  81307. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81308. * The same heap array is used to build all trees.
  81309. */
  81310. uch depth[2*L_CODES+1];
  81311. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81312. */
  81313. uchf *l_buf; /* buffer for literals or lengths */
  81314. uInt lit_bufsize;
  81315. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81316. * limiting lit_bufsize to 64K:
  81317. * - frequencies can be kept in 16 bit counters
  81318. * - if compression is not successful for the first block, all input
  81319. * data is still in the window so we can still emit a stored block even
  81320. * when input comes from standard input. (This can also be done for
  81321. * all blocks if lit_bufsize is not greater than 32K.)
  81322. * - if compression is not successful for a file smaller than 64K, we can
  81323. * even emit a stored file instead of a stored block (saving 5 bytes).
  81324. * This is applicable only for zip (not gzip or zlib).
  81325. * - creating new Huffman trees less frequently may not provide fast
  81326. * adaptation to changes in the input data statistics. (Take for
  81327. * example a binary file with poorly compressible code followed by
  81328. * a highly compressible string table.) Smaller buffer sizes give
  81329. * fast adaptation but have of course the overhead of transmitting
  81330. * trees more frequently.
  81331. * - I can't count above 4
  81332. */
  81333. uInt last_lit; /* running index in l_buf */
  81334. ushf *d_buf;
  81335. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81336. * the same number of elements. To use different lengths, an extra flag
  81337. * array would be necessary.
  81338. */
  81339. ulg opt_len; /* bit length of current block with optimal trees */
  81340. ulg static_len; /* bit length of current block with static trees */
  81341. uInt matches; /* number of string matches in current block */
  81342. int last_eob_len; /* bit length of EOB code for last block */
  81343. #ifdef DEBUG
  81344. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81345. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81346. #endif
  81347. ush bi_buf;
  81348. /* Output buffer. bits are inserted starting at the bottom (least
  81349. * significant bits).
  81350. */
  81351. int bi_valid;
  81352. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81353. * are always zero.
  81354. */
  81355. } FAR deflate_state;
  81356. /* Output a byte on the stream.
  81357. * IN assertion: there is enough room in pending_buf.
  81358. */
  81359. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81360. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81361. /* Minimum amount of lookahead, except at the end of the input file.
  81362. * See deflate.c for comments about the MIN_MATCH+1.
  81363. */
  81364. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81365. /* In order to simplify the code, particularly on 16 bit machines, match
  81366. * distances are limited to MAX_DIST instead of WSIZE.
  81367. */
  81368. /* in trees.c */
  81369. void _tr_init OF((deflate_state *s));
  81370. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81371. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81372. int eof));
  81373. void _tr_align OF((deflate_state *s));
  81374. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81375. int eof));
  81376. #define d_code(dist) \
  81377. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81378. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81379. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81380. * used.
  81381. */
  81382. #ifndef DEBUG
  81383. /* Inline versions of _tr_tally for speed: */
  81384. #if defined(GEN_TREES_H) || !defined(STDC)
  81385. extern uch _length_code[];
  81386. extern uch _dist_code[];
  81387. #else
  81388. extern const uch _length_code[];
  81389. extern const uch _dist_code[];
  81390. #endif
  81391. # define _tr_tally_lit(s, c, flush) \
  81392. { uch cc = (c); \
  81393. s->d_buf[s->last_lit] = 0; \
  81394. s->l_buf[s->last_lit++] = cc; \
  81395. s->dyn_ltree[cc].Freq++; \
  81396. flush = (s->last_lit == s->lit_bufsize-1); \
  81397. }
  81398. # define _tr_tally_dist(s, distance, length, flush) \
  81399. { uch len = (length); \
  81400. ush dist = (distance); \
  81401. s->d_buf[s->last_lit] = dist; \
  81402. s->l_buf[s->last_lit++] = len; \
  81403. dist--; \
  81404. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81405. s->dyn_dtree[d_code(dist)].Freq++; \
  81406. flush = (s->last_lit == s->lit_bufsize-1); \
  81407. }
  81408. #else
  81409. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81410. # define _tr_tally_dist(s, distance, length, flush) \
  81411. flush = _tr_tally(s, distance, length)
  81412. #endif
  81413. #endif /* DEFLATE_H */
  81414. /*** End of inlined file: deflate.h ***/
  81415. const char deflate_copyright[] =
  81416. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81417. /*
  81418. If you use the zlib library in a product, an acknowledgment is welcome
  81419. in the documentation of your product. If for some reason you cannot
  81420. include such an acknowledgment, I would appreciate that you keep this
  81421. copyright string in the executable of your product.
  81422. */
  81423. /* ===========================================================================
  81424. * Function prototypes.
  81425. */
  81426. typedef enum {
  81427. need_more, /* block not completed, need more input or more output */
  81428. block_done, /* block flush performed */
  81429. finish_started, /* finish started, need only more output at next deflate */
  81430. finish_done /* finish done, accept no more input or output */
  81431. } block_state;
  81432. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81433. /* Compression function. Returns the block state after the call. */
  81434. local void fill_window OF((deflate_state *s));
  81435. local block_state deflate_stored OF((deflate_state *s, int flush));
  81436. local block_state deflate_fast OF((deflate_state *s, int flush));
  81437. #ifndef FASTEST
  81438. local block_state deflate_slow OF((deflate_state *s, int flush));
  81439. #endif
  81440. local void lm_init OF((deflate_state *s));
  81441. local void putShortMSB OF((deflate_state *s, uInt b));
  81442. local void flush_pending OF((z_streamp strm));
  81443. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81444. #ifndef FASTEST
  81445. #ifdef ASMV
  81446. void match_init OF((void)); /* asm code initialization */
  81447. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81448. #else
  81449. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81450. #endif
  81451. #endif
  81452. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81453. #ifdef DEBUG
  81454. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81455. int length));
  81456. #endif
  81457. /* ===========================================================================
  81458. * Local data
  81459. */
  81460. #define NIL 0
  81461. /* Tail of hash chains */
  81462. #ifndef TOO_FAR
  81463. # define TOO_FAR 4096
  81464. #endif
  81465. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81466. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81467. /* Minimum amount of lookahead, except at the end of the input file.
  81468. * See deflate.c for comments about the MIN_MATCH+1.
  81469. */
  81470. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81471. * the desired pack level (0..9). The values given below have been tuned to
  81472. * exclude worst case performance for pathological files. Better values may be
  81473. * found for specific files.
  81474. */
  81475. typedef struct config_s {
  81476. ush good_length; /* reduce lazy search above this match length */
  81477. ush max_lazy; /* do not perform lazy search above this match length */
  81478. ush nice_length; /* quit search above this match length */
  81479. ush max_chain;
  81480. compress_func func;
  81481. } config;
  81482. #ifdef FASTEST
  81483. local const config configuration_table[2] = {
  81484. /* good lazy nice chain */
  81485. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81486. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81487. #else
  81488. local const config configuration_table[10] = {
  81489. /* good lazy nice chain */
  81490. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81491. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81492. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81493. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81494. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81495. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81496. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81497. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81498. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81499. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81500. #endif
  81501. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81502. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81503. * meaning.
  81504. */
  81505. #define EQUAL 0
  81506. /* result of memcmp for equal strings */
  81507. #ifndef NO_DUMMY_DECL
  81508. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81509. #endif
  81510. /* ===========================================================================
  81511. * Update a hash value with the given input byte
  81512. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81513. * input characters, so that a running hash key can be computed from the
  81514. * previous key instead of complete recalculation each time.
  81515. */
  81516. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81517. /* ===========================================================================
  81518. * Insert string str in the dictionary and set match_head to the previous head
  81519. * of the hash chain (the most recent string with same hash key). Return
  81520. * the previous length of the hash chain.
  81521. * If this file is compiled with -DFASTEST, the compression level is forced
  81522. * to 1, and no hash chains are maintained.
  81523. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81524. * input characters and the first MIN_MATCH bytes of str are valid
  81525. * (except for the last MIN_MATCH-1 bytes of the input file).
  81526. */
  81527. #ifdef FASTEST
  81528. #define INSERT_STRING(s, str, match_head) \
  81529. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81530. match_head = s->head[s->ins_h], \
  81531. s->head[s->ins_h] = (Pos)(str))
  81532. #else
  81533. #define INSERT_STRING(s, str, match_head) \
  81534. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81535. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81536. s->head[s->ins_h] = (Pos)(str))
  81537. #endif
  81538. /* ===========================================================================
  81539. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81540. * prev[] will be initialized on the fly.
  81541. */
  81542. #define CLEAR_HASH(s) \
  81543. s->head[s->hash_size-1] = NIL; \
  81544. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81545. /* ========================================================================= */
  81546. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81547. {
  81548. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81549. Z_DEFAULT_STRATEGY, version, stream_size);
  81550. /* To do: ignore strm->next_in if we use it as window */
  81551. }
  81552. /* ========================================================================= */
  81553. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81554. {
  81555. deflate_state *s;
  81556. int wrap = 1;
  81557. static const char my_version[] = ZLIB_VERSION;
  81558. ushf *overlay;
  81559. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81560. * output size for (length,distance) codes is <= 24 bits.
  81561. */
  81562. if (version == Z_NULL || version[0] != my_version[0] ||
  81563. stream_size != sizeof(z_stream)) {
  81564. return Z_VERSION_ERROR;
  81565. }
  81566. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81567. strm->msg = Z_NULL;
  81568. if (strm->zalloc == (alloc_func)0) {
  81569. strm->zalloc = zcalloc;
  81570. strm->opaque = (voidpf)0;
  81571. }
  81572. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81573. #ifdef FASTEST
  81574. if (level != 0) level = 1;
  81575. #else
  81576. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81577. #endif
  81578. if (windowBits < 0) { /* suppress zlib wrapper */
  81579. wrap = 0;
  81580. windowBits = -windowBits;
  81581. }
  81582. #ifdef GZIP
  81583. else if (windowBits > 15) {
  81584. wrap = 2; /* write gzip wrapper instead */
  81585. windowBits -= 16;
  81586. }
  81587. #endif
  81588. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81589. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81590. strategy < 0 || strategy > Z_FIXED) {
  81591. return Z_STREAM_ERROR;
  81592. }
  81593. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81594. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81595. if (s == Z_NULL) return Z_MEM_ERROR;
  81596. strm->state = (struct internal_state FAR *)s;
  81597. s->strm = strm;
  81598. s->wrap = wrap;
  81599. s->gzhead = Z_NULL;
  81600. s->w_bits = windowBits;
  81601. s->w_size = 1 << s->w_bits;
  81602. s->w_mask = s->w_size - 1;
  81603. s->hash_bits = memLevel + 7;
  81604. s->hash_size = 1 << s->hash_bits;
  81605. s->hash_mask = s->hash_size - 1;
  81606. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81607. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81608. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81609. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81610. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81611. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81612. s->pending_buf = (uchf *) overlay;
  81613. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81614. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81615. s->pending_buf == Z_NULL) {
  81616. s->status = FINISH_STATE;
  81617. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81618. deflateEnd (strm);
  81619. return Z_MEM_ERROR;
  81620. }
  81621. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81622. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81623. s->level = level;
  81624. s->strategy = strategy;
  81625. s->method = (Byte)method;
  81626. return deflateReset(strm);
  81627. }
  81628. /* ========================================================================= */
  81629. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81630. {
  81631. deflate_state *s;
  81632. uInt length = dictLength;
  81633. uInt n;
  81634. IPos hash_head = 0;
  81635. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81636. strm->state->wrap == 2 ||
  81637. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81638. return Z_STREAM_ERROR;
  81639. s = strm->state;
  81640. if (s->wrap)
  81641. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81642. if (length < MIN_MATCH) return Z_OK;
  81643. if (length > MAX_DIST(s)) {
  81644. length = MAX_DIST(s);
  81645. dictionary += dictLength - length; /* use the tail of the dictionary */
  81646. }
  81647. zmemcpy(s->window, dictionary, length);
  81648. s->strstart = length;
  81649. s->block_start = (long)length;
  81650. /* Insert all strings in the hash table (except for the last two bytes).
  81651. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81652. * call of fill_window.
  81653. */
  81654. s->ins_h = s->window[0];
  81655. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81656. for (n = 0; n <= length - MIN_MATCH; n++) {
  81657. INSERT_STRING(s, n, hash_head);
  81658. }
  81659. if (hash_head) hash_head = 0; /* to make compiler happy */
  81660. return Z_OK;
  81661. }
  81662. /* ========================================================================= */
  81663. int ZEXPORT deflateReset (z_streamp strm)
  81664. {
  81665. deflate_state *s;
  81666. if (strm == Z_NULL || strm->state == Z_NULL ||
  81667. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81668. return Z_STREAM_ERROR;
  81669. }
  81670. strm->total_in = strm->total_out = 0;
  81671. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81672. strm->data_type = Z_UNKNOWN;
  81673. s = (deflate_state *)strm->state;
  81674. s->pending = 0;
  81675. s->pending_out = s->pending_buf;
  81676. if (s->wrap < 0) {
  81677. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81678. }
  81679. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81680. strm->adler =
  81681. #ifdef GZIP
  81682. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81683. #endif
  81684. adler32(0L, Z_NULL, 0);
  81685. s->last_flush = Z_NO_FLUSH;
  81686. _tr_init(s);
  81687. lm_init(s);
  81688. return Z_OK;
  81689. }
  81690. /* ========================================================================= */
  81691. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81692. {
  81693. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81694. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81695. strm->state->gzhead = head;
  81696. return Z_OK;
  81697. }
  81698. /* ========================================================================= */
  81699. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81700. {
  81701. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81702. strm->state->bi_valid = bits;
  81703. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81704. return Z_OK;
  81705. }
  81706. /* ========================================================================= */
  81707. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81708. {
  81709. deflate_state *s;
  81710. compress_func func;
  81711. int err = Z_OK;
  81712. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81713. s = strm->state;
  81714. #ifdef FASTEST
  81715. if (level != 0) level = 1;
  81716. #else
  81717. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81718. #endif
  81719. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81720. return Z_STREAM_ERROR;
  81721. }
  81722. func = configuration_table[s->level].func;
  81723. if (func != configuration_table[level].func && strm->total_in != 0) {
  81724. /* Flush the last buffer: */
  81725. err = deflate(strm, Z_PARTIAL_FLUSH);
  81726. }
  81727. if (s->level != level) {
  81728. s->level = level;
  81729. s->max_lazy_match = configuration_table[level].max_lazy;
  81730. s->good_match = configuration_table[level].good_length;
  81731. s->nice_match = configuration_table[level].nice_length;
  81732. s->max_chain_length = configuration_table[level].max_chain;
  81733. }
  81734. s->strategy = strategy;
  81735. return err;
  81736. }
  81737. /* ========================================================================= */
  81738. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81739. {
  81740. deflate_state *s;
  81741. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81742. s = strm->state;
  81743. s->good_match = good_length;
  81744. s->max_lazy_match = max_lazy;
  81745. s->nice_match = nice_length;
  81746. s->max_chain_length = max_chain;
  81747. return Z_OK;
  81748. }
  81749. /* =========================================================================
  81750. * For the default windowBits of 15 and memLevel of 8, this function returns
  81751. * a close to exact, as well as small, upper bound on the compressed size.
  81752. * They are coded as constants here for a reason--if the #define's are
  81753. * changed, then this function needs to be changed as well. The return
  81754. * value for 15 and 8 only works for those exact settings.
  81755. *
  81756. * For any setting other than those defaults for windowBits and memLevel,
  81757. * the value returned is a conservative worst case for the maximum expansion
  81758. * resulting from using fixed blocks instead of stored blocks, which deflate
  81759. * can emit on compressed data for some combinations of the parameters.
  81760. *
  81761. * This function could be more sophisticated to provide closer upper bounds
  81762. * for every combination of windowBits and memLevel, as well as wrap.
  81763. * But even the conservative upper bound of about 14% expansion does not
  81764. * seem onerous for output buffer allocation.
  81765. */
  81766. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81767. {
  81768. deflate_state *s;
  81769. uLong destLen;
  81770. /* conservative upper bound */
  81771. destLen = sourceLen +
  81772. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81773. /* if can't get parameters, return conservative bound */
  81774. if (strm == Z_NULL || strm->state == Z_NULL)
  81775. return destLen;
  81776. /* if not default parameters, return conservative bound */
  81777. s = strm->state;
  81778. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81779. return destLen;
  81780. /* default settings: return tight bound for that case */
  81781. return compressBound(sourceLen);
  81782. }
  81783. /* =========================================================================
  81784. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81785. * IN assertion: the stream state is correct and there is enough room in
  81786. * pending_buf.
  81787. */
  81788. local void putShortMSB (deflate_state *s, uInt b)
  81789. {
  81790. put_byte(s, (Byte)(b >> 8));
  81791. put_byte(s, (Byte)(b & 0xff));
  81792. }
  81793. /* =========================================================================
  81794. * Flush as much pending output as possible. All deflate() output goes
  81795. * through this function so some applications may wish to modify it
  81796. * to avoid allocating a large strm->next_out buffer and copying into it.
  81797. * (See also read_buf()).
  81798. */
  81799. local void flush_pending (z_streamp strm)
  81800. {
  81801. unsigned len = strm->state->pending;
  81802. if (len > strm->avail_out) len = strm->avail_out;
  81803. if (len == 0) return;
  81804. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81805. strm->next_out += len;
  81806. strm->state->pending_out += len;
  81807. strm->total_out += len;
  81808. strm->avail_out -= len;
  81809. strm->state->pending -= len;
  81810. if (strm->state->pending == 0) {
  81811. strm->state->pending_out = strm->state->pending_buf;
  81812. }
  81813. }
  81814. /* ========================================================================= */
  81815. int ZEXPORT deflate (z_streamp strm, int flush)
  81816. {
  81817. int old_flush; /* value of flush param for previous deflate call */
  81818. deflate_state *s;
  81819. if (strm == Z_NULL || strm->state == Z_NULL ||
  81820. flush > Z_FINISH || flush < 0) {
  81821. return Z_STREAM_ERROR;
  81822. }
  81823. s = strm->state;
  81824. if (strm->next_out == Z_NULL ||
  81825. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81826. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81827. ERR_RETURN(strm, Z_STREAM_ERROR);
  81828. }
  81829. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81830. s->strm = strm; /* just in case */
  81831. old_flush = s->last_flush;
  81832. s->last_flush = flush;
  81833. /* Write the header */
  81834. if (s->status == INIT_STATE) {
  81835. #ifdef GZIP
  81836. if (s->wrap == 2) {
  81837. strm->adler = crc32(0L, Z_NULL, 0);
  81838. put_byte(s, 31);
  81839. put_byte(s, 139);
  81840. put_byte(s, 8);
  81841. if (s->gzhead == NULL) {
  81842. put_byte(s, 0);
  81843. put_byte(s, 0);
  81844. put_byte(s, 0);
  81845. put_byte(s, 0);
  81846. put_byte(s, 0);
  81847. put_byte(s, s->level == 9 ? 2 :
  81848. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81849. 4 : 0));
  81850. put_byte(s, OS_CODE);
  81851. s->status = BUSY_STATE;
  81852. }
  81853. else {
  81854. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81855. (s->gzhead->hcrc ? 2 : 0) +
  81856. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81857. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81858. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81859. );
  81860. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81861. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81862. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81863. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81864. put_byte(s, s->level == 9 ? 2 :
  81865. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81866. 4 : 0));
  81867. put_byte(s, s->gzhead->os & 0xff);
  81868. if (s->gzhead->extra != NULL) {
  81869. put_byte(s, s->gzhead->extra_len & 0xff);
  81870. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81871. }
  81872. if (s->gzhead->hcrc)
  81873. strm->adler = crc32(strm->adler, s->pending_buf,
  81874. s->pending);
  81875. s->gzindex = 0;
  81876. s->status = EXTRA_STATE;
  81877. }
  81878. }
  81879. else
  81880. #endif
  81881. {
  81882. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81883. uInt level_flags;
  81884. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81885. level_flags = 0;
  81886. else if (s->level < 6)
  81887. level_flags = 1;
  81888. else if (s->level == 6)
  81889. level_flags = 2;
  81890. else
  81891. level_flags = 3;
  81892. header |= (level_flags << 6);
  81893. if (s->strstart != 0) header |= PRESET_DICT;
  81894. header += 31 - (header % 31);
  81895. s->status = BUSY_STATE;
  81896. putShortMSB(s, header);
  81897. /* Save the adler32 of the preset dictionary: */
  81898. if (s->strstart != 0) {
  81899. putShortMSB(s, (uInt)(strm->adler >> 16));
  81900. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81901. }
  81902. strm->adler = adler32(0L, Z_NULL, 0);
  81903. }
  81904. }
  81905. #ifdef GZIP
  81906. if (s->status == EXTRA_STATE) {
  81907. if (s->gzhead->extra != NULL) {
  81908. uInt beg = s->pending; /* start of bytes to update crc */
  81909. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81910. if (s->pending == s->pending_buf_size) {
  81911. if (s->gzhead->hcrc && s->pending > beg)
  81912. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81913. s->pending - beg);
  81914. flush_pending(strm);
  81915. beg = s->pending;
  81916. if (s->pending == s->pending_buf_size)
  81917. break;
  81918. }
  81919. put_byte(s, s->gzhead->extra[s->gzindex]);
  81920. s->gzindex++;
  81921. }
  81922. if (s->gzhead->hcrc && s->pending > beg)
  81923. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81924. s->pending - beg);
  81925. if (s->gzindex == s->gzhead->extra_len) {
  81926. s->gzindex = 0;
  81927. s->status = NAME_STATE;
  81928. }
  81929. }
  81930. else
  81931. s->status = NAME_STATE;
  81932. }
  81933. if (s->status == NAME_STATE) {
  81934. if (s->gzhead->name != NULL) {
  81935. uInt beg = s->pending; /* start of bytes to update crc */
  81936. int val;
  81937. do {
  81938. if (s->pending == s->pending_buf_size) {
  81939. if (s->gzhead->hcrc && s->pending > beg)
  81940. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81941. s->pending - beg);
  81942. flush_pending(strm);
  81943. beg = s->pending;
  81944. if (s->pending == s->pending_buf_size) {
  81945. val = 1;
  81946. break;
  81947. }
  81948. }
  81949. val = s->gzhead->name[s->gzindex++];
  81950. put_byte(s, val);
  81951. } while (val != 0);
  81952. if (s->gzhead->hcrc && s->pending > beg)
  81953. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81954. s->pending - beg);
  81955. if (val == 0) {
  81956. s->gzindex = 0;
  81957. s->status = COMMENT_STATE;
  81958. }
  81959. }
  81960. else
  81961. s->status = COMMENT_STATE;
  81962. }
  81963. if (s->status == COMMENT_STATE) {
  81964. if (s->gzhead->comment != NULL) {
  81965. uInt beg = s->pending; /* start of bytes to update crc */
  81966. int val;
  81967. do {
  81968. if (s->pending == s->pending_buf_size) {
  81969. if (s->gzhead->hcrc && s->pending > beg)
  81970. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81971. s->pending - beg);
  81972. flush_pending(strm);
  81973. beg = s->pending;
  81974. if (s->pending == s->pending_buf_size) {
  81975. val = 1;
  81976. break;
  81977. }
  81978. }
  81979. val = s->gzhead->comment[s->gzindex++];
  81980. put_byte(s, val);
  81981. } while (val != 0);
  81982. if (s->gzhead->hcrc && s->pending > beg)
  81983. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81984. s->pending - beg);
  81985. if (val == 0)
  81986. s->status = HCRC_STATE;
  81987. }
  81988. else
  81989. s->status = HCRC_STATE;
  81990. }
  81991. if (s->status == HCRC_STATE) {
  81992. if (s->gzhead->hcrc) {
  81993. if (s->pending + 2 > s->pending_buf_size)
  81994. flush_pending(strm);
  81995. if (s->pending + 2 <= s->pending_buf_size) {
  81996. put_byte(s, (Byte)(strm->adler & 0xff));
  81997. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81998. strm->adler = crc32(0L, Z_NULL, 0);
  81999. s->status = BUSY_STATE;
  82000. }
  82001. }
  82002. else
  82003. s->status = BUSY_STATE;
  82004. }
  82005. #endif
  82006. /* Flush as much pending output as possible */
  82007. if (s->pending != 0) {
  82008. flush_pending(strm);
  82009. if (strm->avail_out == 0) {
  82010. /* Since avail_out is 0, deflate will be called again with
  82011. * more output space, but possibly with both pending and
  82012. * avail_in equal to zero. There won't be anything to do,
  82013. * but this is not an error situation so make sure we
  82014. * return OK instead of BUF_ERROR at next call of deflate:
  82015. */
  82016. s->last_flush = -1;
  82017. return Z_OK;
  82018. }
  82019. /* Make sure there is something to do and avoid duplicate consecutive
  82020. * flushes. For repeated and useless calls with Z_FINISH, we keep
  82021. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  82022. */
  82023. } else if (strm->avail_in == 0 && flush <= old_flush &&
  82024. flush != Z_FINISH) {
  82025. ERR_RETURN(strm, Z_BUF_ERROR);
  82026. }
  82027. /* User must not provide more input after the first FINISH: */
  82028. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  82029. ERR_RETURN(strm, Z_BUF_ERROR);
  82030. }
  82031. /* Start a new block or continue the current one.
  82032. */
  82033. if (strm->avail_in != 0 || s->lookahead != 0 ||
  82034. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  82035. block_state bstate;
  82036. bstate = (*(configuration_table[s->level].func))(s, flush);
  82037. if (bstate == finish_started || bstate == finish_done) {
  82038. s->status = FINISH_STATE;
  82039. }
  82040. if (bstate == need_more || bstate == finish_started) {
  82041. if (strm->avail_out == 0) {
  82042. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  82043. }
  82044. return Z_OK;
  82045. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  82046. * of deflate should use the same flush parameter to make sure
  82047. * that the flush is complete. So we don't have to output an
  82048. * empty block here, this will be done at next call. This also
  82049. * ensures that for a very small output buffer, we emit at most
  82050. * one empty block.
  82051. */
  82052. }
  82053. if (bstate == block_done) {
  82054. if (flush == Z_PARTIAL_FLUSH) {
  82055. _tr_align(s);
  82056. } else { /* FULL_FLUSH or SYNC_FLUSH */
  82057. _tr_stored_block(s, (char*)0, 0L, 0);
  82058. /* For a full flush, this empty block will be recognized
  82059. * as a special marker by inflate_sync().
  82060. */
  82061. if (flush == Z_FULL_FLUSH) {
  82062. CLEAR_HASH(s); /* forget history */
  82063. }
  82064. }
  82065. flush_pending(strm);
  82066. if (strm->avail_out == 0) {
  82067. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82068. return Z_OK;
  82069. }
  82070. }
  82071. }
  82072. Assert(strm->avail_out > 0, "bug2");
  82073. if (flush != Z_FINISH) return Z_OK;
  82074. if (s->wrap <= 0) return Z_STREAM_END;
  82075. /* Write the trailer */
  82076. #ifdef GZIP
  82077. if (s->wrap == 2) {
  82078. put_byte(s, (Byte)(strm->adler & 0xff));
  82079. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82080. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82081. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82082. put_byte(s, (Byte)(strm->total_in & 0xff));
  82083. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82084. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82085. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82086. }
  82087. else
  82088. #endif
  82089. {
  82090. putShortMSB(s, (uInt)(strm->adler >> 16));
  82091. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82092. }
  82093. flush_pending(strm);
  82094. /* If avail_out is zero, the application will call deflate again
  82095. * to flush the rest.
  82096. */
  82097. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82098. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82099. }
  82100. /* ========================================================================= */
  82101. int ZEXPORT deflateEnd (z_streamp strm)
  82102. {
  82103. int status;
  82104. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82105. status = strm->state->status;
  82106. if (status != INIT_STATE &&
  82107. status != EXTRA_STATE &&
  82108. status != NAME_STATE &&
  82109. status != COMMENT_STATE &&
  82110. status != HCRC_STATE &&
  82111. status != BUSY_STATE &&
  82112. status != FINISH_STATE) {
  82113. return Z_STREAM_ERROR;
  82114. }
  82115. /* Deallocate in reverse order of allocations: */
  82116. TRY_FREE(strm, strm->state->pending_buf);
  82117. TRY_FREE(strm, strm->state->head);
  82118. TRY_FREE(strm, strm->state->prev);
  82119. TRY_FREE(strm, strm->state->window);
  82120. ZFREE(strm, strm->state);
  82121. strm->state = Z_NULL;
  82122. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82123. }
  82124. /* =========================================================================
  82125. * Copy the source state to the destination state.
  82126. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82127. * doesn't have enough memory anyway to duplicate compression states).
  82128. */
  82129. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82130. {
  82131. #ifdef MAXSEG_64K
  82132. return Z_STREAM_ERROR;
  82133. #else
  82134. deflate_state *ds;
  82135. deflate_state *ss;
  82136. ushf *overlay;
  82137. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82138. return Z_STREAM_ERROR;
  82139. }
  82140. ss = source->state;
  82141. zmemcpy(dest, source, sizeof(z_stream));
  82142. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82143. if (ds == Z_NULL) return Z_MEM_ERROR;
  82144. dest->state = (struct internal_state FAR *) ds;
  82145. zmemcpy(ds, ss, sizeof(deflate_state));
  82146. ds->strm = dest;
  82147. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82148. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82149. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82150. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82151. ds->pending_buf = (uchf *) overlay;
  82152. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82153. ds->pending_buf == Z_NULL) {
  82154. deflateEnd (dest);
  82155. return Z_MEM_ERROR;
  82156. }
  82157. /* following zmemcpy do not work for 16-bit MSDOS */
  82158. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82159. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82160. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82161. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82162. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82163. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82164. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82165. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82166. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82167. ds->bl_desc.dyn_tree = ds->bl_tree;
  82168. return Z_OK;
  82169. #endif /* MAXSEG_64K */
  82170. }
  82171. /* ===========================================================================
  82172. * Read a new buffer from the current input stream, update the adler32
  82173. * and total number of bytes read. All deflate() input goes through
  82174. * this function so some applications may wish to modify it to avoid
  82175. * allocating a large strm->next_in buffer and copying from it.
  82176. * (See also flush_pending()).
  82177. */
  82178. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82179. {
  82180. unsigned len = strm->avail_in;
  82181. if (len > size) len = size;
  82182. if (len == 0) return 0;
  82183. strm->avail_in -= len;
  82184. if (strm->state->wrap == 1) {
  82185. strm->adler = adler32(strm->adler, strm->next_in, len);
  82186. }
  82187. #ifdef GZIP
  82188. else if (strm->state->wrap == 2) {
  82189. strm->adler = crc32(strm->adler, strm->next_in, len);
  82190. }
  82191. #endif
  82192. zmemcpy(buf, strm->next_in, len);
  82193. strm->next_in += len;
  82194. strm->total_in += len;
  82195. return (int)len;
  82196. }
  82197. /* ===========================================================================
  82198. * Initialize the "longest match" routines for a new zlib stream
  82199. */
  82200. local void lm_init (deflate_state *s)
  82201. {
  82202. s->window_size = (ulg)2L*s->w_size;
  82203. CLEAR_HASH(s);
  82204. /* Set the default configuration parameters:
  82205. */
  82206. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82207. s->good_match = configuration_table[s->level].good_length;
  82208. s->nice_match = configuration_table[s->level].nice_length;
  82209. s->max_chain_length = configuration_table[s->level].max_chain;
  82210. s->strstart = 0;
  82211. s->block_start = 0L;
  82212. s->lookahead = 0;
  82213. s->match_length = s->prev_length = MIN_MATCH-1;
  82214. s->match_available = 0;
  82215. s->ins_h = 0;
  82216. #ifndef FASTEST
  82217. #ifdef ASMV
  82218. match_init(); /* initialize the asm code */
  82219. #endif
  82220. #endif
  82221. }
  82222. #ifndef FASTEST
  82223. /* ===========================================================================
  82224. * Set match_start to the longest match starting at the given string and
  82225. * return its length. Matches shorter or equal to prev_length are discarded,
  82226. * in which case the result is equal to prev_length and match_start is
  82227. * garbage.
  82228. * IN assertions: cur_match is the head of the hash chain for the current
  82229. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82230. * OUT assertion: the match length is not greater than s->lookahead.
  82231. */
  82232. #ifndef ASMV
  82233. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82234. * match.S. The code will be functionally equivalent.
  82235. */
  82236. local uInt longest_match(deflate_state *s, IPos cur_match)
  82237. {
  82238. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82239. register Bytef *scan = s->window + s->strstart; /* current string */
  82240. register Bytef *match; /* matched string */
  82241. register int len; /* length of current match */
  82242. int best_len = s->prev_length; /* best match length so far */
  82243. int nice_match = s->nice_match; /* stop if match long enough */
  82244. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82245. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82246. /* Stop when cur_match becomes <= limit. To simplify the code,
  82247. * we prevent matches with the string of window index 0.
  82248. */
  82249. Posf *prev = s->prev;
  82250. uInt wmask = s->w_mask;
  82251. #ifdef UNALIGNED_OK
  82252. /* Compare two bytes at a time. Note: this is not always beneficial.
  82253. * Try with and without -DUNALIGNED_OK to check.
  82254. */
  82255. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82256. register ush scan_start = *(ushf*)scan;
  82257. register ush scan_end = *(ushf*)(scan+best_len-1);
  82258. #else
  82259. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82260. register Byte scan_end1 = scan[best_len-1];
  82261. register Byte scan_end = scan[best_len];
  82262. #endif
  82263. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82264. * It is easy to get rid of this optimization if necessary.
  82265. */
  82266. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82267. /* Do not waste too much time if we already have a good match: */
  82268. if (s->prev_length >= s->good_match) {
  82269. chain_length >>= 2;
  82270. }
  82271. /* Do not look for matches beyond the end of the input. This is necessary
  82272. * to make deflate deterministic.
  82273. */
  82274. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82275. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82276. do {
  82277. Assert(cur_match < s->strstart, "no future");
  82278. match = s->window + cur_match;
  82279. /* Skip to next match if the match length cannot increase
  82280. * or if the match length is less than 2. Note that the checks below
  82281. * for insufficient lookahead only occur occasionally for performance
  82282. * reasons. Therefore uninitialized memory will be accessed, and
  82283. * conditional jumps will be made that depend on those values.
  82284. * However the length of the match is limited to the lookahead, so
  82285. * the output of deflate is not affected by the uninitialized values.
  82286. */
  82287. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82288. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82289. * UNALIGNED_OK if your compiler uses a different size.
  82290. */
  82291. if (*(ushf*)(match+best_len-1) != scan_end ||
  82292. *(ushf*)match != scan_start) continue;
  82293. /* It is not necessary to compare scan[2] and match[2] since they are
  82294. * always equal when the other bytes match, given that the hash keys
  82295. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82296. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82297. * lookahead only every 4th comparison; the 128th check will be made
  82298. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82299. * necessary to put more guard bytes at the end of the window, or
  82300. * to check more often for insufficient lookahead.
  82301. */
  82302. Assert(scan[2] == match[2], "scan[2]?");
  82303. scan++, match++;
  82304. do {
  82305. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82306. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82307. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82308. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82309. scan < strend);
  82310. /* The funny "do {}" generates better code on most compilers */
  82311. /* Here, scan <= window+strstart+257 */
  82312. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82313. if (*scan == *match) scan++;
  82314. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82315. scan = strend - (MAX_MATCH-1);
  82316. #else /* UNALIGNED_OK */
  82317. if (match[best_len] != scan_end ||
  82318. match[best_len-1] != scan_end1 ||
  82319. *match != *scan ||
  82320. *++match != scan[1]) continue;
  82321. /* The check at best_len-1 can be removed because it will be made
  82322. * again later. (This heuristic is not always a win.)
  82323. * It is not necessary to compare scan[2] and match[2] since they
  82324. * are always equal when the other bytes match, given that
  82325. * the hash keys are equal and that HASH_BITS >= 8.
  82326. */
  82327. scan += 2, match++;
  82328. Assert(*scan == *match, "match[2]?");
  82329. /* We check for insufficient lookahead only every 8th comparison;
  82330. * the 256th check will be made at strstart+258.
  82331. */
  82332. do {
  82333. } while (*++scan == *++match && *++scan == *++match &&
  82334. *++scan == *++match && *++scan == *++match &&
  82335. *++scan == *++match && *++scan == *++match &&
  82336. *++scan == *++match && *++scan == *++match &&
  82337. scan < strend);
  82338. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82339. len = MAX_MATCH - (int)(strend - scan);
  82340. scan = strend - MAX_MATCH;
  82341. #endif /* UNALIGNED_OK */
  82342. if (len > best_len) {
  82343. s->match_start = cur_match;
  82344. best_len = len;
  82345. if (len >= nice_match) break;
  82346. #ifdef UNALIGNED_OK
  82347. scan_end = *(ushf*)(scan+best_len-1);
  82348. #else
  82349. scan_end1 = scan[best_len-1];
  82350. scan_end = scan[best_len];
  82351. #endif
  82352. }
  82353. } while ((cur_match = prev[cur_match & wmask]) > limit
  82354. && --chain_length != 0);
  82355. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82356. return s->lookahead;
  82357. }
  82358. #endif /* ASMV */
  82359. #endif /* FASTEST */
  82360. /* ---------------------------------------------------------------------------
  82361. * Optimized version for level == 1 or strategy == Z_RLE only
  82362. */
  82363. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82364. {
  82365. register Bytef *scan = s->window + s->strstart; /* current string */
  82366. register Bytef *match; /* matched string */
  82367. register int len; /* length of current match */
  82368. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82369. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82370. * It is easy to get rid of this optimization if necessary.
  82371. */
  82372. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82373. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82374. Assert(cur_match < s->strstart, "no future");
  82375. match = s->window + cur_match;
  82376. /* Return failure if the match length is less than 2:
  82377. */
  82378. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82379. /* The check at best_len-1 can be removed because it will be made
  82380. * again later. (This heuristic is not always a win.)
  82381. * It is not necessary to compare scan[2] and match[2] since they
  82382. * are always equal when the other bytes match, given that
  82383. * the hash keys are equal and that HASH_BITS >= 8.
  82384. */
  82385. scan += 2, match += 2;
  82386. Assert(*scan == *match, "match[2]?");
  82387. /* We check for insufficient lookahead only every 8th comparison;
  82388. * the 256th check will be made at strstart+258.
  82389. */
  82390. do {
  82391. } while (*++scan == *++match && *++scan == *++match &&
  82392. *++scan == *++match && *++scan == *++match &&
  82393. *++scan == *++match && *++scan == *++match &&
  82394. *++scan == *++match && *++scan == *++match &&
  82395. scan < strend);
  82396. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82397. len = MAX_MATCH - (int)(strend - scan);
  82398. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82399. s->match_start = cur_match;
  82400. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82401. }
  82402. #ifdef DEBUG
  82403. /* ===========================================================================
  82404. * Check that the match at match_start is indeed a match.
  82405. */
  82406. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82407. {
  82408. /* check that the match is indeed a match */
  82409. if (zmemcmp(s->window + match,
  82410. s->window + start, length) != EQUAL) {
  82411. fprintf(stderr, " start %u, match %u, length %d\n",
  82412. start, match, length);
  82413. do {
  82414. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82415. } while (--length != 0);
  82416. z_error("invalid match");
  82417. }
  82418. if (z_verbose > 1) {
  82419. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82420. do { putc(s->window[start++], stderr); } while (--length != 0);
  82421. }
  82422. }
  82423. #else
  82424. # define check_match(s, start, match, length)
  82425. #endif /* DEBUG */
  82426. /* ===========================================================================
  82427. * Fill the window when the lookahead becomes insufficient.
  82428. * Updates strstart and lookahead.
  82429. *
  82430. * IN assertion: lookahead < MIN_LOOKAHEAD
  82431. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82432. * At least one byte has been read, or avail_in == 0; reads are
  82433. * performed for at least two bytes (required for the zip translate_eol
  82434. * option -- not supported here).
  82435. */
  82436. local void fill_window (deflate_state *s)
  82437. {
  82438. register unsigned n, m;
  82439. register Posf *p;
  82440. unsigned more; /* Amount of free space at the end of the window. */
  82441. uInt wsize = s->w_size;
  82442. do {
  82443. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82444. /* Deal with !@#$% 64K limit: */
  82445. if (sizeof(int) <= 2) {
  82446. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82447. more = wsize;
  82448. } else if (more == (unsigned)(-1)) {
  82449. /* Very unlikely, but possible on 16 bit machine if
  82450. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82451. */
  82452. more--;
  82453. }
  82454. }
  82455. /* If the window is almost full and there is insufficient lookahead,
  82456. * move the upper half to the lower one to make room in the upper half.
  82457. */
  82458. if (s->strstart >= wsize+MAX_DIST(s)) {
  82459. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82460. s->match_start -= wsize;
  82461. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82462. s->block_start -= (long) wsize;
  82463. /* Slide the hash table (could be avoided with 32 bit values
  82464. at the expense of memory usage). We slide even when level == 0
  82465. to keep the hash table consistent if we switch back to level > 0
  82466. later. (Using level 0 permanently is not an optimal usage of
  82467. zlib, so we don't care about this pathological case.)
  82468. */
  82469. /* %%% avoid this when Z_RLE */
  82470. n = s->hash_size;
  82471. p = &s->head[n];
  82472. do {
  82473. m = *--p;
  82474. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82475. } while (--n);
  82476. n = wsize;
  82477. #ifndef FASTEST
  82478. p = &s->prev[n];
  82479. do {
  82480. m = *--p;
  82481. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82482. /* If n is not on any hash chain, prev[n] is garbage but
  82483. * its value will never be used.
  82484. */
  82485. } while (--n);
  82486. #endif
  82487. more += wsize;
  82488. }
  82489. if (s->strm->avail_in == 0) return;
  82490. /* If there was no sliding:
  82491. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82492. * more == window_size - lookahead - strstart
  82493. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82494. * => more >= window_size - 2*WSIZE + 2
  82495. * In the BIG_MEM or MMAP case (not yet supported),
  82496. * window_size == input_size + MIN_LOOKAHEAD &&
  82497. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82498. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82499. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82500. */
  82501. Assert(more >= 2, "more < 2");
  82502. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82503. s->lookahead += n;
  82504. /* Initialize the hash value now that we have some input: */
  82505. if (s->lookahead >= MIN_MATCH) {
  82506. s->ins_h = s->window[s->strstart];
  82507. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82508. #if MIN_MATCH != 3
  82509. Call UPDATE_HASH() MIN_MATCH-3 more times
  82510. #endif
  82511. }
  82512. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82513. * but this is not important since only literal bytes will be emitted.
  82514. */
  82515. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82516. }
  82517. /* ===========================================================================
  82518. * Flush the current block, with given end-of-file flag.
  82519. * IN assertion: strstart is set to the end of the current match.
  82520. */
  82521. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82522. _tr_flush_block(s, (s->block_start >= 0L ? \
  82523. (charf *)&s->window[(unsigned)s->block_start] : \
  82524. (charf *)Z_NULL), \
  82525. (ulg)((long)s->strstart - s->block_start), \
  82526. (eof)); \
  82527. s->block_start = s->strstart; \
  82528. flush_pending(s->strm); \
  82529. Tracev((stderr,"[FLUSH]")); \
  82530. }
  82531. /* Same but force premature exit if necessary. */
  82532. #define FLUSH_BLOCK(s, eof) { \
  82533. FLUSH_BLOCK_ONLY(s, eof); \
  82534. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82535. }
  82536. /* ===========================================================================
  82537. * Copy without compression as much as possible from the input stream, return
  82538. * the current block state.
  82539. * This function does not insert new strings in the dictionary since
  82540. * uncompressible data is probably not useful. This function is used
  82541. * only for the level=0 compression option.
  82542. * NOTE: this function should be optimized to avoid extra copying from
  82543. * window to pending_buf.
  82544. */
  82545. local block_state deflate_stored(deflate_state *s, int flush)
  82546. {
  82547. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82548. * to pending_buf_size, and each stored block has a 5 byte header:
  82549. */
  82550. ulg max_block_size = 0xffff;
  82551. ulg max_start;
  82552. if (max_block_size > s->pending_buf_size - 5) {
  82553. max_block_size = s->pending_buf_size - 5;
  82554. }
  82555. /* Copy as much as possible from input to output: */
  82556. for (;;) {
  82557. /* Fill the window as much as possible: */
  82558. if (s->lookahead <= 1) {
  82559. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82560. s->block_start >= (long)s->w_size, "slide too late");
  82561. fill_window(s);
  82562. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82563. if (s->lookahead == 0) break; /* flush the current block */
  82564. }
  82565. Assert(s->block_start >= 0L, "block gone");
  82566. s->strstart += s->lookahead;
  82567. s->lookahead = 0;
  82568. /* Emit a stored block if pending_buf will be full: */
  82569. max_start = s->block_start + max_block_size;
  82570. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82571. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82572. s->lookahead = (uInt)(s->strstart - max_start);
  82573. s->strstart = (uInt)max_start;
  82574. FLUSH_BLOCK(s, 0);
  82575. }
  82576. /* Flush if we may have to slide, otherwise block_start may become
  82577. * negative and the data will be gone:
  82578. */
  82579. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82580. FLUSH_BLOCK(s, 0);
  82581. }
  82582. }
  82583. FLUSH_BLOCK(s, flush == Z_FINISH);
  82584. return flush == Z_FINISH ? finish_done : block_done;
  82585. }
  82586. /* ===========================================================================
  82587. * Compress as much as possible from the input stream, return the current
  82588. * block state.
  82589. * This function does not perform lazy evaluation of matches and inserts
  82590. * new strings in the dictionary only for unmatched strings or for short
  82591. * matches. It is used only for the fast compression options.
  82592. */
  82593. local block_state deflate_fast(deflate_state *s, int flush)
  82594. {
  82595. IPos hash_head = NIL; /* head of the hash chain */
  82596. int bflush; /* set if current block must be flushed */
  82597. for (;;) {
  82598. /* Make sure that we always have enough lookahead, except
  82599. * at the end of the input file. We need MAX_MATCH bytes
  82600. * for the next match, plus MIN_MATCH bytes to insert the
  82601. * string following the next match.
  82602. */
  82603. if (s->lookahead < MIN_LOOKAHEAD) {
  82604. fill_window(s);
  82605. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82606. return need_more;
  82607. }
  82608. if (s->lookahead == 0) break; /* flush the current block */
  82609. }
  82610. /* Insert the string window[strstart .. strstart+2] in the
  82611. * dictionary, and set hash_head to the head of the hash chain:
  82612. */
  82613. if (s->lookahead >= MIN_MATCH) {
  82614. INSERT_STRING(s, s->strstart, hash_head);
  82615. }
  82616. /* Find the longest match, discarding those <= prev_length.
  82617. * At this point we have always match_length < MIN_MATCH
  82618. */
  82619. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82620. /* To simplify the code, we prevent matches with the string
  82621. * of window index 0 (in particular we have to avoid a match
  82622. * of the string with itself at the start of the input file).
  82623. */
  82624. #ifdef FASTEST
  82625. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82626. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82627. s->match_length = longest_match_fast (s, hash_head);
  82628. }
  82629. #else
  82630. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82631. s->match_length = longest_match (s, hash_head);
  82632. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82633. s->match_length = longest_match_fast (s, hash_head);
  82634. }
  82635. #endif
  82636. /* longest_match() or longest_match_fast() sets match_start */
  82637. }
  82638. if (s->match_length >= MIN_MATCH) {
  82639. check_match(s, s->strstart, s->match_start, s->match_length);
  82640. _tr_tally_dist(s, s->strstart - s->match_start,
  82641. s->match_length - MIN_MATCH, bflush);
  82642. s->lookahead -= s->match_length;
  82643. /* Insert new strings in the hash table only if the match length
  82644. * is not too large. This saves time but degrades compression.
  82645. */
  82646. #ifndef FASTEST
  82647. if (s->match_length <= s->max_insert_length &&
  82648. s->lookahead >= MIN_MATCH) {
  82649. s->match_length--; /* string at strstart already in table */
  82650. do {
  82651. s->strstart++;
  82652. INSERT_STRING(s, s->strstart, hash_head);
  82653. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82654. * always MIN_MATCH bytes ahead.
  82655. */
  82656. } while (--s->match_length != 0);
  82657. s->strstart++;
  82658. } else
  82659. #endif
  82660. {
  82661. s->strstart += s->match_length;
  82662. s->match_length = 0;
  82663. s->ins_h = s->window[s->strstart];
  82664. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82665. #if MIN_MATCH != 3
  82666. Call UPDATE_HASH() MIN_MATCH-3 more times
  82667. #endif
  82668. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82669. * matter since it will be recomputed at next deflate call.
  82670. */
  82671. }
  82672. } else {
  82673. /* No match, output a literal byte */
  82674. Tracevv((stderr,"%c", s->window[s->strstart]));
  82675. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82676. s->lookahead--;
  82677. s->strstart++;
  82678. }
  82679. if (bflush) FLUSH_BLOCK(s, 0);
  82680. }
  82681. FLUSH_BLOCK(s, flush == Z_FINISH);
  82682. return flush == Z_FINISH ? finish_done : block_done;
  82683. }
  82684. #ifndef FASTEST
  82685. /* ===========================================================================
  82686. * Same as above, but achieves better compression. We use a lazy
  82687. * evaluation for matches: a match is finally adopted only if there is
  82688. * no better match at the next window position.
  82689. */
  82690. local block_state deflate_slow(deflate_state *s, int flush)
  82691. {
  82692. IPos hash_head = NIL; /* head of hash chain */
  82693. int bflush; /* set if current block must be flushed */
  82694. /* Process the input block. */
  82695. for (;;) {
  82696. /* Make sure that we always have enough lookahead, except
  82697. * at the end of the input file. We need MAX_MATCH bytes
  82698. * for the next match, plus MIN_MATCH bytes to insert the
  82699. * string following the next match.
  82700. */
  82701. if (s->lookahead < MIN_LOOKAHEAD) {
  82702. fill_window(s);
  82703. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82704. return need_more;
  82705. }
  82706. if (s->lookahead == 0) break; /* flush the current block */
  82707. }
  82708. /* Insert the string window[strstart .. strstart+2] in the
  82709. * dictionary, and set hash_head to the head of the hash chain:
  82710. */
  82711. if (s->lookahead >= MIN_MATCH) {
  82712. INSERT_STRING(s, s->strstart, hash_head);
  82713. }
  82714. /* Find the longest match, discarding those <= prev_length.
  82715. */
  82716. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82717. s->match_length = MIN_MATCH-1;
  82718. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82719. s->strstart - hash_head <= MAX_DIST(s)) {
  82720. /* To simplify the code, we prevent matches with the string
  82721. * of window index 0 (in particular we have to avoid a match
  82722. * of the string with itself at the start of the input file).
  82723. */
  82724. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82725. s->match_length = longest_match (s, hash_head);
  82726. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82727. s->match_length = longest_match_fast (s, hash_head);
  82728. }
  82729. /* longest_match() or longest_match_fast() sets match_start */
  82730. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82731. #if TOO_FAR <= 32767
  82732. || (s->match_length == MIN_MATCH &&
  82733. s->strstart - s->match_start > TOO_FAR)
  82734. #endif
  82735. )) {
  82736. /* If prev_match is also MIN_MATCH, match_start is garbage
  82737. * but we will ignore the current match anyway.
  82738. */
  82739. s->match_length = MIN_MATCH-1;
  82740. }
  82741. }
  82742. /* If there was a match at the previous step and the current
  82743. * match is not better, output the previous match:
  82744. */
  82745. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82746. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82747. /* Do not insert strings in hash table beyond this. */
  82748. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82749. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82750. s->prev_length - MIN_MATCH, bflush);
  82751. /* Insert in hash table all strings up to the end of the match.
  82752. * strstart-1 and strstart are already inserted. If there is not
  82753. * enough lookahead, the last two strings are not inserted in
  82754. * the hash table.
  82755. */
  82756. s->lookahead -= s->prev_length-1;
  82757. s->prev_length -= 2;
  82758. do {
  82759. if (++s->strstart <= max_insert) {
  82760. INSERT_STRING(s, s->strstart, hash_head);
  82761. }
  82762. } while (--s->prev_length != 0);
  82763. s->match_available = 0;
  82764. s->match_length = MIN_MATCH-1;
  82765. s->strstart++;
  82766. if (bflush) FLUSH_BLOCK(s, 0);
  82767. } else if (s->match_available) {
  82768. /* If there was no match at the previous position, output a
  82769. * single literal. If there was a match but the current match
  82770. * is longer, truncate the previous match to a single literal.
  82771. */
  82772. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82773. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82774. if (bflush) {
  82775. FLUSH_BLOCK_ONLY(s, 0);
  82776. }
  82777. s->strstart++;
  82778. s->lookahead--;
  82779. if (s->strm->avail_out == 0) return need_more;
  82780. } else {
  82781. /* There is no previous match to compare with, wait for
  82782. * the next step to decide.
  82783. */
  82784. s->match_available = 1;
  82785. s->strstart++;
  82786. s->lookahead--;
  82787. }
  82788. }
  82789. Assert (flush != Z_NO_FLUSH, "no flush?");
  82790. if (s->match_available) {
  82791. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82792. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82793. s->match_available = 0;
  82794. }
  82795. FLUSH_BLOCK(s, flush == Z_FINISH);
  82796. return flush == Z_FINISH ? finish_done : block_done;
  82797. }
  82798. #endif /* FASTEST */
  82799. #if 0
  82800. /* ===========================================================================
  82801. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82802. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82803. * deflate switches away from Z_RLE.)
  82804. */
  82805. local block_state deflate_rle(s, flush)
  82806. deflate_state *s;
  82807. int flush;
  82808. {
  82809. int bflush; /* set if current block must be flushed */
  82810. uInt run; /* length of run */
  82811. uInt max; /* maximum length of run */
  82812. uInt prev; /* byte at distance one to match */
  82813. Bytef *scan; /* scan for end of run */
  82814. for (;;) {
  82815. /* Make sure that we always have enough lookahead, except
  82816. * at the end of the input file. We need MAX_MATCH bytes
  82817. * for the longest encodable run.
  82818. */
  82819. if (s->lookahead < MAX_MATCH) {
  82820. fill_window(s);
  82821. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82822. return need_more;
  82823. }
  82824. if (s->lookahead == 0) break; /* flush the current block */
  82825. }
  82826. /* See how many times the previous byte repeats */
  82827. run = 0;
  82828. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82829. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82830. scan = s->window + s->strstart - 1;
  82831. prev = *scan++;
  82832. do {
  82833. if (*scan++ != prev)
  82834. break;
  82835. } while (++run < max);
  82836. }
  82837. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82838. if (run >= MIN_MATCH) {
  82839. check_match(s, s->strstart, s->strstart - 1, run);
  82840. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82841. s->lookahead -= run;
  82842. s->strstart += run;
  82843. } else {
  82844. /* No match, output a literal byte */
  82845. Tracevv((stderr,"%c", s->window[s->strstart]));
  82846. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82847. s->lookahead--;
  82848. s->strstart++;
  82849. }
  82850. if (bflush) FLUSH_BLOCK(s, 0);
  82851. }
  82852. FLUSH_BLOCK(s, flush == Z_FINISH);
  82853. return flush == Z_FINISH ? finish_done : block_done;
  82854. }
  82855. #endif
  82856. /*** End of inlined file: deflate.c ***/
  82857. /*** Start of inlined file: inffast.c ***/
  82858. /*** Start of inlined file: inftrees.h ***/
  82859. /* WARNING: this file should *not* be used by applications. It is
  82860. part of the implementation of the compression library and is
  82861. subject to change. Applications should only use zlib.h.
  82862. */
  82863. #ifndef _INFTREES_H_
  82864. #define _INFTREES_H_
  82865. /* Structure for decoding tables. Each entry provides either the
  82866. information needed to do the operation requested by the code that
  82867. indexed that table entry, or it provides a pointer to another
  82868. table that indexes more bits of the code. op indicates whether
  82869. the entry is a pointer to another table, a literal, a length or
  82870. distance, an end-of-block, or an invalid code. For a table
  82871. pointer, the low four bits of op is the number of index bits of
  82872. that table. For a length or distance, the low four bits of op
  82873. is the number of extra bits to get after the code. bits is
  82874. the number of bits in this code or part of the code to drop off
  82875. of the bit buffer. val is the actual byte to output in the case
  82876. of a literal, the base length or distance, or the offset from
  82877. the current table to the next table. Each entry is four bytes. */
  82878. typedef struct {
  82879. unsigned char op; /* operation, extra bits, table bits */
  82880. unsigned char bits; /* bits in this part of the code */
  82881. unsigned short val; /* offset in table or code value */
  82882. } code;
  82883. /* op values as set by inflate_table():
  82884. 00000000 - literal
  82885. 0000tttt - table link, tttt != 0 is the number of table index bits
  82886. 0001eeee - length or distance, eeee is the number of extra bits
  82887. 01100000 - end of block
  82888. 01000000 - invalid code
  82889. */
  82890. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82891. exhaustive search was 1444 code structures (852 for length/literals
  82892. and 592 for distances, the latter actually the result of an
  82893. exhaustive search). The true maximum is not known, but the value
  82894. below is more than safe. */
  82895. #define ENOUGH 2048
  82896. #define MAXD 592
  82897. /* Type of code to build for inftable() */
  82898. typedef enum {
  82899. CODES,
  82900. LENS,
  82901. DISTS
  82902. } codetype;
  82903. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82904. unsigned codes, code FAR * FAR *table,
  82905. unsigned FAR *bits, unsigned short FAR *work));
  82906. #endif
  82907. /*** End of inlined file: inftrees.h ***/
  82908. /*** Start of inlined file: inflate.h ***/
  82909. /* WARNING: this file should *not* be used by applications. It is
  82910. part of the implementation of the compression library and is
  82911. subject to change. Applications should only use zlib.h.
  82912. */
  82913. #ifndef _INFLATE_H_
  82914. #define _INFLATE_H_
  82915. /* define NO_GZIP when compiling if you want to disable gzip header and
  82916. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82917. the crc code when it is not needed. For shared libraries, gzip decoding
  82918. should be left enabled. */
  82919. #ifndef NO_GZIP
  82920. # define GUNZIP
  82921. #endif
  82922. /* Possible inflate modes between inflate() calls */
  82923. typedef enum {
  82924. HEAD, /* i: waiting for magic header */
  82925. FLAGS, /* i: waiting for method and flags (gzip) */
  82926. TIME, /* i: waiting for modification time (gzip) */
  82927. OS, /* i: waiting for extra flags and operating system (gzip) */
  82928. EXLEN, /* i: waiting for extra length (gzip) */
  82929. EXTRA, /* i: waiting for extra bytes (gzip) */
  82930. NAME, /* i: waiting for end of file name (gzip) */
  82931. COMMENT, /* i: waiting for end of comment (gzip) */
  82932. HCRC, /* i: waiting for header crc (gzip) */
  82933. DICTID, /* i: waiting for dictionary check value */
  82934. DICT, /* waiting for inflateSetDictionary() call */
  82935. TYPE, /* i: waiting for type bits, including last-flag bit */
  82936. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82937. STORED, /* i: waiting for stored size (length and complement) */
  82938. COPY, /* i/o: waiting for input or output to copy stored block */
  82939. TABLE, /* i: waiting for dynamic block table lengths */
  82940. LENLENS, /* i: waiting for code length code lengths */
  82941. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82942. LEN, /* i: waiting for length/lit code */
  82943. LENEXT, /* i: waiting for length extra bits */
  82944. DIST, /* i: waiting for distance code */
  82945. DISTEXT, /* i: waiting for distance extra bits */
  82946. MATCH, /* o: waiting for output space to copy string */
  82947. LIT, /* o: waiting for output space to write literal */
  82948. CHECK, /* i: waiting for 32-bit check value */
  82949. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82950. DONE, /* finished check, done -- remain here until reset */
  82951. BAD, /* got a data error -- remain here until reset */
  82952. MEM, /* got an inflate() memory error -- remain here until reset */
  82953. SYNC /* looking for synchronization bytes to restart inflate() */
  82954. } inflate_mode;
  82955. /*
  82956. State transitions between above modes -
  82957. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82958. Process header:
  82959. HEAD -> (gzip) or (zlib)
  82960. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82961. NAME -> COMMENT -> HCRC -> TYPE
  82962. (zlib) -> DICTID or TYPE
  82963. DICTID -> DICT -> TYPE
  82964. Read deflate blocks:
  82965. TYPE -> STORED or TABLE or LEN or CHECK
  82966. STORED -> COPY -> TYPE
  82967. TABLE -> LENLENS -> CODELENS -> LEN
  82968. Read deflate codes:
  82969. LEN -> LENEXT or LIT or TYPE
  82970. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82971. LIT -> LEN
  82972. Process trailer:
  82973. CHECK -> LENGTH -> DONE
  82974. */
  82975. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82976. struct inflate_state {
  82977. inflate_mode mode; /* current inflate mode */
  82978. int last; /* true if processing last block */
  82979. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82980. int havedict; /* true if dictionary provided */
  82981. int flags; /* gzip header method and flags (0 if zlib) */
  82982. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82983. unsigned long check; /* protected copy of check value */
  82984. unsigned long total; /* protected copy of output count */
  82985. gz_headerp head; /* where to save gzip header information */
  82986. /* sliding window */
  82987. unsigned wbits; /* log base 2 of requested window size */
  82988. unsigned wsize; /* window size or zero if not using window */
  82989. unsigned whave; /* valid bytes in the window */
  82990. unsigned write; /* window write index */
  82991. unsigned char FAR *window; /* allocated sliding window, if needed */
  82992. /* bit accumulator */
  82993. unsigned long hold; /* input bit accumulator */
  82994. unsigned bits; /* number of bits in "in" */
  82995. /* for string and stored block copying */
  82996. unsigned length; /* literal or length of data to copy */
  82997. unsigned offset; /* distance back to copy string from */
  82998. /* for table and code decoding */
  82999. unsigned extra; /* extra bits needed */
  83000. /* fixed and dynamic code tables */
  83001. code const FAR *lencode; /* starting table for length/literal codes */
  83002. code const FAR *distcode; /* starting table for distance codes */
  83003. unsigned lenbits; /* index bits for lencode */
  83004. unsigned distbits; /* index bits for distcode */
  83005. /* dynamic table building */
  83006. unsigned ncode; /* number of code length code lengths */
  83007. unsigned nlen; /* number of length code lengths */
  83008. unsigned ndist; /* number of distance code lengths */
  83009. unsigned have; /* number of code lengths in lens[] */
  83010. code FAR *next; /* next available space in codes[] */
  83011. unsigned short lens[320]; /* temporary storage for code lengths */
  83012. unsigned short work[288]; /* work area for code table building */
  83013. code codes[ENOUGH]; /* space for code tables */
  83014. };
  83015. #endif
  83016. /*** End of inlined file: inflate.h ***/
  83017. /*** Start of inlined file: inffast.h ***/
  83018. /* WARNING: this file should *not* be used by applications. It is
  83019. part of the implementation of the compression library and is
  83020. subject to change. Applications should only use zlib.h.
  83021. */
  83022. void inflate_fast OF((z_streamp strm, unsigned start));
  83023. /*** End of inlined file: inffast.h ***/
  83024. #ifndef ASMINF
  83025. /* Allow machine dependent optimization for post-increment or pre-increment.
  83026. Based on testing to date,
  83027. Pre-increment preferred for:
  83028. - PowerPC G3 (Adler)
  83029. - MIPS R5000 (Randers-Pehrson)
  83030. Post-increment preferred for:
  83031. - none
  83032. No measurable difference:
  83033. - Pentium III (Anderson)
  83034. - M68060 (Nikl)
  83035. */
  83036. #ifdef POSTINC
  83037. # define OFF 0
  83038. # define PUP(a) *(a)++
  83039. #else
  83040. # define OFF 1
  83041. # define PUP(a) *++(a)
  83042. #endif
  83043. /*
  83044. Decode literal, length, and distance codes and write out the resulting
  83045. literal and match bytes until either not enough input or output is
  83046. available, an end-of-block is encountered, or a data error is encountered.
  83047. When large enough input and output buffers are supplied to inflate(), for
  83048. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83049. inflate execution time is spent in this routine.
  83050. Entry assumptions:
  83051. state->mode == LEN
  83052. strm->avail_in >= 6
  83053. strm->avail_out >= 258
  83054. start >= strm->avail_out
  83055. state->bits < 8
  83056. On return, state->mode is one of:
  83057. LEN -- ran out of enough output space or enough available input
  83058. TYPE -- reached end of block code, inflate() to interpret next block
  83059. BAD -- error in block data
  83060. Notes:
  83061. - The maximum input bits used by a length/distance pair is 15 bits for the
  83062. length code, 5 bits for the length extra, 15 bits for the distance code,
  83063. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83064. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83065. checking for available input while decoding.
  83066. - The maximum bytes that a single length/distance pair can output is 258
  83067. bytes, which is the maximum length that can be coded. inflate_fast()
  83068. requires strm->avail_out >= 258 for each loop to avoid checking for
  83069. output space.
  83070. */
  83071. void inflate_fast (z_streamp strm, unsigned start)
  83072. {
  83073. struct inflate_state FAR *state;
  83074. unsigned char FAR *in; /* local strm->next_in */
  83075. unsigned char FAR *last; /* while in < last, enough input available */
  83076. unsigned char FAR *out; /* local strm->next_out */
  83077. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83078. unsigned char FAR *end; /* while out < end, enough space available */
  83079. #ifdef INFLATE_STRICT
  83080. unsigned dmax; /* maximum distance from zlib header */
  83081. #endif
  83082. unsigned wsize; /* window size or zero if not using window */
  83083. unsigned whave; /* valid bytes in the window */
  83084. unsigned write; /* window write index */
  83085. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83086. unsigned long hold; /* local strm->hold */
  83087. unsigned bits; /* local strm->bits */
  83088. code const FAR *lcode; /* local strm->lencode */
  83089. code const FAR *dcode; /* local strm->distcode */
  83090. unsigned lmask; /* mask for first level of length codes */
  83091. unsigned dmask; /* mask for first level of distance codes */
  83092. code thisx; /* retrieved table entry */
  83093. unsigned op; /* code bits, operation, extra bits, or */
  83094. /* window position, window bytes to copy */
  83095. unsigned len; /* match length, unused bytes */
  83096. unsigned dist; /* match distance */
  83097. unsigned char FAR *from; /* where to copy match from */
  83098. /* copy state to local variables */
  83099. state = (struct inflate_state FAR *)strm->state;
  83100. in = strm->next_in - OFF;
  83101. last = in + (strm->avail_in - 5);
  83102. out = strm->next_out - OFF;
  83103. beg = out - (start - strm->avail_out);
  83104. end = out + (strm->avail_out - 257);
  83105. #ifdef INFLATE_STRICT
  83106. dmax = state->dmax;
  83107. #endif
  83108. wsize = state->wsize;
  83109. whave = state->whave;
  83110. write = state->write;
  83111. window = state->window;
  83112. hold = state->hold;
  83113. bits = state->bits;
  83114. lcode = state->lencode;
  83115. dcode = state->distcode;
  83116. lmask = (1U << state->lenbits) - 1;
  83117. dmask = (1U << state->distbits) - 1;
  83118. /* decode literals and length/distances until end-of-block or not enough
  83119. input data or output space */
  83120. do {
  83121. if (bits < 15) {
  83122. hold += (unsigned long)(PUP(in)) << bits;
  83123. bits += 8;
  83124. hold += (unsigned long)(PUP(in)) << bits;
  83125. bits += 8;
  83126. }
  83127. thisx = lcode[hold & lmask];
  83128. dolen:
  83129. op = (unsigned)(thisx.bits);
  83130. hold >>= op;
  83131. bits -= op;
  83132. op = (unsigned)(thisx.op);
  83133. if (op == 0) { /* literal */
  83134. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83135. "inflate: literal '%c'\n" :
  83136. "inflate: literal 0x%02x\n", thisx.val));
  83137. PUP(out) = (unsigned char)(thisx.val);
  83138. }
  83139. else if (op & 16) { /* length base */
  83140. len = (unsigned)(thisx.val);
  83141. op &= 15; /* number of extra bits */
  83142. if (op) {
  83143. if (bits < op) {
  83144. hold += (unsigned long)(PUP(in)) << bits;
  83145. bits += 8;
  83146. }
  83147. len += (unsigned)hold & ((1U << op) - 1);
  83148. hold >>= op;
  83149. bits -= op;
  83150. }
  83151. Tracevv((stderr, "inflate: length %u\n", len));
  83152. if (bits < 15) {
  83153. hold += (unsigned long)(PUP(in)) << bits;
  83154. bits += 8;
  83155. hold += (unsigned long)(PUP(in)) << bits;
  83156. bits += 8;
  83157. }
  83158. thisx = dcode[hold & dmask];
  83159. dodist:
  83160. op = (unsigned)(thisx.bits);
  83161. hold >>= op;
  83162. bits -= op;
  83163. op = (unsigned)(thisx.op);
  83164. if (op & 16) { /* distance base */
  83165. dist = (unsigned)(thisx.val);
  83166. op &= 15; /* number of extra bits */
  83167. if (bits < op) {
  83168. hold += (unsigned long)(PUP(in)) << bits;
  83169. bits += 8;
  83170. if (bits < op) {
  83171. hold += (unsigned long)(PUP(in)) << bits;
  83172. bits += 8;
  83173. }
  83174. }
  83175. dist += (unsigned)hold & ((1U << op) - 1);
  83176. #ifdef INFLATE_STRICT
  83177. if (dist > dmax) {
  83178. strm->msg = (char *)"invalid distance too far back";
  83179. state->mode = BAD;
  83180. break;
  83181. }
  83182. #endif
  83183. hold >>= op;
  83184. bits -= op;
  83185. Tracevv((stderr, "inflate: distance %u\n", dist));
  83186. op = (unsigned)(out - beg); /* max distance in output */
  83187. if (dist > op) { /* see if copy from window */
  83188. op = dist - op; /* distance back in window */
  83189. if (op > whave) {
  83190. strm->msg = (char *)"invalid distance too far back";
  83191. state->mode = BAD;
  83192. break;
  83193. }
  83194. from = window - OFF;
  83195. if (write == 0) { /* very common case */
  83196. from += wsize - op;
  83197. if (op < len) { /* some from window */
  83198. len -= op;
  83199. do {
  83200. PUP(out) = PUP(from);
  83201. } while (--op);
  83202. from = out - dist; /* rest from output */
  83203. }
  83204. }
  83205. else if (write < op) { /* wrap around window */
  83206. from += wsize + write - op;
  83207. op -= write;
  83208. if (op < len) { /* some from end of window */
  83209. len -= op;
  83210. do {
  83211. PUP(out) = PUP(from);
  83212. } while (--op);
  83213. from = window - OFF;
  83214. if (write < len) { /* some from start of window */
  83215. op = write;
  83216. len -= op;
  83217. do {
  83218. PUP(out) = PUP(from);
  83219. } while (--op);
  83220. from = out - dist; /* rest from output */
  83221. }
  83222. }
  83223. }
  83224. else { /* contiguous in window */
  83225. from += write - op;
  83226. if (op < len) { /* some from window */
  83227. len -= op;
  83228. do {
  83229. PUP(out) = PUP(from);
  83230. } while (--op);
  83231. from = out - dist; /* rest from output */
  83232. }
  83233. }
  83234. while (len > 2) {
  83235. PUP(out) = PUP(from);
  83236. PUP(out) = PUP(from);
  83237. PUP(out) = PUP(from);
  83238. len -= 3;
  83239. }
  83240. if (len) {
  83241. PUP(out) = PUP(from);
  83242. if (len > 1)
  83243. PUP(out) = PUP(from);
  83244. }
  83245. }
  83246. else {
  83247. from = out - dist; /* copy direct from output */
  83248. do { /* minimum length is three */
  83249. PUP(out) = PUP(from);
  83250. PUP(out) = PUP(from);
  83251. PUP(out) = PUP(from);
  83252. len -= 3;
  83253. } while (len > 2);
  83254. if (len) {
  83255. PUP(out) = PUP(from);
  83256. if (len > 1)
  83257. PUP(out) = PUP(from);
  83258. }
  83259. }
  83260. }
  83261. else if ((op & 64) == 0) { /* 2nd level distance code */
  83262. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83263. goto dodist;
  83264. }
  83265. else {
  83266. strm->msg = (char *)"invalid distance code";
  83267. state->mode = BAD;
  83268. break;
  83269. }
  83270. }
  83271. else if ((op & 64) == 0) { /* 2nd level length code */
  83272. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83273. goto dolen;
  83274. }
  83275. else if (op & 32) { /* end-of-block */
  83276. Tracevv((stderr, "inflate: end of block\n"));
  83277. state->mode = TYPE;
  83278. break;
  83279. }
  83280. else {
  83281. strm->msg = (char *)"invalid literal/length code";
  83282. state->mode = BAD;
  83283. break;
  83284. }
  83285. } while (in < last && out < end);
  83286. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83287. len = bits >> 3;
  83288. in -= len;
  83289. bits -= len << 3;
  83290. hold &= (1U << bits) - 1;
  83291. /* update state and return */
  83292. strm->next_in = in + OFF;
  83293. strm->next_out = out + OFF;
  83294. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83295. strm->avail_out = (unsigned)(out < end ?
  83296. 257 + (end - out) : 257 - (out - end));
  83297. state->hold = hold;
  83298. state->bits = bits;
  83299. return;
  83300. }
  83301. /*
  83302. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83303. - Using bit fields for code structure
  83304. - Different op definition to avoid & for extra bits (do & for table bits)
  83305. - Three separate decoding do-loops for direct, window, and write == 0
  83306. - Special case for distance > 1 copies to do overlapped load and store copy
  83307. - Explicit branch predictions (based on measured branch probabilities)
  83308. - Deferring match copy and interspersed it with decoding subsequent codes
  83309. - Swapping literal/length else
  83310. - Swapping window/direct else
  83311. - Larger unrolled copy loops (three is about right)
  83312. - Moving len -= 3 statement into middle of loop
  83313. */
  83314. #endif /* !ASMINF */
  83315. /*** End of inlined file: inffast.c ***/
  83316. #undef PULLBYTE
  83317. #undef LOAD
  83318. #undef RESTORE
  83319. #undef INITBITS
  83320. #undef NEEDBITS
  83321. #undef DROPBITS
  83322. #undef BYTEBITS
  83323. /*** Start of inlined file: inflate.c ***/
  83324. /*
  83325. * Change history:
  83326. *
  83327. * 1.2.beta0 24 Nov 2002
  83328. * - First version -- complete rewrite of inflate to simplify code, avoid
  83329. * creation of window when not needed, minimize use of window when it is
  83330. * needed, make inffast.c even faster, implement gzip decoding, and to
  83331. * improve code readability and style over the previous zlib inflate code
  83332. *
  83333. * 1.2.beta1 25 Nov 2002
  83334. * - Use pointers for available input and output checking in inffast.c
  83335. * - Remove input and output counters in inffast.c
  83336. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83337. * - Remove unnecessary second byte pull from length extra in inffast.c
  83338. * - Unroll direct copy to three copies per loop in inffast.c
  83339. *
  83340. * 1.2.beta2 4 Dec 2002
  83341. * - Change external routine names to reduce potential conflicts
  83342. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83343. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83344. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83345. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83346. *
  83347. * 1.2.beta3 22 Dec 2002
  83348. * - Add comments on state->bits assertion in inffast.c
  83349. * - Add comments on op field in inftrees.h
  83350. * - Fix bug in reuse of allocated window after inflateReset()
  83351. * - Remove bit fields--back to byte structure for speed
  83352. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83353. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83354. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83355. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83356. * - Use local copies of stream next and avail values, as well as local bit
  83357. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83358. *
  83359. * 1.2.beta4 1 Jan 2003
  83360. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83361. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83362. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83363. * - Rearrange window copies in inflate_fast() for speed and simplification
  83364. * - Unroll last copy for window match in inflate_fast()
  83365. * - Use local copies of window variables in inflate_fast() for speed
  83366. * - Pull out common write == 0 case for speed in inflate_fast()
  83367. * - Make op and len in inflate_fast() unsigned for consistency
  83368. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83369. * - Simplified bad distance check in inflate_fast()
  83370. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83371. * source file infback.c to provide a call-back interface to inflate for
  83372. * programs like gzip and unzip -- uses window as output buffer to avoid
  83373. * window copying
  83374. *
  83375. * 1.2.beta5 1 Jan 2003
  83376. * - Improved inflateBack() interface to allow the caller to provide initial
  83377. * input in strm.
  83378. * - Fixed stored blocks bug in inflateBack()
  83379. *
  83380. * 1.2.beta6 4 Jan 2003
  83381. * - Added comments in inffast.c on effectiveness of POSTINC
  83382. * - Typecasting all around to reduce compiler warnings
  83383. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83384. * make compilers happy
  83385. * - Changed type of window in inflateBackInit() to unsigned char *
  83386. *
  83387. * 1.2.beta7 27 Jan 2003
  83388. * - Changed many types to unsigned or unsigned short to avoid warnings
  83389. * - Added inflateCopy() function
  83390. *
  83391. * 1.2.0 9 Mar 2003
  83392. * - Changed inflateBack() interface to provide separate opaque descriptors
  83393. * for the in() and out() functions
  83394. * - Changed inflateBack() argument and in_func typedef to swap the length
  83395. * and buffer address return values for the input function
  83396. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83397. *
  83398. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83399. */
  83400. /*** Start of inlined file: inffast.h ***/
  83401. /* WARNING: this file should *not* be used by applications. It is
  83402. part of the implementation of the compression library and is
  83403. subject to change. Applications should only use zlib.h.
  83404. */
  83405. void inflate_fast OF((z_streamp strm, unsigned start));
  83406. /*** End of inlined file: inffast.h ***/
  83407. #ifdef MAKEFIXED
  83408. # ifndef BUILDFIXED
  83409. # define BUILDFIXED
  83410. # endif
  83411. #endif
  83412. /* function prototypes */
  83413. local void fixedtables OF((struct inflate_state FAR *state));
  83414. local int updatewindow OF((z_streamp strm, unsigned out));
  83415. #ifdef BUILDFIXED
  83416. void makefixed OF((void));
  83417. #endif
  83418. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83419. unsigned len));
  83420. int ZEXPORT inflateReset (z_streamp strm)
  83421. {
  83422. struct inflate_state FAR *state;
  83423. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83424. state = (struct inflate_state FAR *)strm->state;
  83425. strm->total_in = strm->total_out = state->total = 0;
  83426. strm->msg = Z_NULL;
  83427. strm->adler = 1; /* to support ill-conceived Java test suite */
  83428. state->mode = HEAD;
  83429. state->last = 0;
  83430. state->havedict = 0;
  83431. state->dmax = 32768U;
  83432. state->head = Z_NULL;
  83433. state->wsize = 0;
  83434. state->whave = 0;
  83435. state->write = 0;
  83436. state->hold = 0;
  83437. state->bits = 0;
  83438. state->lencode = state->distcode = state->next = state->codes;
  83439. Tracev((stderr, "inflate: reset\n"));
  83440. return Z_OK;
  83441. }
  83442. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83443. {
  83444. struct inflate_state FAR *state;
  83445. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83446. state = (struct inflate_state FAR *)strm->state;
  83447. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83448. value &= (1L << bits) - 1;
  83449. state->hold += value << state->bits;
  83450. state->bits += bits;
  83451. return Z_OK;
  83452. }
  83453. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83454. {
  83455. struct inflate_state FAR *state;
  83456. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83457. stream_size != (int)(sizeof(z_stream)))
  83458. return Z_VERSION_ERROR;
  83459. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83460. strm->msg = Z_NULL; /* in case we return an error */
  83461. if (strm->zalloc == (alloc_func)0) {
  83462. strm->zalloc = zcalloc;
  83463. strm->opaque = (voidpf)0;
  83464. }
  83465. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83466. state = (struct inflate_state FAR *)
  83467. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83468. if (state == Z_NULL) return Z_MEM_ERROR;
  83469. Tracev((stderr, "inflate: allocated\n"));
  83470. strm->state = (struct internal_state FAR *)state;
  83471. if (windowBits < 0) {
  83472. state->wrap = 0;
  83473. windowBits = -windowBits;
  83474. }
  83475. else {
  83476. state->wrap = (windowBits >> 4) + 1;
  83477. #ifdef GUNZIP
  83478. if (windowBits < 48) windowBits &= 15;
  83479. #endif
  83480. }
  83481. if (windowBits < 8 || windowBits > 15) {
  83482. ZFREE(strm, state);
  83483. strm->state = Z_NULL;
  83484. return Z_STREAM_ERROR;
  83485. }
  83486. state->wbits = (unsigned)windowBits;
  83487. state->window = Z_NULL;
  83488. return inflateReset(strm);
  83489. }
  83490. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83491. {
  83492. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83493. }
  83494. /*
  83495. Return state with length and distance decoding tables and index sizes set to
  83496. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83497. If BUILDFIXED is defined, then instead this routine builds the tables the
  83498. first time it's called, and returns those tables the first time and
  83499. thereafter. This reduces the size of the code by about 2K bytes, in
  83500. exchange for a little execution time. However, BUILDFIXED should not be
  83501. used for threaded applications, since the rewriting of the tables and virgin
  83502. may not be thread-safe.
  83503. */
  83504. local void fixedtables (struct inflate_state FAR *state)
  83505. {
  83506. #ifdef BUILDFIXED
  83507. static int virgin = 1;
  83508. static code *lenfix, *distfix;
  83509. static code fixed[544];
  83510. /* build fixed huffman tables if first call (may not be thread safe) */
  83511. if (virgin) {
  83512. unsigned sym, bits;
  83513. static code *next;
  83514. /* literal/length table */
  83515. sym = 0;
  83516. while (sym < 144) state->lens[sym++] = 8;
  83517. while (sym < 256) state->lens[sym++] = 9;
  83518. while (sym < 280) state->lens[sym++] = 7;
  83519. while (sym < 288) state->lens[sym++] = 8;
  83520. next = fixed;
  83521. lenfix = next;
  83522. bits = 9;
  83523. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83524. /* distance table */
  83525. sym = 0;
  83526. while (sym < 32) state->lens[sym++] = 5;
  83527. distfix = next;
  83528. bits = 5;
  83529. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83530. /* do this just once */
  83531. virgin = 0;
  83532. }
  83533. #else /* !BUILDFIXED */
  83534. /*** Start of inlined file: inffixed.h ***/
  83535. /* WARNING: this file should *not* be used by applications. It
  83536. is part of the implementation of the compression library and
  83537. is subject to change. Applications should only use zlib.h.
  83538. */
  83539. static const code lenfix[512] = {
  83540. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83541. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83542. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83543. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83544. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83545. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83546. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83547. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83548. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83549. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83550. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83551. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83552. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83553. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83554. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83555. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83556. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83557. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83558. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83559. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83560. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83561. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83562. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83563. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83564. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83565. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83566. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83567. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83568. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83569. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83570. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83571. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83572. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83573. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83574. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83575. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83576. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83577. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83578. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83579. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83580. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83581. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83582. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83583. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83584. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83585. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83586. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83587. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83588. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83589. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83590. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83591. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83592. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83593. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83594. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83595. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83596. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83597. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83598. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83599. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83600. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83601. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83602. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83603. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83604. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83605. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83606. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83607. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83608. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83609. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83610. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83611. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83612. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83613. {0,9,255}
  83614. };
  83615. static const code distfix[32] = {
  83616. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83617. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83618. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83619. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83620. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83621. {22,5,193},{64,5,0}
  83622. };
  83623. /*** End of inlined file: inffixed.h ***/
  83624. #endif /* BUILDFIXED */
  83625. state->lencode = lenfix;
  83626. state->lenbits = 9;
  83627. state->distcode = distfix;
  83628. state->distbits = 5;
  83629. }
  83630. #ifdef MAKEFIXED
  83631. #include <stdio.h>
  83632. /*
  83633. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83634. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83635. those tables to stdout, which would be piped to inffixed.h. A small program
  83636. can simply call makefixed to do this:
  83637. void makefixed(void);
  83638. int main(void)
  83639. {
  83640. makefixed();
  83641. return 0;
  83642. }
  83643. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83644. a.out > inffixed.h
  83645. */
  83646. void makefixed()
  83647. {
  83648. unsigned low, size;
  83649. struct inflate_state state;
  83650. fixedtables(&state);
  83651. puts(" /* inffixed.h -- table for decoding fixed codes");
  83652. puts(" * Generated automatically by makefixed().");
  83653. puts(" */");
  83654. puts("");
  83655. puts(" /* WARNING: this file should *not* be used by applications.");
  83656. puts(" It is part of the implementation of this library and is");
  83657. puts(" subject to change. Applications should only use zlib.h.");
  83658. puts(" */");
  83659. puts("");
  83660. size = 1U << 9;
  83661. printf(" static const code lenfix[%u] = {", size);
  83662. low = 0;
  83663. for (;;) {
  83664. if ((low % 7) == 0) printf("\n ");
  83665. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83666. state.lencode[low].val);
  83667. if (++low == size) break;
  83668. putchar(',');
  83669. }
  83670. puts("\n };");
  83671. size = 1U << 5;
  83672. printf("\n static const code distfix[%u] = {", size);
  83673. low = 0;
  83674. for (;;) {
  83675. if ((low % 6) == 0) printf("\n ");
  83676. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83677. state.distcode[low].val);
  83678. if (++low == size) break;
  83679. putchar(',');
  83680. }
  83681. puts("\n };");
  83682. }
  83683. #endif /* MAKEFIXED */
  83684. /*
  83685. Update the window with the last wsize (normally 32K) bytes written before
  83686. returning. If window does not exist yet, create it. This is only called
  83687. when a window is already in use, or when output has been written during this
  83688. inflate call, but the end of the deflate stream has not been reached yet.
  83689. It is also called to create a window for dictionary data when a dictionary
  83690. is loaded.
  83691. Providing output buffers larger than 32K to inflate() should provide a speed
  83692. advantage, since only the last 32K of output is copied to the sliding window
  83693. upon return from inflate(), and since all distances after the first 32K of
  83694. output will fall in the output data, making match copies simpler and faster.
  83695. The advantage may be dependent on the size of the processor's data caches.
  83696. */
  83697. local int updatewindow (z_streamp strm, unsigned out)
  83698. {
  83699. struct inflate_state FAR *state;
  83700. unsigned copy, dist;
  83701. state = (struct inflate_state FAR *)strm->state;
  83702. /* if it hasn't been done already, allocate space for the window */
  83703. if (state->window == Z_NULL) {
  83704. state->window = (unsigned char FAR *)
  83705. ZALLOC(strm, 1U << state->wbits,
  83706. sizeof(unsigned char));
  83707. if (state->window == Z_NULL) return 1;
  83708. }
  83709. /* if window not in use yet, initialize */
  83710. if (state->wsize == 0) {
  83711. state->wsize = 1U << state->wbits;
  83712. state->write = 0;
  83713. state->whave = 0;
  83714. }
  83715. /* copy state->wsize or less output bytes into the circular window */
  83716. copy = out - strm->avail_out;
  83717. if (copy >= state->wsize) {
  83718. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83719. state->write = 0;
  83720. state->whave = state->wsize;
  83721. }
  83722. else {
  83723. dist = state->wsize - state->write;
  83724. if (dist > copy) dist = copy;
  83725. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83726. copy -= dist;
  83727. if (copy) {
  83728. zmemcpy(state->window, strm->next_out - copy, copy);
  83729. state->write = copy;
  83730. state->whave = state->wsize;
  83731. }
  83732. else {
  83733. state->write += dist;
  83734. if (state->write == state->wsize) state->write = 0;
  83735. if (state->whave < state->wsize) state->whave += dist;
  83736. }
  83737. }
  83738. return 0;
  83739. }
  83740. /* Macros for inflate(): */
  83741. /* check function to use adler32() for zlib or crc32() for gzip */
  83742. #ifdef GUNZIP
  83743. # define UPDATE(check, buf, len) \
  83744. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83745. #else
  83746. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83747. #endif
  83748. /* check macros for header crc */
  83749. #ifdef GUNZIP
  83750. # define CRC2(check, word) \
  83751. do { \
  83752. hbuf[0] = (unsigned char)(word); \
  83753. hbuf[1] = (unsigned char)((word) >> 8); \
  83754. check = crc32(check, hbuf, 2); \
  83755. } while (0)
  83756. # define CRC4(check, word) \
  83757. do { \
  83758. hbuf[0] = (unsigned char)(word); \
  83759. hbuf[1] = (unsigned char)((word) >> 8); \
  83760. hbuf[2] = (unsigned char)((word) >> 16); \
  83761. hbuf[3] = (unsigned char)((word) >> 24); \
  83762. check = crc32(check, hbuf, 4); \
  83763. } while (0)
  83764. #endif
  83765. /* Load registers with state in inflate() for speed */
  83766. #define LOAD() \
  83767. do { \
  83768. put = strm->next_out; \
  83769. left = strm->avail_out; \
  83770. next = strm->next_in; \
  83771. have = strm->avail_in; \
  83772. hold = state->hold; \
  83773. bits = state->bits; \
  83774. } while (0)
  83775. /* Restore state from registers in inflate() */
  83776. #define RESTORE() \
  83777. do { \
  83778. strm->next_out = put; \
  83779. strm->avail_out = left; \
  83780. strm->next_in = next; \
  83781. strm->avail_in = have; \
  83782. state->hold = hold; \
  83783. state->bits = bits; \
  83784. } while (0)
  83785. /* Clear the input bit accumulator */
  83786. #define INITBITS() \
  83787. do { \
  83788. hold = 0; \
  83789. bits = 0; \
  83790. } while (0)
  83791. /* Get a byte of input into the bit accumulator, or return from inflate()
  83792. if there is no input available. */
  83793. #define PULLBYTE() \
  83794. do { \
  83795. if (have == 0) goto inf_leave; \
  83796. have--; \
  83797. hold += (unsigned long)(*next++) << bits; \
  83798. bits += 8; \
  83799. } while (0)
  83800. /* Assure that there are at least n bits in the bit accumulator. If there is
  83801. not enough available input to do that, then return from inflate(). */
  83802. #define NEEDBITS(n) \
  83803. do { \
  83804. while (bits < (unsigned)(n)) \
  83805. PULLBYTE(); \
  83806. } while (0)
  83807. /* Return the low n bits of the bit accumulator (n < 16) */
  83808. #define BITS(n) \
  83809. ((unsigned)hold & ((1U << (n)) - 1))
  83810. /* Remove n bits from the bit accumulator */
  83811. #define DROPBITS(n) \
  83812. do { \
  83813. hold >>= (n); \
  83814. bits -= (unsigned)(n); \
  83815. } while (0)
  83816. /* Remove zero to seven bits as needed to go to a byte boundary */
  83817. #define BYTEBITS() \
  83818. do { \
  83819. hold >>= bits & 7; \
  83820. bits -= bits & 7; \
  83821. } while (0)
  83822. /* Reverse the bytes in a 32-bit value */
  83823. #define REVERSE(q) \
  83824. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83825. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83826. /*
  83827. inflate() uses a state machine to process as much input data and generate as
  83828. much output data as possible before returning. The state machine is
  83829. structured roughly as follows:
  83830. for (;;) switch (state) {
  83831. ...
  83832. case STATEn:
  83833. if (not enough input data or output space to make progress)
  83834. return;
  83835. ... make progress ...
  83836. state = STATEm;
  83837. break;
  83838. ...
  83839. }
  83840. so when inflate() is called again, the same case is attempted again, and
  83841. if the appropriate resources are provided, the machine proceeds to the
  83842. next state. The NEEDBITS() macro is usually the way the state evaluates
  83843. whether it can proceed or should return. NEEDBITS() does the return if
  83844. the requested bits are not available. The typical use of the BITS macros
  83845. is:
  83846. NEEDBITS(n);
  83847. ... do something with BITS(n) ...
  83848. DROPBITS(n);
  83849. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83850. input left to load n bits into the accumulator, or it continues. BITS(n)
  83851. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83852. the low n bits off the accumulator. INITBITS() clears the accumulator
  83853. and sets the number of available bits to zero. BYTEBITS() discards just
  83854. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83855. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83856. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83857. if there is no input available. The decoding of variable length codes uses
  83858. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83859. code, and no more.
  83860. Some states loop until they get enough input, making sure that enough
  83861. state information is maintained to continue the loop where it left off
  83862. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83863. would all have to actually be part of the saved state in case NEEDBITS()
  83864. returns:
  83865. case STATEw:
  83866. while (want < need) {
  83867. NEEDBITS(n);
  83868. keep[want++] = BITS(n);
  83869. DROPBITS(n);
  83870. }
  83871. state = STATEx;
  83872. case STATEx:
  83873. As shown above, if the next state is also the next case, then the break
  83874. is omitted.
  83875. A state may also return if there is not enough output space available to
  83876. complete that state. Those states are copying stored data, writing a
  83877. literal byte, and copying a matching string.
  83878. When returning, a "goto inf_leave" is used to update the total counters,
  83879. update the check value, and determine whether any progress has been made
  83880. during that inflate() call in order to return the proper return code.
  83881. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83882. When there is a window, goto inf_leave will update the window with the last
  83883. output written. If a goto inf_leave occurs in the middle of decompression
  83884. and there is no window currently, goto inf_leave will create one and copy
  83885. output to the window for the next call of inflate().
  83886. In this implementation, the flush parameter of inflate() only affects the
  83887. return code (per zlib.h). inflate() always writes as much as possible to
  83888. strm->next_out, given the space available and the provided input--the effect
  83889. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83890. the allocation of and copying into a sliding window until necessary, which
  83891. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83892. stream available. So the only thing the flush parameter actually does is:
  83893. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83894. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83895. */
  83896. int ZEXPORT inflate (z_streamp strm, int flush)
  83897. {
  83898. struct inflate_state FAR *state;
  83899. unsigned char FAR *next; /* next input */
  83900. unsigned char FAR *put; /* next output */
  83901. unsigned have, left; /* available input and output */
  83902. unsigned long hold; /* bit buffer */
  83903. unsigned bits; /* bits in bit buffer */
  83904. unsigned in, out; /* save starting available input and output */
  83905. unsigned copy; /* number of stored or match bytes to copy */
  83906. unsigned char FAR *from; /* where to copy match bytes from */
  83907. code thisx; /* current decoding table entry */
  83908. code last; /* parent table entry */
  83909. unsigned len; /* length to copy for repeats, bits to drop */
  83910. int ret; /* return code */
  83911. #ifdef GUNZIP
  83912. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83913. #endif
  83914. static const unsigned short order[19] = /* permutation of code lengths */
  83915. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83916. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83917. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83918. return Z_STREAM_ERROR;
  83919. state = (struct inflate_state FAR *)strm->state;
  83920. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83921. LOAD();
  83922. in = have;
  83923. out = left;
  83924. ret = Z_OK;
  83925. for (;;)
  83926. switch (state->mode) {
  83927. case HEAD:
  83928. if (state->wrap == 0) {
  83929. state->mode = TYPEDO;
  83930. break;
  83931. }
  83932. NEEDBITS(16);
  83933. #ifdef GUNZIP
  83934. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83935. state->check = crc32(0L, Z_NULL, 0);
  83936. CRC2(state->check, hold);
  83937. INITBITS();
  83938. state->mode = FLAGS;
  83939. break;
  83940. }
  83941. state->flags = 0; /* expect zlib header */
  83942. if (state->head != Z_NULL)
  83943. state->head->done = -1;
  83944. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83945. #else
  83946. if (
  83947. #endif
  83948. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83949. strm->msg = (char *)"incorrect header check";
  83950. state->mode = BAD;
  83951. break;
  83952. }
  83953. if (BITS(4) != Z_DEFLATED) {
  83954. strm->msg = (char *)"unknown compression method";
  83955. state->mode = BAD;
  83956. break;
  83957. }
  83958. DROPBITS(4);
  83959. len = BITS(4) + 8;
  83960. if (len > state->wbits) {
  83961. strm->msg = (char *)"invalid window size";
  83962. state->mode = BAD;
  83963. break;
  83964. }
  83965. state->dmax = 1U << len;
  83966. Tracev((stderr, "inflate: zlib header ok\n"));
  83967. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83968. state->mode = hold & 0x200 ? DICTID : TYPE;
  83969. INITBITS();
  83970. break;
  83971. #ifdef GUNZIP
  83972. case FLAGS:
  83973. NEEDBITS(16);
  83974. state->flags = (int)(hold);
  83975. if ((state->flags & 0xff) != Z_DEFLATED) {
  83976. strm->msg = (char *)"unknown compression method";
  83977. state->mode = BAD;
  83978. break;
  83979. }
  83980. if (state->flags & 0xe000) {
  83981. strm->msg = (char *)"unknown header flags set";
  83982. state->mode = BAD;
  83983. break;
  83984. }
  83985. if (state->head != Z_NULL)
  83986. state->head->text = (int)((hold >> 8) & 1);
  83987. if (state->flags & 0x0200) CRC2(state->check, hold);
  83988. INITBITS();
  83989. state->mode = TIME;
  83990. case TIME:
  83991. NEEDBITS(32);
  83992. if (state->head != Z_NULL)
  83993. state->head->time = hold;
  83994. if (state->flags & 0x0200) CRC4(state->check, hold);
  83995. INITBITS();
  83996. state->mode = OS;
  83997. case OS:
  83998. NEEDBITS(16);
  83999. if (state->head != Z_NULL) {
  84000. state->head->xflags = (int)(hold & 0xff);
  84001. state->head->os = (int)(hold >> 8);
  84002. }
  84003. if (state->flags & 0x0200) CRC2(state->check, hold);
  84004. INITBITS();
  84005. state->mode = EXLEN;
  84006. case EXLEN:
  84007. if (state->flags & 0x0400) {
  84008. NEEDBITS(16);
  84009. state->length = (unsigned)(hold);
  84010. if (state->head != Z_NULL)
  84011. state->head->extra_len = (unsigned)hold;
  84012. if (state->flags & 0x0200) CRC2(state->check, hold);
  84013. INITBITS();
  84014. }
  84015. else if (state->head != Z_NULL)
  84016. state->head->extra = Z_NULL;
  84017. state->mode = EXTRA;
  84018. case EXTRA:
  84019. if (state->flags & 0x0400) {
  84020. copy = state->length;
  84021. if (copy > have) copy = have;
  84022. if (copy) {
  84023. if (state->head != Z_NULL &&
  84024. state->head->extra != Z_NULL) {
  84025. len = state->head->extra_len - state->length;
  84026. zmemcpy(state->head->extra + len, next,
  84027. len + copy > state->head->extra_max ?
  84028. state->head->extra_max - len : copy);
  84029. }
  84030. if (state->flags & 0x0200)
  84031. state->check = crc32(state->check, next, copy);
  84032. have -= copy;
  84033. next += copy;
  84034. state->length -= copy;
  84035. }
  84036. if (state->length) goto inf_leave;
  84037. }
  84038. state->length = 0;
  84039. state->mode = NAME;
  84040. case NAME:
  84041. if (state->flags & 0x0800) {
  84042. if (have == 0) goto inf_leave;
  84043. copy = 0;
  84044. do {
  84045. len = (unsigned)(next[copy++]);
  84046. if (state->head != Z_NULL &&
  84047. state->head->name != Z_NULL &&
  84048. state->length < state->head->name_max)
  84049. state->head->name[state->length++] = len;
  84050. } while (len && copy < have);
  84051. if (state->flags & 0x0200)
  84052. state->check = crc32(state->check, next, copy);
  84053. have -= copy;
  84054. next += copy;
  84055. if (len) goto inf_leave;
  84056. }
  84057. else if (state->head != Z_NULL)
  84058. state->head->name = Z_NULL;
  84059. state->length = 0;
  84060. state->mode = COMMENT;
  84061. case COMMENT:
  84062. if (state->flags & 0x1000) {
  84063. if (have == 0) goto inf_leave;
  84064. copy = 0;
  84065. do {
  84066. len = (unsigned)(next[copy++]);
  84067. if (state->head != Z_NULL &&
  84068. state->head->comment != Z_NULL &&
  84069. state->length < state->head->comm_max)
  84070. state->head->comment[state->length++] = len;
  84071. } while (len && copy < have);
  84072. if (state->flags & 0x0200)
  84073. state->check = crc32(state->check, next, copy);
  84074. have -= copy;
  84075. next += copy;
  84076. if (len) goto inf_leave;
  84077. }
  84078. else if (state->head != Z_NULL)
  84079. state->head->comment = Z_NULL;
  84080. state->mode = HCRC;
  84081. case HCRC:
  84082. if (state->flags & 0x0200) {
  84083. NEEDBITS(16);
  84084. if (hold != (state->check & 0xffff)) {
  84085. strm->msg = (char *)"header crc mismatch";
  84086. state->mode = BAD;
  84087. break;
  84088. }
  84089. INITBITS();
  84090. }
  84091. if (state->head != Z_NULL) {
  84092. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84093. state->head->done = 1;
  84094. }
  84095. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84096. state->mode = TYPE;
  84097. break;
  84098. #endif
  84099. case DICTID:
  84100. NEEDBITS(32);
  84101. strm->adler = state->check = REVERSE(hold);
  84102. INITBITS();
  84103. state->mode = DICT;
  84104. case DICT:
  84105. if (state->havedict == 0) {
  84106. RESTORE();
  84107. return Z_NEED_DICT;
  84108. }
  84109. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84110. state->mode = TYPE;
  84111. case TYPE:
  84112. if (flush == Z_BLOCK) goto inf_leave;
  84113. case TYPEDO:
  84114. if (state->last) {
  84115. BYTEBITS();
  84116. state->mode = CHECK;
  84117. break;
  84118. }
  84119. NEEDBITS(3);
  84120. state->last = BITS(1);
  84121. DROPBITS(1);
  84122. switch (BITS(2)) {
  84123. case 0: /* stored block */
  84124. Tracev((stderr, "inflate: stored block%s\n",
  84125. state->last ? " (last)" : ""));
  84126. state->mode = STORED;
  84127. break;
  84128. case 1: /* fixed block */
  84129. fixedtables(state);
  84130. Tracev((stderr, "inflate: fixed codes block%s\n",
  84131. state->last ? " (last)" : ""));
  84132. state->mode = LEN; /* decode codes */
  84133. break;
  84134. case 2: /* dynamic block */
  84135. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84136. state->last ? " (last)" : ""));
  84137. state->mode = TABLE;
  84138. break;
  84139. case 3:
  84140. strm->msg = (char *)"invalid block type";
  84141. state->mode = BAD;
  84142. }
  84143. DROPBITS(2);
  84144. break;
  84145. case STORED:
  84146. BYTEBITS(); /* go to byte boundary */
  84147. NEEDBITS(32);
  84148. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84149. strm->msg = (char *)"invalid stored block lengths";
  84150. state->mode = BAD;
  84151. break;
  84152. }
  84153. state->length = (unsigned)hold & 0xffff;
  84154. Tracev((stderr, "inflate: stored length %u\n",
  84155. state->length));
  84156. INITBITS();
  84157. state->mode = COPY;
  84158. case COPY:
  84159. copy = state->length;
  84160. if (copy) {
  84161. if (copy > have) copy = have;
  84162. if (copy > left) copy = left;
  84163. if (copy == 0) goto inf_leave;
  84164. zmemcpy(put, next, copy);
  84165. have -= copy;
  84166. next += copy;
  84167. left -= copy;
  84168. put += copy;
  84169. state->length -= copy;
  84170. break;
  84171. }
  84172. Tracev((stderr, "inflate: stored end\n"));
  84173. state->mode = TYPE;
  84174. break;
  84175. case TABLE:
  84176. NEEDBITS(14);
  84177. state->nlen = BITS(5) + 257;
  84178. DROPBITS(5);
  84179. state->ndist = BITS(5) + 1;
  84180. DROPBITS(5);
  84181. state->ncode = BITS(4) + 4;
  84182. DROPBITS(4);
  84183. #ifndef PKZIP_BUG_WORKAROUND
  84184. if (state->nlen > 286 || state->ndist > 30) {
  84185. strm->msg = (char *)"too many length or distance symbols";
  84186. state->mode = BAD;
  84187. break;
  84188. }
  84189. #endif
  84190. Tracev((stderr, "inflate: table sizes ok\n"));
  84191. state->have = 0;
  84192. state->mode = LENLENS;
  84193. case LENLENS:
  84194. while (state->have < state->ncode) {
  84195. NEEDBITS(3);
  84196. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84197. DROPBITS(3);
  84198. }
  84199. while (state->have < 19)
  84200. state->lens[order[state->have++]] = 0;
  84201. state->next = state->codes;
  84202. state->lencode = (code const FAR *)(state->next);
  84203. state->lenbits = 7;
  84204. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84205. &(state->lenbits), state->work);
  84206. if (ret) {
  84207. strm->msg = (char *)"invalid code lengths set";
  84208. state->mode = BAD;
  84209. break;
  84210. }
  84211. Tracev((stderr, "inflate: code lengths ok\n"));
  84212. state->have = 0;
  84213. state->mode = CODELENS;
  84214. case CODELENS:
  84215. while (state->have < state->nlen + state->ndist) {
  84216. for (;;) {
  84217. thisx = state->lencode[BITS(state->lenbits)];
  84218. if ((unsigned)(thisx.bits) <= bits) break;
  84219. PULLBYTE();
  84220. }
  84221. if (thisx.val < 16) {
  84222. NEEDBITS(thisx.bits);
  84223. DROPBITS(thisx.bits);
  84224. state->lens[state->have++] = thisx.val;
  84225. }
  84226. else {
  84227. if (thisx.val == 16) {
  84228. NEEDBITS(thisx.bits + 2);
  84229. DROPBITS(thisx.bits);
  84230. if (state->have == 0) {
  84231. strm->msg = (char *)"invalid bit length repeat";
  84232. state->mode = BAD;
  84233. break;
  84234. }
  84235. len = state->lens[state->have - 1];
  84236. copy = 3 + BITS(2);
  84237. DROPBITS(2);
  84238. }
  84239. else if (thisx.val == 17) {
  84240. NEEDBITS(thisx.bits + 3);
  84241. DROPBITS(thisx.bits);
  84242. len = 0;
  84243. copy = 3 + BITS(3);
  84244. DROPBITS(3);
  84245. }
  84246. else {
  84247. NEEDBITS(thisx.bits + 7);
  84248. DROPBITS(thisx.bits);
  84249. len = 0;
  84250. copy = 11 + BITS(7);
  84251. DROPBITS(7);
  84252. }
  84253. if (state->have + copy > state->nlen + state->ndist) {
  84254. strm->msg = (char *)"invalid bit length repeat";
  84255. state->mode = BAD;
  84256. break;
  84257. }
  84258. while (copy--)
  84259. state->lens[state->have++] = (unsigned short)len;
  84260. }
  84261. }
  84262. /* handle error breaks in while */
  84263. if (state->mode == BAD) break;
  84264. /* build code tables */
  84265. state->next = state->codes;
  84266. state->lencode = (code const FAR *)(state->next);
  84267. state->lenbits = 9;
  84268. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84269. &(state->lenbits), state->work);
  84270. if (ret) {
  84271. strm->msg = (char *)"invalid literal/lengths set";
  84272. state->mode = BAD;
  84273. break;
  84274. }
  84275. state->distcode = (code const FAR *)(state->next);
  84276. state->distbits = 6;
  84277. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84278. &(state->next), &(state->distbits), state->work);
  84279. if (ret) {
  84280. strm->msg = (char *)"invalid distances set";
  84281. state->mode = BAD;
  84282. break;
  84283. }
  84284. Tracev((stderr, "inflate: codes ok\n"));
  84285. state->mode = LEN;
  84286. case LEN:
  84287. if (have >= 6 && left >= 258) {
  84288. RESTORE();
  84289. inflate_fast(strm, out);
  84290. LOAD();
  84291. break;
  84292. }
  84293. for (;;) {
  84294. thisx = state->lencode[BITS(state->lenbits)];
  84295. if ((unsigned)(thisx.bits) <= bits) break;
  84296. PULLBYTE();
  84297. }
  84298. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84299. last = thisx;
  84300. for (;;) {
  84301. thisx = state->lencode[last.val +
  84302. (BITS(last.bits + last.op) >> last.bits)];
  84303. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84304. PULLBYTE();
  84305. }
  84306. DROPBITS(last.bits);
  84307. }
  84308. DROPBITS(thisx.bits);
  84309. state->length = (unsigned)thisx.val;
  84310. if ((int)(thisx.op) == 0) {
  84311. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84312. "inflate: literal '%c'\n" :
  84313. "inflate: literal 0x%02x\n", thisx.val));
  84314. state->mode = LIT;
  84315. break;
  84316. }
  84317. if (thisx.op & 32) {
  84318. Tracevv((stderr, "inflate: end of block\n"));
  84319. state->mode = TYPE;
  84320. break;
  84321. }
  84322. if (thisx.op & 64) {
  84323. strm->msg = (char *)"invalid literal/length code";
  84324. state->mode = BAD;
  84325. break;
  84326. }
  84327. state->extra = (unsigned)(thisx.op) & 15;
  84328. state->mode = LENEXT;
  84329. case LENEXT:
  84330. if (state->extra) {
  84331. NEEDBITS(state->extra);
  84332. state->length += BITS(state->extra);
  84333. DROPBITS(state->extra);
  84334. }
  84335. Tracevv((stderr, "inflate: length %u\n", state->length));
  84336. state->mode = DIST;
  84337. case DIST:
  84338. for (;;) {
  84339. thisx = state->distcode[BITS(state->distbits)];
  84340. if ((unsigned)(thisx.bits) <= bits) break;
  84341. PULLBYTE();
  84342. }
  84343. if ((thisx.op & 0xf0) == 0) {
  84344. last = thisx;
  84345. for (;;) {
  84346. thisx = state->distcode[last.val +
  84347. (BITS(last.bits + last.op) >> last.bits)];
  84348. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84349. PULLBYTE();
  84350. }
  84351. DROPBITS(last.bits);
  84352. }
  84353. DROPBITS(thisx.bits);
  84354. if (thisx.op & 64) {
  84355. strm->msg = (char *)"invalid distance code";
  84356. state->mode = BAD;
  84357. break;
  84358. }
  84359. state->offset = (unsigned)thisx.val;
  84360. state->extra = (unsigned)(thisx.op) & 15;
  84361. state->mode = DISTEXT;
  84362. case DISTEXT:
  84363. if (state->extra) {
  84364. NEEDBITS(state->extra);
  84365. state->offset += BITS(state->extra);
  84366. DROPBITS(state->extra);
  84367. }
  84368. #ifdef INFLATE_STRICT
  84369. if (state->offset > state->dmax) {
  84370. strm->msg = (char *)"invalid distance too far back";
  84371. state->mode = BAD;
  84372. break;
  84373. }
  84374. #endif
  84375. if (state->offset > state->whave + out - left) {
  84376. strm->msg = (char *)"invalid distance too far back";
  84377. state->mode = BAD;
  84378. break;
  84379. }
  84380. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84381. state->mode = MATCH;
  84382. case MATCH:
  84383. if (left == 0) goto inf_leave;
  84384. copy = out - left;
  84385. if (state->offset > copy) { /* copy from window */
  84386. copy = state->offset - copy;
  84387. if (copy > state->write) {
  84388. copy -= state->write;
  84389. from = state->window + (state->wsize - copy);
  84390. }
  84391. else
  84392. from = state->window + (state->write - copy);
  84393. if (copy > state->length) copy = state->length;
  84394. }
  84395. else { /* copy from output */
  84396. from = put - state->offset;
  84397. copy = state->length;
  84398. }
  84399. if (copy > left) copy = left;
  84400. left -= copy;
  84401. state->length -= copy;
  84402. do {
  84403. *put++ = *from++;
  84404. } while (--copy);
  84405. if (state->length == 0) state->mode = LEN;
  84406. break;
  84407. case LIT:
  84408. if (left == 0) goto inf_leave;
  84409. *put++ = (unsigned char)(state->length);
  84410. left--;
  84411. state->mode = LEN;
  84412. break;
  84413. case CHECK:
  84414. if (state->wrap) {
  84415. NEEDBITS(32);
  84416. out -= left;
  84417. strm->total_out += out;
  84418. state->total += out;
  84419. if (out)
  84420. strm->adler = state->check =
  84421. UPDATE(state->check, put - out, out);
  84422. out = left;
  84423. if ((
  84424. #ifdef GUNZIP
  84425. state->flags ? hold :
  84426. #endif
  84427. REVERSE(hold)) != state->check) {
  84428. strm->msg = (char *)"incorrect data check";
  84429. state->mode = BAD;
  84430. break;
  84431. }
  84432. INITBITS();
  84433. Tracev((stderr, "inflate: check matches trailer\n"));
  84434. }
  84435. #ifdef GUNZIP
  84436. state->mode = LENGTH;
  84437. case LENGTH:
  84438. if (state->wrap && state->flags) {
  84439. NEEDBITS(32);
  84440. if (hold != (state->total & 0xffffffffUL)) {
  84441. strm->msg = (char *)"incorrect length check";
  84442. state->mode = BAD;
  84443. break;
  84444. }
  84445. INITBITS();
  84446. Tracev((stderr, "inflate: length matches trailer\n"));
  84447. }
  84448. #endif
  84449. state->mode = DONE;
  84450. case DONE:
  84451. ret = Z_STREAM_END;
  84452. goto inf_leave;
  84453. case BAD:
  84454. ret = Z_DATA_ERROR;
  84455. goto inf_leave;
  84456. case MEM:
  84457. return Z_MEM_ERROR;
  84458. case SYNC:
  84459. default:
  84460. return Z_STREAM_ERROR;
  84461. }
  84462. /*
  84463. Return from inflate(), updating the total counts and the check value.
  84464. If there was no progress during the inflate() call, return a buffer
  84465. error. Call updatewindow() to create and/or update the window state.
  84466. Note: a memory error from inflate() is non-recoverable.
  84467. */
  84468. inf_leave:
  84469. RESTORE();
  84470. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84471. if (updatewindow(strm, out)) {
  84472. state->mode = MEM;
  84473. return Z_MEM_ERROR;
  84474. }
  84475. in -= strm->avail_in;
  84476. out -= strm->avail_out;
  84477. strm->total_in += in;
  84478. strm->total_out += out;
  84479. state->total += out;
  84480. if (state->wrap && out)
  84481. strm->adler = state->check =
  84482. UPDATE(state->check, strm->next_out - out, out);
  84483. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84484. (state->mode == TYPE ? 128 : 0);
  84485. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84486. ret = Z_BUF_ERROR;
  84487. return ret;
  84488. }
  84489. int ZEXPORT inflateEnd (z_streamp strm)
  84490. {
  84491. struct inflate_state FAR *state;
  84492. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84493. return Z_STREAM_ERROR;
  84494. state = (struct inflate_state FAR *)strm->state;
  84495. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84496. ZFREE(strm, strm->state);
  84497. strm->state = Z_NULL;
  84498. Tracev((stderr, "inflate: end\n"));
  84499. return Z_OK;
  84500. }
  84501. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84502. {
  84503. struct inflate_state FAR *state;
  84504. unsigned long id_;
  84505. /* check state */
  84506. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84507. state = (struct inflate_state FAR *)strm->state;
  84508. if (state->wrap != 0 && state->mode != DICT)
  84509. return Z_STREAM_ERROR;
  84510. /* check for correct dictionary id */
  84511. if (state->mode == DICT) {
  84512. id_ = adler32(0L, Z_NULL, 0);
  84513. id_ = adler32(id_, dictionary, dictLength);
  84514. if (id_ != state->check)
  84515. return Z_DATA_ERROR;
  84516. }
  84517. /* copy dictionary to window */
  84518. if (updatewindow(strm, strm->avail_out)) {
  84519. state->mode = MEM;
  84520. return Z_MEM_ERROR;
  84521. }
  84522. if (dictLength > state->wsize) {
  84523. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84524. state->wsize);
  84525. state->whave = state->wsize;
  84526. }
  84527. else {
  84528. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84529. dictLength);
  84530. state->whave = dictLength;
  84531. }
  84532. state->havedict = 1;
  84533. Tracev((stderr, "inflate: dictionary set\n"));
  84534. return Z_OK;
  84535. }
  84536. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84537. {
  84538. struct inflate_state FAR *state;
  84539. /* check state */
  84540. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84541. state = (struct inflate_state FAR *)strm->state;
  84542. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84543. /* save header structure */
  84544. state->head = head;
  84545. head->done = 0;
  84546. return Z_OK;
  84547. }
  84548. /*
  84549. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84550. or when out of input. When called, *have is the number of pattern bytes
  84551. found in order so far, in 0..3. On return *have is updated to the new
  84552. state. If on return *have equals four, then the pattern was found and the
  84553. return value is how many bytes were read including the last byte of the
  84554. pattern. If *have is less than four, then the pattern has not been found
  84555. yet and the return value is len. In the latter case, syncsearch() can be
  84556. called again with more data and the *have state. *have is initialized to
  84557. zero for the first call.
  84558. */
  84559. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84560. {
  84561. unsigned got;
  84562. unsigned next;
  84563. got = *have;
  84564. next = 0;
  84565. while (next < len && got < 4) {
  84566. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84567. got++;
  84568. else if (buf[next])
  84569. got = 0;
  84570. else
  84571. got = 4 - got;
  84572. next++;
  84573. }
  84574. *have = got;
  84575. return next;
  84576. }
  84577. int ZEXPORT inflateSync (z_streamp strm)
  84578. {
  84579. unsigned len; /* number of bytes to look at or looked at */
  84580. unsigned long in, out; /* temporary to save total_in and total_out */
  84581. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84582. struct inflate_state FAR *state;
  84583. /* check parameters */
  84584. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84585. state = (struct inflate_state FAR *)strm->state;
  84586. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84587. /* if first time, start search in bit buffer */
  84588. if (state->mode != SYNC) {
  84589. state->mode = SYNC;
  84590. state->hold <<= state->bits & 7;
  84591. state->bits -= state->bits & 7;
  84592. len = 0;
  84593. while (state->bits >= 8) {
  84594. buf[len++] = (unsigned char)(state->hold);
  84595. state->hold >>= 8;
  84596. state->bits -= 8;
  84597. }
  84598. state->have = 0;
  84599. syncsearch(&(state->have), buf, len);
  84600. }
  84601. /* search available input */
  84602. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84603. strm->avail_in -= len;
  84604. strm->next_in += len;
  84605. strm->total_in += len;
  84606. /* return no joy or set up to restart inflate() on a new block */
  84607. if (state->have != 4) return Z_DATA_ERROR;
  84608. in = strm->total_in; out = strm->total_out;
  84609. inflateReset(strm);
  84610. strm->total_in = in; strm->total_out = out;
  84611. state->mode = TYPE;
  84612. return Z_OK;
  84613. }
  84614. /*
  84615. Returns true if inflate is currently at the end of a block generated by
  84616. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84617. implementation to provide an additional safety check. PPP uses
  84618. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84619. block. When decompressing, PPP checks that at the end of input packet,
  84620. inflate is waiting for these length bytes.
  84621. */
  84622. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84623. {
  84624. struct inflate_state FAR *state;
  84625. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84626. state = (struct inflate_state FAR *)strm->state;
  84627. return state->mode == STORED && state->bits == 0;
  84628. }
  84629. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84630. {
  84631. struct inflate_state FAR *state;
  84632. struct inflate_state FAR *copy;
  84633. unsigned char FAR *window;
  84634. unsigned wsize;
  84635. /* check input */
  84636. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84637. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84638. return Z_STREAM_ERROR;
  84639. state = (struct inflate_state FAR *)source->state;
  84640. /* allocate space */
  84641. copy = (struct inflate_state FAR *)
  84642. ZALLOC(source, 1, sizeof(struct inflate_state));
  84643. if (copy == Z_NULL) return Z_MEM_ERROR;
  84644. window = Z_NULL;
  84645. if (state->window != Z_NULL) {
  84646. window = (unsigned char FAR *)
  84647. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84648. if (window == Z_NULL) {
  84649. ZFREE(source, copy);
  84650. return Z_MEM_ERROR;
  84651. }
  84652. }
  84653. /* copy state */
  84654. zmemcpy(dest, source, sizeof(z_stream));
  84655. zmemcpy(copy, state, sizeof(struct inflate_state));
  84656. if (state->lencode >= state->codes &&
  84657. state->lencode <= state->codes + ENOUGH - 1) {
  84658. copy->lencode = copy->codes + (state->lencode - state->codes);
  84659. copy->distcode = copy->codes + (state->distcode - state->codes);
  84660. }
  84661. copy->next = copy->codes + (state->next - state->codes);
  84662. if (window != Z_NULL) {
  84663. wsize = 1U << state->wbits;
  84664. zmemcpy(window, state->window, wsize);
  84665. }
  84666. copy->window = window;
  84667. dest->state = (struct internal_state FAR *)copy;
  84668. return Z_OK;
  84669. }
  84670. /*** End of inlined file: inflate.c ***/
  84671. /*** Start of inlined file: inftrees.c ***/
  84672. #define MAXBITS 15
  84673. const char inflate_copyright[] =
  84674. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84675. /*
  84676. If you use the zlib library in a product, an acknowledgment is welcome
  84677. in the documentation of your product. If for some reason you cannot
  84678. include such an acknowledgment, I would appreciate that you keep this
  84679. copyright string in the executable of your product.
  84680. */
  84681. /*
  84682. Build a set of tables to decode the provided canonical Huffman code.
  84683. The code lengths are lens[0..codes-1]. The result starts at *table,
  84684. whose indices are 0..2^bits-1. work is a writable array of at least
  84685. lens shorts, which is used as a work area. type is the type of code
  84686. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84687. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84688. on return points to the next available entry's address. bits is the
  84689. requested root table index bits, and on return it is the actual root
  84690. table index bits. It will differ if the request is greater than the
  84691. longest code or if it is less than the shortest code.
  84692. */
  84693. int inflate_table (codetype type,
  84694. unsigned short FAR *lens,
  84695. unsigned codes,
  84696. code FAR * FAR *table,
  84697. unsigned FAR *bits,
  84698. unsigned short FAR *work)
  84699. {
  84700. unsigned len; /* a code's length in bits */
  84701. unsigned sym; /* index of code symbols */
  84702. unsigned min, max; /* minimum and maximum code lengths */
  84703. unsigned root; /* number of index bits for root table */
  84704. unsigned curr; /* number of index bits for current table */
  84705. unsigned drop; /* code bits to drop for sub-table */
  84706. int left; /* number of prefix codes available */
  84707. unsigned used; /* code entries in table used */
  84708. unsigned huff; /* Huffman code */
  84709. unsigned incr; /* for incrementing code, index */
  84710. unsigned fill; /* index for replicating entries */
  84711. unsigned low; /* low bits for current root entry */
  84712. unsigned mask; /* mask for low root bits */
  84713. code thisx; /* table entry for duplication */
  84714. code FAR *next; /* next available space in table */
  84715. const unsigned short FAR *base; /* base value table to use */
  84716. const unsigned short FAR *extra; /* extra bits table to use */
  84717. int end; /* use base and extra for symbol > end */
  84718. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84719. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84720. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84721. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84722. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84723. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84724. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84725. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84726. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84727. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84728. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84729. 8193, 12289, 16385, 24577, 0, 0};
  84730. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84731. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84732. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84733. 28, 28, 29, 29, 64, 64};
  84734. /*
  84735. Process a set of code lengths to create a canonical Huffman code. The
  84736. code lengths are lens[0..codes-1]. Each length corresponds to the
  84737. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84738. symbols by length from short to long, and retaining the symbol order
  84739. for codes with equal lengths. Then the code starts with all zero bits
  84740. for the first code of the shortest length, and the codes are integer
  84741. increments for the same length, and zeros are appended as the length
  84742. increases. For the deflate format, these bits are stored backwards
  84743. from their more natural integer increment ordering, and so when the
  84744. decoding tables are built in the large loop below, the integer codes
  84745. are incremented backwards.
  84746. This routine assumes, but does not check, that all of the entries in
  84747. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84748. 1..MAXBITS is interpreted as that code length. zero means that that
  84749. symbol does not occur in this code.
  84750. The codes are sorted by computing a count of codes for each length,
  84751. creating from that a table of starting indices for each length in the
  84752. sorted table, and then entering the symbols in order in the sorted
  84753. table. The sorted table is work[], with that space being provided by
  84754. the caller.
  84755. The length counts are used for other purposes as well, i.e. finding
  84756. the minimum and maximum length codes, determining if there are any
  84757. codes at all, checking for a valid set of lengths, and looking ahead
  84758. at length counts to determine sub-table sizes when building the
  84759. decoding tables.
  84760. */
  84761. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84762. for (len = 0; len <= MAXBITS; len++)
  84763. count[len] = 0;
  84764. for (sym = 0; sym < codes; sym++)
  84765. count[lens[sym]]++;
  84766. /* bound code lengths, force root to be within code lengths */
  84767. root = *bits;
  84768. for (max = MAXBITS; max >= 1; max--)
  84769. if (count[max] != 0) break;
  84770. if (root > max) root = max;
  84771. if (max == 0) { /* no symbols to code at all */
  84772. thisx.op = (unsigned char)64; /* invalid code marker */
  84773. thisx.bits = (unsigned char)1;
  84774. thisx.val = (unsigned short)0;
  84775. *(*table)++ = thisx; /* make a table to force an error */
  84776. *(*table)++ = thisx;
  84777. *bits = 1;
  84778. return 0; /* no symbols, but wait for decoding to report error */
  84779. }
  84780. for (min = 1; min <= MAXBITS; min++)
  84781. if (count[min] != 0) break;
  84782. if (root < min) root = min;
  84783. /* check for an over-subscribed or incomplete set of lengths */
  84784. left = 1;
  84785. for (len = 1; len <= MAXBITS; len++) {
  84786. left <<= 1;
  84787. left -= count[len];
  84788. if (left < 0) return -1; /* over-subscribed */
  84789. }
  84790. if (left > 0 && (type == CODES || max != 1))
  84791. return -1; /* incomplete set */
  84792. /* generate offsets into symbol table for each length for sorting */
  84793. offs[1] = 0;
  84794. for (len = 1; len < MAXBITS; len++)
  84795. offs[len + 1] = offs[len] + count[len];
  84796. /* sort symbols by length, by symbol order within each length */
  84797. for (sym = 0; sym < codes; sym++)
  84798. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84799. /*
  84800. Create and fill in decoding tables. In this loop, the table being
  84801. filled is at next and has curr index bits. The code being used is huff
  84802. with length len. That code is converted to an index by dropping drop
  84803. bits off of the bottom. For codes where len is less than drop + curr,
  84804. those top drop + curr - len bits are incremented through all values to
  84805. fill the table with replicated entries.
  84806. root is the number of index bits for the root table. When len exceeds
  84807. root, sub-tables are created pointed to by the root entry with an index
  84808. of the low root bits of huff. This is saved in low to check for when a
  84809. new sub-table should be started. drop is zero when the root table is
  84810. being filled, and drop is root when sub-tables are being filled.
  84811. When a new sub-table is needed, it is necessary to look ahead in the
  84812. code lengths to determine what size sub-table is needed. The length
  84813. counts are used for this, and so count[] is decremented as codes are
  84814. entered in the tables.
  84815. used keeps track of how many table entries have been allocated from the
  84816. provided *table space. It is checked when a LENS table is being made
  84817. against the space in *table, ENOUGH, minus the maximum space needed by
  84818. the worst case distance code, MAXD. This should never happen, but the
  84819. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84820. This assumes that when type == LENS, bits == 9.
  84821. sym increments through all symbols, and the loop terminates when
  84822. all codes of length max, i.e. all codes, have been processed. This
  84823. routine permits incomplete codes, so another loop after this one fills
  84824. in the rest of the decoding tables with invalid code markers.
  84825. */
  84826. /* set up for code type */
  84827. switch (type) {
  84828. case CODES:
  84829. base = extra = work; /* dummy value--not used */
  84830. end = 19;
  84831. break;
  84832. case LENS:
  84833. base = lbase;
  84834. base -= 257;
  84835. extra = lext;
  84836. extra -= 257;
  84837. end = 256;
  84838. break;
  84839. default: /* DISTS */
  84840. base = dbase;
  84841. extra = dext;
  84842. end = -1;
  84843. }
  84844. /* initialize state for loop */
  84845. huff = 0; /* starting code */
  84846. sym = 0; /* starting code symbol */
  84847. len = min; /* starting code length */
  84848. next = *table; /* current table to fill in */
  84849. curr = root; /* current table index bits */
  84850. drop = 0; /* current bits to drop from code for index */
  84851. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84852. used = 1U << root; /* use root table entries */
  84853. mask = used - 1; /* mask for comparing low */
  84854. /* check available table space */
  84855. if (type == LENS && used >= ENOUGH - MAXD)
  84856. return 1;
  84857. /* process all codes and make table entries */
  84858. for (;;) {
  84859. /* create table entry */
  84860. thisx.bits = (unsigned char)(len - drop);
  84861. if ((int)(work[sym]) < end) {
  84862. thisx.op = (unsigned char)0;
  84863. thisx.val = work[sym];
  84864. }
  84865. else if ((int)(work[sym]) > end) {
  84866. thisx.op = (unsigned char)(extra[work[sym]]);
  84867. thisx.val = base[work[sym]];
  84868. }
  84869. else {
  84870. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84871. thisx.val = 0;
  84872. }
  84873. /* replicate for those indices with low len bits equal to huff */
  84874. incr = 1U << (len - drop);
  84875. fill = 1U << curr;
  84876. min = fill; /* save offset to next table */
  84877. do {
  84878. fill -= incr;
  84879. next[(huff >> drop) + fill] = thisx;
  84880. } while (fill != 0);
  84881. /* backwards increment the len-bit code huff */
  84882. incr = 1U << (len - 1);
  84883. while (huff & incr)
  84884. incr >>= 1;
  84885. if (incr != 0) {
  84886. huff &= incr - 1;
  84887. huff += incr;
  84888. }
  84889. else
  84890. huff = 0;
  84891. /* go to next symbol, update count, len */
  84892. sym++;
  84893. if (--(count[len]) == 0) {
  84894. if (len == max) break;
  84895. len = lens[work[sym]];
  84896. }
  84897. /* create new sub-table if needed */
  84898. if (len > root && (huff & mask) != low) {
  84899. /* if first time, transition to sub-tables */
  84900. if (drop == 0)
  84901. drop = root;
  84902. /* increment past last table */
  84903. next += min; /* here min is 1 << curr */
  84904. /* determine length of next table */
  84905. curr = len - drop;
  84906. left = (int)(1 << curr);
  84907. while (curr + drop < max) {
  84908. left -= count[curr + drop];
  84909. if (left <= 0) break;
  84910. curr++;
  84911. left <<= 1;
  84912. }
  84913. /* check for enough space */
  84914. used += 1U << curr;
  84915. if (type == LENS && used >= ENOUGH - MAXD)
  84916. return 1;
  84917. /* point entry in root table to sub-table */
  84918. low = huff & mask;
  84919. (*table)[low].op = (unsigned char)curr;
  84920. (*table)[low].bits = (unsigned char)root;
  84921. (*table)[low].val = (unsigned short)(next - *table);
  84922. }
  84923. }
  84924. /*
  84925. Fill in rest of table for incomplete codes. This loop is similar to the
  84926. loop above in incrementing huff for table indices. It is assumed that
  84927. len is equal to curr + drop, so there is no loop needed to increment
  84928. through high index bits. When the current sub-table is filled, the loop
  84929. drops back to the root table to fill in any remaining entries there.
  84930. */
  84931. thisx.op = (unsigned char)64; /* invalid code marker */
  84932. thisx.bits = (unsigned char)(len - drop);
  84933. thisx.val = (unsigned short)0;
  84934. while (huff != 0) {
  84935. /* when done with sub-table, drop back to root table */
  84936. if (drop != 0 && (huff & mask) != low) {
  84937. drop = 0;
  84938. len = root;
  84939. next = *table;
  84940. thisx.bits = (unsigned char)len;
  84941. }
  84942. /* put invalid code marker in table */
  84943. next[huff >> drop] = thisx;
  84944. /* backwards increment the len-bit code huff */
  84945. incr = 1U << (len - 1);
  84946. while (huff & incr)
  84947. incr >>= 1;
  84948. if (incr != 0) {
  84949. huff &= incr - 1;
  84950. huff += incr;
  84951. }
  84952. else
  84953. huff = 0;
  84954. }
  84955. /* set return parameters */
  84956. *table += used;
  84957. *bits = root;
  84958. return 0;
  84959. }
  84960. /*** End of inlined file: inftrees.c ***/
  84961. /*** Start of inlined file: trees.c ***/
  84962. /*
  84963. * ALGORITHM
  84964. *
  84965. * The "deflation" process uses several Huffman trees. The more
  84966. * common source values are represented by shorter bit sequences.
  84967. *
  84968. * Each code tree is stored in a compressed form which is itself
  84969. * a Huffman encoding of the lengths of all the code strings (in
  84970. * ascending order by source values). The actual code strings are
  84971. * reconstructed from the lengths in the inflate process, as described
  84972. * in the deflate specification.
  84973. *
  84974. * REFERENCES
  84975. *
  84976. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84977. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84978. *
  84979. * Storer, James A.
  84980. * Data Compression: Methods and Theory, pp. 49-50.
  84981. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84982. *
  84983. * Sedgewick, R.
  84984. * Algorithms, p290.
  84985. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84986. */
  84987. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84988. /* #define GEN_TREES_H */
  84989. #ifdef DEBUG
  84990. # include <ctype.h>
  84991. #endif
  84992. /* ===========================================================================
  84993. * Constants
  84994. */
  84995. #define MAX_BL_BITS 7
  84996. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84997. #define END_BLOCK 256
  84998. /* end of block literal code */
  84999. #define REP_3_6 16
  85000. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  85001. #define REPZ_3_10 17
  85002. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  85003. #define REPZ_11_138 18
  85004. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  85005. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  85006. = {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};
  85007. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  85008. = {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};
  85009. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  85010. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  85011. local const uch bl_order[BL_CODES]
  85012. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  85013. /* The lengths of the bit length codes are sent in order of decreasing
  85014. * probability, to avoid transmitting the lengths for unused bit length codes.
  85015. */
  85016. #define Buf_size (8 * 2*sizeof(char))
  85017. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  85018. * more than 16 bits on some systems.)
  85019. */
  85020. /* ===========================================================================
  85021. * Local data. These are initialized only once.
  85022. */
  85023. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  85024. #if defined(GEN_TREES_H) || !defined(STDC)
  85025. /* non ANSI compilers may not accept trees.h */
  85026. local ct_data static_ltree[L_CODES+2];
  85027. /* The static literal tree. Since the bit lengths are imposed, there is no
  85028. * need for the L_CODES extra codes used during heap construction. However
  85029. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  85030. * below).
  85031. */
  85032. local ct_data static_dtree[D_CODES];
  85033. /* The static distance tree. (Actually a trivial tree since all codes use
  85034. * 5 bits.)
  85035. */
  85036. uch _dist_code[DIST_CODE_LEN];
  85037. /* Distance codes. The first 256 values correspond to the distances
  85038. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85039. * the 15 bit distances.
  85040. */
  85041. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  85042. /* length code for each normalized match length (0 == MIN_MATCH) */
  85043. local int base_length[LENGTH_CODES];
  85044. /* First normalized length for each code (0 = MIN_MATCH) */
  85045. local int base_dist[D_CODES];
  85046. /* First normalized distance for each code (0 = distance of 1) */
  85047. #else
  85048. /*** Start of inlined file: trees.h ***/
  85049. local const ct_data static_ltree[L_CODES+2] = {
  85050. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  85051. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  85052. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  85053. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  85054. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  85055. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  85056. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  85057. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  85058. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  85059. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  85060. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  85061. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  85062. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85063. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85064. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85065. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85066. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85067. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85068. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85069. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85070. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85071. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85072. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85073. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85074. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85075. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85076. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85077. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85078. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85079. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85080. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85081. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85082. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85083. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85084. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85085. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85086. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85087. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85088. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85089. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85090. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85091. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85092. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85093. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85094. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85095. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85096. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85097. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85098. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85099. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85100. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85101. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85102. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85103. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85104. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85105. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85106. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85107. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85108. };
  85109. local const ct_data static_dtree[D_CODES] = {
  85110. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85111. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85112. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85113. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85114. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85115. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85116. };
  85117. const uch _dist_code[DIST_CODE_LEN] = {
  85118. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85119. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85120. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85121. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85122. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85123. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85124. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85125. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85126. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85127. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85128. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85129. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85130. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85131. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85132. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85133. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85134. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85135. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85136. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85137. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85138. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85139. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85140. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85141. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85142. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85143. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85144. };
  85145. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85146. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85147. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85148. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85149. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85150. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85151. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85152. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85153. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85154. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85155. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85156. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85157. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85158. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85159. };
  85160. local const int base_length[LENGTH_CODES] = {
  85161. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85162. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85163. };
  85164. local const int base_dist[D_CODES] = {
  85165. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85166. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85167. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85168. };
  85169. /*** End of inlined file: trees.h ***/
  85170. #endif /* GEN_TREES_H */
  85171. struct static_tree_desc_s {
  85172. const ct_data *static_tree; /* static tree or NULL */
  85173. const intf *extra_bits; /* extra bits for each code or NULL */
  85174. int extra_base; /* base index for extra_bits */
  85175. int elems; /* max number of elements in the tree */
  85176. int max_length; /* max bit length for the codes */
  85177. };
  85178. local static_tree_desc static_l_desc =
  85179. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85180. local static_tree_desc static_d_desc =
  85181. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85182. local static_tree_desc static_bl_desc =
  85183. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85184. /* ===========================================================================
  85185. * Local (static) routines in this file.
  85186. */
  85187. local void tr_static_init OF((void));
  85188. local void init_block OF((deflate_state *s));
  85189. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85190. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85191. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85192. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85193. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85194. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85195. local int build_bl_tree OF((deflate_state *s));
  85196. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85197. int blcodes));
  85198. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85199. ct_data *dtree));
  85200. local void set_data_type OF((deflate_state *s));
  85201. local unsigned bi_reverse OF((unsigned value, int length));
  85202. local void bi_windup OF((deflate_state *s));
  85203. local void bi_flush OF((deflate_state *s));
  85204. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85205. int header));
  85206. #ifdef GEN_TREES_H
  85207. local void gen_trees_header OF((void));
  85208. #endif
  85209. #ifndef DEBUG
  85210. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85211. /* Send a code of the given tree. c and tree must not have side effects */
  85212. #else /* DEBUG */
  85213. # define send_code(s, c, tree) \
  85214. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85215. send_bits(s, tree[c].Code, tree[c].Len); }
  85216. #endif
  85217. /* ===========================================================================
  85218. * Output a short LSB first on the stream.
  85219. * IN assertion: there is enough room in pendingBuf.
  85220. */
  85221. #define put_short(s, w) { \
  85222. put_byte(s, (uch)((w) & 0xff)); \
  85223. put_byte(s, (uch)((ush)(w) >> 8)); \
  85224. }
  85225. /* ===========================================================================
  85226. * Send a value on a given number of bits.
  85227. * IN assertion: length <= 16 and value fits in length bits.
  85228. */
  85229. #ifdef DEBUG
  85230. local void send_bits OF((deflate_state *s, int value, int length));
  85231. local void send_bits (deflate_state *s, int value, int length)
  85232. {
  85233. Tracevv((stderr," l %2d v %4x ", length, value));
  85234. Assert(length > 0 && length <= 15, "invalid length");
  85235. s->bits_sent += (ulg)length;
  85236. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85237. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85238. * unused bits in value.
  85239. */
  85240. if (s->bi_valid > (int)Buf_size - length) {
  85241. s->bi_buf |= (value << s->bi_valid);
  85242. put_short(s, s->bi_buf);
  85243. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85244. s->bi_valid += length - Buf_size;
  85245. } else {
  85246. s->bi_buf |= value << s->bi_valid;
  85247. s->bi_valid += length;
  85248. }
  85249. }
  85250. #else /* !DEBUG */
  85251. #define send_bits(s, value, length) \
  85252. { int len = length;\
  85253. if (s->bi_valid > (int)Buf_size - len) {\
  85254. int val = value;\
  85255. s->bi_buf |= (val << s->bi_valid);\
  85256. put_short(s, s->bi_buf);\
  85257. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85258. s->bi_valid += len - Buf_size;\
  85259. } else {\
  85260. s->bi_buf |= (value) << s->bi_valid;\
  85261. s->bi_valid += len;\
  85262. }\
  85263. }
  85264. #endif /* DEBUG */
  85265. /* the arguments must not have side effects */
  85266. /* ===========================================================================
  85267. * Initialize the various 'constant' tables.
  85268. */
  85269. local void tr_static_init()
  85270. {
  85271. #if defined(GEN_TREES_H) || !defined(STDC)
  85272. static int static_init_done = 0;
  85273. int n; /* iterates over tree elements */
  85274. int bits; /* bit counter */
  85275. int length; /* length value */
  85276. int code; /* code value */
  85277. int dist; /* distance index */
  85278. ush bl_count[MAX_BITS+1];
  85279. /* number of codes at each bit length for an optimal tree */
  85280. if (static_init_done) return;
  85281. /* For some embedded targets, global variables are not initialized: */
  85282. static_l_desc.static_tree = static_ltree;
  85283. static_l_desc.extra_bits = extra_lbits;
  85284. static_d_desc.static_tree = static_dtree;
  85285. static_d_desc.extra_bits = extra_dbits;
  85286. static_bl_desc.extra_bits = extra_blbits;
  85287. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85288. length = 0;
  85289. for (code = 0; code < LENGTH_CODES-1; code++) {
  85290. base_length[code] = length;
  85291. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85292. _length_code[length++] = (uch)code;
  85293. }
  85294. }
  85295. Assert (length == 256, "tr_static_init: length != 256");
  85296. /* Note that the length 255 (match length 258) can be represented
  85297. * in two different ways: code 284 + 5 bits or code 285, so we
  85298. * overwrite length_code[255] to use the best encoding:
  85299. */
  85300. _length_code[length-1] = (uch)code;
  85301. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85302. dist = 0;
  85303. for (code = 0 ; code < 16; code++) {
  85304. base_dist[code] = dist;
  85305. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85306. _dist_code[dist++] = (uch)code;
  85307. }
  85308. }
  85309. Assert (dist == 256, "tr_static_init: dist != 256");
  85310. dist >>= 7; /* from now on, all distances are divided by 128 */
  85311. for ( ; code < D_CODES; code++) {
  85312. base_dist[code] = dist << 7;
  85313. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85314. _dist_code[256 + dist++] = (uch)code;
  85315. }
  85316. }
  85317. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85318. /* Construct the codes of the static literal tree */
  85319. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85320. n = 0;
  85321. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85322. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85323. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85324. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85325. /* Codes 286 and 287 do not exist, but we must include them in the
  85326. * tree construction to get a canonical Huffman tree (longest code
  85327. * all ones)
  85328. */
  85329. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85330. /* The static distance tree is trivial: */
  85331. for (n = 0; n < D_CODES; n++) {
  85332. static_dtree[n].Len = 5;
  85333. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85334. }
  85335. static_init_done = 1;
  85336. # ifdef GEN_TREES_H
  85337. gen_trees_header();
  85338. # endif
  85339. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85340. }
  85341. /* ===========================================================================
  85342. * Genererate the file trees.h describing the static trees.
  85343. */
  85344. #ifdef GEN_TREES_H
  85345. # ifndef DEBUG
  85346. # include <stdio.h>
  85347. # endif
  85348. # define SEPARATOR(i, last, width) \
  85349. ((i) == (last)? "\n};\n\n" : \
  85350. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85351. void gen_trees_header()
  85352. {
  85353. FILE *header = fopen("trees.h", "w");
  85354. int i;
  85355. Assert (header != NULL, "Can't open trees.h");
  85356. fprintf(header,
  85357. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85358. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85359. for (i = 0; i < L_CODES+2; i++) {
  85360. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85361. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85362. }
  85363. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85364. for (i = 0; i < D_CODES; i++) {
  85365. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85366. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85367. }
  85368. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85369. for (i = 0; i < DIST_CODE_LEN; i++) {
  85370. fprintf(header, "%2u%s", _dist_code[i],
  85371. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85372. }
  85373. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85374. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85375. fprintf(header, "%2u%s", _length_code[i],
  85376. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85377. }
  85378. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85379. for (i = 0; i < LENGTH_CODES; i++) {
  85380. fprintf(header, "%1u%s", base_length[i],
  85381. SEPARATOR(i, LENGTH_CODES-1, 20));
  85382. }
  85383. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85384. for (i = 0; i < D_CODES; i++) {
  85385. fprintf(header, "%5u%s", base_dist[i],
  85386. SEPARATOR(i, D_CODES-1, 10));
  85387. }
  85388. fclose(header);
  85389. }
  85390. #endif /* GEN_TREES_H */
  85391. /* ===========================================================================
  85392. * Initialize the tree data structures for a new zlib stream.
  85393. */
  85394. void _tr_init(deflate_state *s)
  85395. {
  85396. tr_static_init();
  85397. s->l_desc.dyn_tree = s->dyn_ltree;
  85398. s->l_desc.stat_desc = &static_l_desc;
  85399. s->d_desc.dyn_tree = s->dyn_dtree;
  85400. s->d_desc.stat_desc = &static_d_desc;
  85401. s->bl_desc.dyn_tree = s->bl_tree;
  85402. s->bl_desc.stat_desc = &static_bl_desc;
  85403. s->bi_buf = 0;
  85404. s->bi_valid = 0;
  85405. s->last_eob_len = 8; /* enough lookahead for inflate */
  85406. #ifdef DEBUG
  85407. s->compressed_len = 0L;
  85408. s->bits_sent = 0L;
  85409. #endif
  85410. /* Initialize the first block of the first file: */
  85411. init_block(s);
  85412. }
  85413. /* ===========================================================================
  85414. * Initialize a new block.
  85415. */
  85416. local void init_block (deflate_state *s)
  85417. {
  85418. int n; /* iterates over tree elements */
  85419. /* Initialize the trees. */
  85420. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85421. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85422. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85423. s->dyn_ltree[END_BLOCK].Freq = 1;
  85424. s->opt_len = s->static_len = 0L;
  85425. s->last_lit = s->matches = 0;
  85426. }
  85427. #define SMALLEST 1
  85428. /* Index within the heap array of least frequent node in the Huffman tree */
  85429. /* ===========================================================================
  85430. * Remove the smallest element from the heap and recreate the heap with
  85431. * one less element. Updates heap and heap_len.
  85432. */
  85433. #define pqremove(s, tree, top) \
  85434. {\
  85435. top = s->heap[SMALLEST]; \
  85436. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85437. pqdownheap(s, tree, SMALLEST); \
  85438. }
  85439. /* ===========================================================================
  85440. * Compares to subtrees, using the tree depth as tie breaker when
  85441. * the subtrees have equal frequency. This minimizes the worst case length.
  85442. */
  85443. #define smaller(tree, n, m, depth) \
  85444. (tree[n].Freq < tree[m].Freq || \
  85445. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85446. /* ===========================================================================
  85447. * Restore the heap property by moving down the tree starting at node k,
  85448. * exchanging a node with the smallest of its two sons if necessary, stopping
  85449. * when the heap property is re-established (each father smaller than its
  85450. * two sons).
  85451. */
  85452. local void pqdownheap (deflate_state *s,
  85453. ct_data *tree, /* the tree to restore */
  85454. int k) /* node to move down */
  85455. {
  85456. int v = s->heap[k];
  85457. int j = k << 1; /* left son of k */
  85458. while (j <= s->heap_len) {
  85459. /* Set j to the smallest of the two sons: */
  85460. if (j < s->heap_len &&
  85461. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85462. j++;
  85463. }
  85464. /* Exit if v is smaller than both sons */
  85465. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85466. /* Exchange v with the smallest son */
  85467. s->heap[k] = s->heap[j]; k = j;
  85468. /* And continue down the tree, setting j to the left son of k */
  85469. j <<= 1;
  85470. }
  85471. s->heap[k] = v;
  85472. }
  85473. /* ===========================================================================
  85474. * Compute the optimal bit lengths for a tree and update the total bit length
  85475. * for the current block.
  85476. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85477. * above are the tree nodes sorted by increasing frequency.
  85478. * OUT assertions: the field len is set to the optimal bit length, the
  85479. * array bl_count contains the frequencies for each bit length.
  85480. * The length opt_len is updated; static_len is also updated if stree is
  85481. * not null.
  85482. */
  85483. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85484. {
  85485. ct_data *tree = desc->dyn_tree;
  85486. int max_code = desc->max_code;
  85487. const ct_data *stree = desc->stat_desc->static_tree;
  85488. const intf *extra = desc->stat_desc->extra_bits;
  85489. int base = desc->stat_desc->extra_base;
  85490. int max_length = desc->stat_desc->max_length;
  85491. int h; /* heap index */
  85492. int n, m; /* iterate over the tree elements */
  85493. int bits; /* bit length */
  85494. int xbits; /* extra bits */
  85495. ush f; /* frequency */
  85496. int overflow = 0; /* number of elements with bit length too large */
  85497. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85498. /* In a first pass, compute the optimal bit lengths (which may
  85499. * overflow in the case of the bit length tree).
  85500. */
  85501. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85502. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85503. n = s->heap[h];
  85504. bits = tree[tree[n].Dad].Len + 1;
  85505. if (bits > max_length) bits = max_length, overflow++;
  85506. tree[n].Len = (ush)bits;
  85507. /* We overwrite tree[n].Dad which is no longer needed */
  85508. if (n > max_code) continue; /* not a leaf node */
  85509. s->bl_count[bits]++;
  85510. xbits = 0;
  85511. if (n >= base) xbits = extra[n-base];
  85512. f = tree[n].Freq;
  85513. s->opt_len += (ulg)f * (bits + xbits);
  85514. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85515. }
  85516. if (overflow == 0) return;
  85517. Trace((stderr,"\nbit length overflow\n"));
  85518. /* This happens for example on obj2 and pic of the Calgary corpus */
  85519. /* Find the first bit length which could increase: */
  85520. do {
  85521. bits = max_length-1;
  85522. while (s->bl_count[bits] == 0) bits--;
  85523. s->bl_count[bits]--; /* move one leaf down the tree */
  85524. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85525. s->bl_count[max_length]--;
  85526. /* The brother of the overflow item also moves one step up,
  85527. * but this does not affect bl_count[max_length]
  85528. */
  85529. overflow -= 2;
  85530. } while (overflow > 0);
  85531. /* Now recompute all bit lengths, scanning in increasing frequency.
  85532. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85533. * lengths instead of fixing only the wrong ones. This idea is taken
  85534. * from 'ar' written by Haruhiko Okumura.)
  85535. */
  85536. for (bits = max_length; bits != 0; bits--) {
  85537. n = s->bl_count[bits];
  85538. while (n != 0) {
  85539. m = s->heap[--h];
  85540. if (m > max_code) continue;
  85541. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85542. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85543. s->opt_len += ((long)bits - (long)tree[m].Len)
  85544. *(long)tree[m].Freq;
  85545. tree[m].Len = (ush)bits;
  85546. }
  85547. n--;
  85548. }
  85549. }
  85550. }
  85551. /* ===========================================================================
  85552. * Generate the codes for a given tree and bit counts (which need not be
  85553. * optimal).
  85554. * IN assertion: the array bl_count contains the bit length statistics for
  85555. * the given tree and the field len is set for all tree elements.
  85556. * OUT assertion: the field code is set for all tree elements of non
  85557. * zero code length.
  85558. */
  85559. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85560. int max_code, /* largest code with non zero frequency */
  85561. ushf *bl_count) /* number of codes at each bit length */
  85562. {
  85563. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85564. ush code = 0; /* running code value */
  85565. int bits; /* bit index */
  85566. int n; /* code index */
  85567. /* The distribution counts are first used to generate the code values
  85568. * without bit reversal.
  85569. */
  85570. for (bits = 1; bits <= MAX_BITS; bits++) {
  85571. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85572. }
  85573. /* Check that the bit counts in bl_count are consistent. The last code
  85574. * must be all ones.
  85575. */
  85576. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85577. "inconsistent bit counts");
  85578. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85579. for (n = 0; n <= max_code; n++) {
  85580. int len = tree[n].Len;
  85581. if (len == 0) continue;
  85582. /* Now reverse the bits */
  85583. tree[n].Code = bi_reverse(next_code[len]++, len);
  85584. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85585. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85586. }
  85587. }
  85588. /* ===========================================================================
  85589. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85590. * Update the total bit length for the current block.
  85591. * IN assertion: the field freq is set for all tree elements.
  85592. * OUT assertions: the fields len and code are set to the optimal bit length
  85593. * and corresponding code. The length opt_len is updated; static_len is
  85594. * also updated if stree is not null. The field max_code is set.
  85595. */
  85596. local void build_tree (deflate_state *s,
  85597. tree_desc *desc) /* the tree descriptor */
  85598. {
  85599. ct_data *tree = desc->dyn_tree;
  85600. const ct_data *stree = desc->stat_desc->static_tree;
  85601. int elems = desc->stat_desc->elems;
  85602. int n, m; /* iterate over heap elements */
  85603. int max_code = -1; /* largest code with non zero frequency */
  85604. int node; /* new node being created */
  85605. /* Construct the initial heap, with least frequent element in
  85606. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85607. * heap[0] is not used.
  85608. */
  85609. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85610. for (n = 0; n < elems; n++) {
  85611. if (tree[n].Freq != 0) {
  85612. s->heap[++(s->heap_len)] = max_code = n;
  85613. s->depth[n] = 0;
  85614. } else {
  85615. tree[n].Len = 0;
  85616. }
  85617. }
  85618. /* The pkzip format requires that at least one distance code exists,
  85619. * and that at least one bit should be sent even if there is only one
  85620. * possible code. So to avoid special checks later on we force at least
  85621. * two codes of non zero frequency.
  85622. */
  85623. while (s->heap_len < 2) {
  85624. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85625. tree[node].Freq = 1;
  85626. s->depth[node] = 0;
  85627. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85628. /* node is 0 or 1 so it does not have extra bits */
  85629. }
  85630. desc->max_code = max_code;
  85631. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85632. * establish sub-heaps of increasing lengths:
  85633. */
  85634. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85635. /* Construct the Huffman tree by repeatedly combining the least two
  85636. * frequent nodes.
  85637. */
  85638. node = elems; /* next internal node of the tree */
  85639. do {
  85640. pqremove(s, tree, n); /* n = node of least frequency */
  85641. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85642. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85643. s->heap[--(s->heap_max)] = m;
  85644. /* Create a new node father of n and m */
  85645. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85646. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85647. s->depth[n] : s->depth[m]) + 1);
  85648. tree[n].Dad = tree[m].Dad = (ush)node;
  85649. #ifdef DUMP_BL_TREE
  85650. if (tree == s->bl_tree) {
  85651. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85652. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85653. }
  85654. #endif
  85655. /* and insert the new node in the heap */
  85656. s->heap[SMALLEST] = node++;
  85657. pqdownheap(s, tree, SMALLEST);
  85658. } while (s->heap_len >= 2);
  85659. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85660. /* At this point, the fields freq and dad are set. We can now
  85661. * generate the bit lengths.
  85662. */
  85663. gen_bitlen(s, (tree_desc *)desc);
  85664. /* The field len is now set, we can generate the bit codes */
  85665. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85666. }
  85667. /* ===========================================================================
  85668. * Scan a literal or distance tree to determine the frequencies of the codes
  85669. * in the bit length tree.
  85670. */
  85671. local void scan_tree (deflate_state *s,
  85672. ct_data *tree, /* the tree to be scanned */
  85673. int max_code) /* and its largest code of non zero frequency */
  85674. {
  85675. int n; /* iterates over all tree elements */
  85676. int prevlen = -1; /* last emitted length */
  85677. int curlen; /* length of current code */
  85678. int nextlen = tree[0].Len; /* length of next code */
  85679. int count = 0; /* repeat count of the current code */
  85680. int max_count = 7; /* max repeat count */
  85681. int min_count = 4; /* min repeat count */
  85682. if (nextlen == 0) max_count = 138, min_count = 3;
  85683. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85684. for (n = 0; n <= max_code; n++) {
  85685. curlen = nextlen; nextlen = tree[n+1].Len;
  85686. if (++count < max_count && curlen == nextlen) {
  85687. continue;
  85688. } else if (count < min_count) {
  85689. s->bl_tree[curlen].Freq += count;
  85690. } else if (curlen != 0) {
  85691. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85692. s->bl_tree[REP_3_6].Freq++;
  85693. } else if (count <= 10) {
  85694. s->bl_tree[REPZ_3_10].Freq++;
  85695. } else {
  85696. s->bl_tree[REPZ_11_138].Freq++;
  85697. }
  85698. count = 0; prevlen = curlen;
  85699. if (nextlen == 0) {
  85700. max_count = 138, min_count = 3;
  85701. } else if (curlen == nextlen) {
  85702. max_count = 6, min_count = 3;
  85703. } else {
  85704. max_count = 7, min_count = 4;
  85705. }
  85706. }
  85707. }
  85708. /* ===========================================================================
  85709. * Send a literal or distance tree in compressed form, using the codes in
  85710. * bl_tree.
  85711. */
  85712. local void send_tree (deflate_state *s,
  85713. ct_data *tree, /* the tree to be scanned */
  85714. int max_code) /* and its largest code of non zero frequency */
  85715. {
  85716. int n; /* iterates over all tree elements */
  85717. int prevlen = -1; /* last emitted length */
  85718. int curlen; /* length of current code */
  85719. int nextlen = tree[0].Len; /* length of next code */
  85720. int count = 0; /* repeat count of the current code */
  85721. int max_count = 7; /* max repeat count */
  85722. int min_count = 4; /* min repeat count */
  85723. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85724. if (nextlen == 0) max_count = 138, min_count = 3;
  85725. for (n = 0; n <= max_code; n++) {
  85726. curlen = nextlen; nextlen = tree[n+1].Len;
  85727. if (++count < max_count && curlen == nextlen) {
  85728. continue;
  85729. } else if (count < min_count) {
  85730. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85731. } else if (curlen != 0) {
  85732. if (curlen != prevlen) {
  85733. send_code(s, curlen, s->bl_tree); count--;
  85734. }
  85735. Assert(count >= 3 && count <= 6, " 3_6?");
  85736. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85737. } else if (count <= 10) {
  85738. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85739. } else {
  85740. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85741. }
  85742. count = 0; prevlen = curlen;
  85743. if (nextlen == 0) {
  85744. max_count = 138, min_count = 3;
  85745. } else if (curlen == nextlen) {
  85746. max_count = 6, min_count = 3;
  85747. } else {
  85748. max_count = 7, min_count = 4;
  85749. }
  85750. }
  85751. }
  85752. /* ===========================================================================
  85753. * Construct the Huffman tree for the bit lengths and return the index in
  85754. * bl_order of the last bit length code to send.
  85755. */
  85756. local int build_bl_tree (deflate_state *s)
  85757. {
  85758. int max_blindex; /* index of last bit length code of non zero freq */
  85759. /* Determine the bit length frequencies for literal and distance trees */
  85760. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85761. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85762. /* Build the bit length tree: */
  85763. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85764. /* opt_len now includes the length of the tree representations, except
  85765. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85766. */
  85767. /* Determine the number of bit length codes to send. The pkzip format
  85768. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85769. * 3 but the actual value used is 4.)
  85770. */
  85771. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85772. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85773. }
  85774. /* Update opt_len to include the bit length tree and counts */
  85775. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85776. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85777. s->opt_len, s->static_len));
  85778. return max_blindex;
  85779. }
  85780. /* ===========================================================================
  85781. * Send the header for a block using dynamic Huffman trees: the counts, the
  85782. * lengths of the bit length codes, the literal tree and the distance tree.
  85783. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85784. */
  85785. local void send_all_trees (deflate_state *s,
  85786. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85787. {
  85788. int rank; /* index in bl_order */
  85789. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85790. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85791. "too many codes");
  85792. Tracev((stderr, "\nbl counts: "));
  85793. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85794. send_bits(s, dcodes-1, 5);
  85795. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85796. for (rank = 0; rank < blcodes; rank++) {
  85797. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85798. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85799. }
  85800. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85801. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85802. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85803. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85804. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85805. }
  85806. /* ===========================================================================
  85807. * Send a stored block
  85808. */
  85809. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85810. {
  85811. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85812. #ifdef DEBUG
  85813. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85814. s->compressed_len += (stored_len + 4) << 3;
  85815. #endif
  85816. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85817. }
  85818. /* ===========================================================================
  85819. * Send one empty static block to give enough lookahead for inflate.
  85820. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85821. * The current inflate code requires 9 bits of lookahead. If the
  85822. * last two codes for the previous block (real code plus EOB) were coded
  85823. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85824. * the last real code. In this case we send two empty static blocks instead
  85825. * of one. (There are no problems if the previous block is stored or fixed.)
  85826. * To simplify the code, we assume the worst case of last real code encoded
  85827. * on one bit only.
  85828. */
  85829. void _tr_align (deflate_state *s)
  85830. {
  85831. send_bits(s, STATIC_TREES<<1, 3);
  85832. send_code(s, END_BLOCK, static_ltree);
  85833. #ifdef DEBUG
  85834. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85835. #endif
  85836. bi_flush(s);
  85837. /* Of the 10 bits for the empty block, we have already sent
  85838. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85839. * the EOB of the previous block) was thus at least one plus the length
  85840. * of the EOB plus what we have just sent of the empty static block.
  85841. */
  85842. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85843. send_bits(s, STATIC_TREES<<1, 3);
  85844. send_code(s, END_BLOCK, static_ltree);
  85845. #ifdef DEBUG
  85846. s->compressed_len += 10L;
  85847. #endif
  85848. bi_flush(s);
  85849. }
  85850. s->last_eob_len = 7;
  85851. }
  85852. /* ===========================================================================
  85853. * Determine the best encoding for the current block: dynamic trees, static
  85854. * trees or store, and output the encoded block to the zip file.
  85855. */
  85856. void _tr_flush_block (deflate_state *s,
  85857. charf *buf, /* input block, or NULL if too old */
  85858. ulg stored_len, /* length of input block */
  85859. int eof) /* true if this is the last block for a file */
  85860. {
  85861. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85862. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85863. /* Build the Huffman trees unless a stored block is forced */
  85864. if (s->level > 0) {
  85865. /* Check if the file is binary or text */
  85866. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85867. set_data_type(s);
  85868. /* Construct the literal and distance trees */
  85869. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85870. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85871. s->static_len));
  85872. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85873. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85874. s->static_len));
  85875. /* At this point, opt_len and static_len are the total bit lengths of
  85876. * the compressed block data, excluding the tree representations.
  85877. */
  85878. /* Build the bit length tree for the above two trees, and get the index
  85879. * in bl_order of the last bit length code to send.
  85880. */
  85881. max_blindex = build_bl_tree(s);
  85882. /* Determine the best encoding. Compute the block lengths in bytes. */
  85883. opt_lenb = (s->opt_len+3+7)>>3;
  85884. static_lenb = (s->static_len+3+7)>>3;
  85885. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85886. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85887. s->last_lit));
  85888. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85889. } else {
  85890. Assert(buf != (char*)0, "lost buf");
  85891. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85892. }
  85893. #ifdef FORCE_STORED
  85894. if (buf != (char*)0) { /* force stored block */
  85895. #else
  85896. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85897. /* 4: two words for the lengths */
  85898. #endif
  85899. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85900. * Otherwise we can't have processed more than WSIZE input bytes since
  85901. * the last block flush, because compression would have been
  85902. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85903. * transform a block into a stored block.
  85904. */
  85905. _tr_stored_block(s, buf, stored_len, eof);
  85906. #ifdef FORCE_STATIC
  85907. } else if (static_lenb >= 0) { /* force static trees */
  85908. #else
  85909. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85910. #endif
  85911. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85912. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85913. #ifdef DEBUG
  85914. s->compressed_len += 3 + s->static_len;
  85915. #endif
  85916. } else {
  85917. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85918. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85919. max_blindex+1);
  85920. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85921. #ifdef DEBUG
  85922. s->compressed_len += 3 + s->opt_len;
  85923. #endif
  85924. }
  85925. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85926. /* The above check is made mod 2^32, for files larger than 512 MB
  85927. * and uLong implemented on 32 bits.
  85928. */
  85929. init_block(s);
  85930. if (eof) {
  85931. bi_windup(s);
  85932. #ifdef DEBUG
  85933. s->compressed_len += 7; /* align on byte boundary */
  85934. #endif
  85935. }
  85936. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85937. s->compressed_len-7*eof));
  85938. }
  85939. /* ===========================================================================
  85940. * Save the match info and tally the frequency counts. Return true if
  85941. * the current block must be flushed.
  85942. */
  85943. int _tr_tally (deflate_state *s,
  85944. unsigned dist, /* distance of matched string */
  85945. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85946. {
  85947. s->d_buf[s->last_lit] = (ush)dist;
  85948. s->l_buf[s->last_lit++] = (uch)lc;
  85949. if (dist == 0) {
  85950. /* lc is the unmatched char */
  85951. s->dyn_ltree[lc].Freq++;
  85952. } else {
  85953. s->matches++;
  85954. /* Here, lc is the match length - MIN_MATCH */
  85955. dist--; /* dist = match distance - 1 */
  85956. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85957. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85958. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85959. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85960. s->dyn_dtree[d_code(dist)].Freq++;
  85961. }
  85962. #ifdef TRUNCATE_BLOCK
  85963. /* Try to guess if it is profitable to stop the current block here */
  85964. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85965. /* Compute an upper bound for the compressed length */
  85966. ulg out_length = (ulg)s->last_lit*8L;
  85967. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85968. int dcode;
  85969. for (dcode = 0; dcode < D_CODES; dcode++) {
  85970. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85971. (5L+extra_dbits[dcode]);
  85972. }
  85973. out_length >>= 3;
  85974. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85975. s->last_lit, in_length, out_length,
  85976. 100L - out_length*100L/in_length));
  85977. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85978. }
  85979. #endif
  85980. return (s->last_lit == s->lit_bufsize-1);
  85981. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85982. * on 16 bit machines and because stored blocks are restricted to
  85983. * 64K-1 bytes.
  85984. */
  85985. }
  85986. /* ===========================================================================
  85987. * Send the block data compressed using the given Huffman trees
  85988. */
  85989. local void compress_block (deflate_state *s,
  85990. ct_data *ltree, /* literal tree */
  85991. ct_data *dtree) /* distance tree */
  85992. {
  85993. unsigned dist; /* distance of matched string */
  85994. int lc; /* match length or unmatched char (if dist == 0) */
  85995. unsigned lx = 0; /* running index in l_buf */
  85996. unsigned code; /* the code to send */
  85997. int extra; /* number of extra bits to send */
  85998. if (s->last_lit != 0) do {
  85999. dist = s->d_buf[lx];
  86000. lc = s->l_buf[lx++];
  86001. if (dist == 0) {
  86002. send_code(s, lc, ltree); /* send a literal byte */
  86003. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  86004. } else {
  86005. /* Here, lc is the match length - MIN_MATCH */
  86006. code = _length_code[lc];
  86007. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  86008. extra = extra_lbits[code];
  86009. if (extra != 0) {
  86010. lc -= base_length[code];
  86011. send_bits(s, lc, extra); /* send the extra length bits */
  86012. }
  86013. dist--; /* dist is now the match distance - 1 */
  86014. code = d_code(dist);
  86015. Assert (code < D_CODES, "bad d_code");
  86016. send_code(s, code, dtree); /* send the distance code */
  86017. extra = extra_dbits[code];
  86018. if (extra != 0) {
  86019. dist -= base_dist[code];
  86020. send_bits(s, dist, extra); /* send the extra distance bits */
  86021. }
  86022. } /* literal or match pair ? */
  86023. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  86024. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  86025. "pendingBuf overflow");
  86026. } while (lx < s->last_lit);
  86027. send_code(s, END_BLOCK, ltree);
  86028. s->last_eob_len = ltree[END_BLOCK].Len;
  86029. }
  86030. /* ===========================================================================
  86031. * Set the data type to BINARY or TEXT, using a crude approximation:
  86032. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  86033. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  86034. * IN assertion: the fields Freq of dyn_ltree are set.
  86035. */
  86036. local void set_data_type (deflate_state *s)
  86037. {
  86038. int n;
  86039. for (n = 0; n < 9; n++)
  86040. if (s->dyn_ltree[n].Freq != 0)
  86041. break;
  86042. if (n == 9)
  86043. for (n = 14; n < 32; n++)
  86044. if (s->dyn_ltree[n].Freq != 0)
  86045. break;
  86046. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  86047. }
  86048. /* ===========================================================================
  86049. * Reverse the first len bits of a code, using straightforward code (a faster
  86050. * method would use a table)
  86051. * IN assertion: 1 <= len <= 15
  86052. */
  86053. local unsigned bi_reverse (unsigned code, int len)
  86054. {
  86055. register unsigned res = 0;
  86056. do {
  86057. res |= code & 1;
  86058. code >>= 1, res <<= 1;
  86059. } while (--len > 0);
  86060. return res >> 1;
  86061. }
  86062. /* ===========================================================================
  86063. * Flush the bit buffer, keeping at most 7 bits in it.
  86064. */
  86065. local void bi_flush (deflate_state *s)
  86066. {
  86067. if (s->bi_valid == 16) {
  86068. put_short(s, s->bi_buf);
  86069. s->bi_buf = 0;
  86070. s->bi_valid = 0;
  86071. } else if (s->bi_valid >= 8) {
  86072. put_byte(s, (Byte)s->bi_buf);
  86073. s->bi_buf >>= 8;
  86074. s->bi_valid -= 8;
  86075. }
  86076. }
  86077. /* ===========================================================================
  86078. * Flush the bit buffer and align the output on a byte boundary
  86079. */
  86080. local void bi_windup (deflate_state *s)
  86081. {
  86082. if (s->bi_valid > 8) {
  86083. put_short(s, s->bi_buf);
  86084. } else if (s->bi_valid > 0) {
  86085. put_byte(s, (Byte)s->bi_buf);
  86086. }
  86087. s->bi_buf = 0;
  86088. s->bi_valid = 0;
  86089. #ifdef DEBUG
  86090. s->bits_sent = (s->bits_sent+7) & ~7;
  86091. #endif
  86092. }
  86093. /* ===========================================================================
  86094. * Copy a stored block, storing first the length and its
  86095. * one's complement if requested.
  86096. */
  86097. local void copy_block(deflate_state *s,
  86098. charf *buf, /* the input data */
  86099. unsigned len, /* its length */
  86100. int header) /* true if block header must be written */
  86101. {
  86102. bi_windup(s); /* align on byte boundary */
  86103. s->last_eob_len = 8; /* enough lookahead for inflate */
  86104. if (header) {
  86105. put_short(s, (ush)len);
  86106. put_short(s, (ush)~len);
  86107. #ifdef DEBUG
  86108. s->bits_sent += 2*16;
  86109. #endif
  86110. }
  86111. #ifdef DEBUG
  86112. s->bits_sent += (ulg)len<<3;
  86113. #endif
  86114. while (len--) {
  86115. put_byte(s, *buf++);
  86116. }
  86117. }
  86118. /*** End of inlined file: trees.c ***/
  86119. /*** Start of inlined file: zutil.c ***/
  86120. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86121. #ifndef NO_DUMMY_DECL
  86122. struct internal_state {int dummy;}; /* for buggy compilers */
  86123. #endif
  86124. const char * const z_errmsg[10] = {
  86125. "need dictionary", /* Z_NEED_DICT 2 */
  86126. "stream end", /* Z_STREAM_END 1 */
  86127. "", /* Z_OK 0 */
  86128. "file error", /* Z_ERRNO (-1) */
  86129. "stream error", /* Z_STREAM_ERROR (-2) */
  86130. "data error", /* Z_DATA_ERROR (-3) */
  86131. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86132. "buffer error", /* Z_BUF_ERROR (-5) */
  86133. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86134. ""};
  86135. /*const char * ZEXPORT zlibVersion()
  86136. {
  86137. return ZLIB_VERSION;
  86138. }
  86139. uLong ZEXPORT zlibCompileFlags()
  86140. {
  86141. uLong flags;
  86142. flags = 0;
  86143. switch (sizeof(uInt)) {
  86144. case 2: break;
  86145. case 4: flags += 1; break;
  86146. case 8: flags += 2; break;
  86147. default: flags += 3;
  86148. }
  86149. switch (sizeof(uLong)) {
  86150. case 2: break;
  86151. case 4: flags += 1 << 2; break;
  86152. case 8: flags += 2 << 2; break;
  86153. default: flags += 3 << 2;
  86154. }
  86155. switch (sizeof(voidpf)) {
  86156. case 2: break;
  86157. case 4: flags += 1 << 4; break;
  86158. case 8: flags += 2 << 4; break;
  86159. default: flags += 3 << 4;
  86160. }
  86161. switch (sizeof(z_off_t)) {
  86162. case 2: break;
  86163. case 4: flags += 1 << 6; break;
  86164. case 8: flags += 2 << 6; break;
  86165. default: flags += 3 << 6;
  86166. }
  86167. #ifdef DEBUG
  86168. flags += 1 << 8;
  86169. #endif
  86170. #if defined(ASMV) || defined(ASMINF)
  86171. flags += 1 << 9;
  86172. #endif
  86173. #ifdef ZLIB_WINAPI
  86174. flags += 1 << 10;
  86175. #endif
  86176. #ifdef BUILDFIXED
  86177. flags += 1 << 12;
  86178. #endif
  86179. #ifdef DYNAMIC_CRC_TABLE
  86180. flags += 1 << 13;
  86181. #endif
  86182. #ifdef NO_GZCOMPRESS
  86183. flags += 1L << 16;
  86184. #endif
  86185. #ifdef NO_GZIP
  86186. flags += 1L << 17;
  86187. #endif
  86188. #ifdef PKZIP_BUG_WORKAROUND
  86189. flags += 1L << 20;
  86190. #endif
  86191. #ifdef FASTEST
  86192. flags += 1L << 21;
  86193. #endif
  86194. #ifdef STDC
  86195. # ifdef NO_vsnprintf
  86196. flags += 1L << 25;
  86197. # ifdef HAS_vsprintf_void
  86198. flags += 1L << 26;
  86199. # endif
  86200. # else
  86201. # ifdef HAS_vsnprintf_void
  86202. flags += 1L << 26;
  86203. # endif
  86204. # endif
  86205. #else
  86206. flags += 1L << 24;
  86207. # ifdef NO_snprintf
  86208. flags += 1L << 25;
  86209. # ifdef HAS_sprintf_void
  86210. flags += 1L << 26;
  86211. # endif
  86212. # else
  86213. # ifdef HAS_snprintf_void
  86214. flags += 1L << 26;
  86215. # endif
  86216. # endif
  86217. #endif
  86218. return flags;
  86219. }*/
  86220. #ifdef DEBUG
  86221. # ifndef verbose
  86222. # define verbose 0
  86223. # endif
  86224. int z_verbose = verbose;
  86225. void z_error (const char *m)
  86226. {
  86227. fprintf(stderr, "%s\n", m);
  86228. exit(1);
  86229. }
  86230. #endif
  86231. /* exported to allow conversion of error code to string for compress() and
  86232. * uncompress()
  86233. */
  86234. const char * ZEXPORT zError(int err)
  86235. {
  86236. return ERR_MSG(err);
  86237. }
  86238. #if defined(_WIN32_WCE)
  86239. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86240. * errno. We define it as a global variable to simplify porting.
  86241. * Its value is always 0 and should not be used.
  86242. */
  86243. int errno = 0;
  86244. #endif
  86245. #ifndef HAVE_MEMCPY
  86246. void zmemcpy(dest, source, len)
  86247. Bytef* dest;
  86248. const Bytef* source;
  86249. uInt len;
  86250. {
  86251. if (len == 0) return;
  86252. do {
  86253. *dest++ = *source++; /* ??? to be unrolled */
  86254. } while (--len != 0);
  86255. }
  86256. int zmemcmp(s1, s2, len)
  86257. const Bytef* s1;
  86258. const Bytef* s2;
  86259. uInt len;
  86260. {
  86261. uInt j;
  86262. for (j = 0; j < len; j++) {
  86263. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86264. }
  86265. return 0;
  86266. }
  86267. void zmemzero(dest, len)
  86268. Bytef* dest;
  86269. uInt len;
  86270. {
  86271. if (len == 0) return;
  86272. do {
  86273. *dest++ = 0; /* ??? to be unrolled */
  86274. } while (--len != 0);
  86275. }
  86276. #endif
  86277. #ifdef SYS16BIT
  86278. #ifdef __TURBOC__
  86279. /* Turbo C in 16-bit mode */
  86280. # define MY_ZCALLOC
  86281. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86282. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86283. * must fix the pointer. Warning: the pointer must be put back to its
  86284. * original form in order to free it, use zcfree().
  86285. */
  86286. #define MAX_PTR 10
  86287. /* 10*64K = 640K */
  86288. local int next_ptr = 0;
  86289. typedef struct ptr_table_s {
  86290. voidpf org_ptr;
  86291. voidpf new_ptr;
  86292. } ptr_table;
  86293. local ptr_table table[MAX_PTR];
  86294. /* This table is used to remember the original form of pointers
  86295. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86296. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86297. * protected from concurrent access. This hack doesn't work anyway on
  86298. * a protected system like OS/2. Use Microsoft C instead.
  86299. */
  86300. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86301. {
  86302. voidpf buf = opaque; /* just to make some compilers happy */
  86303. ulg bsize = (ulg)items*size;
  86304. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86305. * will return a usable pointer which doesn't have to be normalized.
  86306. */
  86307. if (bsize < 65520L) {
  86308. buf = farmalloc(bsize);
  86309. if (*(ush*)&buf != 0) return buf;
  86310. } else {
  86311. buf = farmalloc(bsize + 16L);
  86312. }
  86313. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86314. table[next_ptr].org_ptr = buf;
  86315. /* Normalize the pointer to seg:0 */
  86316. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86317. *(ush*)&buf = 0;
  86318. table[next_ptr++].new_ptr = buf;
  86319. return buf;
  86320. }
  86321. void zcfree (voidpf opaque, voidpf ptr)
  86322. {
  86323. int n;
  86324. if (*(ush*)&ptr != 0) { /* object < 64K */
  86325. farfree(ptr);
  86326. return;
  86327. }
  86328. /* Find the original pointer */
  86329. for (n = 0; n < next_ptr; n++) {
  86330. if (ptr != table[n].new_ptr) continue;
  86331. farfree(table[n].org_ptr);
  86332. while (++n < next_ptr) {
  86333. table[n-1] = table[n];
  86334. }
  86335. next_ptr--;
  86336. return;
  86337. }
  86338. ptr = opaque; /* just to make some compilers happy */
  86339. Assert(0, "zcfree: ptr not found");
  86340. }
  86341. #endif /* __TURBOC__ */
  86342. #ifdef M_I86
  86343. /* Microsoft C in 16-bit mode */
  86344. # define MY_ZCALLOC
  86345. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86346. # define _halloc halloc
  86347. # define _hfree hfree
  86348. #endif
  86349. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86350. {
  86351. if (opaque) opaque = 0; /* to make compiler happy */
  86352. return _halloc((long)items, size);
  86353. }
  86354. void zcfree (voidpf opaque, voidpf ptr)
  86355. {
  86356. if (opaque) opaque = 0; /* to make compiler happy */
  86357. _hfree(ptr);
  86358. }
  86359. #endif /* M_I86 */
  86360. #endif /* SYS16BIT */
  86361. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86362. #ifndef STDC
  86363. extern voidp malloc OF((uInt size));
  86364. extern voidp calloc OF((uInt items, uInt size));
  86365. extern void free OF((voidpf ptr));
  86366. #endif
  86367. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86368. {
  86369. if (opaque) items += size - size; /* make compiler happy */
  86370. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86371. (voidpf)calloc(items, size);
  86372. }
  86373. void zcfree (voidpf opaque, voidpf ptr)
  86374. {
  86375. free(ptr);
  86376. if (opaque) return; /* make compiler happy */
  86377. }
  86378. #endif /* MY_ZCALLOC */
  86379. /*** End of inlined file: zutil.c ***/
  86380. #undef Byte
  86381. #else
  86382. #include <zlib.h>
  86383. #endif
  86384. }
  86385. #if JUCE_MSVC
  86386. #pragma warning (pop)
  86387. #endif
  86388. BEGIN_JUCE_NAMESPACE
  86389. // internal helper object that holds the zlib structures so they don't have to be
  86390. // included publicly.
  86391. class GZIPDecompressHelper
  86392. {
  86393. public:
  86394. GZIPDecompressHelper (const bool noWrap)
  86395. : finished (true),
  86396. needsDictionary (false),
  86397. error (true),
  86398. streamIsValid (false),
  86399. data (0),
  86400. dataSize (0)
  86401. {
  86402. using namespace zlibNamespace;
  86403. zerostruct (stream);
  86404. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86405. finished = error = ! streamIsValid;
  86406. }
  86407. ~GZIPDecompressHelper()
  86408. {
  86409. using namespace zlibNamespace;
  86410. if (streamIsValid)
  86411. inflateEnd (&stream);
  86412. }
  86413. bool needsInput() const throw() { return dataSize <= 0; }
  86414. void setInput (uint8* const data_, const int size) throw()
  86415. {
  86416. data = data_;
  86417. dataSize = size;
  86418. }
  86419. int doNextBlock (uint8* const dest, const int destSize)
  86420. {
  86421. using namespace zlibNamespace;
  86422. if (streamIsValid && data != 0 && ! finished)
  86423. {
  86424. stream.next_in = data;
  86425. stream.next_out = dest;
  86426. stream.avail_in = dataSize;
  86427. stream.avail_out = destSize;
  86428. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86429. {
  86430. case Z_STREAM_END:
  86431. finished = true;
  86432. // deliberate fall-through
  86433. case Z_OK:
  86434. data += dataSize - stream.avail_in;
  86435. dataSize = stream.avail_in;
  86436. return destSize - stream.avail_out;
  86437. case Z_NEED_DICT:
  86438. needsDictionary = true;
  86439. data += dataSize - stream.avail_in;
  86440. dataSize = stream.avail_in;
  86441. break;
  86442. case Z_DATA_ERROR:
  86443. case Z_MEM_ERROR:
  86444. error = true;
  86445. default:
  86446. break;
  86447. }
  86448. }
  86449. return 0;
  86450. }
  86451. bool finished, needsDictionary, error, streamIsValid;
  86452. private:
  86453. zlibNamespace::z_stream stream;
  86454. uint8* data;
  86455. int dataSize;
  86456. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86457. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86458. };
  86459. const int gzipDecompBufferSize = 32768;
  86460. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86461. const bool deleteSourceWhenDestroyed,
  86462. const bool noWrap_,
  86463. const int64 uncompressedStreamLength_)
  86464. : sourceStream (sourceStream_),
  86465. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86466. uncompressedStreamLength (uncompressedStreamLength_),
  86467. noWrap (noWrap_),
  86468. isEof (false),
  86469. activeBufferSize (0),
  86470. originalSourcePos (sourceStream_->getPosition()),
  86471. currentPos (0),
  86472. buffer (gzipDecompBufferSize),
  86473. helper (new GZIPDecompressHelper (noWrap_))
  86474. {
  86475. }
  86476. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86477. {
  86478. }
  86479. int64 GZIPDecompressorInputStream::getTotalLength()
  86480. {
  86481. return uncompressedStreamLength;
  86482. }
  86483. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86484. {
  86485. if ((howMany > 0) && ! isEof)
  86486. {
  86487. jassert (destBuffer != 0);
  86488. if (destBuffer != 0)
  86489. {
  86490. int numRead = 0;
  86491. uint8* d = static_cast <uint8*> (destBuffer);
  86492. while (! helper->error)
  86493. {
  86494. const int n = helper->doNextBlock (d, howMany);
  86495. currentPos += n;
  86496. if (n == 0)
  86497. {
  86498. if (helper->finished || helper->needsDictionary)
  86499. {
  86500. isEof = true;
  86501. return numRead;
  86502. }
  86503. if (helper->needsInput())
  86504. {
  86505. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86506. if (activeBufferSize > 0)
  86507. {
  86508. helper->setInput (buffer, activeBufferSize);
  86509. }
  86510. else
  86511. {
  86512. isEof = true;
  86513. return numRead;
  86514. }
  86515. }
  86516. }
  86517. else
  86518. {
  86519. numRead += n;
  86520. howMany -= n;
  86521. d += n;
  86522. if (howMany <= 0)
  86523. return numRead;
  86524. }
  86525. }
  86526. }
  86527. }
  86528. return 0;
  86529. }
  86530. bool GZIPDecompressorInputStream::isExhausted()
  86531. {
  86532. return helper->error || isEof;
  86533. }
  86534. int64 GZIPDecompressorInputStream::getPosition()
  86535. {
  86536. return currentPos;
  86537. }
  86538. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86539. {
  86540. if (newPos < currentPos)
  86541. {
  86542. // to go backwards, reset the stream and start again..
  86543. isEof = false;
  86544. activeBufferSize = 0;
  86545. currentPos = 0;
  86546. helper = new GZIPDecompressHelper (noWrap);
  86547. sourceStream->setPosition (originalSourcePos);
  86548. }
  86549. skipNextBytes (newPos - currentPos);
  86550. return true;
  86551. }
  86552. END_JUCE_NAMESPACE
  86553. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86554. #endif
  86555. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86556. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86557. #if JUCE_USE_FLAC
  86558. #if JUCE_WINDOWS
  86559. #include <windows.h>
  86560. #endif
  86561. namespace FlacNamespace
  86562. {
  86563. #if JUCE_INCLUDE_FLAC_CODE
  86564. #if JUCE_MSVC
  86565. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86566. #endif
  86567. #define FLAC__NO_DLL 1
  86568. #if ! defined (SIZE_MAX)
  86569. #define SIZE_MAX 0xffffffff
  86570. #endif
  86571. #define __STDC_LIMIT_MACROS 1
  86572. /*** Start of inlined file: all.h ***/
  86573. #ifndef FLAC__ALL_H
  86574. #define FLAC__ALL_H
  86575. /*** Start of inlined file: export.h ***/
  86576. #ifndef FLAC__EXPORT_H
  86577. #define FLAC__EXPORT_H
  86578. /** \file include/FLAC/export.h
  86579. *
  86580. * \brief
  86581. * This module contains #defines and symbols for exporting function
  86582. * calls, and providing version information and compiled-in features.
  86583. *
  86584. * See the \link flac_export export \endlink module.
  86585. */
  86586. /** \defgroup flac_export FLAC/export.h: export symbols
  86587. * \ingroup flac
  86588. *
  86589. * \brief
  86590. * This module contains #defines and symbols for exporting function
  86591. * calls, and providing version information and compiled-in features.
  86592. *
  86593. * If you are compiling with MSVC and will link to the static library
  86594. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86595. * make sure the symbols are exported properly.
  86596. *
  86597. * \{
  86598. */
  86599. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86600. #define FLAC_API
  86601. #else
  86602. #ifdef FLAC_API_EXPORTS
  86603. #define FLAC_API _declspec(dllexport)
  86604. #else
  86605. #define FLAC_API _declspec(dllimport)
  86606. #endif
  86607. #endif
  86608. /** These #defines will mirror the libtool-based library version number, see
  86609. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86610. */
  86611. #define FLAC_API_VERSION_CURRENT 10
  86612. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86613. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86614. #ifdef __cplusplus
  86615. extern "C" {
  86616. #endif
  86617. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86618. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86619. #ifdef __cplusplus
  86620. }
  86621. #endif
  86622. /* \} */
  86623. #endif
  86624. /*** End of inlined file: export.h ***/
  86625. /*** Start of inlined file: assert.h ***/
  86626. #ifndef FLAC__ASSERT_H
  86627. #define FLAC__ASSERT_H
  86628. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86629. #ifdef DEBUG
  86630. #include <assert.h>
  86631. #define FLAC__ASSERT(x) assert(x)
  86632. #define FLAC__ASSERT_DECLARATION(x) x
  86633. #else
  86634. #define FLAC__ASSERT(x)
  86635. #define FLAC__ASSERT_DECLARATION(x)
  86636. #endif
  86637. #endif
  86638. /*** End of inlined file: assert.h ***/
  86639. /*** Start of inlined file: callback.h ***/
  86640. #ifndef FLAC__CALLBACK_H
  86641. #define FLAC__CALLBACK_H
  86642. /*** Start of inlined file: ordinals.h ***/
  86643. #ifndef FLAC__ORDINALS_H
  86644. #define FLAC__ORDINALS_H
  86645. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86646. #include <inttypes.h>
  86647. #endif
  86648. typedef signed char FLAC__int8;
  86649. typedef unsigned char FLAC__uint8;
  86650. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86651. typedef __int16 FLAC__int16;
  86652. typedef __int32 FLAC__int32;
  86653. typedef __int64 FLAC__int64;
  86654. typedef unsigned __int16 FLAC__uint16;
  86655. typedef unsigned __int32 FLAC__uint32;
  86656. typedef unsigned __int64 FLAC__uint64;
  86657. #elif defined(__EMX__)
  86658. typedef short FLAC__int16;
  86659. typedef long FLAC__int32;
  86660. typedef long long FLAC__int64;
  86661. typedef unsigned short FLAC__uint16;
  86662. typedef unsigned long FLAC__uint32;
  86663. typedef unsigned long long FLAC__uint64;
  86664. #else
  86665. typedef int16_t FLAC__int16;
  86666. typedef int32_t FLAC__int32;
  86667. typedef int64_t FLAC__int64;
  86668. typedef uint16_t FLAC__uint16;
  86669. typedef uint32_t FLAC__uint32;
  86670. typedef uint64_t FLAC__uint64;
  86671. #endif
  86672. typedef int FLAC__bool;
  86673. typedef FLAC__uint8 FLAC__byte;
  86674. #ifdef true
  86675. #undef true
  86676. #endif
  86677. #ifdef false
  86678. #undef false
  86679. #endif
  86680. #ifndef __cplusplus
  86681. #define true 1
  86682. #define false 0
  86683. #endif
  86684. #endif
  86685. /*** End of inlined file: ordinals.h ***/
  86686. #include <stdlib.h> /* for size_t */
  86687. /** \file include/FLAC/callback.h
  86688. *
  86689. * \brief
  86690. * This module defines the structures for describing I/O callbacks
  86691. * to the other FLAC interfaces.
  86692. *
  86693. * See the detailed documentation for callbacks in the
  86694. * \link flac_callbacks callbacks \endlink module.
  86695. */
  86696. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86697. * \ingroup flac
  86698. *
  86699. * \brief
  86700. * This module defines the structures for describing I/O callbacks
  86701. * to the other FLAC interfaces.
  86702. *
  86703. * The purpose of the I/O callback functions is to create a common way
  86704. * for the metadata interfaces to handle I/O.
  86705. *
  86706. * Originally the metadata interfaces required filenames as the way of
  86707. * specifying FLAC files to operate on. This is problematic in some
  86708. * environments so there is an additional option to specify a set of
  86709. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86710. *
  86711. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86712. * opaque structure for a data source.
  86713. *
  86714. * The callback function prototypes are similar (but not identical) to the
  86715. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86716. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86717. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86718. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86719. * is required. \warning You generally CANNOT directly use fseek or ftell
  86720. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86721. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86722. * large files. You will have to find an equivalent function (e.g. ftello),
  86723. * or write a wrapper. The same is true for feof() since this is usually
  86724. * implemented as a macro, not as a function whose address can be taken.
  86725. *
  86726. * \{
  86727. */
  86728. #ifdef __cplusplus
  86729. extern "C" {
  86730. #endif
  86731. /** This is the opaque handle type used by the callbacks. Typically
  86732. * this is a \c FILE* or address of a file descriptor.
  86733. */
  86734. typedef void* FLAC__IOHandle;
  86735. /** Signature for the read callback.
  86736. * The signature and semantics match POSIX fread() implementations
  86737. * and can generally be used interchangeably.
  86738. *
  86739. * \param ptr The address of the read buffer.
  86740. * \param size The size of the records to be read.
  86741. * \param nmemb The number of records to be read.
  86742. * \param handle The handle to the data source.
  86743. * \retval size_t
  86744. * The number of records read.
  86745. */
  86746. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86747. /** Signature for the write callback.
  86748. * The signature and semantics match POSIX fwrite() implementations
  86749. * and can generally be used interchangeably.
  86750. *
  86751. * \param ptr The address of the write buffer.
  86752. * \param size The size of the records to be written.
  86753. * \param nmemb The number of records to be written.
  86754. * \param handle The handle to the data source.
  86755. * \retval size_t
  86756. * The number of records written.
  86757. */
  86758. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86759. /** Signature for the seek callback.
  86760. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86761. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86762. * and 32-bits wide.
  86763. *
  86764. * \param handle The handle to the data source.
  86765. * \param offset The new position, relative to \a whence
  86766. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86767. * \retval int
  86768. * \c 0 on success, \c -1 on error.
  86769. */
  86770. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86771. /** Signature for the tell callback.
  86772. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86773. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86774. * and 32-bits wide.
  86775. *
  86776. * \param handle The handle to the data source.
  86777. * \retval FLAC__int64
  86778. * The current position on success, \c -1 on error.
  86779. */
  86780. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86781. /** Signature for the EOF callback.
  86782. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86783. * on many systems, feof() is a macro, so in this case a wrapper function
  86784. * must be provided instead.
  86785. *
  86786. * \param handle The handle to the data source.
  86787. * \retval int
  86788. * \c 0 if not at end of file, nonzero if at end of file.
  86789. */
  86790. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86791. /** Signature for the close callback.
  86792. * The signature and semantics match POSIX fclose() implementations
  86793. * and can generally be used interchangeably.
  86794. *
  86795. * \param handle The handle to the data source.
  86796. * \retval int
  86797. * \c 0 on success, \c EOF on error.
  86798. */
  86799. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86800. /** A structure for holding a set of callbacks.
  86801. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86802. * describe which of the callbacks are required. The ones that are not
  86803. * required may be set to NULL.
  86804. *
  86805. * If the seek requirement for an interface is optional, you can signify that
  86806. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86807. */
  86808. typedef struct {
  86809. FLAC__IOCallback_Read read;
  86810. FLAC__IOCallback_Write write;
  86811. FLAC__IOCallback_Seek seek;
  86812. FLAC__IOCallback_Tell tell;
  86813. FLAC__IOCallback_Eof eof;
  86814. FLAC__IOCallback_Close close;
  86815. } FLAC__IOCallbacks;
  86816. /* \} */
  86817. #ifdef __cplusplus
  86818. }
  86819. #endif
  86820. #endif
  86821. /*** End of inlined file: callback.h ***/
  86822. /*** Start of inlined file: format.h ***/
  86823. #ifndef FLAC__FORMAT_H
  86824. #define FLAC__FORMAT_H
  86825. #ifdef __cplusplus
  86826. extern "C" {
  86827. #endif
  86828. /** \file include/FLAC/format.h
  86829. *
  86830. * \brief
  86831. * This module contains structure definitions for the representation
  86832. * of FLAC format components in memory. These are the basic
  86833. * structures used by the rest of the interfaces.
  86834. *
  86835. * See the detailed documentation in the
  86836. * \link flac_format format \endlink module.
  86837. */
  86838. /** \defgroup flac_format FLAC/format.h: format components
  86839. * \ingroup flac
  86840. *
  86841. * \brief
  86842. * This module contains structure definitions for the representation
  86843. * of FLAC format components in memory. These are the basic
  86844. * structures used by the rest of the interfaces.
  86845. *
  86846. * First, you should be familiar with the
  86847. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86848. * follow directly from the specification. As a user of libFLAC, the
  86849. * interesting parts really are the structures that describe the frame
  86850. * header and metadata blocks.
  86851. *
  86852. * The format structures here are very primitive, designed to store
  86853. * information in an efficient way. Reading information from the
  86854. * structures is easy but creating or modifying them directly is
  86855. * more complex. For the most part, as a user of a library, editing
  86856. * is not necessary; however, for metadata blocks it is, so there are
  86857. * convenience functions provided in the \link flac_metadata metadata
  86858. * module \endlink to simplify the manipulation of metadata blocks.
  86859. *
  86860. * \note
  86861. * It's not the best convention, but symbols ending in _LEN are in bits
  86862. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86863. * global variables because they are usually used when declaring byte
  86864. * arrays and some compilers require compile-time knowledge of array
  86865. * sizes when declared on the stack.
  86866. *
  86867. * \{
  86868. */
  86869. /*
  86870. Most of the values described in this file are defined by the FLAC
  86871. format specification. There is nothing to tune here.
  86872. */
  86873. /** The largest legal metadata type code. */
  86874. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86875. /** The minimum block size, in samples, permitted by the format. */
  86876. #define FLAC__MIN_BLOCK_SIZE (16u)
  86877. /** The maximum block size, in samples, permitted by the format. */
  86878. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86879. /** The maximum block size, in samples, permitted by the FLAC subset for
  86880. * sample rates up to 48kHz. */
  86881. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86882. /** The maximum number of channels permitted by the format. */
  86883. #define FLAC__MAX_CHANNELS (8u)
  86884. /** The minimum sample resolution permitted by the format. */
  86885. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86886. /** The maximum sample resolution permitted by the format. */
  86887. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86888. /** The maximum sample resolution permitted by libFLAC.
  86889. *
  86890. * \warning
  86891. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86892. * the reference encoder/decoder is currently limited to 24 bits because
  86893. * of prevalent 32-bit math, so make sure and use this value when
  86894. * appropriate.
  86895. */
  86896. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86897. /** The maximum sample rate permitted by the format. The value is
  86898. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86899. * as to why.
  86900. */
  86901. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86902. /** The maximum LPC order permitted by the format. */
  86903. #define FLAC__MAX_LPC_ORDER (32u)
  86904. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86905. * up to 48kHz. */
  86906. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86907. /** The minimum quantized linear predictor coefficient precision
  86908. * permitted by the format.
  86909. */
  86910. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86911. /** The maximum quantized linear predictor coefficient precision
  86912. * permitted by the format.
  86913. */
  86914. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86915. /** The maximum order of the fixed predictors permitted by the format. */
  86916. #define FLAC__MAX_FIXED_ORDER (4u)
  86917. /** The maximum Rice partition order permitted by the format. */
  86918. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86919. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86920. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86921. /** The version string of the release, stamped onto the libraries and binaries.
  86922. *
  86923. * \note
  86924. * This does not correspond to the shared library version number, which
  86925. * is used to determine binary compatibility.
  86926. */
  86927. extern FLAC_API const char *FLAC__VERSION_STRING;
  86928. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86929. * This is a NUL-terminated ASCII string; when inserted into the
  86930. * VORBIS_COMMENT the trailing null is stripped.
  86931. */
  86932. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86933. /** The byte string representation of the beginning of a FLAC stream. */
  86934. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86935. /** The 32-bit integer big-endian representation of the beginning of
  86936. * a FLAC stream.
  86937. */
  86938. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86939. /** The length of the FLAC signature in bits. */
  86940. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86941. /** The length of the FLAC signature in bytes. */
  86942. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86943. /*****************************************************************************
  86944. *
  86945. * Subframe structures
  86946. *
  86947. *****************************************************************************/
  86948. /*****************************************************************************/
  86949. /** An enumeration of the available entropy coding methods. */
  86950. typedef enum {
  86951. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86952. /**< Residual is coded by partitioning into contexts, each with it's own
  86953. * 4-bit Rice parameter. */
  86954. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86955. /**< Residual is coded by partitioning into contexts, each with it's own
  86956. * 5-bit Rice parameter. */
  86957. } FLAC__EntropyCodingMethodType;
  86958. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86959. *
  86960. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86961. * give the string equivalent. The contents should not be modified.
  86962. */
  86963. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86964. /** Contents of a Rice partitioned residual
  86965. */
  86966. typedef struct {
  86967. unsigned *parameters;
  86968. /**< The Rice parameters for each context. */
  86969. unsigned *raw_bits;
  86970. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86971. * partitions and zero for unescaped partitions.
  86972. */
  86973. unsigned capacity_by_order;
  86974. /**< The capacity of the \a parameters and \a raw_bits arrays
  86975. * specified as an order, i.e. the number of array elements
  86976. * allocated is 2 ^ \a capacity_by_order.
  86977. */
  86978. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86979. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86980. */
  86981. typedef struct {
  86982. unsigned order;
  86983. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86984. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86985. /**< The context's Rice parameters and/or raw bits. */
  86986. } FLAC__EntropyCodingMethod_PartitionedRice;
  86987. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86988. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86989. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86990. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86991. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86992. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86993. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86994. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86995. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86996. */
  86997. typedef struct {
  86998. FLAC__EntropyCodingMethodType type;
  86999. union {
  87000. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  87001. } data;
  87002. } FLAC__EntropyCodingMethod;
  87003. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  87004. /*****************************************************************************/
  87005. /** An enumeration of the available subframe types. */
  87006. typedef enum {
  87007. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  87008. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  87009. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  87010. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  87011. } FLAC__SubframeType;
  87012. /** Maps a FLAC__SubframeType to a C string.
  87013. *
  87014. * Using a FLAC__SubframeType as the index to this array will
  87015. * give the string equivalent. The contents should not be modified.
  87016. */
  87017. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  87018. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  87019. */
  87020. typedef struct {
  87021. FLAC__int32 value; /**< The constant signal value. */
  87022. } FLAC__Subframe_Constant;
  87023. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  87024. */
  87025. typedef struct {
  87026. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  87027. } FLAC__Subframe_Verbatim;
  87028. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  87029. */
  87030. typedef struct {
  87031. FLAC__EntropyCodingMethod entropy_coding_method;
  87032. /**< The residual coding method. */
  87033. unsigned order;
  87034. /**< The polynomial order. */
  87035. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  87036. /**< Warmup samples to prime the predictor, length == order. */
  87037. const FLAC__int32 *residual;
  87038. /**< The residual signal, length == (blocksize minus order) samples. */
  87039. } FLAC__Subframe_Fixed;
  87040. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  87041. */
  87042. typedef struct {
  87043. FLAC__EntropyCodingMethod entropy_coding_method;
  87044. /**< The residual coding method. */
  87045. unsigned order;
  87046. /**< The FIR order. */
  87047. unsigned qlp_coeff_precision;
  87048. /**< Quantized FIR filter coefficient precision in bits. */
  87049. int quantization_level;
  87050. /**< The qlp coeff shift needed. */
  87051. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  87052. /**< FIR filter coefficients. */
  87053. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87054. /**< Warmup samples to prime the predictor, length == order. */
  87055. const FLAC__int32 *residual;
  87056. /**< The residual signal, length == (blocksize minus order) samples. */
  87057. } FLAC__Subframe_LPC;
  87058. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87059. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87060. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87061. */
  87062. typedef struct {
  87063. FLAC__SubframeType type;
  87064. union {
  87065. FLAC__Subframe_Constant constant;
  87066. FLAC__Subframe_Fixed fixed;
  87067. FLAC__Subframe_LPC lpc;
  87068. FLAC__Subframe_Verbatim verbatim;
  87069. } data;
  87070. unsigned wasted_bits;
  87071. } FLAC__Subframe;
  87072. /** == 1 (bit)
  87073. *
  87074. * This used to be a zero-padding bit (hence the name
  87075. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87076. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87077. * to mean something else.
  87078. */
  87079. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87080. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87081. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87082. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87083. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87084. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87085. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87086. /*****************************************************************************/
  87087. /*****************************************************************************
  87088. *
  87089. * Frame structures
  87090. *
  87091. *****************************************************************************/
  87092. /** An enumeration of the available channel assignments. */
  87093. typedef enum {
  87094. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87095. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87096. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87097. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87098. } FLAC__ChannelAssignment;
  87099. /** Maps a FLAC__ChannelAssignment to a C string.
  87100. *
  87101. * Using a FLAC__ChannelAssignment as the index to this array will
  87102. * give the string equivalent. The contents should not be modified.
  87103. */
  87104. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87105. /** An enumeration of the possible frame numbering methods. */
  87106. typedef enum {
  87107. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87108. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87109. } FLAC__FrameNumberType;
  87110. /** Maps a FLAC__FrameNumberType to a C string.
  87111. *
  87112. * Using a FLAC__FrameNumberType as the index to this array will
  87113. * give the string equivalent. The contents should not be modified.
  87114. */
  87115. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87116. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87117. */
  87118. typedef struct {
  87119. unsigned blocksize;
  87120. /**< The number of samples per subframe. */
  87121. unsigned sample_rate;
  87122. /**< The sample rate in Hz. */
  87123. unsigned channels;
  87124. /**< The number of channels (== number of subframes). */
  87125. FLAC__ChannelAssignment channel_assignment;
  87126. /**< The channel assignment for the frame. */
  87127. unsigned bits_per_sample;
  87128. /**< The sample resolution. */
  87129. FLAC__FrameNumberType number_type;
  87130. /**< The numbering scheme used for the frame. As a convenience, the
  87131. * decoder will always convert a frame number to a sample number because
  87132. * the rules are complex. */
  87133. union {
  87134. FLAC__uint32 frame_number;
  87135. FLAC__uint64 sample_number;
  87136. } number;
  87137. /**< The frame number or sample number of first sample in frame;
  87138. * use the \a number_type value to determine which to use. */
  87139. FLAC__uint8 crc;
  87140. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87141. * of the raw frame header bytes, meaning everything before the CRC byte
  87142. * including the sync code.
  87143. */
  87144. } FLAC__FrameHeader;
  87145. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87146. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87147. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87148. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87149. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87150. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87151. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87152. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87153. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87154. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87155. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87156. */
  87157. typedef struct {
  87158. FLAC__uint16 crc;
  87159. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87160. * 0) of the bytes before the crc, back to and including the frame header
  87161. * sync code.
  87162. */
  87163. } FLAC__FrameFooter;
  87164. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87165. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87166. */
  87167. typedef struct {
  87168. FLAC__FrameHeader header;
  87169. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87170. FLAC__FrameFooter footer;
  87171. } FLAC__Frame;
  87172. /*****************************************************************************/
  87173. /*****************************************************************************
  87174. *
  87175. * Meta-data structures
  87176. *
  87177. *****************************************************************************/
  87178. /** An enumeration of the available metadata block types. */
  87179. typedef enum {
  87180. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87181. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87182. FLAC__METADATA_TYPE_PADDING = 1,
  87183. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87184. FLAC__METADATA_TYPE_APPLICATION = 2,
  87185. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87186. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87187. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87188. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87189. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87190. FLAC__METADATA_TYPE_CUESHEET = 5,
  87191. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87192. FLAC__METADATA_TYPE_PICTURE = 6,
  87193. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87194. FLAC__METADATA_TYPE_UNDEFINED = 7
  87195. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87196. } FLAC__MetadataType;
  87197. /** Maps a FLAC__MetadataType to a C string.
  87198. *
  87199. * Using a FLAC__MetadataType as the index to this array will
  87200. * give the string equivalent. The contents should not be modified.
  87201. */
  87202. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87203. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87204. */
  87205. typedef struct {
  87206. unsigned min_blocksize, max_blocksize;
  87207. unsigned min_framesize, max_framesize;
  87208. unsigned sample_rate;
  87209. unsigned channels;
  87210. unsigned bits_per_sample;
  87211. FLAC__uint64 total_samples;
  87212. FLAC__byte md5sum[16];
  87213. } FLAC__StreamMetadata_StreamInfo;
  87214. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87215. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87216. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87217. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87218. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87220. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87221. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87222. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87223. /** The total stream length of the STREAMINFO block in bytes. */
  87224. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87225. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87226. */
  87227. typedef struct {
  87228. int dummy;
  87229. /**< Conceptually this is an empty struct since we don't store the
  87230. * padding bytes. Empty structs are not allowed by some C compilers,
  87231. * hence the dummy.
  87232. */
  87233. } FLAC__StreamMetadata_Padding;
  87234. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87235. */
  87236. typedef struct {
  87237. FLAC__byte id[4];
  87238. FLAC__byte *data;
  87239. } FLAC__StreamMetadata_Application;
  87240. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87241. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87242. */
  87243. typedef struct {
  87244. FLAC__uint64 sample_number;
  87245. /**< The sample number of the target frame. */
  87246. FLAC__uint64 stream_offset;
  87247. /**< The offset, in bytes, of the target frame with respect to
  87248. * beginning of the first frame. */
  87249. unsigned frame_samples;
  87250. /**< The number of samples in the target frame. */
  87251. } FLAC__StreamMetadata_SeekPoint;
  87252. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87253. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87254. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87255. /** The total stream length of a seek point in bytes. */
  87256. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87257. /** The value used in the \a sample_number field of
  87258. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87259. * point (== 0xffffffffffffffff).
  87260. */
  87261. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87262. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87263. *
  87264. * \note From the format specification:
  87265. * - The seek points must be sorted by ascending sample number.
  87266. * - Each seek point's sample number must be the first sample of the
  87267. * target frame.
  87268. * - Each seek point's sample number must be unique within the table.
  87269. * - Existence of a SEEKTABLE block implies a correct setting of
  87270. * total_samples in the stream_info block.
  87271. * - Behavior is undefined when more than one SEEKTABLE block is
  87272. * present in a stream.
  87273. */
  87274. typedef struct {
  87275. unsigned num_points;
  87276. FLAC__StreamMetadata_SeekPoint *points;
  87277. } FLAC__StreamMetadata_SeekTable;
  87278. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87279. *
  87280. * For convenience, the APIs maintain a trailing NUL character at the end of
  87281. * \a entry which is not counted toward \a length, i.e.
  87282. * \code strlen(entry) == length \endcode
  87283. */
  87284. typedef struct {
  87285. FLAC__uint32 length;
  87286. FLAC__byte *entry;
  87287. } FLAC__StreamMetadata_VorbisComment_Entry;
  87288. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87289. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87290. */
  87291. typedef struct {
  87292. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87293. FLAC__uint32 num_comments;
  87294. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87295. } FLAC__StreamMetadata_VorbisComment;
  87296. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87297. /** FLAC CUESHEET track index structure. (See the
  87298. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87299. * the full description of each field.)
  87300. */
  87301. typedef struct {
  87302. FLAC__uint64 offset;
  87303. /**< Offset in samples, relative to the track offset, of the index
  87304. * point.
  87305. */
  87306. FLAC__byte number;
  87307. /**< The index point number. */
  87308. } FLAC__StreamMetadata_CueSheet_Index;
  87309. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87310. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87311. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87312. /** FLAC CUESHEET track structure. (See the
  87313. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87314. * the full description of each field.)
  87315. */
  87316. typedef struct {
  87317. FLAC__uint64 offset;
  87318. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87319. FLAC__byte number;
  87320. /**< The track number. */
  87321. char isrc[13];
  87322. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87323. unsigned type:1;
  87324. /**< The track type: 0 for audio, 1 for non-audio. */
  87325. unsigned pre_emphasis:1;
  87326. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87327. FLAC__byte num_indices;
  87328. /**< The number of track index points. */
  87329. FLAC__StreamMetadata_CueSheet_Index *indices;
  87330. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87331. } FLAC__StreamMetadata_CueSheet_Track;
  87332. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87333. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87334. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87335. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87336. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87337. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87338. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87339. /** FLAC CUESHEET structure. (See the
  87340. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87341. * for the full description of each field.)
  87342. */
  87343. typedef struct {
  87344. char media_catalog_number[129];
  87345. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87346. * general, the media catalog number may be 0 to 128 bytes long; any
  87347. * unused characters should be right-padded with NUL characters.
  87348. */
  87349. FLAC__uint64 lead_in;
  87350. /**< The number of lead-in samples. */
  87351. FLAC__bool is_cd;
  87352. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87353. unsigned num_tracks;
  87354. /**< The number of tracks. */
  87355. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87356. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87357. } FLAC__StreamMetadata_CueSheet;
  87358. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87359. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87360. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87361. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87362. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87363. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87364. typedef enum {
  87365. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87366. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87367. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87368. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87369. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87370. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87371. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87372. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87373. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87374. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87375. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87376. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87377. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87378. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87379. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87380. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87381. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87382. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87383. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87384. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87385. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87386. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87387. } FLAC__StreamMetadata_Picture_Type;
  87388. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87389. *
  87390. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87391. * will give the string equivalent. The contents should not be
  87392. * modified.
  87393. */
  87394. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87395. /** FLAC PICTURE structure. (See the
  87396. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87397. * for the full description of each field.)
  87398. */
  87399. typedef struct {
  87400. FLAC__StreamMetadata_Picture_Type type;
  87401. /**< The kind of picture stored. */
  87402. char *mime_type;
  87403. /**< Picture data's MIME type, in ASCII printable characters
  87404. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87405. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87406. * MIME type of '-->' is also allowed, in which case the picture
  87407. * data should be a complete URL. In file storage, the MIME type is
  87408. * stored as a 32-bit length followed by the ASCII string with no NUL
  87409. * terminator, but is converted to a plain C string in this structure
  87410. * for convenience.
  87411. */
  87412. FLAC__byte *description;
  87413. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87414. * the description is stored as a 32-bit length followed by the UTF-8
  87415. * string with no NUL terminator, but is converted to a plain C string
  87416. * in this structure for convenience.
  87417. */
  87418. FLAC__uint32 width;
  87419. /**< Picture's width in pixels. */
  87420. FLAC__uint32 height;
  87421. /**< Picture's height in pixels. */
  87422. FLAC__uint32 depth;
  87423. /**< Picture's color depth in bits-per-pixel. */
  87424. FLAC__uint32 colors;
  87425. /**< For indexed palettes (like GIF), picture's number of colors (the
  87426. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87427. */
  87428. FLAC__uint32 data_length;
  87429. /**< Length of binary picture data in bytes. */
  87430. FLAC__byte *data;
  87431. /**< Binary picture data. */
  87432. } FLAC__StreamMetadata_Picture;
  87433. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87434. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87435. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87436. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87437. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87438. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87439. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87440. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87441. /** Structure that is used when a metadata block of unknown type is loaded.
  87442. * The contents are opaque. The structure is used only internally to
  87443. * correctly handle unknown metadata.
  87444. */
  87445. typedef struct {
  87446. FLAC__byte *data;
  87447. } FLAC__StreamMetadata_Unknown;
  87448. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87449. */
  87450. typedef struct {
  87451. FLAC__MetadataType type;
  87452. /**< The type of the metadata block; used determine which member of the
  87453. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87454. * then \a data.unknown must be used. */
  87455. FLAC__bool is_last;
  87456. /**< \c true if this metadata block is the last, else \a false */
  87457. unsigned length;
  87458. /**< Length, in bytes, of the block data as it appears in the stream. */
  87459. union {
  87460. FLAC__StreamMetadata_StreamInfo stream_info;
  87461. FLAC__StreamMetadata_Padding padding;
  87462. FLAC__StreamMetadata_Application application;
  87463. FLAC__StreamMetadata_SeekTable seek_table;
  87464. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87465. FLAC__StreamMetadata_CueSheet cue_sheet;
  87466. FLAC__StreamMetadata_Picture picture;
  87467. FLAC__StreamMetadata_Unknown unknown;
  87468. } data;
  87469. /**< Polymorphic block data; use the \a type value to determine which
  87470. * to use. */
  87471. } FLAC__StreamMetadata;
  87472. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87473. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87474. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87475. /** The total stream length of a metadata block header in bytes. */
  87476. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87477. /*****************************************************************************/
  87478. /*****************************************************************************
  87479. *
  87480. * Utility functions
  87481. *
  87482. *****************************************************************************/
  87483. /** Tests that a sample rate is valid for FLAC.
  87484. *
  87485. * \param sample_rate The sample rate to test for compliance.
  87486. * \retval FLAC__bool
  87487. * \c true if the given sample rate conforms to the specification, else
  87488. * \c false.
  87489. */
  87490. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87491. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87492. * for valid sample rates are slightly more complex since the rate has to
  87493. * be expressible completely in the frame header.
  87494. *
  87495. * \param sample_rate The sample rate to test for compliance.
  87496. * \retval FLAC__bool
  87497. * \c true if the given sample rate conforms to the specification for the
  87498. * subset, else \c false.
  87499. */
  87500. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87501. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87502. * comment specification.
  87503. *
  87504. * Vorbis comment names must be composed only of characters from
  87505. * [0x20-0x3C,0x3E-0x7D].
  87506. *
  87507. * \param name A NUL-terminated string to be checked.
  87508. * \assert
  87509. * \code name != NULL \endcode
  87510. * \retval FLAC__bool
  87511. * \c false if entry name is illegal, else \c true.
  87512. */
  87513. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87514. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87515. * comment specification.
  87516. *
  87517. * Vorbis comment values must be valid UTF-8 sequences.
  87518. *
  87519. * \param value A string to be checked.
  87520. * \param length A the length of \a value in bytes. May be
  87521. * \c (unsigned)(-1) to indicate that \a value is a plain
  87522. * UTF-8 NUL-terminated string.
  87523. * \assert
  87524. * \code value != NULL \endcode
  87525. * \retval FLAC__bool
  87526. * \c false if entry name is illegal, else \c true.
  87527. */
  87528. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87529. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87530. * comment specification.
  87531. *
  87532. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87533. * 'value' must be legal according to
  87534. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87535. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87536. *
  87537. * \param entry An entry to be checked.
  87538. * \param length The length of \a entry in bytes.
  87539. * \assert
  87540. * \code value != NULL \endcode
  87541. * \retval FLAC__bool
  87542. * \c false if entry name is illegal, else \c true.
  87543. */
  87544. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87545. /** Check a seek table to see if it conforms to the FLAC specification.
  87546. * See the format specification for limits on the contents of the
  87547. * seek table.
  87548. *
  87549. * \param seek_table A pointer to a seek table to be checked.
  87550. * \assert
  87551. * \code seek_table != NULL \endcode
  87552. * \retval FLAC__bool
  87553. * \c false if seek table is illegal, else \c true.
  87554. */
  87555. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87556. /** Sort a seek table's seek points according to the format specification.
  87557. * This includes a "unique-ification" step to remove duplicates, i.e.
  87558. * seek points with identical \a sample_number values. Duplicate seek
  87559. * points are converted into placeholder points and sorted to the end of
  87560. * the table.
  87561. *
  87562. * \param seek_table A pointer to a seek table to be sorted.
  87563. * \assert
  87564. * \code seek_table != NULL \endcode
  87565. * \retval unsigned
  87566. * The number of duplicate seek points converted into placeholders.
  87567. */
  87568. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87569. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87570. * See the format specification for limits on the contents of the
  87571. * cue sheet.
  87572. *
  87573. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87574. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87575. * stringent requirements for a CD-DA (audio) disc.
  87576. * \param violation Address of a pointer to a string. If there is a
  87577. * violation, a pointer to a string explanation of the
  87578. * violation will be returned here. \a violation may be
  87579. * \c NULL if you don't need the returned string. Do not
  87580. * free the returned string; it will always point to static
  87581. * data.
  87582. * \assert
  87583. * \code cue_sheet != NULL \endcode
  87584. * \retval FLAC__bool
  87585. * \c false if cue sheet is illegal, else \c true.
  87586. */
  87587. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87588. /** Check picture data to see if it conforms to the FLAC specification.
  87589. * See the format specification for limits on the contents of the
  87590. * PICTURE block.
  87591. *
  87592. * \param picture A pointer to existing picture data to be checked.
  87593. * \param violation Address of a pointer to a string. If there is a
  87594. * violation, a pointer to a string explanation of the
  87595. * violation will be returned here. \a violation may be
  87596. * \c NULL if you don't need the returned string. Do not
  87597. * free the returned string; it will always point to static
  87598. * data.
  87599. * \assert
  87600. * \code picture != NULL \endcode
  87601. * \retval FLAC__bool
  87602. * \c false if picture data is illegal, else \c true.
  87603. */
  87604. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87605. /* \} */
  87606. #ifdef __cplusplus
  87607. }
  87608. #endif
  87609. #endif
  87610. /*** End of inlined file: format.h ***/
  87611. /*** Start of inlined file: metadata.h ***/
  87612. #ifndef FLAC__METADATA_H
  87613. #define FLAC__METADATA_H
  87614. #include <sys/types.h> /* for off_t */
  87615. /* --------------------------------------------------------------------
  87616. (For an example of how all these routines are used, see the source
  87617. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87618. metaflac in src/metaflac/)
  87619. ------------------------------------------------------------------*/
  87620. /** \file include/FLAC/metadata.h
  87621. *
  87622. * \brief
  87623. * This module provides functions for creating and manipulating FLAC
  87624. * metadata blocks in memory, and three progressively more powerful
  87625. * interfaces for traversing and editing metadata in FLAC files.
  87626. *
  87627. * See the detailed documentation for each interface in the
  87628. * \link flac_metadata metadata \endlink module.
  87629. */
  87630. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87631. * \ingroup flac
  87632. *
  87633. * \brief
  87634. * This module provides functions for creating and manipulating FLAC
  87635. * metadata blocks in memory, and three progressively more powerful
  87636. * interfaces for traversing and editing metadata in native FLAC files.
  87637. * Note that currently only the Chain interface (level 2) supports Ogg
  87638. * FLAC files, and it is read-only i.e. no writing back changed
  87639. * metadata to file.
  87640. *
  87641. * There are three metadata interfaces of increasing complexity:
  87642. *
  87643. * Level 0:
  87644. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87645. * PICTURE blocks.
  87646. *
  87647. * Level 1:
  87648. * Read-write access to all metadata blocks. This level is write-
  87649. * efficient in most cases (more on this below), and uses less memory
  87650. * than level 2.
  87651. *
  87652. * Level 2:
  87653. * Read-write access to all metadata blocks. This level is write-
  87654. * efficient in all cases, but uses more memory since all metadata for
  87655. * the whole file is read into memory and manipulated before writing
  87656. * out again.
  87657. *
  87658. * What do we mean by efficient? Since FLAC metadata appears at the
  87659. * beginning of the file, when writing metadata back to a FLAC file
  87660. * it is possible to grow or shrink the metadata such that the entire
  87661. * file must be rewritten. However, if the size remains the same during
  87662. * changes or PADDING blocks are utilized, only the metadata needs to be
  87663. * overwritten, which is much faster.
  87664. *
  87665. * Efficient means the whole file is rewritten at most one time, and only
  87666. * when necessary. Level 1 is not efficient only in the case that you
  87667. * cause more than one metadata block to grow or shrink beyond what can
  87668. * be accomodated by padding. In this case you should probably use level
  87669. * 2, which allows you to edit all the metadata for a file in memory and
  87670. * write it out all at once.
  87671. *
  87672. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87673. * front of the file.
  87674. *
  87675. * All levels access files via their filenames. In addition, level 2
  87676. * has additional alternative read and write functions that take an I/O
  87677. * handle and callbacks, for situations where access by filename is not
  87678. * possible.
  87679. *
  87680. * In addition to the three interfaces, this module defines functions for
  87681. * creating and manipulating various metadata objects in memory. As we see
  87682. * from the Format module, FLAC metadata blocks in memory are very primitive
  87683. * structures for storing information in an efficient way. Reading
  87684. * information from the structures is easy but creating or modifying them
  87685. * directly is more complex. The metadata object routines here facilitate
  87686. * this by taking care of the consistency and memory management drudgery.
  87687. *
  87688. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87689. * metadata however, you will not probably not need these.
  87690. *
  87691. * From a dependency standpoint, none of the encoders or decoders require
  87692. * the metadata module. This is so that embedded users can strip out the
  87693. * metadata module from libFLAC to reduce the size and complexity.
  87694. */
  87695. #ifdef __cplusplus
  87696. extern "C" {
  87697. #endif
  87698. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87699. * \ingroup flac_metadata
  87700. *
  87701. * \brief
  87702. * The level 0 interface consists of individual routines to read the
  87703. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87704. * only a filename.
  87705. *
  87706. * They try to skip any ID3v2 tag at the head of the file.
  87707. *
  87708. * \{
  87709. */
  87710. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87711. * will try to skip any ID3v2 tag at the head of the file.
  87712. *
  87713. * \param filename The path to the FLAC file to read.
  87714. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87715. * FLAC__StreamMetadata is a simple structure with no
  87716. * memory allocation involved, you pass the address of
  87717. * an existing structure. It need not be initialized.
  87718. * \assert
  87719. * \code filename != NULL \endcode
  87720. * \code streaminfo != NULL \endcode
  87721. * \retval FLAC__bool
  87722. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87723. * \c false if there was a memory allocation error, a file decoder error,
  87724. * or the file contained no STREAMINFO block. (A memory allocation error
  87725. * is possible because this function must set up a file decoder.)
  87726. */
  87727. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87728. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87729. * function will try to skip any ID3v2 tag at the head of the file.
  87730. *
  87731. * \param filename The path to the FLAC file to read.
  87732. * \param tags The address where the returned pointer will be
  87733. * stored. The \a tags object must be deleted by
  87734. * the caller using FLAC__metadata_object_delete().
  87735. * \assert
  87736. * \code filename != NULL \endcode
  87737. * \code tags != NULL \endcode
  87738. * \retval FLAC__bool
  87739. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87740. * and \a *tags will be set to the address of the metadata structure.
  87741. * Returns \c false if there was a memory allocation error, a file
  87742. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87743. * \a *tags will be set to \c NULL.
  87744. */
  87745. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87746. /** Read the CUESHEET metadata block of the given FLAC file. This
  87747. * function will try to skip any ID3v2 tag at the head of the file.
  87748. *
  87749. * \param filename The path to the FLAC file to read.
  87750. * \param cuesheet The address where the returned pointer will be
  87751. * stored. The \a cuesheet object must be deleted by
  87752. * the caller using FLAC__metadata_object_delete().
  87753. * \assert
  87754. * \code filename != NULL \endcode
  87755. * \code cuesheet != NULL \endcode
  87756. * \retval FLAC__bool
  87757. * \c true if a valid CUESHEET block was read from \a filename,
  87758. * and \a *cuesheet will be set to the address of the metadata
  87759. * structure. Returns \c false if there was a memory allocation
  87760. * error, a file decoder error, or the file contained no CUESHEET
  87761. * block, and \a *cuesheet will be set to \c NULL.
  87762. */
  87763. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87764. /** Read a PICTURE metadata block of the given FLAC file. This
  87765. * function will try to skip any ID3v2 tag at the head of the file.
  87766. * Since there can be more than one PICTURE block in a file, this
  87767. * function takes a number of parameters that act as constraints to
  87768. * the search. The PICTURE block with the largest area matching all
  87769. * the constraints will be returned, or \a *picture will be set to
  87770. * \c NULL if there was no such block.
  87771. *
  87772. * \param filename The path to the FLAC file to read.
  87773. * \param picture The address where the returned pointer will be
  87774. * stored. The \a picture object must be deleted by
  87775. * the caller using FLAC__metadata_object_delete().
  87776. * \param type The desired picture type. Use \c -1 to mean
  87777. * "any type".
  87778. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87779. * string will be matched exactly. Use \c NULL to
  87780. * mean "any MIME type".
  87781. * \param description The desired description. The string will be
  87782. * matched exactly. Use \c NULL to mean "any
  87783. * description".
  87784. * \param max_width The maximum width in pixels desired. Use
  87785. * \c (unsigned)(-1) to mean "any width".
  87786. * \param max_height The maximum height in pixels desired. Use
  87787. * \c (unsigned)(-1) to mean "any height".
  87788. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87789. * Use \c (unsigned)(-1) to mean "any depth".
  87790. * \param max_colors The maximum number of colors desired. Use
  87791. * \c (unsigned)(-1) to mean "any number of colors".
  87792. * \assert
  87793. * \code filename != NULL \endcode
  87794. * \code picture != NULL \endcode
  87795. * \retval FLAC__bool
  87796. * \c true if a valid PICTURE block was read from \a filename,
  87797. * and \a *picture will be set to the address of the metadata
  87798. * structure. Returns \c false if there was a memory allocation
  87799. * error, a file decoder error, or the file contained no PICTURE
  87800. * block, and \a *picture will be set to \c NULL.
  87801. */
  87802. 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);
  87803. /* \} */
  87804. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87805. * \ingroup flac_metadata
  87806. *
  87807. * \brief
  87808. * The level 1 interface provides read-write access to FLAC file metadata and
  87809. * operates directly on the FLAC file.
  87810. *
  87811. * The general usage of this interface is:
  87812. *
  87813. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87814. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87815. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87816. * see if the file is writable, or only read access is allowed.
  87817. * - Use FLAC__metadata_simple_iterator_next() and
  87818. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87819. * This is does not read the actual blocks themselves.
  87820. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87821. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87822. * forward from the front of the file.
  87823. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87824. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87825. * the current iterator position. The returned object is yours to modify
  87826. * and free.
  87827. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87828. * back. You must have write permission to the original file. Make sure to
  87829. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87830. * below.
  87831. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87832. * Use the object creation functions from
  87833. * \link flac_metadata_object here \endlink to generate new objects.
  87834. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87835. * currently referred to by the iterator, or replace it with padding.
  87836. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87837. * finished.
  87838. *
  87839. * \note
  87840. * The FLAC file remains open the whole time between
  87841. * FLAC__metadata_simple_iterator_init() and
  87842. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87843. * the file during this time.
  87844. *
  87845. * \note
  87846. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87847. * FLAC__StreamMetadata objects. These are managed automatically.
  87848. *
  87849. * \note
  87850. * If any of the modification functions
  87851. * (FLAC__metadata_simple_iterator_set_block(),
  87852. * FLAC__metadata_simple_iterator_delete_block(),
  87853. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87854. * you should delete the iterator as it may no longer be valid.
  87855. *
  87856. * \{
  87857. */
  87858. struct FLAC__Metadata_SimpleIterator;
  87859. /** The opaque structure definition for the level 1 iterator type.
  87860. * See the
  87861. * \link flac_metadata_level1 metadata level 1 module \endlink
  87862. * for a detailed description.
  87863. */
  87864. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87865. /** Status type for FLAC__Metadata_SimpleIterator.
  87866. *
  87867. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87868. */
  87869. typedef enum {
  87870. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87871. /**< The iterator is in the normal OK state */
  87872. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87873. /**< The data passed into a function violated the function's usage criteria */
  87874. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87875. /**< The iterator could not open the target file */
  87876. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87877. /**< The iterator could not find the FLAC signature at the start of the file */
  87878. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87879. /**< The iterator tried to write to a file that was not writable */
  87880. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87881. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87882. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87883. /**< The iterator encountered an error while reading the FLAC file */
  87884. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87885. /**< The iterator encountered an error while seeking in the FLAC file */
  87886. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87887. /**< The iterator encountered an error while writing the FLAC file */
  87888. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87889. /**< The iterator encountered an error renaming the FLAC file */
  87890. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87891. /**< The iterator encountered an error removing the temporary file */
  87892. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87893. /**< Memory allocation failed */
  87894. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87895. /**< The caller violated an assertion or an unexpected error occurred */
  87896. } FLAC__Metadata_SimpleIteratorStatus;
  87897. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87898. *
  87899. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87900. * will give the string equivalent. The contents should not be modified.
  87901. */
  87902. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87903. /** Create a new iterator instance.
  87904. *
  87905. * \retval FLAC__Metadata_SimpleIterator*
  87906. * \c NULL if there was an error allocating memory, else the new instance.
  87907. */
  87908. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87909. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87910. *
  87911. * \param iterator A pointer to an existing iterator.
  87912. * \assert
  87913. * \code iterator != NULL \endcode
  87914. */
  87915. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87916. /** Get the current status of the iterator. Call this after a function
  87917. * returns \c false to get the reason for the error. Also resets the status
  87918. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87919. *
  87920. * \param iterator A pointer to an existing iterator.
  87921. * \assert
  87922. * \code iterator != NULL \endcode
  87923. * \retval FLAC__Metadata_SimpleIteratorStatus
  87924. * The current status of the iterator.
  87925. */
  87926. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87927. /** Initialize the iterator to point to the first metadata block in the
  87928. * given FLAC file.
  87929. *
  87930. * \param iterator A pointer to an existing iterator.
  87931. * \param filename The path to the FLAC file.
  87932. * \param read_only If \c true, the FLAC file will be opened
  87933. * in read-only mode; if \c false, the FLAC
  87934. * file will be opened for edit even if no
  87935. * edits are performed.
  87936. * \param preserve_file_stats If \c true, the owner and modification
  87937. * time will be preserved even if the FLAC
  87938. * file is written to.
  87939. * \assert
  87940. * \code iterator != NULL \endcode
  87941. * \code filename != NULL \endcode
  87942. * \retval FLAC__bool
  87943. * \c false if a memory allocation error occurs, the file can't be
  87944. * opened, or another error occurs, else \c true.
  87945. */
  87946. 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);
  87947. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87948. * FLAC__metadata_simple_iterator_set_block() and
  87949. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87950. *
  87951. * \param iterator A pointer to an existing iterator.
  87952. * \assert
  87953. * \code iterator != NULL \endcode
  87954. * \retval FLAC__bool
  87955. * See above.
  87956. */
  87957. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87958. /** Moves the iterator forward one metadata block, returning \c false if
  87959. * already at the end.
  87960. *
  87961. * \param iterator A pointer to an existing initialized iterator.
  87962. * \assert
  87963. * \code iterator != NULL \endcode
  87964. * \a iterator has been successfully initialized with
  87965. * FLAC__metadata_simple_iterator_init()
  87966. * \retval FLAC__bool
  87967. * \c false if already at the last metadata block of the chain, else
  87968. * \c true.
  87969. */
  87970. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87971. /** Moves the iterator backward one metadata block, returning \c false if
  87972. * already at the beginning.
  87973. *
  87974. * \param iterator A pointer to an existing initialized iterator.
  87975. * \assert
  87976. * \code iterator != NULL \endcode
  87977. * \a iterator has been successfully initialized with
  87978. * FLAC__metadata_simple_iterator_init()
  87979. * \retval FLAC__bool
  87980. * \c false if already at the first metadata block of the chain, else
  87981. * \c true.
  87982. */
  87983. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87984. /** Returns a flag telling if the current metadata block is the last.
  87985. *
  87986. * \param iterator A pointer to an existing initialized iterator.
  87987. * \assert
  87988. * \code iterator != NULL \endcode
  87989. * \a iterator has been successfully initialized with
  87990. * FLAC__metadata_simple_iterator_init()
  87991. * \retval FLAC__bool
  87992. * \c true if the current metadata block is the last in the file,
  87993. * else \c false.
  87994. */
  87995. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87996. /** Get the offset of the metadata block at the current position. This
  87997. * avoids reading the actual block data which can save time for large
  87998. * blocks.
  87999. *
  88000. * \param iterator A pointer to an existing initialized iterator.
  88001. * \assert
  88002. * \code iterator != NULL \endcode
  88003. * \a iterator has been successfully initialized with
  88004. * FLAC__metadata_simple_iterator_init()
  88005. * \retval off_t
  88006. * The offset of the metadata block at the current iterator position.
  88007. * This is the byte offset relative to the beginning of the file of
  88008. * the current metadata block's header.
  88009. */
  88010. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  88011. /** Get the type of the metadata block at the current position. This
  88012. * avoids reading the actual block data which can save time for large
  88013. * blocks.
  88014. *
  88015. * \param iterator A pointer to an existing initialized iterator.
  88016. * \assert
  88017. * \code iterator != NULL \endcode
  88018. * \a iterator has been successfully initialized with
  88019. * FLAC__metadata_simple_iterator_init()
  88020. * \retval FLAC__MetadataType
  88021. * The type of the metadata block at the current iterator position.
  88022. */
  88023. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  88024. /** Get the length of the metadata block at the current position. This
  88025. * avoids reading the actual block data which can save time for large
  88026. * blocks.
  88027. *
  88028. * \param iterator A pointer to an existing initialized iterator.
  88029. * \assert
  88030. * \code iterator != NULL \endcode
  88031. * \a iterator has been successfully initialized with
  88032. * FLAC__metadata_simple_iterator_init()
  88033. * \retval unsigned
  88034. * The length of the metadata block at the current iterator position.
  88035. * The is same length as that in the
  88036. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  88037. * i.e. the length of the metadata body that follows the header.
  88038. */
  88039. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  88040. /** Get the application ID of the \c APPLICATION block at the current
  88041. * position. This avoids reading the actual block data which can save
  88042. * time for large blocks.
  88043. *
  88044. * \param iterator A pointer to an existing initialized iterator.
  88045. * \param id A pointer to a buffer of at least \c 4 bytes where
  88046. * the ID will be stored.
  88047. * \assert
  88048. * \code iterator != NULL \endcode
  88049. * \code id != NULL \endcode
  88050. * \a iterator has been successfully initialized with
  88051. * FLAC__metadata_simple_iterator_init()
  88052. * \retval FLAC__bool
  88053. * \c true if the ID was successfully read, else \c false, in which
  88054. * case you should check FLAC__metadata_simple_iterator_status() to
  88055. * find out why. If the status is
  88056. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88057. * current metadata block is not an \c APPLICATION block. Otherwise
  88058. * if the status is
  88059. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88060. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88061. * occurred and the iterator can no longer be used.
  88062. */
  88063. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88064. /** Get the metadata block at the current position. You can modify the
  88065. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88066. * write it back to the FLAC file.
  88067. *
  88068. * You must call FLAC__metadata_object_delete() on the returned object
  88069. * when you are finished with it.
  88070. *
  88071. * \param iterator A pointer to an existing initialized iterator.
  88072. * \assert
  88073. * \code iterator != NULL \endcode
  88074. * \a iterator has been successfully initialized with
  88075. * FLAC__metadata_simple_iterator_init()
  88076. * \retval FLAC__StreamMetadata*
  88077. * The current metadata block, or \c NULL if there was a memory
  88078. * allocation error.
  88079. */
  88080. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88081. /** Write a block back to the FLAC file. This function tries to be
  88082. * as efficient as possible; how the block is actually written is
  88083. * shown by the following:
  88084. *
  88085. * Existing block is a STREAMINFO block and the new block is a
  88086. * STREAMINFO block: the new block is written in place. Make sure
  88087. * you know what you're doing when changing the values of a
  88088. * STREAMINFO block.
  88089. *
  88090. * Existing block is a STREAMINFO block and the new block is a
  88091. * not a STREAMINFO block: this is an error since the first block
  88092. * must be a STREAMINFO block. Returns \c false without altering the
  88093. * file.
  88094. *
  88095. * Existing block is not a STREAMINFO block and the new block is a
  88096. * STREAMINFO block: this is an error since there may be only one
  88097. * STREAMINFO block. Returns \c false without altering the file.
  88098. *
  88099. * Existing block and new block are the same length: the existing
  88100. * block will be replaced by the new block, written in place.
  88101. *
  88102. * Existing block is longer than new block: if use_padding is \c true,
  88103. * the existing block will be overwritten in place with the new
  88104. * block followed by a PADDING block, if possible, to make the total
  88105. * size the same as the existing block. Remember that a padding
  88106. * block requires at least four bytes so if the difference in size
  88107. * between the new block and existing block is less than that, the
  88108. * entire file will have to be rewritten, using the new block's
  88109. * exact size. If use_padding is \c false, the entire file will be
  88110. * rewritten, replacing the existing block by the new block.
  88111. *
  88112. * Existing block is shorter than new block: if use_padding is \c true,
  88113. * the function will try and expand the new block into the following
  88114. * PADDING block, if it exists and doing so won't shrink the PADDING
  88115. * block to less than 4 bytes. If there is no following PADDING
  88116. * block, or it will shrink to less than 4 bytes, or use_padding is
  88117. * \c false, the entire file is rewritten, replacing the existing block
  88118. * with the new block. Note that in this case any following PADDING
  88119. * block is preserved as is.
  88120. *
  88121. * After writing the block, the iterator will remain in the same
  88122. * place, i.e. pointing to the new block.
  88123. *
  88124. * \param iterator A pointer to an existing initialized iterator.
  88125. * \param block The block to set.
  88126. * \param use_padding See above.
  88127. * \assert
  88128. * \code iterator != NULL \endcode
  88129. * \a iterator has been successfully initialized with
  88130. * FLAC__metadata_simple_iterator_init()
  88131. * \code block != NULL \endcode
  88132. * \retval FLAC__bool
  88133. * \c true if successful, else \c false.
  88134. */
  88135. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88136. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88137. * except that instead of writing over an existing block, it appends
  88138. * a block after the existing block. \a use_padding is again used to
  88139. * tell the function to try an expand into following padding in an
  88140. * attempt to avoid rewriting the entire file.
  88141. *
  88142. * This function will fail and return \c false if given a STREAMINFO
  88143. * block.
  88144. *
  88145. * After writing the block, the iterator will be pointing to the
  88146. * new block.
  88147. *
  88148. * \param iterator A pointer to an existing initialized iterator.
  88149. * \param block The block to set.
  88150. * \param use_padding See above.
  88151. * \assert
  88152. * \code iterator != NULL \endcode
  88153. * \a iterator has been successfully initialized with
  88154. * FLAC__metadata_simple_iterator_init()
  88155. * \code block != NULL \endcode
  88156. * \retval FLAC__bool
  88157. * \c true if successful, else \c false.
  88158. */
  88159. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88160. /** Deletes the block at the current position. This will cause the
  88161. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88162. * in which case the block will be replaced by an equal-sized PADDING
  88163. * block. The iterator will be left pointing to the block before the
  88164. * one just deleted.
  88165. *
  88166. * You may not delete the STREAMINFO block.
  88167. *
  88168. * \param iterator A pointer to an existing initialized iterator.
  88169. * \param use_padding See above.
  88170. * \assert
  88171. * \code iterator != NULL \endcode
  88172. * \a iterator has been successfully initialized with
  88173. * FLAC__metadata_simple_iterator_init()
  88174. * \retval FLAC__bool
  88175. * \c true if successful, else \c false.
  88176. */
  88177. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88178. /* \} */
  88179. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88180. * \ingroup flac_metadata
  88181. *
  88182. * \brief
  88183. * The level 2 interface provides read-write access to FLAC file metadata;
  88184. * all metadata is read into memory, operated on in memory, and then written
  88185. * to file, which is more efficient than level 1 when editing multiple blocks.
  88186. *
  88187. * Currently Ogg FLAC is supported for read only, via
  88188. * FLAC__metadata_chain_read_ogg() but a subsequent
  88189. * FLAC__metadata_chain_write() will fail.
  88190. *
  88191. * The general usage of this interface is:
  88192. *
  88193. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88194. * linked list of FLAC metadata blocks.
  88195. * - Read all metadata into the the chain from a FLAC file using
  88196. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88197. * check the status.
  88198. * - Optionally, consolidate the padding using
  88199. * FLAC__metadata_chain_merge_padding() or
  88200. * FLAC__metadata_chain_sort_padding().
  88201. * - Create a new iterator using FLAC__metadata_iterator_new()
  88202. * - Initialize the iterator to point to the first element in the chain
  88203. * using FLAC__metadata_iterator_init()
  88204. * - Traverse the chain using FLAC__metadata_iterator_next and
  88205. * FLAC__metadata_iterator_prev().
  88206. * - Get a block for reading or modification using
  88207. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88208. * inside the chain is returned, so the block is yours to modify.
  88209. * Changes will be reflected in the FLAC file when you write the
  88210. * chain. You can also add and delete blocks (see functions below).
  88211. * - When done, write out the chain using FLAC__metadata_chain_write().
  88212. * Make sure to read the whole comment to the function below.
  88213. * - Delete the chain using FLAC__metadata_chain_delete().
  88214. *
  88215. * \note
  88216. * Even though the FLAC file is not open while the chain is being
  88217. * manipulated, you must not alter the file externally during
  88218. * this time. The chain assumes the FLAC file will not change
  88219. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88220. * and FLAC__metadata_chain_write().
  88221. *
  88222. * \note
  88223. * Do not modify the is_last, length, or type fields of returned
  88224. * FLAC__StreamMetadata objects. These are managed automatically.
  88225. *
  88226. * \note
  88227. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88228. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88229. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88230. * become owned by the chain and they will be deleted when the chain is
  88231. * deleted.
  88232. *
  88233. * \{
  88234. */
  88235. struct FLAC__Metadata_Chain;
  88236. /** The opaque structure definition for the level 2 chain type.
  88237. */
  88238. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88239. struct FLAC__Metadata_Iterator;
  88240. /** The opaque structure definition for the level 2 iterator type.
  88241. */
  88242. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88243. typedef enum {
  88244. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88245. /**< The chain is in the normal OK state */
  88246. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88247. /**< The data passed into a function violated the function's usage criteria */
  88248. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88249. /**< The chain could not open the target file */
  88250. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88251. /**< The chain could not find the FLAC signature at the start of the file */
  88252. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88253. /**< The chain tried to write to a file that was not writable */
  88254. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88255. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88256. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88257. /**< The chain encountered an error while reading the FLAC file */
  88258. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88259. /**< The chain encountered an error while seeking in the FLAC file */
  88260. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88261. /**< The chain encountered an error while writing the FLAC file */
  88262. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88263. /**< The chain encountered an error renaming the FLAC file */
  88264. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88265. /**< The chain encountered an error removing the temporary file */
  88266. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88267. /**< Memory allocation failed */
  88268. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88269. /**< The caller violated an assertion or an unexpected error occurred */
  88270. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88271. /**< One or more of the required callbacks was NULL */
  88272. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88273. /**< FLAC__metadata_chain_write() was called on a chain read by
  88274. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88275. * or
  88276. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88277. * was called on a chain read by
  88278. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88279. * Matching read/write methods must always be used. */
  88280. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88281. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88282. * chain write requires a tempfile; use
  88283. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88284. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88285. * called when the chain write does not require a tempfile; use
  88286. * FLAC__metadata_chain_write_with_callbacks() instead.
  88287. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88288. * before writing via callbacks. */
  88289. } FLAC__Metadata_ChainStatus;
  88290. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88291. *
  88292. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88293. * will give the string equivalent. The contents should not be modified.
  88294. */
  88295. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88296. /*********** FLAC__Metadata_Chain ***********/
  88297. /** Create a new chain instance.
  88298. *
  88299. * \retval FLAC__Metadata_Chain*
  88300. * \c NULL if there was an error allocating memory, else the new instance.
  88301. */
  88302. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88303. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88304. *
  88305. * \param chain A pointer to an existing chain.
  88306. * \assert
  88307. * \code chain != NULL \endcode
  88308. */
  88309. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88310. /** Get the current status of the chain. Call this after a function
  88311. * returns \c false to get the reason for the error. Also resets the
  88312. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88313. *
  88314. * \param chain A pointer to an existing chain.
  88315. * \assert
  88316. * \code chain != NULL \endcode
  88317. * \retval FLAC__Metadata_ChainStatus
  88318. * The current status of the chain.
  88319. */
  88320. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88321. /** Read all metadata from a FLAC file into the chain.
  88322. *
  88323. * \param chain A pointer to an existing chain.
  88324. * \param filename The path to the FLAC file to read.
  88325. * \assert
  88326. * \code chain != NULL \endcode
  88327. * \code filename != NULL \endcode
  88328. * \retval FLAC__bool
  88329. * \c true if a valid list of metadata blocks was read from
  88330. * \a filename, else \c false. On failure, check the status with
  88331. * FLAC__metadata_chain_status().
  88332. */
  88333. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88334. /** Read all metadata from an Ogg FLAC file into the chain.
  88335. *
  88336. * \note Ogg FLAC metadata data writing is not supported yet and
  88337. * FLAC__metadata_chain_write() will fail.
  88338. *
  88339. * \param chain A pointer to an existing chain.
  88340. * \param filename The path to the Ogg FLAC file to read.
  88341. * \assert
  88342. * \code chain != NULL \endcode
  88343. * \code filename != NULL \endcode
  88344. * \retval FLAC__bool
  88345. * \c true if a valid list of metadata blocks was read from
  88346. * \a filename, else \c false. On failure, check the status with
  88347. * FLAC__metadata_chain_status().
  88348. */
  88349. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88350. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88351. *
  88352. * The \a handle need only be open for reading, but must be seekable.
  88353. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88354. * for Windows).
  88355. *
  88356. * \param chain A pointer to an existing chain.
  88357. * \param handle The I/O handle of the FLAC stream to read. The
  88358. * handle will NOT be closed after the metadata is read;
  88359. * that is the duty of the caller.
  88360. * \param callbacks
  88361. * A set of callbacks to use for I/O. The mandatory
  88362. * callbacks are \a read, \a seek, and \a tell.
  88363. * \assert
  88364. * \code chain != NULL \endcode
  88365. * \retval FLAC__bool
  88366. * \c true if a valid list of metadata blocks was read from
  88367. * \a handle, else \c false. On failure, check the status with
  88368. * FLAC__metadata_chain_status().
  88369. */
  88370. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88371. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88372. *
  88373. * The \a handle need only be open for reading, but must be seekable.
  88374. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88375. * for Windows).
  88376. *
  88377. * \note Ogg FLAC metadata data writing is not supported yet and
  88378. * FLAC__metadata_chain_write() will fail.
  88379. *
  88380. * \param chain A pointer to an existing chain.
  88381. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88382. * handle will NOT be closed after the metadata is read;
  88383. * that is the duty of the caller.
  88384. * \param callbacks
  88385. * A set of callbacks to use for I/O. The mandatory
  88386. * callbacks are \a read, \a seek, and \a tell.
  88387. * \assert
  88388. * \code chain != NULL \endcode
  88389. * \retval FLAC__bool
  88390. * \c true if a valid list of metadata blocks was read from
  88391. * \a handle, else \c false. On failure, check the status with
  88392. * FLAC__metadata_chain_status().
  88393. */
  88394. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88395. /** Checks if writing the given chain would require the use of a
  88396. * temporary file, or if it could be written in place.
  88397. *
  88398. * Under certain conditions, padding can be utilized so that writing
  88399. * edited metadata back to the FLAC file does not require rewriting the
  88400. * entire file. If rewriting is required, then a temporary workfile is
  88401. * required. When writing metadata using callbacks, you must check
  88402. * this function to know whether to call
  88403. * FLAC__metadata_chain_write_with_callbacks() or
  88404. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88405. * writing with FLAC__metadata_chain_write(), the temporary file is
  88406. * handled internally.
  88407. *
  88408. * \param chain A pointer to an existing chain.
  88409. * \param use_padding
  88410. * Whether or not padding will be allowed to be used
  88411. * during the write. The value of \a use_padding given
  88412. * here must match the value later passed to
  88413. * FLAC__metadata_chain_write_with_callbacks() or
  88414. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88415. * \assert
  88416. * \code chain != NULL \endcode
  88417. * \retval FLAC__bool
  88418. * \c true if writing the current chain would require a tempfile, or
  88419. * \c false if metadata can be written in place.
  88420. */
  88421. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88422. /** Write all metadata out to the FLAC file. This function tries to be as
  88423. * efficient as possible; how the metadata is actually written is shown by
  88424. * the following:
  88425. *
  88426. * If the current chain is the same size as the existing metadata, the new
  88427. * data is written in place.
  88428. *
  88429. * If the current chain is longer than the existing metadata, and
  88430. * \a use_padding is \c true, and the last block is a PADDING block of
  88431. * sufficient length, the function will truncate the final padding block
  88432. * so that the overall size of the metadata is the same as the existing
  88433. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88434. * the above conditions are met, the entire FLAC file must be rewritten.
  88435. * If you want to use padding this way it is a good idea to call
  88436. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88437. * amount of padding to work with, unless you need to preserve ordering
  88438. * of the PADDING blocks for some reason.
  88439. *
  88440. * If the current chain is shorter than the existing metadata, and
  88441. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88442. * is extended to make the overall size the same as the existing data. If
  88443. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88444. * PADDING block is added to the end of the new data to make it the same
  88445. * size as the existing data (if possible, see the note to
  88446. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88447. * and the new data is written in place. If none of the above apply or
  88448. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88449. *
  88450. * If \a preserve_file_stats is \c true, the owner and modification time will
  88451. * be preserved even if the FLAC file is written.
  88452. *
  88453. * For this write function to be used, the chain must have been read with
  88454. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88455. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88456. *
  88457. * \param chain A pointer to an existing chain.
  88458. * \param use_padding See above.
  88459. * \param preserve_file_stats See above.
  88460. * \assert
  88461. * \code chain != NULL \endcode
  88462. * \retval FLAC__bool
  88463. * \c true if the write succeeded, else \c false. On failure,
  88464. * check the status with FLAC__metadata_chain_status().
  88465. */
  88466. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88467. /** Write all metadata out to a FLAC stream via callbacks.
  88468. *
  88469. * (See FLAC__metadata_chain_write() for the details on how padding is
  88470. * used to write metadata in place if possible.)
  88471. *
  88472. * The \a handle must be open for updating and be seekable. The
  88473. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88474. * for Windows).
  88475. *
  88476. * For this write function to be used, the chain must have been read with
  88477. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88478. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88479. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88480. * \c false.
  88481. *
  88482. * \param chain A pointer to an existing chain.
  88483. * \param use_padding See FLAC__metadata_chain_write()
  88484. * \param handle The I/O handle of the FLAC stream to write. The
  88485. * handle will NOT be closed after the metadata is
  88486. * written; that is the duty of the caller.
  88487. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88488. * callbacks are \a write and \a seek.
  88489. * \assert
  88490. * \code chain != NULL \endcode
  88491. * \retval FLAC__bool
  88492. * \c true if the write succeeded, else \c false. On failure,
  88493. * check the status with FLAC__metadata_chain_status().
  88494. */
  88495. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88496. /** Write all metadata out to a FLAC stream via callbacks.
  88497. *
  88498. * (See FLAC__metadata_chain_write() for the details on how padding is
  88499. * used to write metadata in place if possible.)
  88500. *
  88501. * This version of the write-with-callbacks function must be used when
  88502. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88503. * this function, you must supply an I/O handle corresponding to the
  88504. * FLAC file to edit, and a temporary handle to which the new FLAC
  88505. * file will be written. It is the caller's job to move this temporary
  88506. * FLAC file on top of the original FLAC file to complete the metadata
  88507. * edit.
  88508. *
  88509. * The \a handle must be open for reading and be seekable. The
  88510. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88511. * for Windows).
  88512. *
  88513. * The \a temp_handle must be open for writing. The
  88514. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88515. * for Windows). It should be an empty stream, or at least positioned
  88516. * at the start-of-file (in which case it is the caller's duty to
  88517. * truncate it on return).
  88518. *
  88519. * For this write function to be used, the chain must have been read with
  88520. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88521. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88522. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88523. * \c true.
  88524. *
  88525. * \param chain A pointer to an existing chain.
  88526. * \param use_padding See FLAC__metadata_chain_write()
  88527. * \param handle The I/O handle of the original FLAC stream to read.
  88528. * The handle will NOT be closed after the metadata is
  88529. * written; that is the duty of the caller.
  88530. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88531. * The mandatory callbacks are \a read, \a seek, and
  88532. * \a eof.
  88533. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88534. * handle will NOT be closed after the metadata is
  88535. * written; that is the duty of the caller.
  88536. * \param temp_callbacks
  88537. * A set of callbacks to use for I/O on temp_handle.
  88538. * The only mandatory callback is \a write.
  88539. * \assert
  88540. * \code chain != NULL \endcode
  88541. * \retval FLAC__bool
  88542. * \c true if the write succeeded, else \c false. On failure,
  88543. * check the status with FLAC__metadata_chain_status().
  88544. */
  88545. 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);
  88546. /** Merge adjacent PADDING blocks into a single block.
  88547. *
  88548. * \note This function does not write to the FLAC file, it only
  88549. * modifies the chain.
  88550. *
  88551. * \warning Any iterator on the current chain will become invalid after this
  88552. * call. You should delete the iterator and get a new one.
  88553. *
  88554. * \param chain A pointer to an existing chain.
  88555. * \assert
  88556. * \code chain != NULL \endcode
  88557. */
  88558. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88559. /** This function will move all PADDING blocks to the end on the metadata,
  88560. * then merge them into a single block.
  88561. *
  88562. * \note This function does not write to the FLAC file, it only
  88563. * modifies the chain.
  88564. *
  88565. * \warning Any iterator on the current chain will become invalid after this
  88566. * call. You should delete the iterator and get a new one.
  88567. *
  88568. * \param chain A pointer to an existing chain.
  88569. * \assert
  88570. * \code chain != NULL \endcode
  88571. */
  88572. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88573. /*********** FLAC__Metadata_Iterator ***********/
  88574. /** Create a new iterator instance.
  88575. *
  88576. * \retval FLAC__Metadata_Iterator*
  88577. * \c NULL if there was an error allocating memory, else the new instance.
  88578. */
  88579. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88580. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88581. *
  88582. * \param iterator A pointer to an existing iterator.
  88583. * \assert
  88584. * \code iterator != NULL \endcode
  88585. */
  88586. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88587. /** Initialize the iterator to point to the first metadata block in the
  88588. * given chain.
  88589. *
  88590. * \param iterator A pointer to an existing iterator.
  88591. * \param chain A pointer to an existing and initialized (read) chain.
  88592. * \assert
  88593. * \code iterator != NULL \endcode
  88594. * \code chain != NULL \endcode
  88595. */
  88596. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88597. /** Moves the iterator forward one metadata block, returning \c false if
  88598. * already at the end.
  88599. *
  88600. * \param iterator A pointer to an existing initialized iterator.
  88601. * \assert
  88602. * \code iterator != NULL \endcode
  88603. * \a iterator has been successfully initialized with
  88604. * FLAC__metadata_iterator_init()
  88605. * \retval FLAC__bool
  88606. * \c false if already at the last metadata block of the chain, else
  88607. * \c true.
  88608. */
  88609. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88610. /** Moves the iterator backward one metadata block, returning \c false if
  88611. * already at the beginning.
  88612. *
  88613. * \param iterator A pointer to an existing initialized iterator.
  88614. * \assert
  88615. * \code iterator != NULL \endcode
  88616. * \a iterator has been successfully initialized with
  88617. * FLAC__metadata_iterator_init()
  88618. * \retval FLAC__bool
  88619. * \c false if already at the first metadata block of the chain, else
  88620. * \c true.
  88621. */
  88622. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88623. /** Get the type of the metadata block at the current position.
  88624. *
  88625. * \param iterator A pointer to an existing initialized iterator.
  88626. * \assert
  88627. * \code iterator != NULL \endcode
  88628. * \a iterator has been successfully initialized with
  88629. * FLAC__metadata_iterator_init()
  88630. * \retval FLAC__MetadataType
  88631. * The type of the metadata block at the current iterator position.
  88632. */
  88633. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88634. /** Get the metadata block at the current position. You can modify
  88635. * the block in place but must write the chain before the changes
  88636. * are reflected to the FLAC file. You do not need to call
  88637. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88638. * the pointer returned by FLAC__metadata_iterator_get_block()
  88639. * points directly into the chain.
  88640. *
  88641. * \warning
  88642. * Do not call FLAC__metadata_object_delete() on the returned object;
  88643. * to delete a block use FLAC__metadata_iterator_delete_block().
  88644. *
  88645. * \param iterator A pointer to an existing initialized iterator.
  88646. * \assert
  88647. * \code iterator != NULL \endcode
  88648. * \a iterator has been successfully initialized with
  88649. * FLAC__metadata_iterator_init()
  88650. * \retval FLAC__StreamMetadata*
  88651. * The current metadata block.
  88652. */
  88653. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88654. /** Set the metadata block at the current position, replacing the existing
  88655. * block. The new block passed in becomes owned by the chain and it will be
  88656. * deleted when the chain is deleted.
  88657. *
  88658. * \param iterator A pointer to an existing initialized iterator.
  88659. * \param block A pointer to a metadata block.
  88660. * \assert
  88661. * \code iterator != NULL \endcode
  88662. * \a iterator has been successfully initialized with
  88663. * FLAC__metadata_iterator_init()
  88664. * \code block != NULL \endcode
  88665. * \retval FLAC__bool
  88666. * \c false if the conditions in the above description are not met, or
  88667. * a memory allocation error occurs, otherwise \c true.
  88668. */
  88669. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88670. /** Removes the current block from the chain. If \a replace_with_padding is
  88671. * \c true, the block will instead be replaced with a padding block of equal
  88672. * size. You can not delete the STREAMINFO block. The iterator will be
  88673. * left pointing to the block before the one just "deleted", even if
  88674. * \a replace_with_padding is \c true.
  88675. *
  88676. * \param iterator A pointer to an existing initialized iterator.
  88677. * \param replace_with_padding See above.
  88678. * \assert
  88679. * \code iterator != NULL \endcode
  88680. * \a iterator has been successfully initialized with
  88681. * FLAC__metadata_iterator_init()
  88682. * \retval FLAC__bool
  88683. * \c false if the conditions in the above description are not met,
  88684. * otherwise \c true.
  88685. */
  88686. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88687. /** Insert a new block before the current block. You cannot insert a block
  88688. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88689. * as there can be only one, the one that already exists at the head when you
  88690. * read in a chain. The chain takes ownership of the new block and it will be
  88691. * deleted when the chain is deleted. The iterator will be left pointing to
  88692. * the new block.
  88693. *
  88694. * \param iterator A pointer to an existing initialized iterator.
  88695. * \param block A pointer to a metadata block to insert.
  88696. * \assert
  88697. * \code iterator != NULL \endcode
  88698. * \a iterator has been successfully initialized with
  88699. * FLAC__metadata_iterator_init()
  88700. * \retval FLAC__bool
  88701. * \c false if the conditions in the above description are not met, or
  88702. * a memory allocation error occurs, otherwise \c true.
  88703. */
  88704. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88705. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88706. * block as there can be only one, the one that already exists at the head when
  88707. * you read in a chain. The chain takes ownership of the new block and it will
  88708. * be deleted when the chain is deleted. The iterator will be left pointing to
  88709. * the new block.
  88710. *
  88711. * \param iterator A pointer to an existing initialized iterator.
  88712. * \param block A pointer to a metadata block to insert.
  88713. * \assert
  88714. * \code iterator != NULL \endcode
  88715. * \a iterator has been successfully initialized with
  88716. * FLAC__metadata_iterator_init()
  88717. * \retval FLAC__bool
  88718. * \c false if the conditions in the above description are not met, or
  88719. * a memory allocation error occurs, otherwise \c true.
  88720. */
  88721. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88722. /* \} */
  88723. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88724. * \ingroup flac_metadata
  88725. *
  88726. * \brief
  88727. * This module contains methods for manipulating FLAC metadata objects.
  88728. *
  88729. * Since many are variable length we have to be careful about the memory
  88730. * management. We decree that all pointers to data in the object are
  88731. * owned by the object and memory-managed by the object.
  88732. *
  88733. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88734. * functions to create all instances. When using the
  88735. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88736. * \a copy to \c true to have the function make it's own copy of the data, or
  88737. * to \c false to give the object ownership of your data. In the latter case
  88738. * your pointer must be freeable by free() and will be free()d when the object
  88739. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88740. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88741. * the length argument is 0 and the \a copy argument is \c false.
  88742. *
  88743. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88744. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88745. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88746. * case of a memory allocation error.
  88747. *
  88748. * We don't have the convenience of C++ here, so note that the library relies
  88749. * on you to keep the types straight. In other words, if you pass, for
  88750. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88751. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88752. * failure.
  88753. *
  88754. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88755. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88756. * toward the length or stored in the stream, but it can make working with plain
  88757. * comments (those that don't contain embedded-NULs in the value) easier.
  88758. * Entries passed into these functions have trailing NULs added if missing, and
  88759. * returned entries are guaranteed to have a trailing NUL.
  88760. *
  88761. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88762. * comment entry/name/value will first validate that it complies with the Vorbis
  88763. * comment specification and return false if it does not.
  88764. *
  88765. * There is no need to recalculate the length field on metadata blocks you
  88766. * have modified. They will be calculated automatically before they are
  88767. * written back to a file.
  88768. *
  88769. * \{
  88770. */
  88771. /** Create a new metadata object instance of the given type.
  88772. *
  88773. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88774. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88775. * the vendor string set (but zero comments).
  88776. *
  88777. * Do not pass in a value greater than or equal to
  88778. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88779. * doing.
  88780. *
  88781. * \param type Type of object to create
  88782. * \retval FLAC__StreamMetadata*
  88783. * \c NULL if there was an error allocating memory or the type code is
  88784. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88785. */
  88786. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88787. /** Create a copy of an existing metadata object.
  88788. *
  88789. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88790. * object is also copied. The caller takes ownership of the new block and
  88791. * is responsible for freeing it with FLAC__metadata_object_delete().
  88792. *
  88793. * \param object Pointer to object to copy.
  88794. * \assert
  88795. * \code object != NULL \endcode
  88796. * \retval FLAC__StreamMetadata*
  88797. * \c NULL if there was an error allocating memory, else the new instance.
  88798. */
  88799. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88800. /** Free a metadata object. Deletes the object pointed to by \a object.
  88801. *
  88802. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88803. * object is also deleted.
  88804. *
  88805. * \param object A pointer to an existing object.
  88806. * \assert
  88807. * \code object != NULL \endcode
  88808. */
  88809. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88810. /** Compares two metadata objects.
  88811. *
  88812. * The compare is "deep", i.e. dynamically allocated data within the
  88813. * object is also compared.
  88814. *
  88815. * \param block1 A pointer to an existing object.
  88816. * \param block2 A pointer to an existing object.
  88817. * \assert
  88818. * \code block1 != NULL \endcode
  88819. * \code block2 != NULL \endcode
  88820. * \retval FLAC__bool
  88821. * \c true if objects are identical, else \c false.
  88822. */
  88823. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88824. /** Sets the application data of an APPLICATION block.
  88825. *
  88826. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88827. * takes ownership of the pointer. The existing data will be freed if this
  88828. * function is successful, otherwise the original data will remain if \a copy
  88829. * is \c true and malloc() fails.
  88830. *
  88831. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88832. *
  88833. * \param object A pointer to an existing APPLICATION object.
  88834. * \param data A pointer to the data to set.
  88835. * \param length The length of \a data in bytes.
  88836. * \param copy See above.
  88837. * \assert
  88838. * \code object != NULL \endcode
  88839. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88840. * \code (data != NULL && length > 0) ||
  88841. * (data == NULL && length == 0 && copy == false) \endcode
  88842. * \retval FLAC__bool
  88843. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88844. */
  88845. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88846. /** Resize the seekpoint array.
  88847. *
  88848. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88849. * points will be added to the end.
  88850. *
  88851. * \param object A pointer to an existing SEEKTABLE object.
  88852. * \param new_num_points The desired length of the array; may be \c 0.
  88853. * \assert
  88854. * \code object != NULL \endcode
  88855. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88856. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88857. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88858. * \retval FLAC__bool
  88859. * \c false if memory allocation error, else \c true.
  88860. */
  88861. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88862. /** Set a seekpoint in a seektable.
  88863. *
  88864. * \param object A pointer to an existing SEEKTABLE object.
  88865. * \param point_num Index into seekpoint array to set.
  88866. * \param point The point to set.
  88867. * \assert
  88868. * \code object != NULL \endcode
  88869. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88870. * \code object->data.seek_table.num_points > point_num \endcode
  88871. */
  88872. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88873. /** Insert a seekpoint into a seektable.
  88874. *
  88875. * \param object A pointer to an existing SEEKTABLE object.
  88876. * \param point_num Index into seekpoint array to set.
  88877. * \param point The point to set.
  88878. * \assert
  88879. * \code object != NULL \endcode
  88880. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88881. * \code object->data.seek_table.num_points >= point_num \endcode
  88882. * \retval FLAC__bool
  88883. * \c false if memory allocation error, else \c true.
  88884. */
  88885. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88886. /** Delete a seekpoint from a seektable.
  88887. *
  88888. * \param object A pointer to an existing SEEKTABLE object.
  88889. * \param point_num Index into seekpoint array to set.
  88890. * \assert
  88891. * \code object != NULL \endcode
  88892. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88893. * \code object->data.seek_table.num_points > point_num \endcode
  88894. * \retval FLAC__bool
  88895. * \c false if memory allocation error, else \c true.
  88896. */
  88897. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88898. /** Check a seektable to see if it conforms to the FLAC specification.
  88899. * See the format specification for limits on the contents of the
  88900. * seektable.
  88901. *
  88902. * \param object A pointer to an existing SEEKTABLE object.
  88903. * \assert
  88904. * \code object != NULL \endcode
  88905. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88906. * \retval FLAC__bool
  88907. * \c false if seek table is illegal, else \c true.
  88908. */
  88909. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88910. /** Append a number of placeholder points to the end of a seek table.
  88911. *
  88912. * \note
  88913. * As with the other ..._seektable_template_... functions, you should
  88914. * call FLAC__metadata_object_seektable_template_sort() when finished
  88915. * to make the seek table legal.
  88916. *
  88917. * \param object A pointer to an existing SEEKTABLE object.
  88918. * \param num The number of placeholder points to append.
  88919. * \assert
  88920. * \code object != NULL \endcode
  88921. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88922. * \retval FLAC__bool
  88923. * \c false if memory allocation fails, else \c true.
  88924. */
  88925. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88926. /** Append a specific seek point template to the end of a seek table.
  88927. *
  88928. * \note
  88929. * As with the other ..._seektable_template_... functions, you should
  88930. * call FLAC__metadata_object_seektable_template_sort() when finished
  88931. * to make the seek table legal.
  88932. *
  88933. * \param object A pointer to an existing SEEKTABLE object.
  88934. * \param sample_number The sample number of the seek point template.
  88935. * \assert
  88936. * \code object != NULL \endcode
  88937. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88938. * \retval FLAC__bool
  88939. * \c false if memory allocation fails, else \c true.
  88940. */
  88941. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88942. /** Append specific seek point templates to the end of a seek table.
  88943. *
  88944. * \note
  88945. * As with the other ..._seektable_template_... functions, you should
  88946. * call FLAC__metadata_object_seektable_template_sort() when finished
  88947. * to make the seek table legal.
  88948. *
  88949. * \param object A pointer to an existing SEEKTABLE object.
  88950. * \param sample_numbers An array of sample numbers for the seek points.
  88951. * \param num The number of seek point templates to append.
  88952. * \assert
  88953. * \code object != NULL \endcode
  88954. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88955. * \retval FLAC__bool
  88956. * \c false if memory allocation fails, else \c true.
  88957. */
  88958. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88959. /** Append a set of evenly-spaced seek point templates to the end of a
  88960. * seek table.
  88961. *
  88962. * \note
  88963. * As with the other ..._seektable_template_... functions, you should
  88964. * call FLAC__metadata_object_seektable_template_sort() when finished
  88965. * to make the seek table legal.
  88966. *
  88967. * \param object A pointer to an existing SEEKTABLE object.
  88968. * \param num The number of placeholder points to append.
  88969. * \param total_samples The total number of samples to be encoded;
  88970. * the seekpoints will be spaced approximately
  88971. * \a total_samples / \a num samples apart.
  88972. * \assert
  88973. * \code object != NULL \endcode
  88974. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88975. * \code total_samples > 0 \endcode
  88976. * \retval FLAC__bool
  88977. * \c false if memory allocation fails, else \c true.
  88978. */
  88979. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88980. /** Append a set of evenly-spaced seek point templates to the end of a
  88981. * seek table.
  88982. *
  88983. * \note
  88984. * As with the other ..._seektable_template_... functions, you should
  88985. * call FLAC__metadata_object_seektable_template_sort() when finished
  88986. * to make the seek table legal.
  88987. *
  88988. * \param object A pointer to an existing SEEKTABLE object.
  88989. * \param samples The number of samples apart to space the placeholder
  88990. * points. The first point will be at sample \c 0, the
  88991. * second at sample \a samples, then 2*\a samples, and
  88992. * so on. As long as \a samples and \a total_samples
  88993. * are greater than \c 0, there will always be at least
  88994. * one seekpoint at sample \c 0.
  88995. * \param total_samples The total number of samples to be encoded;
  88996. * the seekpoints will be spaced
  88997. * \a samples samples apart.
  88998. * \assert
  88999. * \code object != NULL \endcode
  89000. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89001. * \code samples > 0 \endcode
  89002. * \code total_samples > 0 \endcode
  89003. * \retval FLAC__bool
  89004. * \c false if memory allocation fails, else \c true.
  89005. */
  89006. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  89007. /** Sort a seek table's seek points according to the format specification,
  89008. * removing duplicates.
  89009. *
  89010. * \param object A pointer to a seek table to be sorted.
  89011. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  89012. * If \c true, duplicates are deleted and the seek table is
  89013. * shrunk appropriately; the number of placeholder points
  89014. * present in the seek table will be the same after the call
  89015. * as before.
  89016. * \assert
  89017. * \code object != NULL \endcode
  89018. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89019. * \retval FLAC__bool
  89020. * \c false if realloc() fails, else \c true.
  89021. */
  89022. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  89023. /** Sets the vendor string in a VORBIS_COMMENT block.
  89024. *
  89025. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89026. * one already.
  89027. *
  89028. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89029. * takes ownership of the \c entry.entry pointer.
  89030. *
  89031. * \note If this function returns \c false, the caller still owns the
  89032. * pointer.
  89033. *
  89034. * \param object A pointer to an existing VORBIS_COMMENT object.
  89035. * \param entry The entry to set the vendor string to.
  89036. * \param copy See above.
  89037. * \assert
  89038. * \code object != NULL \endcode
  89039. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89040. * \code (entry.entry != NULL && entry.length > 0) ||
  89041. * (entry.entry == NULL && entry.length == 0) \endcode
  89042. * \retval FLAC__bool
  89043. * \c false if memory allocation fails or \a entry does not comply with the
  89044. * Vorbis comment specification, else \c true.
  89045. */
  89046. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89047. /** Resize the comment array.
  89048. *
  89049. * If the size shrinks, elements will truncated; if it grows, new empty
  89050. * fields will be added to the end.
  89051. *
  89052. * \param object A pointer to an existing VORBIS_COMMENT object.
  89053. * \param new_num_comments The desired length of the array; may be \c 0.
  89054. * \assert
  89055. * \code object != NULL \endcode
  89056. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89057. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89058. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89059. * \retval FLAC__bool
  89060. * \c false if memory allocation fails, else \c true.
  89061. */
  89062. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89063. /** Sets a comment in a VORBIS_COMMENT block.
  89064. *
  89065. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89066. * one already.
  89067. *
  89068. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89069. * takes ownership of the \c entry.entry pointer.
  89070. *
  89071. * \note If this function returns \c false, the caller still owns the
  89072. * pointer.
  89073. *
  89074. * \param object A pointer to an existing VORBIS_COMMENT object.
  89075. * \param comment_num Index into comment array to set.
  89076. * \param entry The entry to set the comment to.
  89077. * \param copy See above.
  89078. * \assert
  89079. * \code object != NULL \endcode
  89080. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89081. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89082. * \code (entry.entry != NULL && entry.length > 0) ||
  89083. * (entry.entry == NULL && entry.length == 0) \endcode
  89084. * \retval FLAC__bool
  89085. * \c false if memory allocation fails or \a entry does not comply with the
  89086. * Vorbis comment specification, else \c true.
  89087. */
  89088. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89089. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89090. *
  89091. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89092. * one already.
  89093. *
  89094. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89095. * takes ownership of the \c entry.entry pointer.
  89096. *
  89097. * \note If this function returns \c false, the caller still owns the
  89098. * pointer.
  89099. *
  89100. * \param object A pointer to an existing VORBIS_COMMENT object.
  89101. * \param comment_num The index at which to insert the comment. The comments
  89102. * at and after \a comment_num move right one position.
  89103. * To append a comment to the end, set \a comment_num to
  89104. * \c object->data.vorbis_comment.num_comments .
  89105. * \param entry The comment to insert.
  89106. * \param copy See above.
  89107. * \assert
  89108. * \code object != NULL \endcode
  89109. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89110. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89111. * \code (entry.entry != NULL && entry.length > 0) ||
  89112. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89113. * \retval FLAC__bool
  89114. * \c false if memory allocation fails or \a entry does not comply with the
  89115. * Vorbis comment specification, else \c true.
  89116. */
  89117. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89118. /** Appends a comment to a VORBIS_COMMENT block.
  89119. *
  89120. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89121. * one already.
  89122. *
  89123. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89124. * takes ownership of the \c entry.entry pointer.
  89125. *
  89126. * \note If this function returns \c false, the caller still owns the
  89127. * pointer.
  89128. *
  89129. * \param object A pointer to an existing VORBIS_COMMENT object.
  89130. * \param entry The comment to insert.
  89131. * \param copy See above.
  89132. * \assert
  89133. * \code object != NULL \endcode
  89134. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89135. * \code (entry.entry != NULL && entry.length > 0) ||
  89136. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89137. * \retval FLAC__bool
  89138. * \c false if memory allocation fails or \a entry does not comply with the
  89139. * Vorbis comment specification, else \c true.
  89140. */
  89141. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89142. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89143. *
  89144. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89145. * one already.
  89146. *
  89147. * Depending on the the value of \a all, either all or just the first comment
  89148. * whose field name(s) match the given entry's name will be replaced by the
  89149. * given entry. If no comments match, \a entry will simply be appended.
  89150. *
  89151. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89152. * takes ownership of the \c entry.entry pointer.
  89153. *
  89154. * \note If this function returns \c false, the caller still owns the
  89155. * pointer.
  89156. *
  89157. * \param object A pointer to an existing VORBIS_COMMENT object.
  89158. * \param entry The comment to insert.
  89159. * \param all If \c true, all comments whose field name matches
  89160. * \a entry's field name will be removed, and \a entry will
  89161. * be inserted at the position of the first matching
  89162. * comment. If \c false, only the first comment whose
  89163. * field name matches \a entry's field name will be
  89164. * replaced with \a entry.
  89165. * \param copy See above.
  89166. * \assert
  89167. * \code object != NULL \endcode
  89168. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89169. * \code (entry.entry != NULL && entry.length > 0) ||
  89170. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89171. * \retval FLAC__bool
  89172. * \c false if memory allocation fails or \a entry does not comply with the
  89173. * Vorbis comment specification, else \c true.
  89174. */
  89175. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89176. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89177. *
  89178. * \param object A pointer to an existing VORBIS_COMMENT object.
  89179. * \param comment_num The index of the comment to delete.
  89180. * \assert
  89181. * \code object != NULL \endcode
  89182. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89183. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89184. * \retval FLAC__bool
  89185. * \c false if realloc() fails, else \c true.
  89186. */
  89187. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89188. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89189. *
  89190. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89191. * memory and shall be owned by the caller. For convenience the entry will
  89192. * have a terminating NUL.
  89193. *
  89194. * \param entry A pointer to a Vorbis comment entry. The entry's
  89195. * \c entry pointer should not point to allocated
  89196. * memory as it will be overwritten.
  89197. * \param field_name The field name in ASCII, \c NUL terminated.
  89198. * \param field_value The field value in UTF-8, \c NUL terminated.
  89199. * \assert
  89200. * \code entry != NULL \endcode
  89201. * \code field_name != NULL \endcode
  89202. * \code field_value != NULL \endcode
  89203. * \retval FLAC__bool
  89204. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89205. * not comply with the Vorbis comment specification, else \c true.
  89206. */
  89207. 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);
  89208. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89209. *
  89210. * The returned pointers to name and value will be allocated by malloc()
  89211. * and shall be owned by the caller.
  89212. *
  89213. * \param entry An existing Vorbis comment entry.
  89214. * \param field_name The address of where the returned pointer to the
  89215. * field name will be stored.
  89216. * \param field_value The address of where the returned pointer to the
  89217. * field value will be stored.
  89218. * \assert
  89219. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89220. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89221. * \code field_name != NULL \endcode
  89222. * \code field_value != NULL \endcode
  89223. * \retval FLAC__bool
  89224. * \c false if memory allocation fails or \a entry does not comply with the
  89225. * Vorbis comment specification, else \c true.
  89226. */
  89227. 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);
  89228. /** Check if the given Vorbis comment entry's field name matches the given
  89229. * field name.
  89230. *
  89231. * \param entry An existing Vorbis comment entry.
  89232. * \param field_name The field name to check.
  89233. * \param field_name_length The length of \a field_name, not including the
  89234. * terminating \c NUL.
  89235. * \assert
  89236. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89237. * \retval FLAC__bool
  89238. * \c true if the field names match, else \c false
  89239. */
  89240. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89241. /** Find a Vorbis comment with the given field name.
  89242. *
  89243. * The search begins at entry number \a offset; use an offset of 0 to
  89244. * search from the beginning of the comment array.
  89245. *
  89246. * \param object A pointer to an existing VORBIS_COMMENT object.
  89247. * \param offset The offset into the comment array from where to start
  89248. * the search.
  89249. * \param field_name The field name of the comment to find.
  89250. * \assert
  89251. * \code object != NULL \endcode
  89252. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89253. * \code field_name != NULL \endcode
  89254. * \retval int
  89255. * The offset in the comment array of the first comment whose field
  89256. * name matches \a field_name, or \c -1 if no match was found.
  89257. */
  89258. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89259. /** Remove first Vorbis comment matching the given field name.
  89260. *
  89261. * \param object A pointer to an existing VORBIS_COMMENT object.
  89262. * \param field_name The field name of comment to delete.
  89263. * \assert
  89264. * \code object != NULL \endcode
  89265. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89266. * \retval int
  89267. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89268. * \c 1 for one matching entry deleted.
  89269. */
  89270. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89271. /** Remove all Vorbis comments matching the given field name.
  89272. *
  89273. * \param object A pointer to an existing VORBIS_COMMENT object.
  89274. * \param field_name The field name of comments to delete.
  89275. * \assert
  89276. * \code object != NULL \endcode
  89277. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89278. * \retval int
  89279. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89280. * else the number of matching entries deleted.
  89281. */
  89282. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89283. /** Create a new CUESHEET track instance.
  89284. *
  89285. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89286. *
  89287. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89288. * \c NULL if there was an error allocating memory, else the new instance.
  89289. */
  89290. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89291. /** Create a copy of an existing CUESHEET track object.
  89292. *
  89293. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89294. * object is also copied. The caller takes ownership of the new object and
  89295. * is responsible for freeing it with
  89296. * FLAC__metadata_object_cuesheet_track_delete().
  89297. *
  89298. * \param object Pointer to object to copy.
  89299. * \assert
  89300. * \code object != NULL \endcode
  89301. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89302. * \c NULL if there was an error allocating memory, else the new instance.
  89303. */
  89304. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89305. /** Delete a CUESHEET track object
  89306. *
  89307. * \param object A pointer to an existing CUESHEET track object.
  89308. * \assert
  89309. * \code object != NULL \endcode
  89310. */
  89311. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89312. /** Resize a track's index point array.
  89313. *
  89314. * If the size shrinks, elements will truncated; if it grows, new blank
  89315. * indices will be added to the end.
  89316. *
  89317. * \param object A pointer to an existing CUESHEET object.
  89318. * \param track_num The index of the track to modify. NOTE: this is not
  89319. * necessarily the same as the track's \a number field.
  89320. * \param new_num_indices The desired length of the array; may be \c 0.
  89321. * \assert
  89322. * \code object != NULL \endcode
  89323. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89324. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89325. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89326. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89327. * \retval FLAC__bool
  89328. * \c false if memory allocation error, else \c true.
  89329. */
  89330. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89331. /** Insert an index point in a CUESHEET track at the given index.
  89332. *
  89333. * \param object A pointer to an existing CUESHEET object.
  89334. * \param track_num The index of the track to modify. NOTE: this is not
  89335. * necessarily the same as the track's \a number field.
  89336. * \param index_num The index into the track's index array at which to
  89337. * insert the index point. NOTE: this is not necessarily
  89338. * the same as the index point's \a number field. The
  89339. * indices at and after \a index_num move right one
  89340. * position. To append an index point to the end, set
  89341. * \a index_num to
  89342. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89343. * \param index The index point to insert.
  89344. * \assert
  89345. * \code object != NULL \endcode
  89346. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89347. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89348. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_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_track_insert_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num, FLAC__StreamMetadata_CueSheet_Index index);
  89353. /** Insert a blank index point in a CUESHEET track at the given index.
  89354. *
  89355. * A blank index point is one in which all field values are zero.
  89356. *
  89357. * \param object A pointer to an existing CUESHEET object.
  89358. * \param track_num The index of the track to modify. NOTE: this is not
  89359. * necessarily the same as the track's \a number field.
  89360. * \param index_num The index into the track's index array at which to
  89361. * insert the index point. NOTE: this is not necessarily
  89362. * the same as the index point's \a number field. The
  89363. * indices at and after \a index_num move right one
  89364. * position. To append an index point to the end, set
  89365. * \a index_num to
  89366. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89367. * \assert
  89368. * \code object != NULL \endcode
  89369. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89370. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89371. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89372. * \retval FLAC__bool
  89373. * \c false if realloc() fails, else \c true.
  89374. */
  89375. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89376. /** Delete an index point in a CUESHEET track at the given index.
  89377. *
  89378. * \param object A pointer to an existing CUESHEET object.
  89379. * \param track_num The index into the track array of the track to
  89380. * modify. NOTE: this is not necessarily the same
  89381. * as the track's \a number field.
  89382. * \param index_num The index into the track's index array of the index
  89383. * to delete. NOTE: this is not necessarily the same
  89384. * as the index's \a number field.
  89385. * \assert
  89386. * \code object != NULL \endcode
  89387. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89388. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89389. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89390. * \retval FLAC__bool
  89391. * \c false if realloc() fails, else \c true.
  89392. */
  89393. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89394. /** Resize the track array.
  89395. *
  89396. * If the size shrinks, elements will truncated; if it grows, new blank
  89397. * tracks will be added to the end.
  89398. *
  89399. * \param object A pointer to an existing CUESHEET object.
  89400. * \param new_num_tracks The desired length of the array; may be \c 0.
  89401. * \assert
  89402. * \code object != NULL \endcode
  89403. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89404. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89405. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89406. * \retval FLAC__bool
  89407. * \c false if memory allocation error, else \c true.
  89408. */
  89409. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89410. /** Sets a track in a CUESHEET block.
  89411. *
  89412. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89413. * takes ownership of the \a track pointer.
  89414. *
  89415. * \param object A pointer to an existing CUESHEET object.
  89416. * \param track_num Index into track array to set. NOTE: this is not
  89417. * necessarily the same as the track's \a number field.
  89418. * \param track The track to set the track to. You may safely pass in
  89419. * a const pointer if \a copy is \c true.
  89420. * \param copy See above.
  89421. * \assert
  89422. * \code object != NULL \endcode
  89423. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89424. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89425. * \code (track->indices != NULL && track->num_indices > 0) ||
  89426. * (track->indices == NULL && track->num_indices == 0)
  89427. * \retval FLAC__bool
  89428. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89429. */
  89430. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89431. /** Insert a track in a CUESHEET block at the given index.
  89432. *
  89433. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89434. * takes ownership of the \a track pointer.
  89435. *
  89436. * \param object A pointer to an existing CUESHEET object.
  89437. * \param track_num The index at which to insert the track. NOTE: this
  89438. * is not necessarily the same as the track's \a number
  89439. * field. The tracks at and after \a track_num move right
  89440. * one position. To append a track to the end, set
  89441. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89442. * \param track The track to insert. You may safely pass in a const
  89443. * pointer if \a copy is \c true.
  89444. * \param copy See above.
  89445. * \assert
  89446. * \code object != NULL \endcode
  89447. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89448. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89449. * \retval FLAC__bool
  89450. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89451. */
  89452. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89453. /** Insert a blank track in a CUESHEET block at the given index.
  89454. *
  89455. * A blank track is one in which all field values are zero.
  89456. *
  89457. * \param object A pointer to an existing CUESHEET object.
  89458. * \param track_num The index at which to insert the track. NOTE: this
  89459. * is not necessarily the same as the track's \a number
  89460. * field. The tracks at and after \a track_num move right
  89461. * one position. To append a track to the end, set
  89462. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89463. * \assert
  89464. * \code object != NULL \endcode
  89465. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89466. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89467. * \retval FLAC__bool
  89468. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89469. */
  89470. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89471. /** Delete a track in a CUESHEET block at the given index.
  89472. *
  89473. * \param object A pointer to an existing CUESHEET object.
  89474. * \param track_num The index into the track array of the track to
  89475. * delete. NOTE: this is not necessarily the same
  89476. * as the track's \a number field.
  89477. * \assert
  89478. * \code object != NULL \endcode
  89479. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89480. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89481. * \retval FLAC__bool
  89482. * \c false if realloc() fails, else \c true.
  89483. */
  89484. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89485. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89486. * See the format specification for limits on the contents of the
  89487. * cue sheet.
  89488. *
  89489. * \param object A pointer to an existing CUESHEET object.
  89490. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89491. * stringent requirements for a CD-DA (audio) disc.
  89492. * \param violation Address of a pointer to a string. If there is a
  89493. * violation, a pointer to a string explanation of the
  89494. * violation will be returned here. \a violation may be
  89495. * \c NULL if you don't need the returned string. Do not
  89496. * free the returned string; it will always point to static
  89497. * data.
  89498. * \assert
  89499. * \code object != NULL \endcode
  89500. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89501. * \retval FLAC__bool
  89502. * \c false if cue sheet is illegal, else \c true.
  89503. */
  89504. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89505. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89506. * assumes the cue sheet corresponds to a CD; the result is undefined
  89507. * if the cuesheet's is_cd bit is not set.
  89508. *
  89509. * \param object A pointer to an existing CUESHEET object.
  89510. * \assert
  89511. * \code object != NULL \endcode
  89512. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89513. * \retval FLAC__uint32
  89514. * The unsigned integer representation of the CDDB/freedb ID
  89515. */
  89516. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89517. /** Sets the MIME type of a PICTURE block.
  89518. *
  89519. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89520. * takes ownership of the pointer. The existing string will be freed if this
  89521. * function is successful, otherwise the original string will remain if \a copy
  89522. * is \c true and malloc() fails.
  89523. *
  89524. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89525. *
  89526. * \param object A pointer to an existing PICTURE object.
  89527. * \param mime_type A pointer to the MIME type string. The string must be
  89528. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89529. * is done.
  89530. * \param copy See above.
  89531. * \assert
  89532. * \code object != NULL \endcode
  89533. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89534. * \code (mime_type != NULL) \endcode
  89535. * \retval FLAC__bool
  89536. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89537. */
  89538. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89539. /** Sets the description of a PICTURE block.
  89540. *
  89541. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89542. * takes ownership of the pointer. The existing string will be freed if this
  89543. * function is successful, otherwise the original string will remain if \a copy
  89544. * is \c true and malloc() fails.
  89545. *
  89546. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89547. *
  89548. * \param object A pointer to an existing PICTURE object.
  89549. * \param description A pointer to the description string. The string must be
  89550. * valid UTF-8, NUL-terminated. No validation is done.
  89551. * \param copy See above.
  89552. * \assert
  89553. * \code object != NULL \endcode
  89554. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89555. * \code (description != NULL) \endcode
  89556. * \retval FLAC__bool
  89557. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89558. */
  89559. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89560. /** Sets the picture data of a PICTURE block.
  89561. *
  89562. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89563. * takes ownership of the pointer. Also sets the \a data_length field of the
  89564. * metadata object to what is passed in as the \a length parameter. The
  89565. * existing data will be freed if this function is successful, otherwise the
  89566. * original data and data_length will remain if \a copy is \c true and
  89567. * malloc() fails.
  89568. *
  89569. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89570. *
  89571. * \param object A pointer to an existing PICTURE object.
  89572. * \param data A pointer to the data to set.
  89573. * \param length The length of \a data in bytes.
  89574. * \param copy See above.
  89575. * \assert
  89576. * \code object != NULL \endcode
  89577. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89578. * \code (data != NULL && length > 0) ||
  89579. * (data == NULL && length == 0 && copy == false) \endcode
  89580. * \retval FLAC__bool
  89581. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89582. */
  89583. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89584. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89585. * See the format specification for limits on the contents of the
  89586. * PICTURE block.
  89587. *
  89588. * \param object A pointer to existing PICTURE block to be checked.
  89589. * \param violation Address of a pointer to a string. If there is a
  89590. * violation, a pointer to a string explanation of the
  89591. * violation will be returned here. \a violation may be
  89592. * \c NULL if you don't need the returned string. Do not
  89593. * free the returned string; it will always point to static
  89594. * data.
  89595. * \assert
  89596. * \code object != NULL \endcode
  89597. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89598. * \retval FLAC__bool
  89599. * \c false if PICTURE block is illegal, else \c true.
  89600. */
  89601. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89602. /* \} */
  89603. #ifdef __cplusplus
  89604. }
  89605. #endif
  89606. #endif
  89607. /*** End of inlined file: metadata.h ***/
  89608. /*** Start of inlined file: stream_decoder.h ***/
  89609. #ifndef FLAC__STREAM_DECODER_H
  89610. #define FLAC__STREAM_DECODER_H
  89611. #include <stdio.h> /* for FILE */
  89612. #ifdef __cplusplus
  89613. extern "C" {
  89614. #endif
  89615. /** \file include/FLAC/stream_decoder.h
  89616. *
  89617. * \brief
  89618. * This module contains the functions which implement the stream
  89619. * decoder.
  89620. *
  89621. * See the detailed documentation in the
  89622. * \link flac_stream_decoder stream decoder \endlink module.
  89623. */
  89624. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89625. * \ingroup flac
  89626. *
  89627. * \brief
  89628. * This module describes the decoder layers provided by libFLAC.
  89629. *
  89630. * The stream decoder can be used to decode complete streams either from
  89631. * the client via callbacks, or directly from a file, depending on how
  89632. * it is initialized. When decoding via callbacks, the client provides
  89633. * callbacks for reading FLAC data and writing decoded samples, and
  89634. * handling metadata and errors. If the client also supplies seek-related
  89635. * callback, the decoder function for sample-accurate seeking within the
  89636. * FLAC input is also available. When decoding from a file, the client
  89637. * needs only supply a filename or open \c FILE* and write/metadata/error
  89638. * callbacks; the rest of the callbacks are supplied internally. For more
  89639. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89640. */
  89641. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89642. * \ingroup flac_decoder
  89643. *
  89644. * \brief
  89645. * This module contains the functions which implement the stream
  89646. * decoder.
  89647. *
  89648. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89649. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89650. *
  89651. * The basic usage of this decoder is as follows:
  89652. * - The program creates an instance of a decoder using
  89653. * FLAC__stream_decoder_new().
  89654. * - The program overrides the default settings using
  89655. * FLAC__stream_decoder_set_*() functions.
  89656. * - The program initializes the instance to validate the settings and
  89657. * prepare for decoding using
  89658. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89659. * or FLAC__stream_decoder_init_file() for native FLAC,
  89660. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89661. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89662. * - The program calls the FLAC__stream_decoder_process_*() functions
  89663. * to decode data, which subsequently calls the callbacks.
  89664. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89665. * which flushes the input and output and resets the decoder to the
  89666. * uninitialized state.
  89667. * - The instance may be used again or deleted with
  89668. * FLAC__stream_decoder_delete().
  89669. *
  89670. * In more detail, the program will create a new instance by calling
  89671. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89672. * functions to override the default decoder options, and call
  89673. * one of the FLAC__stream_decoder_init_*() functions.
  89674. *
  89675. * There are three initialization functions for native FLAC, one for
  89676. * setting up the decoder to decode FLAC data from the client via
  89677. * callbacks, and two for decoding directly from a FLAC file.
  89678. *
  89679. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89680. * You must also supply several callbacks for handling I/O. Some (like
  89681. * seeking) are optional, depending on the capabilities of the input.
  89682. *
  89683. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89684. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89685. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89686. * the other callbacks internally.
  89687. *
  89688. * There are three similarly-named init functions for decoding from Ogg
  89689. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89690. * library has been built with Ogg support.
  89691. *
  89692. * Once the decoder is initialized, your program will call one of several
  89693. * functions to start the decoding process:
  89694. *
  89695. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89696. * most one metadata block or audio frame and return, calling either the
  89697. * metadata callback or write callback, respectively, once. If the decoder
  89698. * loses sync it will return with only the error callback being called.
  89699. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89700. * to process the stream from the current location and stop upon reaching
  89701. * the first audio frame. The client will get one metadata, write, or error
  89702. * callback per metadata block, audio frame, or sync error, respectively.
  89703. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89704. * to process the stream from the current location until the read callback
  89705. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89706. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89707. * write, or error callback per metadata block, audio frame, or sync error,
  89708. * respectively.
  89709. *
  89710. * When the decoder has finished decoding (normally or through an abort),
  89711. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89712. * ensures the decoder is in the correct state and frees memory. Then the
  89713. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89714. * again to decode another stream.
  89715. *
  89716. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89717. * At any point after the stream decoder has been initialized, the client can
  89718. * call this function to seek to an exact sample within the stream.
  89719. * Subsequently, the first time the write callback is called it will be
  89720. * passed a (possibly partial) block starting at that sample.
  89721. *
  89722. * If the client cannot seek via the callback interface provided, but still
  89723. * has another way of seeking, it can flush the decoder using
  89724. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89725. * through the read callback.
  89726. *
  89727. * The stream decoder also provides MD5 signature checking. If this is
  89728. * turned on before initialization, FLAC__stream_decoder_finish() will
  89729. * report when the decoded MD5 signature does not match the one stored
  89730. * in the STREAMINFO block. MD5 checking is automatically turned off
  89731. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89732. * in the STREAMINFO block or when a seek is attempted.
  89733. *
  89734. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89735. * attention. By default, the decoder only calls the metadata_callback for
  89736. * the STREAMINFO block. These functions allow you to tell the decoder
  89737. * explicitly which blocks to parse and return via the metadata_callback
  89738. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89739. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89740. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89741. * which blocks to return. Remember that metadata blocks can potentially
  89742. * be big (for example, cover art) so filtering out the ones you don't
  89743. * use can reduce the memory requirements of the decoder. Also note the
  89744. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89745. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89746. * filtering APPLICATION blocks based on the application ID.
  89747. *
  89748. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89749. * they still can legally be filtered from the metadata_callback.
  89750. *
  89751. * \note
  89752. * The "set" functions may only be called when the decoder is in the
  89753. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89754. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89755. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89756. * return \c true, otherwise \c false.
  89757. *
  89758. * \note
  89759. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89760. * defaults, including the callbacks.
  89761. *
  89762. * \{
  89763. */
  89764. /** State values for a FLAC__StreamDecoder
  89765. *
  89766. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89767. */
  89768. typedef enum {
  89769. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89770. /**< The decoder is ready to search for metadata. */
  89771. FLAC__STREAM_DECODER_READ_METADATA,
  89772. /**< The decoder is ready to or is in the process of reading metadata. */
  89773. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89774. /**< The decoder is ready to or is in the process of searching for the
  89775. * frame sync code.
  89776. */
  89777. FLAC__STREAM_DECODER_READ_FRAME,
  89778. /**< The decoder is ready to or is in the process of reading a frame. */
  89779. FLAC__STREAM_DECODER_END_OF_STREAM,
  89780. /**< The decoder has reached the end of the stream. */
  89781. FLAC__STREAM_DECODER_OGG_ERROR,
  89782. /**< An error occurred in the underlying Ogg layer. */
  89783. FLAC__STREAM_DECODER_SEEK_ERROR,
  89784. /**< An error occurred while seeking. The decoder must be flushed
  89785. * with FLAC__stream_decoder_flush() or reset with
  89786. * FLAC__stream_decoder_reset() before decoding can continue.
  89787. */
  89788. FLAC__STREAM_DECODER_ABORTED,
  89789. /**< The decoder was aborted by the read callback. */
  89790. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89791. /**< An error occurred allocating memory. The decoder is in an invalid
  89792. * state and can no longer be used.
  89793. */
  89794. FLAC__STREAM_DECODER_UNINITIALIZED
  89795. /**< The decoder is in the uninitialized state; one of the
  89796. * FLAC__stream_decoder_init_*() functions must be called before samples
  89797. * can be processed.
  89798. */
  89799. } FLAC__StreamDecoderState;
  89800. /** Maps a FLAC__StreamDecoderState to a C string.
  89801. *
  89802. * Using a FLAC__StreamDecoderState as the index to this array
  89803. * will give the string equivalent. The contents should not be modified.
  89804. */
  89805. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89806. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89807. */
  89808. typedef enum {
  89809. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89810. /**< Initialization was successful. */
  89811. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89812. /**< The library was not compiled with support for the given container
  89813. * format.
  89814. */
  89815. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89816. /**< A required callback was not supplied. */
  89817. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89818. /**< An error occurred allocating memory. */
  89819. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89820. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89821. * FLAC__stream_decoder_init_ogg_file(). */
  89822. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89823. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89824. * already initialized, usually because
  89825. * FLAC__stream_decoder_finish() was not called.
  89826. */
  89827. } FLAC__StreamDecoderInitStatus;
  89828. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89829. *
  89830. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89831. * will give the string equivalent. The contents should not be modified.
  89832. */
  89833. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89834. /** Return values for the FLAC__StreamDecoder read callback.
  89835. */
  89836. typedef enum {
  89837. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89838. /**< The read was OK and decoding can continue. */
  89839. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89840. /**< The read was attempted while at the end of the stream. Note that
  89841. * the client must only return this value when the read callback was
  89842. * called when already at the end of the stream. Otherwise, if the read
  89843. * itself moves to the end of the stream, the client should still return
  89844. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89845. * the next read callback it should return
  89846. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89847. * of \c 0.
  89848. */
  89849. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89850. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89851. } FLAC__StreamDecoderReadStatus;
  89852. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89853. *
  89854. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89855. * will give the string equivalent. The contents should not be modified.
  89856. */
  89857. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89858. /** Return values for the FLAC__StreamDecoder seek callback.
  89859. */
  89860. typedef enum {
  89861. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89862. /**< The seek was OK and decoding can continue. */
  89863. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89864. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89865. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89866. /**< Client does not support seeking. */
  89867. } FLAC__StreamDecoderSeekStatus;
  89868. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89869. *
  89870. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89871. * will give the string equivalent. The contents should not be modified.
  89872. */
  89873. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89874. /** Return values for the FLAC__StreamDecoder tell callback.
  89875. */
  89876. typedef enum {
  89877. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89878. /**< The tell was OK and decoding can continue. */
  89879. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89880. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89881. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89882. /**< Client does not support telling the position. */
  89883. } FLAC__StreamDecoderTellStatus;
  89884. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89885. *
  89886. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89887. * will give the string equivalent. The contents should not be modified.
  89888. */
  89889. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89890. /** Return values for the FLAC__StreamDecoder length callback.
  89891. */
  89892. typedef enum {
  89893. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89894. /**< The length call was OK and decoding can continue. */
  89895. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89896. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89897. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89898. /**< Client does not support reporting the length. */
  89899. } FLAC__StreamDecoderLengthStatus;
  89900. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89901. *
  89902. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89903. * will give the string equivalent. The contents should not be modified.
  89904. */
  89905. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89906. /** Return values for the FLAC__StreamDecoder write callback.
  89907. */
  89908. typedef enum {
  89909. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89910. /**< The write was OK and decoding can continue. */
  89911. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89912. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89913. } FLAC__StreamDecoderWriteStatus;
  89914. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89915. *
  89916. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89917. * will give the string equivalent. The contents should not be modified.
  89918. */
  89919. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89920. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89921. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89922. * all. The rest could be caused by bad sync (false synchronization on
  89923. * data that is not the start of a frame) or corrupted data. The error
  89924. * itself is the decoder's best guess at what happened assuming a correct
  89925. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89926. * could be caused by a correct sync on the start of a frame, but some
  89927. * data in the frame header was corrupted. Or it could be the result of
  89928. * syncing on a point the stream that looked like the starting of a frame
  89929. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89930. * could be because the decoder encountered a valid frame made by a future
  89931. * version of the encoder which it cannot parse, or because of a false
  89932. * sync making it appear as though an encountered frame was generated by
  89933. * a future encoder.
  89934. */
  89935. typedef enum {
  89936. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89937. /**< An error in the stream caused the decoder to lose synchronization. */
  89938. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89939. /**< The decoder encountered a corrupted frame header. */
  89940. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89941. /**< The frame's data did not match the CRC in the footer. */
  89942. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89943. /**< The decoder encountered reserved fields in use in the stream. */
  89944. } FLAC__StreamDecoderErrorStatus;
  89945. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89946. *
  89947. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89948. * will give the string equivalent. The contents should not be modified.
  89949. */
  89950. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89951. /***********************************************************************
  89952. *
  89953. * class FLAC__StreamDecoder
  89954. *
  89955. ***********************************************************************/
  89956. struct FLAC__StreamDecoderProtected;
  89957. struct FLAC__StreamDecoderPrivate;
  89958. /** The opaque structure definition for the stream decoder type.
  89959. * See the \link flac_stream_decoder stream decoder module \endlink
  89960. * for a detailed description.
  89961. */
  89962. typedef struct {
  89963. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89964. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89965. } FLAC__StreamDecoder;
  89966. /** Signature for the read callback.
  89967. *
  89968. * A function pointer matching this signature must be passed to
  89969. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89970. * called when the decoder needs more input data. The address of the
  89971. * buffer to be filled is supplied, along with the number of bytes the
  89972. * buffer can hold. The callback may choose to supply less data and
  89973. * modify the byte count but must be careful not to overflow the buffer.
  89974. * The callback then returns a status code chosen from
  89975. * FLAC__StreamDecoderReadStatus.
  89976. *
  89977. * Here is an example of a read callback for stdio streams:
  89978. * \code
  89979. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89980. * {
  89981. * FILE *file = ((MyClientData*)client_data)->file;
  89982. * if(*bytes > 0) {
  89983. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89984. * if(ferror(file))
  89985. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89986. * else if(*bytes == 0)
  89987. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89988. * else
  89989. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89990. * }
  89991. * else
  89992. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89993. * }
  89994. * \endcode
  89995. *
  89996. * \note In general, FLAC__StreamDecoder functions which change the
  89997. * state should not be called on the \a decoder while in the callback.
  89998. *
  89999. * \param decoder The decoder instance calling the callback.
  90000. * \param buffer A pointer to a location for the callee to store
  90001. * data to be decoded.
  90002. * \param bytes A pointer to the size of the buffer. On entry
  90003. * to the callback, it contains the maximum number
  90004. * of bytes that may be stored in \a buffer. The
  90005. * callee must set it to the actual number of bytes
  90006. * stored (0 in case of error or end-of-stream) before
  90007. * returning.
  90008. * \param client_data The callee's client data set through
  90009. * FLAC__stream_decoder_init_*().
  90010. * \retval FLAC__StreamDecoderReadStatus
  90011. * The callee's return status. Note that the callback should return
  90012. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  90013. * zero bytes were read and there is no more data to be read.
  90014. */
  90015. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90016. /** Signature for the seek callback.
  90017. *
  90018. * A function pointer matching this signature may be passed to
  90019. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90020. * called when the decoder needs to seek the input stream. The decoder
  90021. * will pass the absolute byte offset to seek to, 0 meaning the
  90022. * beginning of the stream.
  90023. *
  90024. * Here is an example of a seek callback for stdio streams:
  90025. * \code
  90026. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90027. * {
  90028. * FILE *file = ((MyClientData*)client_data)->file;
  90029. * if(file == stdin)
  90030. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  90031. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90032. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  90033. * else
  90034. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  90035. * }
  90036. * \endcode
  90037. *
  90038. * \note In general, FLAC__StreamDecoder functions which change the
  90039. * state should not be called on the \a decoder while in the callback.
  90040. *
  90041. * \param decoder The decoder instance calling the callback.
  90042. * \param absolute_byte_offset The offset from the beginning of the stream
  90043. * to seek to.
  90044. * \param client_data The callee's client data set through
  90045. * FLAC__stream_decoder_init_*().
  90046. * \retval FLAC__StreamDecoderSeekStatus
  90047. * The callee's return status.
  90048. */
  90049. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90050. /** Signature for the tell callback.
  90051. *
  90052. * A function pointer matching this signature may be passed to
  90053. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90054. * called when the decoder wants to know the current position of the
  90055. * stream. The callback should return the byte offset from the
  90056. * beginning of the stream.
  90057. *
  90058. * Here is an example of a tell callback for stdio streams:
  90059. * \code
  90060. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90061. * {
  90062. * FILE *file = ((MyClientData*)client_data)->file;
  90063. * off_t pos;
  90064. * if(file == stdin)
  90065. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90066. * else if((pos = ftello(file)) < 0)
  90067. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90068. * else {
  90069. * *absolute_byte_offset = (FLAC__uint64)pos;
  90070. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90071. * }
  90072. * }
  90073. * \endcode
  90074. *
  90075. * \note In general, FLAC__StreamDecoder functions which change the
  90076. * state should not be called on the \a decoder while in the callback.
  90077. *
  90078. * \param decoder The decoder instance calling the callback.
  90079. * \param absolute_byte_offset A pointer to storage for the current offset
  90080. * from the beginning of the stream.
  90081. * \param client_data The callee's client data set through
  90082. * FLAC__stream_decoder_init_*().
  90083. * \retval FLAC__StreamDecoderTellStatus
  90084. * The callee's return status.
  90085. */
  90086. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90087. /** Signature for the length callback.
  90088. *
  90089. * A function pointer matching this signature may be passed to
  90090. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90091. * called when the decoder wants to know the total length of the stream
  90092. * in bytes.
  90093. *
  90094. * Here is an example of a length callback for stdio streams:
  90095. * \code
  90096. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90097. * {
  90098. * FILE *file = ((MyClientData*)client_data)->file;
  90099. * struct stat filestats;
  90100. *
  90101. * if(file == stdin)
  90102. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90103. * else if(fstat(fileno(file), &filestats) != 0)
  90104. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90105. * else {
  90106. * *stream_length = (FLAC__uint64)filestats.st_size;
  90107. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90108. * }
  90109. * }
  90110. * \endcode
  90111. *
  90112. * \note In general, FLAC__StreamDecoder functions which change the
  90113. * state should not be called on the \a decoder while in the callback.
  90114. *
  90115. * \param decoder The decoder instance calling the callback.
  90116. * \param stream_length A pointer to storage for the length of the stream
  90117. * in bytes.
  90118. * \param client_data The callee's client data set through
  90119. * FLAC__stream_decoder_init_*().
  90120. * \retval FLAC__StreamDecoderLengthStatus
  90121. * The callee's return status.
  90122. */
  90123. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90124. /** Signature for the EOF callback.
  90125. *
  90126. * A function pointer matching this signature may be passed to
  90127. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90128. * called when the decoder needs to know if the end of the stream has
  90129. * been reached.
  90130. *
  90131. * Here is an example of a EOF callback for stdio streams:
  90132. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90133. * \code
  90134. * {
  90135. * FILE *file = ((MyClientData*)client_data)->file;
  90136. * return feof(file)? true : false;
  90137. * }
  90138. * \endcode
  90139. *
  90140. * \note In general, FLAC__StreamDecoder functions which change the
  90141. * state should not be called on the \a decoder while in the callback.
  90142. *
  90143. * \param decoder The decoder instance calling the callback.
  90144. * \param client_data The callee's client data set through
  90145. * FLAC__stream_decoder_init_*().
  90146. * \retval FLAC__bool
  90147. * \c true if the currently at the end of the stream, else \c false.
  90148. */
  90149. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90150. /** Signature for the write callback.
  90151. *
  90152. * A function pointer matching this signature must be passed to one of
  90153. * the FLAC__stream_decoder_init_*() functions.
  90154. * The supplied function will be called when the decoder has decoded a
  90155. * single audio frame. The decoder will pass the frame metadata as well
  90156. * as an array of pointers (one for each channel) pointing to the
  90157. * decoded audio.
  90158. *
  90159. * \note In general, FLAC__StreamDecoder functions which change the
  90160. * state should not be called on the \a decoder while in the callback.
  90161. *
  90162. * \param decoder The decoder instance calling the callback.
  90163. * \param frame The description of the decoded frame. See
  90164. * FLAC__Frame.
  90165. * \param buffer An array of pointers to decoded channels of data.
  90166. * Each pointer will point to an array of signed
  90167. * samples of length \a frame->header.blocksize.
  90168. * Channels will be ordered according to the FLAC
  90169. * specification; see the documentation for the
  90170. * <A HREF="../format.html#frame_header">frame header</A>.
  90171. * \param client_data The callee's client data set through
  90172. * FLAC__stream_decoder_init_*().
  90173. * \retval FLAC__StreamDecoderWriteStatus
  90174. * The callee's return status.
  90175. */
  90176. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90177. /** Signature for the metadata callback.
  90178. *
  90179. * A function pointer matching this signature must be passed to one of
  90180. * the FLAC__stream_decoder_init_*() functions.
  90181. * The supplied function will be called when the decoder has decoded a
  90182. * metadata block. In a valid FLAC file there will always be one
  90183. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90184. * These will be supplied by the decoder in the same order as they
  90185. * appear in the stream and always before the first audio frame (i.e.
  90186. * write callback). The metadata block that is passed in must not be
  90187. * modified, and it doesn't live beyond the callback, so you should make
  90188. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90189. * elsewhere. Since metadata blocks can potentially be large, by
  90190. * default the decoder only calls the metadata callback for the
  90191. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90192. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90193. *
  90194. * \note In general, FLAC__StreamDecoder functions which change the
  90195. * state should not be called on the \a decoder while in the callback.
  90196. *
  90197. * \param decoder The decoder instance calling the callback.
  90198. * \param metadata The decoded metadata block.
  90199. * \param client_data The callee's client data set through
  90200. * FLAC__stream_decoder_init_*().
  90201. */
  90202. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90203. /** Signature for the error callback.
  90204. *
  90205. * A function pointer matching this signature must be passed to one of
  90206. * the FLAC__stream_decoder_init_*() functions.
  90207. * The supplied function will be called whenever an error occurs during
  90208. * decoding.
  90209. *
  90210. * \note In general, FLAC__StreamDecoder functions which change the
  90211. * state should not be called on the \a decoder while in the callback.
  90212. *
  90213. * \param decoder The decoder instance calling the callback.
  90214. * \param status The error encountered by the decoder.
  90215. * \param client_data The callee's client data set through
  90216. * FLAC__stream_decoder_init_*().
  90217. */
  90218. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90219. /***********************************************************************
  90220. *
  90221. * Class constructor/destructor
  90222. *
  90223. ***********************************************************************/
  90224. /** Create a new stream decoder instance. The instance is created with
  90225. * default settings; see the individual FLAC__stream_decoder_set_*()
  90226. * functions for each setting's default.
  90227. *
  90228. * \retval FLAC__StreamDecoder*
  90229. * \c NULL if there was an error allocating memory, else the new instance.
  90230. */
  90231. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90232. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90233. *
  90234. * \param decoder A pointer to an existing decoder.
  90235. * \assert
  90236. * \code decoder != NULL \endcode
  90237. */
  90238. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90239. /***********************************************************************
  90240. *
  90241. * Public class method prototypes
  90242. *
  90243. ***********************************************************************/
  90244. /** Set the serial number for the FLAC stream within the Ogg container.
  90245. * The default behavior is to use the serial number of the first Ogg
  90246. * page. Setting a serial number here will explicitly specify which
  90247. * stream is to be decoded.
  90248. *
  90249. * \note
  90250. * This does not need to be set for native FLAC decoding.
  90251. *
  90252. * \default \c use serial number of first page
  90253. * \param decoder A decoder instance to set.
  90254. * \param serial_number See above.
  90255. * \assert
  90256. * \code decoder != NULL \endcode
  90257. * \retval FLAC__bool
  90258. * \c false if the decoder is already initialized, else \c true.
  90259. */
  90260. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90261. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90262. * compute the MD5 signature of the unencoded audio data while decoding
  90263. * and compare it to the signature from the STREAMINFO block, if it
  90264. * exists, during FLAC__stream_decoder_finish().
  90265. *
  90266. * MD5 signature checking will be turned off (until the next
  90267. * FLAC__stream_decoder_reset()) if there is no signature in the
  90268. * STREAMINFO block or when a seek is attempted.
  90269. *
  90270. * Clients that do not use the MD5 check should leave this off to speed
  90271. * up decoding.
  90272. *
  90273. * \default \c false
  90274. * \param decoder A decoder instance to set.
  90275. * \param value Flag value (see above).
  90276. * \assert
  90277. * \code decoder != NULL \endcode
  90278. * \retval FLAC__bool
  90279. * \c false if the decoder is already initialized, else \c true.
  90280. */
  90281. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90282. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90283. *
  90284. * \default By default, only the \c STREAMINFO block is returned via the
  90285. * metadata callback.
  90286. * \param decoder A decoder instance to set.
  90287. * \param type See above.
  90288. * \assert
  90289. * \code decoder != NULL \endcode
  90290. * \a type is valid
  90291. * \retval FLAC__bool
  90292. * \c false if the decoder is already initialized, else \c true.
  90293. */
  90294. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90295. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90296. * given \a id.
  90297. *
  90298. * \default By default, only the \c STREAMINFO block is returned via the
  90299. * metadata callback.
  90300. * \param decoder A decoder instance to set.
  90301. * \param id See above.
  90302. * \assert
  90303. * \code decoder != NULL \endcode
  90304. * \code id != NULL \endcode
  90305. * \retval FLAC__bool
  90306. * \c false if the decoder is already initialized, else \c true.
  90307. */
  90308. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90309. /** Direct the decoder to pass on all metadata blocks of any type.
  90310. *
  90311. * \default By default, only the \c STREAMINFO block is returned via the
  90312. * metadata callback.
  90313. * \param decoder A decoder instance to set.
  90314. * \assert
  90315. * \code decoder != NULL \endcode
  90316. * \retval FLAC__bool
  90317. * \c false if the decoder is already initialized, else \c true.
  90318. */
  90319. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90320. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90321. *
  90322. * \default By default, only the \c STREAMINFO block is returned via the
  90323. * metadata callback.
  90324. * \param decoder A decoder instance to set.
  90325. * \param type See above.
  90326. * \assert
  90327. * \code decoder != NULL \endcode
  90328. * \a type is valid
  90329. * \retval FLAC__bool
  90330. * \c false if the decoder is already initialized, else \c true.
  90331. */
  90332. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90333. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90334. * the given \a id.
  90335. *
  90336. * \default By default, only the \c STREAMINFO block is returned via the
  90337. * metadata callback.
  90338. * \param decoder A decoder instance to set.
  90339. * \param id See above.
  90340. * \assert
  90341. * \code decoder != NULL \endcode
  90342. * \code id != NULL \endcode
  90343. * \retval FLAC__bool
  90344. * \c false if the decoder is already initialized, else \c true.
  90345. */
  90346. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90347. /** Direct the decoder to filter out all metadata blocks of any type.
  90348. *
  90349. * \default By default, only the \c STREAMINFO block is returned via the
  90350. * metadata callback.
  90351. * \param decoder A decoder instance to set.
  90352. * \assert
  90353. * \code decoder != NULL \endcode
  90354. * \retval FLAC__bool
  90355. * \c false if the decoder is already initialized, else \c true.
  90356. */
  90357. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90358. /** Get the current decoder state.
  90359. *
  90360. * \param decoder A decoder instance to query.
  90361. * \assert
  90362. * \code decoder != NULL \endcode
  90363. * \retval FLAC__StreamDecoderState
  90364. * The current decoder state.
  90365. */
  90366. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90367. /** Get the current decoder state as a C string.
  90368. *
  90369. * \param decoder A decoder instance to query.
  90370. * \assert
  90371. * \code decoder != NULL \endcode
  90372. * \retval const char *
  90373. * The decoder state as a C string. Do not modify the contents.
  90374. */
  90375. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90376. /** Get the "MD5 signature checking" flag.
  90377. * This is the value of the setting, not whether or not the decoder is
  90378. * currently checking the MD5 (remember, it can be turned off automatically
  90379. * by a seek). When the decoder is reset the flag will be restored to the
  90380. * value returned by this function.
  90381. *
  90382. * \param decoder A decoder instance to query.
  90383. * \assert
  90384. * \code decoder != NULL \endcode
  90385. * \retval FLAC__bool
  90386. * See above.
  90387. */
  90388. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90389. /** Get the total number of samples in the stream being decoded.
  90390. * Will only be valid after decoding has started and will contain the
  90391. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90392. *
  90393. * \param decoder A decoder instance to query.
  90394. * \assert
  90395. * \code decoder != NULL \endcode
  90396. * \retval unsigned
  90397. * See above.
  90398. */
  90399. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90400. /** Get the current number of channels in the stream being decoded.
  90401. * Will only be valid after decoding has started and will contain the
  90402. * value from the most recently decoded frame header.
  90403. *
  90404. * \param decoder A decoder instance to query.
  90405. * \assert
  90406. * \code decoder != NULL \endcode
  90407. * \retval unsigned
  90408. * See above.
  90409. */
  90410. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90411. /** Get the current channel assignment in the stream being decoded.
  90412. * Will only be valid after decoding has started and will contain the
  90413. * value from the most recently decoded frame header.
  90414. *
  90415. * \param decoder A decoder instance to query.
  90416. * \assert
  90417. * \code decoder != NULL \endcode
  90418. * \retval FLAC__ChannelAssignment
  90419. * See above.
  90420. */
  90421. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90422. /** Get the current sample resolution in the stream being decoded.
  90423. * Will only be valid after decoding has started and will contain the
  90424. * value from the most recently decoded frame header.
  90425. *
  90426. * \param decoder A decoder instance to query.
  90427. * \assert
  90428. * \code decoder != NULL \endcode
  90429. * \retval unsigned
  90430. * See above.
  90431. */
  90432. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90433. /** Get the current sample rate in Hz of the stream being decoded.
  90434. * Will only be valid after decoding has started and will contain the
  90435. * value from the most recently decoded frame header.
  90436. *
  90437. * \param decoder A decoder instance to query.
  90438. * \assert
  90439. * \code decoder != NULL \endcode
  90440. * \retval unsigned
  90441. * See above.
  90442. */
  90443. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90444. /** Get the current blocksize of the stream being decoded.
  90445. * Will only be valid after decoding has started and will contain the
  90446. * value from the most recently decoded frame header.
  90447. *
  90448. * \param decoder A decoder instance to query.
  90449. * \assert
  90450. * \code decoder != NULL \endcode
  90451. * \retval unsigned
  90452. * See above.
  90453. */
  90454. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90455. /** Returns the decoder's current read position within the stream.
  90456. * The position is the byte offset from the start of the stream.
  90457. * Bytes before this position have been fully decoded. Note that
  90458. * there may still be undecoded bytes in the decoder's read FIFO.
  90459. * The returned position is correct even after a seek.
  90460. *
  90461. * \warning This function currently only works for native FLAC,
  90462. * not Ogg FLAC streams.
  90463. *
  90464. * \param decoder A decoder instance to query.
  90465. * \param position Address at which to return the desired position.
  90466. * \assert
  90467. * \code decoder != NULL \endcode
  90468. * \code position != NULL \endcode
  90469. * \retval FLAC__bool
  90470. * \c true if successful, \c false if the stream is not native FLAC,
  90471. * or there was an error from the 'tell' callback or it returned
  90472. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90473. */
  90474. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90475. /** Initialize the decoder instance to decode native FLAC streams.
  90476. *
  90477. * This flavor of initialization sets up the decoder to decode from a
  90478. * native FLAC stream. I/O is performed via callbacks to the client.
  90479. * For decoding from a plain file via filename or open FILE*,
  90480. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90481. * provide a simpler interface.
  90482. *
  90483. * This function should be called after FLAC__stream_decoder_new() and
  90484. * FLAC__stream_decoder_set_*() but before any of the
  90485. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90486. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90487. * if initialization succeeded.
  90488. *
  90489. * \param decoder An uninitialized decoder instance.
  90490. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90491. * pointer must not be \c NULL.
  90492. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90493. * pointer may be \c NULL if seeking is not
  90494. * supported. If \a seek_callback is not \c NULL then a
  90495. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90496. * Alternatively, a dummy seek callback that just
  90497. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90498. * may also be supplied, all though this is slightly
  90499. * less efficient for the decoder.
  90500. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90501. * pointer may be \c NULL if not supported by the client. If
  90502. * \a seek_callback is not \c NULL then a
  90503. * \a tell_callback must also be supplied.
  90504. * Alternatively, a dummy tell callback that just
  90505. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90506. * may also be supplied, all though this is slightly
  90507. * less efficient for the decoder.
  90508. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90509. * pointer may be \c NULL if not supported by the client. If
  90510. * \a seek_callback is not \c NULL then a
  90511. * \a length_callback must also be supplied.
  90512. * Alternatively, a dummy length callback that just
  90513. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90514. * may also be supplied, all though this is slightly
  90515. * less efficient for the decoder.
  90516. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90517. * pointer may be \c NULL if not supported by the client. If
  90518. * \a seek_callback is not \c NULL then a
  90519. * \a eof_callback must also be supplied.
  90520. * Alternatively, a dummy length callback that just
  90521. * returns \c false
  90522. * may also be supplied, all though this is slightly
  90523. * less efficient for the decoder.
  90524. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90525. * pointer must not be \c NULL.
  90526. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90527. * pointer may be \c NULL if the callback is not
  90528. * desired.
  90529. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90530. * pointer must not be \c NULL.
  90531. * \param client_data This value will be supplied to callbacks in their
  90532. * \a client_data argument.
  90533. * \assert
  90534. * \code decoder != NULL \endcode
  90535. * \retval FLAC__StreamDecoderInitStatus
  90536. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90537. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90538. */
  90539. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90540. FLAC__StreamDecoder *decoder,
  90541. FLAC__StreamDecoderReadCallback read_callback,
  90542. FLAC__StreamDecoderSeekCallback seek_callback,
  90543. FLAC__StreamDecoderTellCallback tell_callback,
  90544. FLAC__StreamDecoderLengthCallback length_callback,
  90545. FLAC__StreamDecoderEofCallback eof_callback,
  90546. FLAC__StreamDecoderWriteCallback write_callback,
  90547. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90548. FLAC__StreamDecoderErrorCallback error_callback,
  90549. void *client_data
  90550. );
  90551. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90552. *
  90553. * This flavor of initialization sets up the decoder to decode from a
  90554. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90555. * client. For decoding from a plain file via filename or open FILE*,
  90556. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90557. * provide a simpler interface.
  90558. *
  90559. * This function should be called after FLAC__stream_decoder_new() and
  90560. * FLAC__stream_decoder_set_*() but before any of the
  90561. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90562. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90563. * if initialization succeeded.
  90564. *
  90565. * \note Support for Ogg FLAC in the library is optional. If this
  90566. * library has been built without support for Ogg FLAC, this function
  90567. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90568. *
  90569. * \param decoder An uninitialized decoder instance.
  90570. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90571. * pointer must not be \c NULL.
  90572. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90573. * pointer may be \c NULL if seeking is not
  90574. * supported. If \a seek_callback is not \c NULL then a
  90575. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90576. * Alternatively, a dummy seek callback that just
  90577. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90578. * may also be supplied, all though this is slightly
  90579. * less efficient for the decoder.
  90580. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90581. * pointer may be \c NULL if not supported by the client. If
  90582. * \a seek_callback is not \c NULL then a
  90583. * \a tell_callback must also be supplied.
  90584. * Alternatively, a dummy tell callback that just
  90585. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90586. * may also be supplied, all though this is slightly
  90587. * less efficient for the decoder.
  90588. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90589. * pointer may be \c NULL if not supported by the client. If
  90590. * \a seek_callback is not \c NULL then a
  90591. * \a length_callback must also be supplied.
  90592. * Alternatively, a dummy length callback that just
  90593. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90594. * may also be supplied, all though this is slightly
  90595. * less efficient for the decoder.
  90596. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90597. * pointer may be \c NULL if not supported by the client. If
  90598. * \a seek_callback is not \c NULL then a
  90599. * \a eof_callback must also be supplied.
  90600. * Alternatively, a dummy length callback that just
  90601. * returns \c false
  90602. * may also be supplied, all though this is slightly
  90603. * less efficient for the decoder.
  90604. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90605. * pointer must not be \c NULL.
  90606. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90607. * pointer may be \c NULL if the callback is not
  90608. * desired.
  90609. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90610. * pointer must not be \c NULL.
  90611. * \param client_data This value will be supplied to callbacks in their
  90612. * \a client_data argument.
  90613. * \assert
  90614. * \code decoder != NULL \endcode
  90615. * \retval FLAC__StreamDecoderInitStatus
  90616. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90617. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90618. */
  90619. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90620. FLAC__StreamDecoder *decoder,
  90621. FLAC__StreamDecoderReadCallback read_callback,
  90622. FLAC__StreamDecoderSeekCallback seek_callback,
  90623. FLAC__StreamDecoderTellCallback tell_callback,
  90624. FLAC__StreamDecoderLengthCallback length_callback,
  90625. FLAC__StreamDecoderEofCallback eof_callback,
  90626. FLAC__StreamDecoderWriteCallback write_callback,
  90627. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90628. FLAC__StreamDecoderErrorCallback error_callback,
  90629. void *client_data
  90630. );
  90631. /** Initialize the decoder instance to decode native FLAC files.
  90632. *
  90633. * This flavor of initialization sets up the decoder to decode from a
  90634. * plain native FLAC file. For non-stdio streams, you must use
  90635. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90636. *
  90637. * This function should be called after FLAC__stream_decoder_new() and
  90638. * FLAC__stream_decoder_set_*() but before any of the
  90639. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90640. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90641. * if initialization succeeded.
  90642. *
  90643. * \param decoder An uninitialized decoder instance.
  90644. * \param file An open FLAC file. The file should have been
  90645. * opened with mode \c "rb" and rewound. The file
  90646. * becomes owned by the decoder and should not be
  90647. * manipulated by the client while decoding.
  90648. * Unless \a file is \c stdin, it will be closed
  90649. * when FLAC__stream_decoder_finish() is called.
  90650. * Note however that seeking will not work when
  90651. * decoding from \c stdout since it is not seekable.
  90652. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90653. * pointer must not be \c NULL.
  90654. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90655. * pointer may be \c NULL if the callback is not
  90656. * desired.
  90657. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90658. * pointer must not be \c NULL.
  90659. * \param client_data This value will be supplied to callbacks in their
  90660. * \a client_data argument.
  90661. * \assert
  90662. * \code decoder != NULL \endcode
  90663. * \code file != NULL \endcode
  90664. * \retval FLAC__StreamDecoderInitStatus
  90665. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90666. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90667. */
  90668. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90669. FLAC__StreamDecoder *decoder,
  90670. FILE *file,
  90671. FLAC__StreamDecoderWriteCallback write_callback,
  90672. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90673. FLAC__StreamDecoderErrorCallback error_callback,
  90674. void *client_data
  90675. );
  90676. /** Initialize the decoder instance to decode Ogg FLAC files.
  90677. *
  90678. * This flavor of initialization sets up the decoder to decode from a
  90679. * plain Ogg FLAC file. For non-stdio streams, you must use
  90680. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90681. *
  90682. * This function should be called after FLAC__stream_decoder_new() and
  90683. * FLAC__stream_decoder_set_*() but before any of the
  90684. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90685. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90686. * if initialization succeeded.
  90687. *
  90688. * \note Support for Ogg FLAC in the library is optional. If this
  90689. * library has been built without support for Ogg FLAC, this function
  90690. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90691. *
  90692. * \param decoder An uninitialized decoder instance.
  90693. * \param file An open FLAC file. The file should have been
  90694. * opened with mode \c "rb" and rewound. The file
  90695. * becomes owned by the decoder and should not be
  90696. * manipulated by the client while decoding.
  90697. * Unless \a file is \c stdin, it will be closed
  90698. * when FLAC__stream_decoder_finish() is called.
  90699. * Note however that seeking will not work when
  90700. * decoding from \c stdout since it is not seekable.
  90701. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90702. * pointer must not be \c NULL.
  90703. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90704. * pointer may be \c NULL if the callback is not
  90705. * desired.
  90706. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90707. * pointer must not be \c NULL.
  90708. * \param client_data This value will be supplied to callbacks in their
  90709. * \a client_data argument.
  90710. * \assert
  90711. * \code decoder != NULL \endcode
  90712. * \code file != NULL \endcode
  90713. * \retval FLAC__StreamDecoderInitStatus
  90714. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90715. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90716. */
  90717. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90718. FLAC__StreamDecoder *decoder,
  90719. FILE *file,
  90720. FLAC__StreamDecoderWriteCallback write_callback,
  90721. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90722. FLAC__StreamDecoderErrorCallback error_callback,
  90723. void *client_data
  90724. );
  90725. /** Initialize the decoder instance to decode native FLAC files.
  90726. *
  90727. * This flavor of initialization sets up the decoder to decode from a plain
  90728. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90729. * example, with Unicode filenames on Windows), you must use
  90730. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90731. * and provide callbacks for the I/O.
  90732. *
  90733. * This function should be called after FLAC__stream_decoder_new() and
  90734. * FLAC__stream_decoder_set_*() but before any of the
  90735. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90736. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90737. * if initialization succeeded.
  90738. *
  90739. * \param decoder An uninitialized decoder instance.
  90740. * \param filename The name of the file to decode from. The file will
  90741. * be opened with fopen(). Use \c NULL to decode from
  90742. * \c stdin. Note that \c stdin is not seekable.
  90743. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90744. * pointer must not be \c NULL.
  90745. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90746. * pointer may be \c NULL if the callback is not
  90747. * desired.
  90748. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90749. * pointer must not be \c NULL.
  90750. * \param client_data This value will be supplied to callbacks in their
  90751. * \a client_data argument.
  90752. * \assert
  90753. * \code decoder != NULL \endcode
  90754. * \retval FLAC__StreamDecoderInitStatus
  90755. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90756. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90757. */
  90758. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90759. FLAC__StreamDecoder *decoder,
  90760. const char *filename,
  90761. FLAC__StreamDecoderWriteCallback write_callback,
  90762. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90763. FLAC__StreamDecoderErrorCallback error_callback,
  90764. void *client_data
  90765. );
  90766. /** Initialize the decoder instance to decode Ogg FLAC files.
  90767. *
  90768. * This flavor of initialization sets up the decoder to decode from a plain
  90769. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90770. * example, with Unicode filenames on Windows), you must use
  90771. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90772. * and provide callbacks for the I/O.
  90773. *
  90774. * This function should be called after FLAC__stream_decoder_new() and
  90775. * FLAC__stream_decoder_set_*() but before any of the
  90776. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90777. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90778. * if initialization succeeded.
  90779. *
  90780. * \note Support for Ogg FLAC in the library is optional. If this
  90781. * library has been built without support for Ogg FLAC, this function
  90782. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90783. *
  90784. * \param decoder An uninitialized decoder instance.
  90785. * \param filename The name of the file to decode from. The file will
  90786. * be opened with fopen(). Use \c NULL to decode from
  90787. * \c stdin. Note that \c stdin is not seekable.
  90788. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90789. * pointer must not be \c NULL.
  90790. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90791. * pointer may be \c NULL if the callback is not
  90792. * desired.
  90793. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90794. * pointer must not be \c NULL.
  90795. * \param client_data This value will be supplied to callbacks in their
  90796. * \a client_data argument.
  90797. * \assert
  90798. * \code decoder != NULL \endcode
  90799. * \retval FLAC__StreamDecoderInitStatus
  90800. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90801. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90802. */
  90803. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90804. FLAC__StreamDecoder *decoder,
  90805. const char *filename,
  90806. FLAC__StreamDecoderWriteCallback write_callback,
  90807. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90808. FLAC__StreamDecoderErrorCallback error_callback,
  90809. void *client_data
  90810. );
  90811. /** Finish the decoding process.
  90812. * Flushes the decoding buffer, releases resources, resets the decoder
  90813. * settings to their defaults, and returns the decoder state to
  90814. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90815. *
  90816. * In the event of a prematurely-terminated decode, it is not strictly
  90817. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90818. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90819. * with a FLAC__stream_decoder_finish().
  90820. *
  90821. * \param decoder An uninitialized decoder instance.
  90822. * \assert
  90823. * \code decoder != NULL \endcode
  90824. * \retval FLAC__bool
  90825. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90826. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90827. * signature does not match the one computed by the decoder; else
  90828. * \c true.
  90829. */
  90830. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90831. /** Flush the stream input.
  90832. * The decoder's input buffer will be cleared and the state set to
  90833. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90834. * off MD5 checking.
  90835. *
  90836. * \param decoder A decoder instance.
  90837. * \assert
  90838. * \code decoder != NULL \endcode
  90839. * \retval FLAC__bool
  90840. * \c true if successful, else \c false if a memory allocation
  90841. * error occurs (in which case the state will be set to
  90842. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90843. */
  90844. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90845. /** Reset the decoding process.
  90846. * The decoder's input buffer will be cleared and the state set to
  90847. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90848. * FLAC__stream_decoder_finish() except that the settings are
  90849. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90850. * before decoding again. MD5 checking will be restored to its original
  90851. * setting.
  90852. *
  90853. * If the decoder is seekable, or was initialized with
  90854. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90855. * the decoder will also attempt to seek to the beginning of the file.
  90856. * If this rewind fails, this function will return \c false. It follows
  90857. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90858. * \c stdin.
  90859. *
  90860. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90861. * and is not seekable (i.e. no seek callback was provided or the seek
  90862. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90863. * is the duty of the client to start feeding data from the beginning of
  90864. * the stream on the next FLAC__stream_decoder_process() or
  90865. * FLAC__stream_decoder_process_interleaved() call.
  90866. *
  90867. * \param decoder A decoder instance.
  90868. * \assert
  90869. * \code decoder != NULL \endcode
  90870. * \retval FLAC__bool
  90871. * \c true if successful, else \c false if a memory allocation occurs
  90872. * (in which case the state will be set to
  90873. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90874. * occurs (the state will be unchanged).
  90875. */
  90876. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90877. /** Decode one metadata block or audio frame.
  90878. * This version instructs the decoder to decode a either a single metadata
  90879. * block or a single frame and stop, unless the callbacks return a fatal
  90880. * error or the read callback returns
  90881. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90882. *
  90883. * As the decoder needs more input it will call the read callback.
  90884. * Depending on what was decoded, the metadata or write callback will be
  90885. * called with the decoded metadata block or audio frame.
  90886. *
  90887. * Unless there is a fatal read error or end of stream, this function
  90888. * will return once one whole frame is decoded. In other words, if the
  90889. * stream is not synchronized or points to a corrupt frame header, the
  90890. * decoder will continue to try and resync until it gets to a valid
  90891. * frame, then decode one frame, then return. If the decoder points to
  90892. * a frame whose frame CRC in the frame footer does not match the
  90893. * computed frame CRC, this function will issue a
  90894. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90895. * error callback, and return, having decoded one complete, although
  90896. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90897. * correct length to the write callback.)
  90898. *
  90899. * \param decoder An initialized decoder instance.
  90900. * \assert
  90901. * \code decoder != NULL \endcode
  90902. * \retval FLAC__bool
  90903. * \c false if any fatal read, write, or memory allocation error
  90904. * occurred (meaning decoding must stop), else \c true; for more
  90905. * information about the decoder, check the decoder state with
  90906. * FLAC__stream_decoder_get_state().
  90907. */
  90908. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90909. /** Decode until the end of the metadata.
  90910. * This version instructs the decoder to decode from the current position
  90911. * and continue until all the metadata has been read, or until the
  90912. * callbacks return a fatal error or the read callback returns
  90913. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90914. *
  90915. * As the decoder needs more input it will call the read callback.
  90916. * As each metadata block is decoded, the metadata callback will be called
  90917. * with the decoded metadata.
  90918. *
  90919. * \param decoder An initialized decoder instance.
  90920. * \assert
  90921. * \code decoder != NULL \endcode
  90922. * \retval FLAC__bool
  90923. * \c false if any fatal read, write, or memory allocation error
  90924. * occurred (meaning decoding must stop), else \c true; for more
  90925. * information about the decoder, check the decoder state with
  90926. * FLAC__stream_decoder_get_state().
  90927. */
  90928. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90929. /** Decode until the end of the stream.
  90930. * This version instructs the decoder to decode from the current position
  90931. * and continue until the end of stream (the read callback returns
  90932. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90933. * callbacks return a fatal error.
  90934. *
  90935. * As the decoder needs more input it will call the read callback.
  90936. * As each metadata block and frame is decoded, the metadata or write
  90937. * callback will be called with the decoded metadata or frame.
  90938. *
  90939. * \param decoder An initialized decoder instance.
  90940. * \assert
  90941. * \code decoder != NULL \endcode
  90942. * \retval FLAC__bool
  90943. * \c false if any fatal read, write, or memory allocation error
  90944. * occurred (meaning decoding must stop), else \c true; for more
  90945. * information about the decoder, check the decoder state with
  90946. * FLAC__stream_decoder_get_state().
  90947. */
  90948. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90949. /** Skip one audio frame.
  90950. * This version instructs the decoder to 'skip' a single frame and stop,
  90951. * unless the callbacks return a fatal error or the read callback returns
  90952. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90953. *
  90954. * The decoding flow is the same as what occurs when
  90955. * FLAC__stream_decoder_process_single() is called to process an audio
  90956. * frame, except that this function does not decode the parsed data into
  90957. * PCM or call the write callback. The integrity of the frame is still
  90958. * checked the same way as in the other process functions.
  90959. *
  90960. * This function will return once one whole frame is skipped, in the
  90961. * same way that FLAC__stream_decoder_process_single() will return once
  90962. * one whole frame is decoded.
  90963. *
  90964. * This function can be used in more quickly determining FLAC frame
  90965. * boundaries when decoding of the actual data is not needed, for
  90966. * example when an application is separating a FLAC stream into frames
  90967. * for editing or storing in a container. To do this, the application
  90968. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90969. * to the next frame, then use
  90970. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90971. * boundary.
  90972. *
  90973. * This function should only be called when the stream has advanced
  90974. * past all the metadata, otherwise it will return \c false.
  90975. *
  90976. * \param decoder An initialized decoder instance not in a metadata
  90977. * state.
  90978. * \assert
  90979. * \code decoder != NULL \endcode
  90980. * \retval FLAC__bool
  90981. * \c false if any fatal read, write, or memory allocation error
  90982. * occurred (meaning decoding must stop), or if the decoder
  90983. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90984. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90985. * information about the decoder, check the decoder state with
  90986. * FLAC__stream_decoder_get_state().
  90987. */
  90988. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90989. /** Flush the input and seek to an absolute sample.
  90990. * Decoding will resume at the given sample. Note that because of
  90991. * this, the next write callback may contain a partial block. The
  90992. * client must support seeking the input or this function will fail
  90993. * and return \c false. Furthermore, if the decoder state is
  90994. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90995. * with FLAC__stream_decoder_flush() or reset with
  90996. * FLAC__stream_decoder_reset() before decoding can continue.
  90997. *
  90998. * \param decoder A decoder instance.
  90999. * \param sample The target sample number to seek to.
  91000. * \assert
  91001. * \code decoder != NULL \endcode
  91002. * \retval FLAC__bool
  91003. * \c true if successful, else \c false.
  91004. */
  91005. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  91006. /* \} */
  91007. #ifdef __cplusplus
  91008. }
  91009. #endif
  91010. #endif
  91011. /*** End of inlined file: stream_decoder.h ***/
  91012. /*** Start of inlined file: stream_encoder.h ***/
  91013. #ifndef FLAC__STREAM_ENCODER_H
  91014. #define FLAC__STREAM_ENCODER_H
  91015. #include <stdio.h> /* for FILE */
  91016. #ifdef __cplusplus
  91017. extern "C" {
  91018. #endif
  91019. /** \file include/FLAC/stream_encoder.h
  91020. *
  91021. * \brief
  91022. * This module contains the functions which implement the stream
  91023. * encoder.
  91024. *
  91025. * See the detailed documentation in the
  91026. * \link flac_stream_encoder stream encoder \endlink module.
  91027. */
  91028. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  91029. * \ingroup flac
  91030. *
  91031. * \brief
  91032. * This module describes the encoder layers provided by libFLAC.
  91033. *
  91034. * The stream encoder can be used to encode complete streams either to the
  91035. * client via callbacks, or directly to a file, depending on how it is
  91036. * initialized. When encoding via callbacks, the client provides a write
  91037. * callback which will be called whenever FLAC data is ready to be written.
  91038. * If the client also supplies a seek callback, the encoder will also
  91039. * automatically handle the writing back of metadata discovered while
  91040. * encoding, like stream info, seek points offsets, etc. When encoding to
  91041. * a file, the client needs only supply a filename or open \c FILE* and an
  91042. * optional progress callback for periodic notification of progress; the
  91043. * write and seek callbacks are supplied internally. For more info see the
  91044. * \link flac_stream_encoder stream encoder \endlink module.
  91045. */
  91046. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  91047. * \ingroup flac_encoder
  91048. *
  91049. * \brief
  91050. * This module contains the functions which implement the stream
  91051. * encoder.
  91052. *
  91053. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91054. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91055. *
  91056. * The basic usage of this encoder is as follows:
  91057. * - The program creates an instance of an encoder using
  91058. * FLAC__stream_encoder_new().
  91059. * - The program overrides the default settings using
  91060. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91061. * functions should be called:
  91062. * - FLAC__stream_encoder_set_channels()
  91063. * - FLAC__stream_encoder_set_bits_per_sample()
  91064. * - FLAC__stream_encoder_set_sample_rate()
  91065. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91066. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91067. * - If the application wants to control the compression level or set its own
  91068. * metadata, then the following should also be called:
  91069. * - FLAC__stream_encoder_set_compression_level()
  91070. * - FLAC__stream_encoder_set_verify()
  91071. * - FLAC__stream_encoder_set_metadata()
  91072. * - The rest of the set functions should only be called if the client needs
  91073. * exact control over how the audio is compressed; thorough understanding
  91074. * of the FLAC format is necessary to achieve good results.
  91075. * - The program initializes the instance to validate the settings and
  91076. * prepare for encoding using
  91077. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91078. * or FLAC__stream_encoder_init_file() for native FLAC
  91079. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91080. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91081. * - The program calls FLAC__stream_encoder_process() or
  91082. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91083. * subsequently calls the callbacks when there is encoder data ready
  91084. * to be written.
  91085. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91086. * which causes the encoder to encode any data still in its input pipe,
  91087. * update the metadata with the final encoding statistics if output
  91088. * seeking is possible, and finally reset the encoder to the
  91089. * uninitialized state.
  91090. * - The instance may be used again or deleted with
  91091. * FLAC__stream_encoder_delete().
  91092. *
  91093. * In more detail, the stream encoder functions similarly to the
  91094. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91095. * callbacks and more options. Typically the client will create a new
  91096. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91097. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91098. * calling one of the FLAC__stream_encoder_init_*() functions.
  91099. *
  91100. * Unlike the decoders, the stream encoder has many options that can
  91101. * affect the speed and compression ratio. When setting these parameters
  91102. * you should have some basic knowledge of the format (see the
  91103. * <A HREF="../documentation.html#format">user-level documentation</A>
  91104. * or the <A HREF="../format.html">formal description</A>). The
  91105. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91106. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91107. * functions will do this, so make sure to pay attention to the state
  91108. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91109. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91110. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91111. * the constructor.
  91112. *
  91113. * There are three initialization functions for native FLAC, one for
  91114. * setting up the encoder to encode FLAC data to the client via
  91115. * callbacks, and two for encoding directly to a file.
  91116. *
  91117. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91118. * You must also supply a write callback which will be called anytime
  91119. * there is raw encoded data to write. If the client can seek the output
  91120. * it is best to also supply seek and tell callbacks, as this allows the
  91121. * encoder to go back after encoding is finished to write back
  91122. * information that was collected while encoding, like seek point offsets,
  91123. * frame sizes, etc.
  91124. *
  91125. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91126. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91127. * filename or open \c FILE*; the encoder will handle all the callbacks
  91128. * internally. You may also supply a progress callback for periodic
  91129. * notification of the encoding progress.
  91130. *
  91131. * There are three similarly-named init functions for encoding to Ogg
  91132. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91133. * library has been built with Ogg support.
  91134. *
  91135. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91136. * call the write callback several times, once with the \c fLaC signature,
  91137. * and once for each encoded metadata block. Note that for Ogg FLAC
  91138. * encoding you will usually get at least twice the number of callbacks than
  91139. * with native FLAC, one for the Ogg page header and one for the page body.
  91140. *
  91141. * After initializing the instance, the client may feed audio data to the
  91142. * encoder in one of two ways:
  91143. *
  91144. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91145. * will pass an array of pointers to buffers, one for each channel, to
  91146. * the encoder, each of the same length. The samples need not be
  91147. * block-aligned, but each channel should have the same number of samples.
  91148. * - Channel interleaved, through
  91149. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91150. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91151. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91152. * Again, the samples need not be block-aligned but they must be
  91153. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91154. * the last value channelN_sampleM.
  91155. *
  91156. * Note that for either process call, each sample in the buffers should be a
  91157. * signed integer, right-justified to the resolution set by
  91158. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91159. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91160. *
  91161. * When the client is finished encoding data, it calls
  91162. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91163. * data still in its input pipe, and call the metadata callback with the
  91164. * final encoding statistics. Then the instance may be deleted with
  91165. * FLAC__stream_encoder_delete() or initialized again to encode another
  91166. * stream.
  91167. *
  91168. * For programs that write their own metadata, but that do not know the
  91169. * actual metadata until after encoding, it is advantageous to instruct
  91170. * the encoder to write a PADDING block of the correct size, so that
  91171. * instead of rewriting the whole stream after encoding, the program can
  91172. * just overwrite the PADDING block. If only the maximum size of the
  91173. * metadata is known, the program can write a slightly larger padding
  91174. * block, then split it after encoding.
  91175. *
  91176. * Make sure you understand how lengths are calculated. All FLAC metadata
  91177. * blocks have a 4 byte header which contains the type and length. This
  91178. * length does not include the 4 bytes of the header. See the format page
  91179. * for the specification of metadata blocks and their lengths.
  91180. *
  91181. * \note
  91182. * If you are writing the FLAC data to a file via callbacks, make sure it
  91183. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91184. * after the first encoding pass, the encoder will try to seek back to the
  91185. * beginning of the stream, to the STREAMINFO block, to write some data
  91186. * there. (If using FLAC__stream_encoder_init*_file() or
  91187. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91188. *
  91189. * \note
  91190. * The "set" functions may only be called when the encoder is in the
  91191. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91192. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91193. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91194. * return \c true, otherwise \c false.
  91195. *
  91196. * \note
  91197. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91198. * defaults.
  91199. *
  91200. * \{
  91201. */
  91202. /** State values for a FLAC__StreamEncoder.
  91203. *
  91204. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91205. *
  91206. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91207. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91208. * must be deleted with FLAC__stream_encoder_delete().
  91209. */
  91210. typedef enum {
  91211. FLAC__STREAM_ENCODER_OK = 0,
  91212. /**< The encoder is in the normal OK state and samples can be processed. */
  91213. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91214. /**< The encoder is in the uninitialized state; one of the
  91215. * FLAC__stream_encoder_init_*() functions must be called before samples
  91216. * can be processed.
  91217. */
  91218. FLAC__STREAM_ENCODER_OGG_ERROR,
  91219. /**< An error occurred in the underlying Ogg layer. */
  91220. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91221. /**< An error occurred in the underlying verify stream decoder;
  91222. * check FLAC__stream_encoder_get_verify_decoder_state().
  91223. */
  91224. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91225. /**< The verify decoder detected a mismatch between the original
  91226. * audio signal and the decoded audio signal.
  91227. */
  91228. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91229. /**< One of the callbacks returned a fatal error. */
  91230. FLAC__STREAM_ENCODER_IO_ERROR,
  91231. /**< An I/O error occurred while opening/reading/writing a file.
  91232. * Check \c errno.
  91233. */
  91234. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91235. /**< An error occurred while writing the stream; usually, the
  91236. * write_callback returned an error.
  91237. */
  91238. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91239. /**< Memory allocation failed. */
  91240. } FLAC__StreamEncoderState;
  91241. /** Maps a FLAC__StreamEncoderState to a C string.
  91242. *
  91243. * Using a FLAC__StreamEncoderState as the index to this array
  91244. * will give the string equivalent. The contents should not be modified.
  91245. */
  91246. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91247. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91248. */
  91249. typedef enum {
  91250. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91251. /**< Initialization was successful. */
  91252. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91253. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91254. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91255. /**< The library was not compiled with support for the given container
  91256. * format.
  91257. */
  91258. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91259. /**< A required callback was not supplied. */
  91260. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91261. /**< The encoder has an invalid setting for number of channels. */
  91262. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91263. /**< The encoder has an invalid setting for bits-per-sample.
  91264. * FLAC supports 4-32 bps but the reference encoder currently supports
  91265. * only up to 24 bps.
  91266. */
  91267. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91268. /**< The encoder has an invalid setting for the input sample rate. */
  91269. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91270. /**< The encoder has an invalid setting for the block size. */
  91271. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91272. /**< The encoder has an invalid setting for the maximum LPC order. */
  91273. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91274. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91275. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91276. /**< The specified block size is less than the maximum LPC order. */
  91277. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91278. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91279. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91280. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91281. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91282. * - One of the metadata blocks contains an undefined type
  91283. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91284. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91285. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91286. */
  91287. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91288. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91289. * already initialized, usually because
  91290. * FLAC__stream_encoder_finish() was not called.
  91291. */
  91292. } FLAC__StreamEncoderInitStatus;
  91293. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91294. *
  91295. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91296. * will give the string equivalent. The contents should not be modified.
  91297. */
  91298. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91299. /** Return values for the FLAC__StreamEncoder read callback.
  91300. */
  91301. typedef enum {
  91302. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91303. /**< The read was OK and decoding can continue. */
  91304. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91305. /**< The read was attempted at the end of the stream. */
  91306. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91307. /**< An unrecoverable error occurred. */
  91308. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91309. /**< Client does not support reading back from the output. */
  91310. } FLAC__StreamEncoderReadStatus;
  91311. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91312. *
  91313. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91314. * will give the string equivalent. The contents should not be modified.
  91315. */
  91316. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91317. /** Return values for the FLAC__StreamEncoder write callback.
  91318. */
  91319. typedef enum {
  91320. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91321. /**< The write was OK and encoding can continue. */
  91322. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91323. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91324. } FLAC__StreamEncoderWriteStatus;
  91325. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91326. *
  91327. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91328. * will give the string equivalent. The contents should not be modified.
  91329. */
  91330. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91331. /** Return values for the FLAC__StreamEncoder seek callback.
  91332. */
  91333. typedef enum {
  91334. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91335. /**< The seek was OK and encoding can continue. */
  91336. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91337. /**< An unrecoverable error occurred. */
  91338. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91339. /**< Client does not support seeking. */
  91340. } FLAC__StreamEncoderSeekStatus;
  91341. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91342. *
  91343. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91344. * will give the string equivalent. The contents should not be modified.
  91345. */
  91346. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91347. /** Return values for the FLAC__StreamEncoder tell callback.
  91348. */
  91349. typedef enum {
  91350. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91351. /**< The tell was OK and encoding can continue. */
  91352. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91353. /**< An unrecoverable error occurred. */
  91354. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91355. /**< Client does not support seeking. */
  91356. } FLAC__StreamEncoderTellStatus;
  91357. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91358. *
  91359. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91360. * will give the string equivalent. The contents should not be modified.
  91361. */
  91362. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91363. /***********************************************************************
  91364. *
  91365. * class FLAC__StreamEncoder
  91366. *
  91367. ***********************************************************************/
  91368. struct FLAC__StreamEncoderProtected;
  91369. struct FLAC__StreamEncoderPrivate;
  91370. /** The opaque structure definition for the stream encoder type.
  91371. * See the \link flac_stream_encoder stream encoder module \endlink
  91372. * for a detailed description.
  91373. */
  91374. typedef struct {
  91375. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91376. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91377. } FLAC__StreamEncoder;
  91378. /** Signature for the read callback.
  91379. *
  91380. * A function pointer matching this signature must be passed to
  91381. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91382. * The supplied function will be called when the encoder needs to read back
  91383. * encoded data. This happens during the metadata callback, when the encoder
  91384. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91385. * while encoding. The address of the buffer to be filled is supplied, along
  91386. * with the number of bytes the buffer can hold. The callback may choose to
  91387. * supply less data and modify the byte count but must be careful not to
  91388. * overflow the buffer. The callback then returns a status code chosen from
  91389. * FLAC__StreamEncoderReadStatus.
  91390. *
  91391. * Here is an example of a read callback for stdio streams:
  91392. * \code
  91393. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91394. * {
  91395. * FILE *file = ((MyClientData*)client_data)->file;
  91396. * if(*bytes > 0) {
  91397. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91398. * if(ferror(file))
  91399. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91400. * else if(*bytes == 0)
  91401. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91402. * else
  91403. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91404. * }
  91405. * else
  91406. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91407. * }
  91408. * \endcode
  91409. *
  91410. * \note In general, FLAC__StreamEncoder functions which change the
  91411. * state should not be called on the \a encoder while in the callback.
  91412. *
  91413. * \param encoder The encoder instance calling the callback.
  91414. * \param buffer A pointer to a location for the callee to store
  91415. * data to be encoded.
  91416. * \param bytes A pointer to the size of the buffer. On entry
  91417. * to the callback, it contains the maximum number
  91418. * of bytes that may be stored in \a buffer. The
  91419. * callee must set it to the actual number of bytes
  91420. * stored (0 in case of error or end-of-stream) before
  91421. * returning.
  91422. * \param client_data The callee's client data set through
  91423. * FLAC__stream_encoder_set_client_data().
  91424. * \retval FLAC__StreamEncoderReadStatus
  91425. * The callee's return status.
  91426. */
  91427. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91428. /** Signature for the write callback.
  91429. *
  91430. * A function pointer matching this signature must be passed to
  91431. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91432. * by the encoder anytime there is raw encoded data ready to write. It may
  91433. * include metadata mixed with encoded audio frames and the data is not
  91434. * guaranteed to be aligned on frame or metadata block boundaries.
  91435. *
  91436. * The only duty of the callback is to write out the \a bytes worth of data
  91437. * in \a buffer to the current position in the output stream. The arguments
  91438. * \a samples and \a current_frame are purely informational. If \a samples
  91439. * is greater than \c 0, then \a current_frame will hold the current frame
  91440. * number that is being written; otherwise it indicates that the write
  91441. * callback is being called to write metadata.
  91442. *
  91443. * \note
  91444. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91445. * write callback will be called twice when writing each audio
  91446. * frame; once for the page header, and once for the page body.
  91447. * When writing the page header, the \a samples argument to the
  91448. * write callback will be \c 0.
  91449. *
  91450. * \note In general, FLAC__StreamEncoder functions which change the
  91451. * state should not be called on the \a encoder while in the callback.
  91452. *
  91453. * \param encoder The encoder instance calling the callback.
  91454. * \param buffer An array of encoded data of length \a bytes.
  91455. * \param bytes The byte length of \a buffer.
  91456. * \param samples The number of samples encoded by \a buffer.
  91457. * \c 0 has a special meaning; see above.
  91458. * \param current_frame The number of the current frame being encoded.
  91459. * \param client_data The callee's client data set through
  91460. * FLAC__stream_encoder_init_*().
  91461. * \retval FLAC__StreamEncoderWriteStatus
  91462. * The callee's return status.
  91463. */
  91464. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91465. /** Signature for the seek callback.
  91466. *
  91467. * A function pointer matching this signature may be passed to
  91468. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91469. * when the encoder needs to seek the output stream. The encoder will pass
  91470. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91471. *
  91472. * Here is an example of a seek callback for stdio streams:
  91473. * \code
  91474. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91475. * {
  91476. * FILE *file = ((MyClientData*)client_data)->file;
  91477. * if(file == stdin)
  91478. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91479. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91480. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91481. * else
  91482. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91483. * }
  91484. * \endcode
  91485. *
  91486. * \note In general, FLAC__StreamEncoder functions which change the
  91487. * state should not be called on the \a encoder while in the callback.
  91488. *
  91489. * \param encoder The encoder instance calling the callback.
  91490. * \param absolute_byte_offset The offset from the beginning of the stream
  91491. * to seek to.
  91492. * \param client_data The callee's client data set through
  91493. * FLAC__stream_encoder_init_*().
  91494. * \retval FLAC__StreamEncoderSeekStatus
  91495. * The callee's return status.
  91496. */
  91497. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91498. /** Signature for the tell callback.
  91499. *
  91500. * A function pointer matching this signature may be passed to
  91501. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91502. * when the encoder needs to know the current position of the output stream.
  91503. *
  91504. * \warning
  91505. * The callback must return the true current byte offset of the output to
  91506. * which the encoder is writing. If you are buffering the output, make
  91507. * sure and take this into account. If you are writing directly to a
  91508. * FILE* from your write callback, ftell() is sufficient. If you are
  91509. * writing directly to a file descriptor from your write callback, you
  91510. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91511. * these points to rewrite metadata after encoding.
  91512. *
  91513. * Here is an example of a tell callback for stdio streams:
  91514. * \code
  91515. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91516. * {
  91517. * FILE *file = ((MyClientData*)client_data)->file;
  91518. * off_t pos;
  91519. * if(file == stdin)
  91520. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91521. * else if((pos = ftello(file)) < 0)
  91522. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91523. * else {
  91524. * *absolute_byte_offset = (FLAC__uint64)pos;
  91525. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91526. * }
  91527. * }
  91528. * \endcode
  91529. *
  91530. * \note In general, FLAC__StreamEncoder functions which change the
  91531. * state should not be called on the \a encoder while in the callback.
  91532. *
  91533. * \param encoder The encoder instance calling the callback.
  91534. * \param absolute_byte_offset The address at which to store the current
  91535. * position of the output.
  91536. * \param client_data The callee's client data set through
  91537. * FLAC__stream_encoder_init_*().
  91538. * \retval FLAC__StreamEncoderTellStatus
  91539. * The callee's return status.
  91540. */
  91541. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91542. /** Signature for the metadata callback.
  91543. *
  91544. * A function pointer matching this signature may be passed to
  91545. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91546. * once at the end of encoding with the populated STREAMINFO structure. This
  91547. * is so the client can seek back to the beginning of the file and write the
  91548. * STREAMINFO block with the correct statistics after encoding (like
  91549. * minimum/maximum frame size and total samples).
  91550. *
  91551. * \note In general, FLAC__StreamEncoder functions which change the
  91552. * state should not be called on the \a encoder while in the callback.
  91553. *
  91554. * \param encoder The encoder instance calling the callback.
  91555. * \param metadata The final populated STREAMINFO block.
  91556. * \param client_data The callee's client data set through
  91557. * FLAC__stream_encoder_init_*().
  91558. */
  91559. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91560. /** Signature for the progress callback.
  91561. *
  91562. * A function pointer matching this signature may be passed to
  91563. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91564. * The supplied function will be called when the encoder has finished
  91565. * writing a frame. The \c total_frames_estimate argument to the
  91566. * callback will be based on the value from
  91567. * FLAC__stream_encoder_set_total_samples_estimate().
  91568. *
  91569. * \note In general, FLAC__StreamEncoder functions which change the
  91570. * state should not be called on the \a encoder while in the callback.
  91571. *
  91572. * \param encoder The encoder instance calling the callback.
  91573. * \param bytes_written Bytes written so far.
  91574. * \param samples_written Samples written so far.
  91575. * \param frames_written Frames written so far.
  91576. * \param total_frames_estimate The estimate of the total number of
  91577. * frames to be written.
  91578. * \param client_data The callee's client data set through
  91579. * FLAC__stream_encoder_init_*().
  91580. */
  91581. 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);
  91582. /***********************************************************************
  91583. *
  91584. * Class constructor/destructor
  91585. *
  91586. ***********************************************************************/
  91587. /** Create a new stream encoder instance. The instance is created with
  91588. * default settings; see the individual FLAC__stream_encoder_set_*()
  91589. * functions for each setting's default.
  91590. *
  91591. * \retval FLAC__StreamEncoder*
  91592. * \c NULL if there was an error allocating memory, else the new instance.
  91593. */
  91594. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91595. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91596. *
  91597. * \param encoder A pointer to an existing encoder.
  91598. * \assert
  91599. * \code encoder != NULL \endcode
  91600. */
  91601. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91602. /***********************************************************************
  91603. *
  91604. * Public class method prototypes
  91605. *
  91606. ***********************************************************************/
  91607. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91608. *
  91609. * \note
  91610. * This does not need to be set for native FLAC encoding.
  91611. *
  91612. * \note
  91613. * It is recommended to set a serial number explicitly as the default of '0'
  91614. * may collide with other streams.
  91615. *
  91616. * \default \c 0
  91617. * \param encoder An encoder instance to set.
  91618. * \param serial_number See above.
  91619. * \assert
  91620. * \code encoder != NULL \endcode
  91621. * \retval FLAC__bool
  91622. * \c false if the encoder is already initialized, else \c true.
  91623. */
  91624. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91625. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91626. * encoded output by feeding it through an internal decoder and comparing
  91627. * the original signal against the decoded signal. If a mismatch occurs,
  91628. * the process call will return \c false. Note that this will slow the
  91629. * encoding process by the extra time required for decoding and comparison.
  91630. *
  91631. * \default \c false
  91632. * \param encoder An encoder instance to set.
  91633. * \param value Flag value (see above).
  91634. * \assert
  91635. * \code encoder != NULL \endcode
  91636. * \retval FLAC__bool
  91637. * \c false if the encoder is already initialized, else \c true.
  91638. */
  91639. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91640. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91641. * the encoder will comply with the Subset and will check the
  91642. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91643. * comply. If \c false, the settings may take advantage of the full
  91644. * range that the format allows.
  91645. *
  91646. * Make sure you know what it entails before setting this to \c false.
  91647. *
  91648. * \default \c true
  91649. * \param encoder An encoder instance to set.
  91650. * \param value Flag value (see above).
  91651. * \assert
  91652. * \code encoder != NULL \endcode
  91653. * \retval FLAC__bool
  91654. * \c false if the encoder is already initialized, else \c true.
  91655. */
  91656. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91657. /** Set the number of channels to be encoded.
  91658. *
  91659. * \default \c 2
  91660. * \param encoder An encoder instance to set.
  91661. * \param value See above.
  91662. * \assert
  91663. * \code encoder != NULL \endcode
  91664. * \retval FLAC__bool
  91665. * \c false if the encoder is already initialized, else \c true.
  91666. */
  91667. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91668. /** Set the sample resolution of the input to be encoded.
  91669. *
  91670. * \warning
  91671. * Do not feed the encoder data that is wider than the value you
  91672. * set here or you will generate an invalid stream.
  91673. *
  91674. * \default \c 16
  91675. * \param encoder An encoder instance to set.
  91676. * \param value See above.
  91677. * \assert
  91678. * \code encoder != NULL \endcode
  91679. * \retval FLAC__bool
  91680. * \c false if the encoder is already initialized, else \c true.
  91681. */
  91682. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91683. /** Set the sample rate (in Hz) of the input to be encoded.
  91684. *
  91685. * \default \c 44100
  91686. * \param encoder An encoder instance to set.
  91687. * \param value See above.
  91688. * \assert
  91689. * \code encoder != NULL \endcode
  91690. * \retval FLAC__bool
  91691. * \c false if the encoder is already initialized, else \c true.
  91692. */
  91693. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91694. /** Set the compression level
  91695. *
  91696. * The compression level is roughly proportional to the amount of effort
  91697. * the encoder expends to compress the file. A higher level usually
  91698. * means more computation but higher compression. The default level is
  91699. * suitable for most applications.
  91700. *
  91701. * Currently the levels range from \c 0 (fastest, least compression) to
  91702. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91703. * treated as \c 8.
  91704. *
  91705. * This function automatically calls the following other \c _set_
  91706. * functions with appropriate values, so the client does not need to
  91707. * unless it specifically wants to override them:
  91708. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91709. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91710. * - FLAC__stream_encoder_set_apodization()
  91711. * - FLAC__stream_encoder_set_max_lpc_order()
  91712. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91713. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91714. * - FLAC__stream_encoder_set_do_escape_coding()
  91715. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91716. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91717. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91718. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91719. *
  91720. * The actual values set for each level are:
  91721. * <table>
  91722. * <tr>
  91723. * <td><b>level</b><td>
  91724. * <td>do mid-side stereo<td>
  91725. * <td>loose mid-side stereo<td>
  91726. * <td>apodization<td>
  91727. * <td>max lpc order<td>
  91728. * <td>qlp coeff precision<td>
  91729. * <td>qlp coeff prec search<td>
  91730. * <td>escape coding<td>
  91731. * <td>exhaustive model search<td>
  91732. * <td>min residual partition order<td>
  91733. * <td>max residual partition order<td>
  91734. * <td>rice parameter search dist<td>
  91735. * </tr>
  91736. * <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>
  91737. * <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>
  91738. * <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>
  91739. * <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>
  91740. * <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>
  91741. * <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>
  91742. * <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>
  91743. * <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>
  91744. * <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>
  91745. * </table>
  91746. *
  91747. * \default \c 5
  91748. * \param encoder An encoder instance to set.
  91749. * \param value See above.
  91750. * \assert
  91751. * \code encoder != NULL \endcode
  91752. * \retval FLAC__bool
  91753. * \c false if the encoder is already initialized, else \c true.
  91754. */
  91755. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91756. /** Set the blocksize to use while encoding.
  91757. *
  91758. * The number of samples to use per frame. Use \c 0 to let the encoder
  91759. * estimate a blocksize; this is usually best.
  91760. *
  91761. * \default \c 0
  91762. * \param encoder An encoder instance to set.
  91763. * \param value See above.
  91764. * \assert
  91765. * \code encoder != NULL \endcode
  91766. * \retval FLAC__bool
  91767. * \c false if the encoder is already initialized, else \c true.
  91768. */
  91769. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91770. /** Set to \c true to enable mid-side encoding on stereo input. The
  91771. * number of channels must be 2 for this to have any effect. Set to
  91772. * \c false to use only independent channel coding.
  91773. *
  91774. * \default \c false
  91775. * \param encoder An encoder instance to set.
  91776. * \param value Flag value (see above).
  91777. * \assert
  91778. * \code encoder != NULL \endcode
  91779. * \retval FLAC__bool
  91780. * \c false if the encoder is already initialized, else \c true.
  91781. */
  91782. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91783. /** Set to \c true to enable adaptive switching between mid-side and
  91784. * left-right encoding on stereo input. Set to \c false to use
  91785. * exhaustive searching. Setting this to \c true requires
  91786. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91787. * \c true in order to have any effect.
  91788. *
  91789. * \default \c false
  91790. * \param encoder An encoder instance to set.
  91791. * \param value Flag value (see above).
  91792. * \assert
  91793. * \code encoder != NULL \endcode
  91794. * \retval FLAC__bool
  91795. * \c false if the encoder is already initialized, else \c true.
  91796. */
  91797. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91798. /** Sets the apodization function(s) the encoder will use when windowing
  91799. * audio data for LPC analysis.
  91800. *
  91801. * The \a specification is a plain ASCII string which specifies exactly
  91802. * which functions to use. There may be more than one (up to 32),
  91803. * separated by \c ';' characters. Some functions take one or more
  91804. * comma-separated arguments in parentheses.
  91805. *
  91806. * The available functions are \c bartlett, \c bartlett_hann,
  91807. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91808. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91809. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91810. *
  91811. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91812. * (0<STDDEV<=0.5).
  91813. *
  91814. * For \c tukey(P), P specifies the fraction of the window that is
  91815. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91816. * corresponds to \c hann.
  91817. *
  91818. * Example specifications are \c "blackman" or
  91819. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91820. *
  91821. * Any function that is specified erroneously is silently dropped. Up
  91822. * to 32 functions are kept, the rest are dropped. If the specification
  91823. * is empty the encoder defaults to \c "tukey(0.5)".
  91824. *
  91825. * When more than one function is specified, then for every subframe the
  91826. * encoder will try each of them separately and choose the window that
  91827. * results in the smallest compressed subframe.
  91828. *
  91829. * Note that each function specified causes the encoder to occupy a
  91830. * floating point array in which to store the window.
  91831. *
  91832. * \default \c "tukey(0.5)"
  91833. * \param encoder An encoder instance to set.
  91834. * \param specification See above.
  91835. * \assert
  91836. * \code encoder != NULL \endcode
  91837. * \code specification != NULL \endcode
  91838. * \retval FLAC__bool
  91839. * \c false if the encoder is already initialized, else \c true.
  91840. */
  91841. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91842. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91843. *
  91844. * \default \c 0
  91845. * \param encoder An encoder instance to set.
  91846. * \param value See above.
  91847. * \assert
  91848. * \code encoder != NULL \endcode
  91849. * \retval FLAC__bool
  91850. * \c false if the encoder is already initialized, else \c true.
  91851. */
  91852. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91853. /** Set the precision, in bits, of the quantized linear predictor
  91854. * coefficients, or \c 0 to let the encoder select it based on the
  91855. * blocksize.
  91856. *
  91857. * \note
  91858. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91859. * be less than 32.
  91860. *
  91861. * \default \c 0
  91862. * \param encoder An encoder instance to set.
  91863. * \param value See above.
  91864. * \assert
  91865. * \code encoder != NULL \endcode
  91866. * \retval FLAC__bool
  91867. * \c false if the encoder is already initialized, else \c true.
  91868. */
  91869. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91870. /** Set to \c false to use only the specified quantized linear predictor
  91871. * coefficient precision, or \c true to search neighboring precision
  91872. * values and use the best one.
  91873. *
  91874. * \default \c false
  91875. * \param encoder An encoder instance to set.
  91876. * \param value See above.
  91877. * \assert
  91878. * \code encoder != NULL \endcode
  91879. * \retval FLAC__bool
  91880. * \c false if the encoder is already initialized, else \c true.
  91881. */
  91882. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91883. /** Deprecated. Setting this value has no effect.
  91884. *
  91885. * \default \c false
  91886. * \param encoder An encoder instance to set.
  91887. * \param value See above.
  91888. * \assert
  91889. * \code encoder != NULL \endcode
  91890. * \retval FLAC__bool
  91891. * \c false if the encoder is already initialized, else \c true.
  91892. */
  91893. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91894. /** Set to \c false to let the encoder estimate the best model order
  91895. * based on the residual signal energy, or \c true to force the
  91896. * encoder to evaluate all order models and select the best.
  91897. *
  91898. * \default \c false
  91899. * \param encoder An encoder instance to set.
  91900. * \param value See above.
  91901. * \assert
  91902. * \code encoder != NULL \endcode
  91903. * \retval FLAC__bool
  91904. * \c false if the encoder is already initialized, else \c true.
  91905. */
  91906. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91907. /** Set the minimum partition order to search when coding the residual.
  91908. * This is used in tandem with
  91909. * FLAC__stream_encoder_set_max_residual_partition_order().
  91910. *
  91911. * The partition order determines the context size in the residual.
  91912. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91913. *
  91914. * Set both min and max values to \c 0 to force a single context,
  91915. * whose Rice parameter is based on the residual signal variance.
  91916. * Otherwise, set a min and max order, and the encoder will search
  91917. * all orders, using the mean of each context for its Rice parameter,
  91918. * and use the best.
  91919. *
  91920. * \default \c 0
  91921. * \param encoder An encoder instance to set.
  91922. * \param value See above.
  91923. * \assert
  91924. * \code encoder != NULL \endcode
  91925. * \retval FLAC__bool
  91926. * \c false if the encoder is already initialized, else \c true.
  91927. */
  91928. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91929. /** Set the maximum partition order to search when coding the residual.
  91930. * This is used in tandem with
  91931. * FLAC__stream_encoder_set_min_residual_partition_order().
  91932. *
  91933. * The partition order determines the context size in the residual.
  91934. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91935. *
  91936. * Set both min and max values to \c 0 to force a single context,
  91937. * whose Rice parameter is based on the residual signal variance.
  91938. * Otherwise, set a min and max order, and the encoder will search
  91939. * all orders, using the mean of each context for its Rice parameter,
  91940. * and use the best.
  91941. *
  91942. * \default \c 0
  91943. * \param encoder An encoder instance to set.
  91944. * \param value See above.
  91945. * \assert
  91946. * \code encoder != NULL \endcode
  91947. * \retval FLAC__bool
  91948. * \c false if the encoder is already initialized, else \c true.
  91949. */
  91950. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91951. /** Deprecated. Setting this value has no effect.
  91952. *
  91953. * \default \c 0
  91954. * \param encoder An encoder instance to set.
  91955. * \param value See above.
  91956. * \assert
  91957. * \code encoder != NULL \endcode
  91958. * \retval FLAC__bool
  91959. * \c false if the encoder is already initialized, else \c true.
  91960. */
  91961. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91962. /** Set an estimate of the total samples that will be encoded.
  91963. * This is merely an estimate and may be set to \c 0 if unknown.
  91964. * This value will be written to the STREAMINFO block before encoding,
  91965. * and can remove the need for the caller to rewrite the value later
  91966. * if the value is known before encoding.
  91967. *
  91968. * \default \c 0
  91969. * \param encoder An encoder instance to set.
  91970. * \param value See above.
  91971. * \assert
  91972. * \code encoder != NULL \endcode
  91973. * \retval FLAC__bool
  91974. * \c false if the encoder is already initialized, else \c true.
  91975. */
  91976. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91977. /** Set the metadata blocks to be emitted to the stream before encoding.
  91978. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91979. * array of pointers to metadata blocks. The array is non-const since
  91980. * the encoder may need to change the \a is_last flag inside them, and
  91981. * in some cases update seek point offsets. Otherwise, the encoder will
  91982. * not modify or free the blocks. It is up to the caller to free the
  91983. * metadata blocks after encoding finishes.
  91984. *
  91985. * \note
  91986. * The encoder stores only copies of the pointers in the \a metadata array;
  91987. * the metadata blocks themselves must survive at least until after
  91988. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91989. *
  91990. * \note
  91991. * The STREAMINFO block is always written and no STREAMINFO block may
  91992. * occur in the supplied array.
  91993. *
  91994. * \note
  91995. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91996. * in the \a metadata array, but the client has specified that it does not
  91997. * support seeking, then the SEEKTABLE will be written verbatim. However
  91998. * by itself this is not very useful as the client will not know the stream
  91999. * offsets for the seekpoints ahead of time. In order to get a proper
  92000. * seektable the client must support seeking. See next note.
  92001. *
  92002. * \note
  92003. * SEEKTABLE blocks are handled specially. Since you will not know
  92004. * the values for the seek point stream offsets, you should pass in
  92005. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  92006. * required sample numbers (or placeholder points), with \c 0 for the
  92007. * \a frame_samples and \a stream_offset fields for each point. If the
  92008. * client has specified that it supports seeking by providing a seek
  92009. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  92010. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  92011. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  92012. * then while it is encoding the encoder will fill the stream offsets in
  92013. * for you and when encoding is finished, it will seek back and write the
  92014. * real values into the SEEKTABLE block in the stream. There are helper
  92015. * routines for manipulating seektable template blocks; see metadata.h:
  92016. * FLAC__metadata_object_seektable_template_*(). If the client does
  92017. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  92018. * will slow down or remove the ability to seek in the FLAC stream.
  92019. *
  92020. * \note
  92021. * The encoder instance \b will modify the first \c SEEKTABLE block
  92022. * as it transforms the template to a valid seektable while encoding,
  92023. * but it is still up to the caller to free all metadata blocks after
  92024. * encoding.
  92025. *
  92026. * \note
  92027. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  92028. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  92029. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  92030. * will simply write it's own into the stream. If no VORBIS_COMMENT
  92031. * block is present in the \a metadata array, libFLAC will write an
  92032. * empty one, containing only the vendor string.
  92033. *
  92034. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  92035. * the second metadata block of the stream. The encoder already supplies
  92036. * the STREAMINFO block automatically. If \a metadata does not contain a
  92037. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  92038. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  92039. * first, the init function will reorder \a metadata by moving the
  92040. * VORBIS_COMMENT block to the front; the relative ordering of the other
  92041. * blocks will remain as they were.
  92042. *
  92043. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  92044. * stream to \c 65535. If \a num_blocks exceeds this the function will
  92045. * return \c false.
  92046. *
  92047. * \default \c NULL, 0
  92048. * \param encoder An encoder instance to set.
  92049. * \param metadata See above.
  92050. * \param num_blocks See above.
  92051. * \assert
  92052. * \code encoder != NULL \endcode
  92053. * \retval FLAC__bool
  92054. * \c false if the encoder is already initialized, else \c true.
  92055. * \c false if the encoder is already initialized, or if
  92056. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92057. */
  92058. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92059. /** Get the current encoder state.
  92060. *
  92061. * \param encoder An encoder instance to query.
  92062. * \assert
  92063. * \code encoder != NULL \endcode
  92064. * \retval FLAC__StreamEncoderState
  92065. * The current encoder state.
  92066. */
  92067. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92068. /** Get the state of the verify stream decoder.
  92069. * Useful when the stream encoder state is
  92070. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92071. *
  92072. * \param encoder An encoder instance to query.
  92073. * \assert
  92074. * \code encoder != NULL \endcode
  92075. * \retval FLAC__StreamDecoderState
  92076. * The verify stream decoder state.
  92077. */
  92078. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92079. /** Get the current encoder state as a C string.
  92080. * This version automatically resolves
  92081. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92082. * verify decoder's state.
  92083. *
  92084. * \param encoder A encoder instance to query.
  92085. * \assert
  92086. * \code encoder != NULL \endcode
  92087. * \retval const char *
  92088. * The encoder state as a C string. Do not modify the contents.
  92089. */
  92090. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92091. /** Get relevant values about the nature of a verify decoder error.
  92092. * Useful when the stream encoder state is
  92093. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92094. * be addresses in which the stats will be returned, or NULL if value
  92095. * is not desired.
  92096. *
  92097. * \param encoder An encoder instance to query.
  92098. * \param absolute_sample The absolute sample number of the mismatch.
  92099. * \param frame_number The number of the frame in which the mismatch occurred.
  92100. * \param channel The channel in which the mismatch occurred.
  92101. * \param sample The number of the sample (relative to the frame) in
  92102. * which the mismatch occurred.
  92103. * \param expected The expected value for the sample in question.
  92104. * \param got The actual value returned by the decoder.
  92105. * \assert
  92106. * \code encoder != NULL \endcode
  92107. */
  92108. 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);
  92109. /** Get the "verify" flag.
  92110. *
  92111. * \param encoder An encoder instance to query.
  92112. * \assert
  92113. * \code encoder != NULL \endcode
  92114. * \retval FLAC__bool
  92115. * See FLAC__stream_encoder_set_verify().
  92116. */
  92117. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92118. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92119. *
  92120. * \param encoder An encoder instance to query.
  92121. * \assert
  92122. * \code encoder != NULL \endcode
  92123. * \retval FLAC__bool
  92124. * See FLAC__stream_encoder_set_streamable_subset().
  92125. */
  92126. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92127. /** Get the number of input channels being processed.
  92128. *
  92129. * \param encoder An encoder instance to query.
  92130. * \assert
  92131. * \code encoder != NULL \endcode
  92132. * \retval unsigned
  92133. * See FLAC__stream_encoder_set_channels().
  92134. */
  92135. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92136. /** Get the input sample resolution setting.
  92137. *
  92138. * \param encoder An encoder instance to query.
  92139. * \assert
  92140. * \code encoder != NULL \endcode
  92141. * \retval unsigned
  92142. * See FLAC__stream_encoder_set_bits_per_sample().
  92143. */
  92144. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92145. /** Get the input sample rate setting.
  92146. *
  92147. * \param encoder An encoder instance to query.
  92148. * \assert
  92149. * \code encoder != NULL \endcode
  92150. * \retval unsigned
  92151. * See FLAC__stream_encoder_set_sample_rate().
  92152. */
  92153. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92154. /** Get the blocksize setting.
  92155. *
  92156. * \param encoder An encoder instance to query.
  92157. * \assert
  92158. * \code encoder != NULL \endcode
  92159. * \retval unsigned
  92160. * See FLAC__stream_encoder_set_blocksize().
  92161. */
  92162. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92163. /** Get the "mid/side stereo coding" flag.
  92164. *
  92165. * \param encoder An encoder instance to query.
  92166. * \assert
  92167. * \code encoder != NULL \endcode
  92168. * \retval FLAC__bool
  92169. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92170. */
  92171. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92172. /** Get the "adaptive mid/side switching" flag.
  92173. *
  92174. * \param encoder An encoder instance to query.
  92175. * \assert
  92176. * \code encoder != NULL \endcode
  92177. * \retval FLAC__bool
  92178. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92179. */
  92180. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92181. /** Get the maximum LPC order setting.
  92182. *
  92183. * \param encoder An encoder instance to query.
  92184. * \assert
  92185. * \code encoder != NULL \endcode
  92186. * \retval unsigned
  92187. * See FLAC__stream_encoder_set_max_lpc_order().
  92188. */
  92189. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92190. /** Get the quantized linear predictor coefficient precision setting.
  92191. *
  92192. * \param encoder An encoder instance to query.
  92193. * \assert
  92194. * \code encoder != NULL \endcode
  92195. * \retval unsigned
  92196. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92197. */
  92198. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92199. /** Get the qlp coefficient precision search flag.
  92200. *
  92201. * \param encoder An encoder instance to query.
  92202. * \assert
  92203. * \code encoder != NULL \endcode
  92204. * \retval FLAC__bool
  92205. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92206. */
  92207. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92208. /** Get the "escape coding" flag.
  92209. *
  92210. * \param encoder An encoder instance to query.
  92211. * \assert
  92212. * \code encoder != NULL \endcode
  92213. * \retval FLAC__bool
  92214. * See FLAC__stream_encoder_set_do_escape_coding().
  92215. */
  92216. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92217. /** Get the exhaustive model search flag.
  92218. *
  92219. * \param encoder An encoder instance to query.
  92220. * \assert
  92221. * \code encoder != NULL \endcode
  92222. * \retval FLAC__bool
  92223. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92224. */
  92225. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92226. /** Get the minimum residual partition order setting.
  92227. *
  92228. * \param encoder An encoder instance to query.
  92229. * \assert
  92230. * \code encoder != NULL \endcode
  92231. * \retval unsigned
  92232. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92233. */
  92234. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92235. /** Get maximum residual partition order setting.
  92236. *
  92237. * \param encoder An encoder instance to query.
  92238. * \assert
  92239. * \code encoder != NULL \endcode
  92240. * \retval unsigned
  92241. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92242. */
  92243. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92244. /** Get the Rice parameter search distance setting.
  92245. *
  92246. * \param encoder An encoder instance to query.
  92247. * \assert
  92248. * \code encoder != NULL \endcode
  92249. * \retval unsigned
  92250. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92251. */
  92252. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92253. /** Get the previously set estimate of the total samples to be encoded.
  92254. * The encoder merely mimics back the value given to
  92255. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92256. * other way of knowing how many samples the client will encode.
  92257. *
  92258. * \param encoder An encoder instance to set.
  92259. * \assert
  92260. * \code encoder != NULL \endcode
  92261. * \retval FLAC__uint64
  92262. * See FLAC__stream_encoder_get_total_samples_estimate().
  92263. */
  92264. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92265. /** Initialize the encoder instance to encode native FLAC streams.
  92266. *
  92267. * This flavor of initialization sets up the encoder to encode to a
  92268. * native FLAC stream. I/O is performed via callbacks to the client.
  92269. * For encoding to a plain file via filename or open \c FILE*,
  92270. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92271. * provide a simpler interface.
  92272. *
  92273. * This function should be called after FLAC__stream_encoder_new() and
  92274. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92275. * or FLAC__stream_encoder_process_interleaved().
  92276. * initialization succeeded.
  92277. *
  92278. * The call to FLAC__stream_encoder_init_stream() currently will also
  92279. * immediately call the write callback several times, once with the \c fLaC
  92280. * signature, and once for each encoded metadata block.
  92281. *
  92282. * \param encoder An uninitialized encoder instance.
  92283. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92284. * pointer must not be \c NULL.
  92285. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92286. * pointer may be \c NULL if seeking is not
  92287. * supported. The encoder uses seeking to go back
  92288. * and write some some stream statistics to the
  92289. * STREAMINFO block; this is recommended but not
  92290. * necessary to create a valid FLAC stream. If
  92291. * \a seek_callback is not \c NULL then a
  92292. * \a tell_callback must also be supplied.
  92293. * Alternatively, a dummy seek callback that just
  92294. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92295. * may also be supplied, all though this is slightly
  92296. * less efficient for the encoder.
  92297. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92298. * pointer may be \c NULL if seeking is not
  92299. * supported. If \a seek_callback is \c NULL then
  92300. * this argument will be ignored. If
  92301. * \a seek_callback is not \c NULL then a
  92302. * \a tell_callback must also be supplied.
  92303. * Alternatively, a dummy tell callback that just
  92304. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92305. * may also be supplied, all though this is slightly
  92306. * less efficient for the encoder.
  92307. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92308. * pointer may be \c NULL if the callback is not
  92309. * desired. If the client provides a seek callback,
  92310. * this function is not necessary as the encoder
  92311. * will automatically seek back and update the
  92312. * STREAMINFO block. It may also be \c NULL if the
  92313. * client does not support seeking, since it will
  92314. * have no way of going back to update the
  92315. * STREAMINFO. However the client can still supply
  92316. * a callback if it would like to know the details
  92317. * from the STREAMINFO.
  92318. * \param client_data This value will be supplied to callbacks in their
  92319. * \a client_data argument.
  92320. * \assert
  92321. * \code encoder != NULL \endcode
  92322. * \retval FLAC__StreamEncoderInitStatus
  92323. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92324. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92325. */
  92326. 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);
  92327. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92328. *
  92329. * This flavor of initialization sets up the encoder to encode to a FLAC
  92330. * stream in an Ogg container. I/O is performed via callbacks to the
  92331. * client. For encoding to a plain file via filename or open \c FILE*,
  92332. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92333. * provide a simpler interface.
  92334. *
  92335. * This function should be called after FLAC__stream_encoder_new() and
  92336. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92337. * or FLAC__stream_encoder_process_interleaved().
  92338. * initialization succeeded.
  92339. *
  92340. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92341. * immediately call the write callback several times to write the metadata
  92342. * packets.
  92343. *
  92344. * \param encoder An uninitialized encoder instance.
  92345. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92346. * pointer must not be \c NULL if \a seek_callback
  92347. * is non-NULL since they are both needed to be
  92348. * able to write data back to the Ogg FLAC stream
  92349. * in the post-encode phase.
  92350. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92351. * pointer must not be \c NULL.
  92352. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92353. * pointer may be \c NULL if seeking is not
  92354. * supported. The encoder uses seeking to go back
  92355. * and write some some stream statistics to the
  92356. * STREAMINFO block; this is recommended but not
  92357. * necessary to create a valid FLAC stream. If
  92358. * \a seek_callback is not \c NULL then a
  92359. * \a tell_callback must also be supplied.
  92360. * Alternatively, a dummy seek callback that just
  92361. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92362. * may also be supplied, all though this is slightly
  92363. * less efficient for the encoder.
  92364. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92365. * pointer may be \c NULL if seeking is not
  92366. * supported. If \a seek_callback is \c NULL then
  92367. * this argument will be ignored. If
  92368. * \a seek_callback is not \c NULL then a
  92369. * \a tell_callback must also be supplied.
  92370. * Alternatively, a dummy tell callback that just
  92371. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92372. * may also be supplied, all though this is slightly
  92373. * less efficient for the encoder.
  92374. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92375. * pointer may be \c NULL if the callback is not
  92376. * desired. If the client provides a seek callback,
  92377. * this function is not necessary as the encoder
  92378. * will automatically seek back and update the
  92379. * STREAMINFO block. It may also be \c NULL if the
  92380. * client does not support seeking, since it will
  92381. * have no way of going back to update the
  92382. * STREAMINFO. However the client can still supply
  92383. * a callback if it would like to know the details
  92384. * from the STREAMINFO.
  92385. * \param client_data This value will be supplied to callbacks in their
  92386. * \a client_data argument.
  92387. * \assert
  92388. * \code encoder != NULL \endcode
  92389. * \retval FLAC__StreamEncoderInitStatus
  92390. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92391. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92392. */
  92393. 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);
  92394. /** Initialize the encoder instance to encode native FLAC files.
  92395. *
  92396. * This flavor of initialization sets up the encoder to encode to a
  92397. * plain native FLAC file. For non-stdio streams, you must use
  92398. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92399. *
  92400. * This function should be called after FLAC__stream_encoder_new() and
  92401. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92402. * or FLAC__stream_encoder_process_interleaved().
  92403. * initialization succeeded.
  92404. *
  92405. * \param encoder An uninitialized encoder instance.
  92406. * \param file An open file. The file should have been opened
  92407. * with mode \c "w+b" and rewound. The file
  92408. * becomes owned by the encoder and should not be
  92409. * manipulated by the client while encoding.
  92410. * Unless \a file is \c stdout, it will be closed
  92411. * when FLAC__stream_encoder_finish() is called.
  92412. * Note however that a proper SEEKTABLE cannot be
  92413. * created when encoding to \c stdout since it is
  92414. * not seekable.
  92415. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92416. * pointer may be \c NULL if the callback is not
  92417. * desired.
  92418. * \param client_data This value will be supplied to callbacks in their
  92419. * \a client_data argument.
  92420. * \assert
  92421. * \code encoder != NULL \endcode
  92422. * \code file != NULL \endcode
  92423. * \retval FLAC__StreamEncoderInitStatus
  92424. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92425. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92426. */
  92427. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92428. /** Initialize the encoder instance to encode Ogg FLAC files.
  92429. *
  92430. * This flavor of initialization sets up the encoder to encode to a
  92431. * plain Ogg FLAC file. For non-stdio streams, you must use
  92432. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92433. *
  92434. * This function should be called after FLAC__stream_encoder_new() and
  92435. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92436. * or FLAC__stream_encoder_process_interleaved().
  92437. * initialization succeeded.
  92438. *
  92439. * \param encoder An uninitialized encoder instance.
  92440. * \param file An open file. The file should have been opened
  92441. * with mode \c "w+b" and rewound. The file
  92442. * becomes owned by the encoder and should not be
  92443. * manipulated by the client while encoding.
  92444. * Unless \a file is \c stdout, it will be closed
  92445. * when FLAC__stream_encoder_finish() is called.
  92446. * Note however that a proper SEEKTABLE cannot be
  92447. * created when encoding to \c stdout since it is
  92448. * not seekable.
  92449. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92450. * pointer may be \c NULL if the callback is not
  92451. * desired.
  92452. * \param client_data This value will be supplied to callbacks in their
  92453. * \a client_data argument.
  92454. * \assert
  92455. * \code encoder != NULL \endcode
  92456. * \code file != NULL \endcode
  92457. * \retval FLAC__StreamEncoderInitStatus
  92458. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92459. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92460. */
  92461. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92462. /** Initialize the encoder instance to encode native FLAC files.
  92463. *
  92464. * This flavor of initialization sets up the encoder to encode to a plain
  92465. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92466. * with Unicode filenames on Windows), you must use
  92467. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92468. * and provide callbacks for the I/O.
  92469. *
  92470. * This function should be called after FLAC__stream_encoder_new() and
  92471. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92472. * or FLAC__stream_encoder_process_interleaved().
  92473. * initialization succeeded.
  92474. *
  92475. * \param encoder An uninitialized encoder instance.
  92476. * \param filename The name of the file to encode to. The file will
  92477. * be opened with fopen(). Use \c NULL to encode to
  92478. * \c stdout. Note however that a proper SEEKTABLE
  92479. * cannot be created when encoding to \c stdout since
  92480. * it is not seekable.
  92481. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92482. * pointer may be \c NULL if the callback is not
  92483. * desired.
  92484. * \param client_data This value will be supplied to callbacks in their
  92485. * \a client_data argument.
  92486. * \assert
  92487. * \code encoder != NULL \endcode
  92488. * \retval FLAC__StreamEncoderInitStatus
  92489. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92490. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92491. */
  92492. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92493. /** Initialize the encoder instance to encode Ogg FLAC files.
  92494. *
  92495. * This flavor of initialization sets up the encoder to encode to a plain
  92496. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92497. * with Unicode filenames on Windows), you must use
  92498. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92499. * and provide callbacks for the I/O.
  92500. *
  92501. * This function should be called after FLAC__stream_encoder_new() and
  92502. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92503. * or FLAC__stream_encoder_process_interleaved().
  92504. * initialization succeeded.
  92505. *
  92506. * \param encoder An uninitialized encoder instance.
  92507. * \param filename The name of the file to encode to. The file will
  92508. * be opened with fopen(). Use \c NULL to encode to
  92509. * \c stdout. Note however that a proper SEEKTABLE
  92510. * cannot be created when encoding to \c stdout since
  92511. * it is not seekable.
  92512. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92513. * pointer may be \c NULL if the callback is not
  92514. * desired.
  92515. * \param client_data This value will be supplied to callbacks in their
  92516. * \a client_data argument.
  92517. * \assert
  92518. * \code encoder != NULL \endcode
  92519. * \retval FLAC__StreamEncoderInitStatus
  92520. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92521. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92522. */
  92523. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92524. /** Finish the encoding process.
  92525. * Flushes the encoding buffer, releases resources, resets the encoder
  92526. * settings to their defaults, and returns the encoder state to
  92527. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92528. * one or more write callbacks before returning, and will generate
  92529. * a metadata callback.
  92530. *
  92531. * Note that in the course of processing the last frame, errors can
  92532. * occur, so the caller should be sure to check the return value to
  92533. * ensure the file was encoded properly.
  92534. *
  92535. * In the event of a prematurely-terminated encode, it is not strictly
  92536. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92537. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92538. * with a FLAC__stream_encoder_finish().
  92539. *
  92540. * \param encoder An uninitialized encoder instance.
  92541. * \assert
  92542. * \code encoder != NULL \endcode
  92543. * \retval FLAC__bool
  92544. * \c false if an error occurred processing the last frame; or if verify
  92545. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92546. * verify mismatch; else \c true. If \c false, caller should check the
  92547. * state with FLAC__stream_encoder_get_state() for more information
  92548. * about the error.
  92549. */
  92550. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92551. /** Submit data for encoding.
  92552. * This version allows you to supply the input data via an array of
  92553. * pointers, each pointer pointing to an array of \a samples samples
  92554. * representing one channel. The samples need not be block-aligned,
  92555. * but each channel should have the same number of samples. Each sample
  92556. * should be a signed integer, right-justified to the resolution set by
  92557. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92558. * resolution is 16 bits per sample, the samples should all be in the
  92559. * range [-32768,32767].
  92560. *
  92561. * For applications where channel order is important, channels must
  92562. * follow the order as described in the
  92563. * <A HREF="../format.html#frame_header">frame header</A>.
  92564. *
  92565. * \param encoder An initialized encoder instance in the OK state.
  92566. * \param buffer An array of pointers to each channel's signal.
  92567. * \param samples The number of samples in one channel.
  92568. * \assert
  92569. * \code encoder != NULL \endcode
  92570. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92571. * \retval FLAC__bool
  92572. * \c true if successful, else \c false; in this case, check the
  92573. * encoder state with FLAC__stream_encoder_get_state() to see what
  92574. * went wrong.
  92575. */
  92576. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92577. /** Submit data for encoding.
  92578. * This version allows you to supply the input data where the channels
  92579. * are interleaved into a single array (i.e. channel0_sample0,
  92580. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92581. * The samples need not be block-aligned but they must be
  92582. * sample-aligned, i.e. the first value should be channel0_sample0
  92583. * and the last value channelN_sampleM. Each sample should be a signed
  92584. * integer, right-justified to the resolution set by
  92585. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92586. * resolution is 16 bits per sample, the samples should all be in the
  92587. * range [-32768,32767].
  92588. *
  92589. * For applications where channel order is important, channels must
  92590. * follow the order as described in the
  92591. * <A HREF="../format.html#frame_header">frame header</A>.
  92592. *
  92593. * \param encoder An initialized encoder instance in the OK state.
  92594. * \param buffer An array of channel-interleaved data (see above).
  92595. * \param samples The number of samples in one channel, the same as for
  92596. * FLAC__stream_encoder_process(). For example, if
  92597. * encoding two channels, \c 1000 \a samples corresponds
  92598. * to a \a buffer of 2000 values.
  92599. * \assert
  92600. * \code encoder != NULL \endcode
  92601. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92602. * \retval FLAC__bool
  92603. * \c true if successful, else \c false; in this case, check the
  92604. * encoder state with FLAC__stream_encoder_get_state() to see what
  92605. * went wrong.
  92606. */
  92607. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92608. /* \} */
  92609. #ifdef __cplusplus
  92610. }
  92611. #endif
  92612. #endif
  92613. /*** End of inlined file: stream_encoder.h ***/
  92614. #ifdef _MSC_VER
  92615. /* OPT: an MSVC built-in would be better */
  92616. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92617. {
  92618. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92619. return (x>>16) | (x<<16);
  92620. }
  92621. #endif
  92622. #if defined(_MSC_VER) && defined(_X86_)
  92623. /* OPT: an MSVC built-in would be better */
  92624. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92625. {
  92626. __asm {
  92627. mov edx, start
  92628. mov ecx, len
  92629. test ecx, ecx
  92630. loop1:
  92631. jz done1
  92632. mov eax, [edx]
  92633. bswap eax
  92634. mov [edx], eax
  92635. add edx, 4
  92636. dec ecx
  92637. jmp short loop1
  92638. done1:
  92639. }
  92640. }
  92641. #endif
  92642. /** \mainpage
  92643. *
  92644. * \section intro Introduction
  92645. *
  92646. * This is the documentation for the FLAC C and C++ APIs. It is
  92647. * highly interconnected; this introduction should give you a top
  92648. * level idea of the structure and how to find the information you
  92649. * need. As a prerequisite you should have at least a basic
  92650. * knowledge of the FLAC format, documented
  92651. * <A HREF="../format.html">here</A>.
  92652. *
  92653. * \section c_api FLAC C API
  92654. *
  92655. * The FLAC C API is the interface to libFLAC, a set of structures
  92656. * describing the components of FLAC streams, and functions for
  92657. * encoding and decoding streams, as well as manipulating FLAC
  92658. * metadata in files. The public include files will be installed
  92659. * in your include area (for example /usr/include/FLAC/...).
  92660. *
  92661. * By writing a little code and linking against libFLAC, it is
  92662. * relatively easy to add FLAC support to another program. The
  92663. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92664. * Complete source code of libFLAC as well as the command-line
  92665. * encoder and plugins is available and is a useful source of
  92666. * examples.
  92667. *
  92668. * Aside from encoders and decoders, libFLAC provides a powerful
  92669. * metadata interface for manipulating metadata in FLAC files. It
  92670. * allows the user to add, delete, and modify FLAC metadata blocks
  92671. * and it can automatically take advantage of PADDING blocks to avoid
  92672. * rewriting the entire FLAC file when changing the size of the
  92673. * metadata.
  92674. *
  92675. * libFLAC usually only requires the standard C library and C math
  92676. * library. In particular, threading is not used so there is no
  92677. * dependency on a thread library. However, libFLAC does not use
  92678. * global variables and should be thread-safe.
  92679. *
  92680. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92681. * However the metadata editing interfaces currently have limited
  92682. * read-only support for Ogg FLAC files.
  92683. *
  92684. * \section cpp_api FLAC C++ API
  92685. *
  92686. * The FLAC C++ API is a set of classes that encapsulate the
  92687. * structures and functions in libFLAC. They provide slightly more
  92688. * functionality with respect to metadata but are otherwise
  92689. * equivalent. For the most part, they share the same usage as
  92690. * their counterparts in libFLAC, and the FLAC C API documentation
  92691. * can be used as a supplement. The public include files
  92692. * for the C++ API will be installed in your include area (for
  92693. * example /usr/include/FLAC++/...).
  92694. *
  92695. * libFLAC++ is also licensed under
  92696. * <A HREF="../license.html">Xiph's BSD license</A>.
  92697. *
  92698. * \section getting_started Getting Started
  92699. *
  92700. * A good starting point for learning the API is to browse through
  92701. * the <A HREF="modules.html">modules</A>. Modules are logical
  92702. * groupings of related functions or classes, which correspond roughly
  92703. * to header files or sections of header files. Each module includes a
  92704. * detailed description of the general usage of its functions or
  92705. * classes.
  92706. *
  92707. * From there you can go on to look at the documentation of
  92708. * individual functions. You can see different views of the individual
  92709. * functions through the links in top bar across this page.
  92710. *
  92711. * If you prefer a more hands-on approach, you can jump right to some
  92712. * <A HREF="../documentation_example_code.html">example code</A>.
  92713. *
  92714. * \section porting_guide Porting Guide
  92715. *
  92716. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92717. * has been introduced which gives detailed instructions on how to
  92718. * port your code to newer versions of FLAC.
  92719. *
  92720. * \section embedded_developers Embedded Developers
  92721. *
  92722. * libFLAC has grown larger over time as more functionality has been
  92723. * included, but much of it may be unnecessary for a particular embedded
  92724. * implementation. Unused parts may be pruned by some simple editing of
  92725. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92726. * metadata interface are all independent from each other.
  92727. *
  92728. * It is easiest to just describe the dependencies:
  92729. *
  92730. * - All modules depend on the \link flac_format Format \endlink module.
  92731. * - The decoders and encoders depend on the bitbuffer.
  92732. * - The decoder is independent of the encoder. The encoder uses the
  92733. * decoder because of the verify feature, but this can be removed if
  92734. * not needed.
  92735. * - Parts of the metadata interface require the stream decoder (but not
  92736. * the encoder).
  92737. * - Ogg support is selectable through the compile time macro
  92738. * \c FLAC__HAS_OGG.
  92739. *
  92740. * For example, if your application only requires the stream decoder, no
  92741. * encoder, and no metadata interface, you can remove the stream encoder
  92742. * and the metadata interface, which will greatly reduce the size of the
  92743. * library.
  92744. *
  92745. * Also, there are several places in the libFLAC code with comments marked
  92746. * with "OPT:" where a #define can be changed to enable code that might be
  92747. * faster on a specific platform. Experimenting with these can yield faster
  92748. * binaries.
  92749. */
  92750. /** \defgroup porting Porting Guide for New Versions
  92751. *
  92752. * This module describes differences in the library interfaces from
  92753. * version to version. It assists in the porting of code that uses
  92754. * the libraries to newer versions of FLAC.
  92755. *
  92756. * One simple facility for making porting easier that has been added
  92757. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92758. * library's includes (e.g. \c include/FLAC/export.h). The
  92759. * \c #defines mirror the libraries'
  92760. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92761. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92762. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92763. * These can be used to support multiple versions of an API during the
  92764. * transition phase, e.g.
  92765. *
  92766. * \code
  92767. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92768. * legacy code
  92769. * #else
  92770. * new code
  92771. * #endif
  92772. * \endcode
  92773. *
  92774. * The the source will work for multiple versions and the legacy code can
  92775. * easily be removed when the transition is complete.
  92776. *
  92777. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92778. * include/FLAC/export.h), which can be used to determine whether or not
  92779. * the library has been compiled with support for Ogg FLAC. This is
  92780. * simpler than trying to call an Ogg init function and catching the
  92781. * error.
  92782. */
  92783. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92784. * \ingroup porting
  92785. *
  92786. * \brief
  92787. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92788. *
  92789. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92790. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92791. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92792. * decoding layers and three encoding layers have been merged into a
  92793. * single stream decoder and stream encoder. That is, the functionality
  92794. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92795. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92796. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92797. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92798. * is there is now a single API that can be used to encode or decode
  92799. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92800. * on both seekable and non-seekable streams.
  92801. *
  92802. * Instead of creating an encoder or decoder of a certain layer, now the
  92803. * client will always create a FLAC__StreamEncoder or
  92804. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92805. * initialization function. For example, for the decoder,
  92806. * FLAC__stream_decoder_init() has been replaced by
  92807. * FLAC__stream_decoder_init_stream(). This init function takes
  92808. * callbacks for the I/O, and the seeking callbacks are optional. This
  92809. * allows the client to use the same object for seekable and
  92810. * non-seekable streams. For decoding a FLAC file directly, the client
  92811. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92812. * and fewer callbacks; most of the other callbacks are supplied
  92813. * internally. For situations where fopen()ing by filename is not
  92814. * possible (e.g. Unicode filenames on Windows) the client can instead
  92815. * open the file itself and supply the FILE* to
  92816. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92817. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92818. * Since the callbacks and client data are now passed to the init
  92819. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92820. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92821. * rest of the calls to the decoder are the same as before.
  92822. *
  92823. * There are counterpart init functions for Ogg FLAC, e.g.
  92824. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92825. * and callbacks are the same as for native FLAC.
  92826. *
  92827. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92828. * been set up like so:
  92829. *
  92830. * \code
  92831. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92832. * if(decoder == NULL) do_something;
  92833. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92834. * [... other settings ...]
  92835. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92836. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92837. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92838. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92839. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92840. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92841. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92842. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92843. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92844. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92845. * \endcode
  92846. *
  92847. * In FLAC 1.1.3 it is like this:
  92848. *
  92849. * \code
  92850. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92851. * if(decoder == NULL) do_something;
  92852. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92853. * [... other settings ...]
  92854. * if(FLAC__stream_decoder_init_stream(
  92855. * decoder,
  92856. * my_read_callback,
  92857. * my_seek_callback, // or NULL
  92858. * my_tell_callback, // or NULL
  92859. * my_length_callback, // or NULL
  92860. * my_eof_callback, // or NULL
  92861. * my_write_callback,
  92862. * my_metadata_callback, // or NULL
  92863. * my_error_callback,
  92864. * my_client_data
  92865. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92866. * \endcode
  92867. *
  92868. * or you could do;
  92869. *
  92870. * \code
  92871. * [...]
  92872. * FILE *file = fopen("somefile.flac","rb");
  92873. * if(file == NULL) do_somthing;
  92874. * if(FLAC__stream_decoder_init_FILE(
  92875. * decoder,
  92876. * file,
  92877. * my_write_callback,
  92878. * my_metadata_callback, // or NULL
  92879. * my_error_callback,
  92880. * my_client_data
  92881. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92882. * \endcode
  92883. *
  92884. * or just:
  92885. *
  92886. * \code
  92887. * [...]
  92888. * if(FLAC__stream_decoder_init_file(
  92889. * decoder,
  92890. * "somefile.flac",
  92891. * my_write_callback,
  92892. * my_metadata_callback, // or NULL
  92893. * my_error_callback,
  92894. * my_client_data
  92895. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92896. * \endcode
  92897. *
  92898. * Another small change to the decoder is in how it handles unparseable
  92899. * streams. Before, when the decoder found an unparseable stream
  92900. * (reserved for when the decoder encounters a stream from a future
  92901. * encoder that it can't parse), it changed the state to
  92902. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92903. * drops sync and calls the error callback with a new error code
  92904. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92905. * more robust. If your error callback does not discriminate on the the
  92906. * error state, your code does not need to be changed.
  92907. *
  92908. * The encoder now has a new setting:
  92909. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92910. * method used to window the data before LPC analysis. You only need to
  92911. * add a call to this function if the default is not suitable. There
  92912. * are also two new convenience functions that may be useful:
  92913. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92914. * FLAC__metadata_get_cuesheet().
  92915. *
  92916. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92917. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92918. * is now \c size_t instead of \c unsigned.
  92919. */
  92920. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92921. * \ingroup porting
  92922. *
  92923. * \brief
  92924. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92925. *
  92926. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92927. * There was a slight change in the implementation of
  92928. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92929. * of the \a metadata array of pointers so the client no longer needs
  92930. * to maintain it after the call. The objects themselves that are
  92931. * pointed to by the array are still not copied though and must be
  92932. * maintained until the call to FLAC__stream_encoder_finish().
  92933. */
  92934. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92935. * \ingroup porting
  92936. *
  92937. * \brief
  92938. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92939. *
  92940. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92941. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92942. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92943. *
  92944. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92945. * has changed to reflect the conversion of one of the reserved bits
  92946. * into active use. It used to be \c 2 and now is \c 1. However the
  92947. * FLAC frame header length has not changed, so to skip the proper
  92948. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92949. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92950. */
  92951. /** \defgroup flac FLAC C API
  92952. *
  92953. * The FLAC C API is the interface to libFLAC, a set of structures
  92954. * describing the components of FLAC streams, and functions for
  92955. * encoding and decoding streams, as well as manipulating FLAC
  92956. * metadata in files.
  92957. *
  92958. * You should start with the format components as all other modules
  92959. * are dependent on it.
  92960. */
  92961. #endif
  92962. /*** End of inlined file: all.h ***/
  92963. /*** Start of inlined file: bitmath.c ***/
  92964. /*** Start of inlined file: juce_FlacHeader.h ***/
  92965. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92966. // tasks..
  92967. #define VERSION "1.2.1"
  92968. #define FLAC__NO_DLL 1
  92969. #if JUCE_MSVC
  92970. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92971. #endif
  92972. #if JUCE_MAC
  92973. #define FLAC__SYS_DARWIN 1
  92974. #endif
  92975. /*** End of inlined file: juce_FlacHeader.h ***/
  92976. #if JUCE_USE_FLAC
  92977. #if HAVE_CONFIG_H
  92978. # include <config.h>
  92979. #endif
  92980. /*** Start of inlined file: bitmath.h ***/
  92981. #ifndef FLAC__PRIVATE__BITMATH_H
  92982. #define FLAC__PRIVATE__BITMATH_H
  92983. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92984. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92985. unsigned FLAC__bitmath_silog2(int v);
  92986. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92987. #endif
  92988. /*** End of inlined file: bitmath.h ***/
  92989. /* An example of what FLAC__bitmath_ilog2() computes:
  92990. *
  92991. * ilog2( 0) = assertion failure
  92992. * ilog2( 1) = 0
  92993. * ilog2( 2) = 1
  92994. * ilog2( 3) = 1
  92995. * ilog2( 4) = 2
  92996. * ilog2( 5) = 2
  92997. * ilog2( 6) = 2
  92998. * ilog2( 7) = 2
  92999. * ilog2( 8) = 3
  93000. * ilog2( 9) = 3
  93001. * ilog2(10) = 3
  93002. * ilog2(11) = 3
  93003. * ilog2(12) = 3
  93004. * ilog2(13) = 3
  93005. * ilog2(14) = 3
  93006. * ilog2(15) = 3
  93007. * ilog2(16) = 4
  93008. * ilog2(17) = 4
  93009. * ilog2(18) = 4
  93010. */
  93011. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  93012. {
  93013. unsigned l = 0;
  93014. FLAC__ASSERT(v > 0);
  93015. while(v >>= 1)
  93016. l++;
  93017. return l;
  93018. }
  93019. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  93020. {
  93021. unsigned l = 0;
  93022. FLAC__ASSERT(v > 0);
  93023. while(v >>= 1)
  93024. l++;
  93025. return l;
  93026. }
  93027. /* An example of what FLAC__bitmath_silog2() computes:
  93028. *
  93029. * silog2(-10) = 5
  93030. * silog2(- 9) = 5
  93031. * silog2(- 8) = 4
  93032. * silog2(- 7) = 4
  93033. * silog2(- 6) = 4
  93034. * silog2(- 5) = 4
  93035. * silog2(- 4) = 3
  93036. * silog2(- 3) = 3
  93037. * silog2(- 2) = 2
  93038. * silog2(- 1) = 2
  93039. * silog2( 0) = 0
  93040. * silog2( 1) = 2
  93041. * silog2( 2) = 3
  93042. * silog2( 3) = 3
  93043. * silog2( 4) = 4
  93044. * silog2( 5) = 4
  93045. * silog2( 6) = 4
  93046. * silog2( 7) = 4
  93047. * silog2( 8) = 5
  93048. * silog2( 9) = 5
  93049. * silog2( 10) = 5
  93050. */
  93051. unsigned FLAC__bitmath_silog2(int v)
  93052. {
  93053. while(1) {
  93054. if(v == 0) {
  93055. return 0;
  93056. }
  93057. else if(v > 0) {
  93058. unsigned l = 0;
  93059. while(v) {
  93060. l++;
  93061. v >>= 1;
  93062. }
  93063. return l+1;
  93064. }
  93065. else if(v == -1) {
  93066. return 2;
  93067. }
  93068. else {
  93069. v++;
  93070. v = -v;
  93071. }
  93072. }
  93073. }
  93074. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93075. {
  93076. while(1) {
  93077. if(v == 0) {
  93078. return 0;
  93079. }
  93080. else if(v > 0) {
  93081. unsigned l = 0;
  93082. while(v) {
  93083. l++;
  93084. v >>= 1;
  93085. }
  93086. return l+1;
  93087. }
  93088. else if(v == -1) {
  93089. return 2;
  93090. }
  93091. else {
  93092. v++;
  93093. v = -v;
  93094. }
  93095. }
  93096. }
  93097. #endif
  93098. /*** End of inlined file: bitmath.c ***/
  93099. /*** Start of inlined file: bitreader.c ***/
  93100. /*** Start of inlined file: juce_FlacHeader.h ***/
  93101. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93102. // tasks..
  93103. #define VERSION "1.2.1"
  93104. #define FLAC__NO_DLL 1
  93105. #if JUCE_MSVC
  93106. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93107. #endif
  93108. #if JUCE_MAC
  93109. #define FLAC__SYS_DARWIN 1
  93110. #endif
  93111. /*** End of inlined file: juce_FlacHeader.h ***/
  93112. #if JUCE_USE_FLAC
  93113. #if HAVE_CONFIG_H
  93114. # include <config.h>
  93115. #endif
  93116. #include <stdlib.h> /* for malloc() */
  93117. #include <string.h> /* for memcpy(), memset() */
  93118. #ifdef _MSC_VER
  93119. #include <winsock.h> /* for ntohl() */
  93120. #elif defined FLAC__SYS_DARWIN
  93121. #include <machine/endian.h> /* for ntohl() */
  93122. #elif defined __MINGW32__
  93123. #include <winsock.h> /* for ntohl() */
  93124. #else
  93125. #include <netinet/in.h> /* for ntohl() */
  93126. #endif
  93127. /*** Start of inlined file: bitreader.h ***/
  93128. #ifndef FLAC__PRIVATE__BITREADER_H
  93129. #define FLAC__PRIVATE__BITREADER_H
  93130. #include <stdio.h> /* for FILE */
  93131. /*** Start of inlined file: cpu.h ***/
  93132. #ifndef FLAC__PRIVATE__CPU_H
  93133. #define FLAC__PRIVATE__CPU_H
  93134. #ifdef HAVE_CONFIG_H
  93135. #include <config.h>
  93136. #endif
  93137. typedef enum {
  93138. FLAC__CPUINFO_TYPE_IA32,
  93139. FLAC__CPUINFO_TYPE_PPC,
  93140. FLAC__CPUINFO_TYPE_UNKNOWN
  93141. } FLAC__CPUInfo_Type;
  93142. typedef struct {
  93143. FLAC__bool cpuid;
  93144. FLAC__bool bswap;
  93145. FLAC__bool cmov;
  93146. FLAC__bool mmx;
  93147. FLAC__bool fxsr;
  93148. FLAC__bool sse;
  93149. FLAC__bool sse2;
  93150. FLAC__bool sse3;
  93151. FLAC__bool ssse3;
  93152. FLAC__bool _3dnow;
  93153. FLAC__bool ext3dnow;
  93154. FLAC__bool extmmx;
  93155. } FLAC__CPUInfo_IA32;
  93156. typedef struct {
  93157. FLAC__bool altivec;
  93158. FLAC__bool ppc64;
  93159. } FLAC__CPUInfo_PPC;
  93160. typedef struct {
  93161. FLAC__bool use_asm;
  93162. FLAC__CPUInfo_Type type;
  93163. union {
  93164. FLAC__CPUInfo_IA32 ia32;
  93165. FLAC__CPUInfo_PPC ppc;
  93166. } data;
  93167. } FLAC__CPUInfo;
  93168. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93169. #ifndef FLAC__NO_ASM
  93170. #ifdef FLAC__CPU_IA32
  93171. #ifdef FLAC__HAS_NASM
  93172. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93173. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93174. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93175. #endif
  93176. #endif
  93177. #endif
  93178. #endif
  93179. /*** End of inlined file: cpu.h ***/
  93180. /*
  93181. * opaque structure definition
  93182. */
  93183. struct FLAC__BitReader;
  93184. typedef struct FLAC__BitReader FLAC__BitReader;
  93185. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93186. /*
  93187. * construction, deletion, initialization, etc functions
  93188. */
  93189. FLAC__BitReader *FLAC__bitreader_new(void);
  93190. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93191. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93192. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93193. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93194. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93195. /*
  93196. * CRC functions
  93197. */
  93198. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93199. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93200. /*
  93201. * info functions
  93202. */
  93203. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93204. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93205. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93206. /*
  93207. * read functions
  93208. */
  93209. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93210. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93211. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93212. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93213. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93214. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93215. 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! */
  93216. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93217. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93218. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93219. #ifndef FLAC__NO_ASM
  93220. # ifdef FLAC__CPU_IA32
  93221. # ifdef FLAC__HAS_NASM
  93222. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93223. # endif
  93224. # endif
  93225. #endif
  93226. #if 0 /* UNUSED */
  93227. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93228. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93229. #endif
  93230. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93231. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93232. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93233. #endif
  93234. /*** End of inlined file: bitreader.h ***/
  93235. /*** Start of inlined file: crc.h ***/
  93236. #ifndef FLAC__PRIVATE__CRC_H
  93237. #define FLAC__PRIVATE__CRC_H
  93238. /* 8 bit CRC generator, MSB shifted first
  93239. ** polynomial = x^8 + x^2 + x^1 + x^0
  93240. ** init = 0
  93241. */
  93242. extern FLAC__byte const FLAC__crc8_table[256];
  93243. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93244. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93245. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93246. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93247. /* 16 bit CRC generator, MSB shifted first
  93248. ** polynomial = x^16 + x^15 + x^2 + x^0
  93249. ** init = 0
  93250. */
  93251. extern unsigned FLAC__crc16_table[256];
  93252. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93253. /* this alternate may be faster on some systems/compilers */
  93254. #if 0
  93255. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93256. #endif
  93257. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93258. #endif
  93259. /*** End of inlined file: crc.h ***/
  93260. /* Things should be fastest when this matches the machine word size */
  93261. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93262. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93263. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93264. typedef FLAC__uint32 brword;
  93265. #define FLAC__BYTES_PER_WORD 4
  93266. #define FLAC__BITS_PER_WORD 32
  93267. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93268. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93269. #if WORDS_BIGENDIAN
  93270. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93271. #else
  93272. #if defined (_MSC_VER) && defined (_X86_)
  93273. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93274. #else
  93275. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93276. #endif
  93277. #endif
  93278. /* counts the # of zero MSBs in a word */
  93279. #define COUNT_ZERO_MSBS(word) ( \
  93280. (word) <= 0xffff ? \
  93281. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93282. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93283. )
  93284. /* this alternate might be slightly faster on some systems/compilers: */
  93285. #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])) )
  93286. /*
  93287. * This should be at least twice as large as the largest number of words
  93288. * required to represent any 'number' (in any encoding) you are going to
  93289. * read. With FLAC this is on the order of maybe a few hundred bits.
  93290. * If the buffer is smaller than that, the decoder won't be able to read
  93291. * in a whole number that is in a variable length encoding (e.g. Rice).
  93292. * But to be practical it should be at least 1K bytes.
  93293. *
  93294. * Increase this number to decrease the number of read callbacks, at the
  93295. * expense of using more memory. Or decrease for the reverse effect,
  93296. * keeping in mind the limit from the first paragraph. The optimal size
  93297. * also depends on the CPU cache size and other factors; some twiddling
  93298. * may be necessary to squeeze out the best performance.
  93299. */
  93300. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93301. static const unsigned char byte_to_unary_table[] = {
  93302. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93303. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93304. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93305. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93306. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93307. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93308. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93309. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93318. };
  93319. #ifdef min
  93320. #undef min
  93321. #endif
  93322. #define min(x,y) ((x)<(y)?(x):(y))
  93323. #ifdef max
  93324. #undef max
  93325. #endif
  93326. #define max(x,y) ((x)>(y)?(x):(y))
  93327. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93328. #ifdef _MSC_VER
  93329. #define FLAC__U64L(x) x
  93330. #else
  93331. #define FLAC__U64L(x) x##LLU
  93332. #endif
  93333. #ifndef FLaC__INLINE
  93334. #define FLaC__INLINE
  93335. #endif
  93336. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93337. struct FLAC__BitReader {
  93338. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93339. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93340. brword *buffer;
  93341. unsigned capacity; /* in words */
  93342. unsigned words; /* # of completed words in buffer */
  93343. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93344. unsigned consumed_words; /* #words ... */
  93345. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93346. unsigned read_crc16; /* the running frame CRC */
  93347. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93348. FLAC__BitReaderReadCallback read_callback;
  93349. void *client_data;
  93350. FLAC__CPUInfo cpu_info;
  93351. };
  93352. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93353. {
  93354. register unsigned crc = br->read_crc16;
  93355. #if FLAC__BYTES_PER_WORD == 4
  93356. switch(br->crc16_align) {
  93357. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93358. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93359. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93360. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93361. }
  93362. #elif FLAC__BYTES_PER_WORD == 8
  93363. switch(br->crc16_align) {
  93364. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93365. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93366. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93367. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93368. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93369. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93370. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93371. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93372. }
  93373. #else
  93374. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93375. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93376. br->read_crc16 = crc;
  93377. #endif
  93378. br->crc16_align = 0;
  93379. }
  93380. /* would be static except it needs to be called by asm routines */
  93381. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93382. {
  93383. unsigned start, end;
  93384. size_t bytes;
  93385. FLAC__byte *target;
  93386. /* first shift the unconsumed buffer data toward the front as much as possible */
  93387. if(br->consumed_words > 0) {
  93388. start = br->consumed_words;
  93389. end = br->words + (br->bytes? 1:0);
  93390. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93391. br->words -= start;
  93392. br->consumed_words = 0;
  93393. }
  93394. /*
  93395. * set the target for reading, taking into account word alignment and endianness
  93396. */
  93397. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93398. if(bytes == 0)
  93399. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93400. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93401. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93402. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93403. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93404. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93405. * ^^-------target, bytes=3
  93406. * on LE machines, have to byteswap the odd tail word so nothing is
  93407. * overwritten:
  93408. */
  93409. #if WORDS_BIGENDIAN
  93410. #else
  93411. if(br->bytes)
  93412. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93413. #endif
  93414. /* now it looks like:
  93415. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93416. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93417. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93418. * ^^-------target, bytes=3
  93419. */
  93420. /* read in the data; note that the callback may return a smaller number of bytes */
  93421. if(!br->read_callback(target, &bytes, br->client_data))
  93422. return false;
  93423. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93424. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93425. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93426. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93427. * now have to byteswap on LE machines:
  93428. */
  93429. #if WORDS_BIGENDIAN
  93430. #else
  93431. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93432. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93433. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93434. start = br->words;
  93435. local_swap32_block_(br->buffer + start, end - start);
  93436. }
  93437. else
  93438. # endif
  93439. for(start = br->words; start < end; start++)
  93440. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93441. #endif
  93442. /* now it looks like:
  93443. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93444. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93445. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93446. * finally we'll update the reader values:
  93447. */
  93448. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93449. br->words = end / FLAC__BYTES_PER_WORD;
  93450. br->bytes = end % FLAC__BYTES_PER_WORD;
  93451. return true;
  93452. }
  93453. /***********************************************************************
  93454. *
  93455. * Class constructor/destructor
  93456. *
  93457. ***********************************************************************/
  93458. FLAC__BitReader *FLAC__bitreader_new(void)
  93459. {
  93460. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93461. /* calloc() implies:
  93462. memset(br, 0, sizeof(FLAC__BitReader));
  93463. br->buffer = 0;
  93464. br->capacity = 0;
  93465. br->words = br->bytes = 0;
  93466. br->consumed_words = br->consumed_bits = 0;
  93467. br->read_callback = 0;
  93468. br->client_data = 0;
  93469. */
  93470. return br;
  93471. }
  93472. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93473. {
  93474. FLAC__ASSERT(0 != br);
  93475. FLAC__bitreader_free(br);
  93476. free(br);
  93477. }
  93478. /***********************************************************************
  93479. *
  93480. * Public class methods
  93481. *
  93482. ***********************************************************************/
  93483. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93484. {
  93485. FLAC__ASSERT(0 != br);
  93486. br->words = br->bytes = 0;
  93487. br->consumed_words = br->consumed_bits = 0;
  93488. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93489. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93490. if(br->buffer == 0)
  93491. return false;
  93492. br->read_callback = rcb;
  93493. br->client_data = cd;
  93494. br->cpu_info = cpu;
  93495. return true;
  93496. }
  93497. void FLAC__bitreader_free(FLAC__BitReader *br)
  93498. {
  93499. FLAC__ASSERT(0 != br);
  93500. if(0 != br->buffer)
  93501. free(br->buffer);
  93502. br->buffer = 0;
  93503. br->capacity = 0;
  93504. br->words = br->bytes = 0;
  93505. br->consumed_words = br->consumed_bits = 0;
  93506. br->read_callback = 0;
  93507. br->client_data = 0;
  93508. }
  93509. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93510. {
  93511. br->words = br->bytes = 0;
  93512. br->consumed_words = br->consumed_bits = 0;
  93513. return true;
  93514. }
  93515. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93516. {
  93517. unsigned i, j;
  93518. if(br == 0) {
  93519. fprintf(out, "bitreader is NULL\n");
  93520. }
  93521. else {
  93522. 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);
  93523. for(i = 0; i < br->words; i++) {
  93524. fprintf(out, "%08X: ", i);
  93525. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93526. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93527. fprintf(out, ".");
  93528. else
  93529. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93530. fprintf(out, "\n");
  93531. }
  93532. if(br->bytes > 0) {
  93533. fprintf(out, "%08X: ", i);
  93534. for(j = 0; j < br->bytes*8; j++)
  93535. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93536. fprintf(out, ".");
  93537. else
  93538. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93539. fprintf(out, "\n");
  93540. }
  93541. }
  93542. }
  93543. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93544. {
  93545. FLAC__ASSERT(0 != br);
  93546. FLAC__ASSERT(0 != br->buffer);
  93547. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93548. br->read_crc16 = (unsigned)seed;
  93549. br->crc16_align = br->consumed_bits;
  93550. }
  93551. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93552. {
  93553. FLAC__ASSERT(0 != br);
  93554. FLAC__ASSERT(0 != br->buffer);
  93555. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93556. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93557. /* CRC any tail bytes in a partially-consumed word */
  93558. if(br->consumed_bits) {
  93559. const brword tail = br->buffer[br->consumed_words];
  93560. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93561. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93562. }
  93563. return br->read_crc16;
  93564. }
  93565. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93566. {
  93567. return ((br->consumed_bits & 7) == 0);
  93568. }
  93569. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93570. {
  93571. return 8 - (br->consumed_bits & 7);
  93572. }
  93573. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93574. {
  93575. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93576. }
  93577. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93578. {
  93579. FLAC__ASSERT(0 != br);
  93580. FLAC__ASSERT(0 != br->buffer);
  93581. FLAC__ASSERT(bits <= 32);
  93582. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93583. FLAC__ASSERT(br->consumed_words <= br->words);
  93584. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93585. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93586. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93587. *val = 0;
  93588. return true;
  93589. }
  93590. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93591. if(!bitreader_read_from_client_(br))
  93592. return false;
  93593. }
  93594. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93595. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93596. if(br->consumed_bits) {
  93597. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93598. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93599. const brword word = br->buffer[br->consumed_words];
  93600. if(bits < n) {
  93601. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93602. br->consumed_bits += bits;
  93603. return true;
  93604. }
  93605. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93606. bits -= n;
  93607. crc16_update_word_(br, word);
  93608. br->consumed_words++;
  93609. br->consumed_bits = 0;
  93610. 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 */
  93611. *val <<= bits;
  93612. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93613. br->consumed_bits = bits;
  93614. }
  93615. return true;
  93616. }
  93617. else {
  93618. const brword word = br->buffer[br->consumed_words];
  93619. if(bits < FLAC__BITS_PER_WORD) {
  93620. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93621. br->consumed_bits = bits;
  93622. return true;
  93623. }
  93624. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93625. *val = word;
  93626. crc16_update_word_(br, word);
  93627. br->consumed_words++;
  93628. return true;
  93629. }
  93630. }
  93631. else {
  93632. /* in this case we're starting our read at a partial tail word;
  93633. * the reader has guaranteed that we have at least 'bits' bits
  93634. * available to read, which makes this case simpler.
  93635. */
  93636. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93637. if(br->consumed_bits) {
  93638. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93639. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93640. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93641. br->consumed_bits += bits;
  93642. return true;
  93643. }
  93644. else {
  93645. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93646. br->consumed_bits += bits;
  93647. return true;
  93648. }
  93649. }
  93650. }
  93651. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93652. {
  93653. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93654. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93655. return false;
  93656. /* sign-extend: */
  93657. *val <<= (32-bits);
  93658. *val >>= (32-bits);
  93659. return true;
  93660. }
  93661. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93662. {
  93663. FLAC__uint32 hi, lo;
  93664. if(bits > 32) {
  93665. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93666. return false;
  93667. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93668. return false;
  93669. *val = hi;
  93670. *val <<= 32;
  93671. *val |= lo;
  93672. }
  93673. else {
  93674. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93675. return false;
  93676. *val = lo;
  93677. }
  93678. return true;
  93679. }
  93680. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93681. {
  93682. FLAC__uint32 x8, x32 = 0;
  93683. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93684. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93685. return false;
  93686. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93687. return false;
  93688. x32 |= (x8 << 8);
  93689. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93690. return false;
  93691. x32 |= (x8 << 16);
  93692. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93693. return false;
  93694. x32 |= (x8 << 24);
  93695. *val = x32;
  93696. return true;
  93697. }
  93698. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93699. {
  93700. /*
  93701. * OPT: a faster implementation is possible but probably not that useful
  93702. * since this is only called a couple of times in the metadata readers.
  93703. */
  93704. FLAC__ASSERT(0 != br);
  93705. FLAC__ASSERT(0 != br->buffer);
  93706. if(bits > 0) {
  93707. const unsigned n = br->consumed_bits & 7;
  93708. unsigned m;
  93709. FLAC__uint32 x;
  93710. if(n != 0) {
  93711. m = min(8-n, bits);
  93712. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93713. return false;
  93714. bits -= m;
  93715. }
  93716. m = bits / 8;
  93717. if(m > 0) {
  93718. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93719. return false;
  93720. bits %= 8;
  93721. }
  93722. if(bits > 0) {
  93723. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93724. return false;
  93725. }
  93726. }
  93727. return true;
  93728. }
  93729. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93730. {
  93731. FLAC__uint32 x;
  93732. FLAC__ASSERT(0 != br);
  93733. FLAC__ASSERT(0 != br->buffer);
  93734. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93735. /* step 1: skip over partial head word to get word aligned */
  93736. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93737. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93738. return false;
  93739. nvals--;
  93740. }
  93741. if(0 == nvals)
  93742. return true;
  93743. /* step 2: skip whole words in chunks */
  93744. while(nvals >= FLAC__BYTES_PER_WORD) {
  93745. if(br->consumed_words < br->words) {
  93746. br->consumed_words++;
  93747. nvals -= FLAC__BYTES_PER_WORD;
  93748. }
  93749. else if(!bitreader_read_from_client_(br))
  93750. return false;
  93751. }
  93752. /* step 3: skip any remainder from partial tail bytes */
  93753. while(nvals) {
  93754. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93755. return false;
  93756. nvals--;
  93757. }
  93758. return true;
  93759. }
  93760. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93761. {
  93762. FLAC__uint32 x;
  93763. FLAC__ASSERT(0 != br);
  93764. FLAC__ASSERT(0 != br->buffer);
  93765. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93766. /* step 1: read from partial head word to get word aligned */
  93767. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93768. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93769. return false;
  93770. *val++ = (FLAC__byte)x;
  93771. nvals--;
  93772. }
  93773. if(0 == nvals)
  93774. return true;
  93775. /* step 2: read whole words in chunks */
  93776. while(nvals >= FLAC__BYTES_PER_WORD) {
  93777. if(br->consumed_words < br->words) {
  93778. const brword word = br->buffer[br->consumed_words++];
  93779. #if FLAC__BYTES_PER_WORD == 4
  93780. val[0] = (FLAC__byte)(word >> 24);
  93781. val[1] = (FLAC__byte)(word >> 16);
  93782. val[2] = (FLAC__byte)(word >> 8);
  93783. val[3] = (FLAC__byte)word;
  93784. #elif FLAC__BYTES_PER_WORD == 8
  93785. val[0] = (FLAC__byte)(word >> 56);
  93786. val[1] = (FLAC__byte)(word >> 48);
  93787. val[2] = (FLAC__byte)(word >> 40);
  93788. val[3] = (FLAC__byte)(word >> 32);
  93789. val[4] = (FLAC__byte)(word >> 24);
  93790. val[5] = (FLAC__byte)(word >> 16);
  93791. val[6] = (FLAC__byte)(word >> 8);
  93792. val[7] = (FLAC__byte)word;
  93793. #else
  93794. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93795. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93796. #endif
  93797. val += FLAC__BYTES_PER_WORD;
  93798. nvals -= FLAC__BYTES_PER_WORD;
  93799. }
  93800. else if(!bitreader_read_from_client_(br))
  93801. return false;
  93802. }
  93803. /* step 3: read any remainder from partial tail bytes */
  93804. while(nvals) {
  93805. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93806. return false;
  93807. *val++ = (FLAC__byte)x;
  93808. nvals--;
  93809. }
  93810. return true;
  93811. }
  93812. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93813. #if 0 /* slow but readable version */
  93814. {
  93815. unsigned bit;
  93816. FLAC__ASSERT(0 != br);
  93817. FLAC__ASSERT(0 != br->buffer);
  93818. *val = 0;
  93819. while(1) {
  93820. if(!FLAC__bitreader_read_bit(br, &bit))
  93821. return false;
  93822. if(bit)
  93823. break;
  93824. else
  93825. *val++;
  93826. }
  93827. return true;
  93828. }
  93829. #else
  93830. {
  93831. unsigned i;
  93832. FLAC__ASSERT(0 != br);
  93833. FLAC__ASSERT(0 != br->buffer);
  93834. *val = 0;
  93835. while(1) {
  93836. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93837. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93838. if(b) {
  93839. i = COUNT_ZERO_MSBS(b);
  93840. *val += i;
  93841. i++;
  93842. br->consumed_bits += i;
  93843. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93844. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93845. br->consumed_words++;
  93846. br->consumed_bits = 0;
  93847. }
  93848. return true;
  93849. }
  93850. else {
  93851. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93852. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93853. br->consumed_words++;
  93854. br->consumed_bits = 0;
  93855. /* didn't find stop bit yet, have to keep going... */
  93856. }
  93857. }
  93858. /* at this point we've eaten up all the whole words; have to try
  93859. * reading through any tail bytes before calling the read callback.
  93860. * this is a repeat of the above logic adjusted for the fact we
  93861. * don't have a whole word. note though if the client is feeding
  93862. * us data a byte at a time (unlikely), br->consumed_bits may not
  93863. * be zero.
  93864. */
  93865. if(br->bytes) {
  93866. const unsigned end = br->bytes * 8;
  93867. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93868. if(b) {
  93869. i = COUNT_ZERO_MSBS(b);
  93870. *val += i;
  93871. i++;
  93872. br->consumed_bits += i;
  93873. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93874. return true;
  93875. }
  93876. else {
  93877. *val += end - br->consumed_bits;
  93878. br->consumed_bits += end;
  93879. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93880. /* didn't find stop bit yet, have to keep going... */
  93881. }
  93882. }
  93883. if(!bitreader_read_from_client_(br))
  93884. return false;
  93885. }
  93886. }
  93887. #endif
  93888. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93889. {
  93890. FLAC__uint32 lsbs = 0, msbs = 0;
  93891. unsigned uval;
  93892. FLAC__ASSERT(0 != br);
  93893. FLAC__ASSERT(0 != br->buffer);
  93894. FLAC__ASSERT(parameter <= 31);
  93895. /* read the unary MSBs and end bit */
  93896. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93897. return false;
  93898. /* read the binary LSBs */
  93899. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93900. return false;
  93901. /* compose the value */
  93902. uval = (msbs << parameter) | lsbs;
  93903. if(uval & 1)
  93904. *val = -((int)(uval >> 1)) - 1;
  93905. else
  93906. *val = (int)(uval >> 1);
  93907. return true;
  93908. }
  93909. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93910. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93911. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93912. /* OPT: possibly faster version for use with MSVC */
  93913. #ifdef _MSC_VER
  93914. {
  93915. unsigned i;
  93916. unsigned uval = 0;
  93917. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93918. /* try and get br->consumed_words and br->consumed_bits into register;
  93919. * must remember to flush them back to *br before calling other
  93920. * bitwriter functions that use them, and before returning */
  93921. register unsigned cwords;
  93922. register unsigned cbits;
  93923. FLAC__ASSERT(0 != br);
  93924. FLAC__ASSERT(0 != br->buffer);
  93925. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93926. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93927. FLAC__ASSERT(parameter < 32);
  93928. /* 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 */
  93929. if(nvals == 0)
  93930. return true;
  93931. cbits = br->consumed_bits;
  93932. cwords = br->consumed_words;
  93933. while(1) {
  93934. /* read unary part */
  93935. while(1) {
  93936. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93937. brword b = br->buffer[cwords] << cbits;
  93938. if(b) {
  93939. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93940. __asm {
  93941. bsr eax, b
  93942. not eax
  93943. and eax, 31
  93944. mov i, eax
  93945. }
  93946. #else
  93947. i = COUNT_ZERO_MSBS(b);
  93948. #endif
  93949. uval += i;
  93950. bits = parameter;
  93951. i++;
  93952. cbits += i;
  93953. if(cbits == FLAC__BITS_PER_WORD) {
  93954. crc16_update_word_(br, br->buffer[cwords]);
  93955. cwords++;
  93956. cbits = 0;
  93957. }
  93958. goto break1;
  93959. }
  93960. else {
  93961. uval += FLAC__BITS_PER_WORD - cbits;
  93962. crc16_update_word_(br, br->buffer[cwords]);
  93963. cwords++;
  93964. cbits = 0;
  93965. /* didn't find stop bit yet, have to keep going... */
  93966. }
  93967. }
  93968. /* at this point we've eaten up all the whole words; have to try
  93969. * reading through any tail bytes before calling the read callback.
  93970. * this is a repeat of the above logic adjusted for the fact we
  93971. * don't have a whole word. note though if the client is feeding
  93972. * us data a byte at a time (unlikely), br->consumed_bits may not
  93973. * be zero.
  93974. */
  93975. if(br->bytes) {
  93976. const unsigned end = br->bytes * 8;
  93977. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93978. if(b) {
  93979. i = COUNT_ZERO_MSBS(b);
  93980. uval += i;
  93981. bits = parameter;
  93982. i++;
  93983. cbits += i;
  93984. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93985. goto break1;
  93986. }
  93987. else {
  93988. uval += end - cbits;
  93989. cbits += end;
  93990. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93991. /* didn't find stop bit yet, have to keep going... */
  93992. }
  93993. }
  93994. /* flush registers and read; bitreader_read_from_client_() does
  93995. * not touch br->consumed_bits at all but we still need to set
  93996. * it in case it fails and we have to return false.
  93997. */
  93998. br->consumed_bits = cbits;
  93999. br->consumed_words = cwords;
  94000. if(!bitreader_read_from_client_(br))
  94001. return false;
  94002. cwords = br->consumed_words;
  94003. }
  94004. break1:
  94005. /* read binary part */
  94006. FLAC__ASSERT(cwords <= br->words);
  94007. if(bits) {
  94008. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  94009. /* flush registers and read; bitreader_read_from_client_() does
  94010. * not touch br->consumed_bits at all but we still need to set
  94011. * it in case it fails and we have to return false.
  94012. */
  94013. br->consumed_bits = cbits;
  94014. br->consumed_words = cwords;
  94015. if(!bitreader_read_from_client_(br))
  94016. return false;
  94017. cwords = br->consumed_words;
  94018. }
  94019. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94020. if(cbits) {
  94021. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94022. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94023. const brword word = br->buffer[cwords];
  94024. if(bits < n) {
  94025. uval <<= bits;
  94026. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  94027. cbits += bits;
  94028. goto break2;
  94029. }
  94030. uval <<= n;
  94031. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94032. bits -= n;
  94033. crc16_update_word_(br, word);
  94034. cwords++;
  94035. cbits = 0;
  94036. 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 */
  94037. uval <<= bits;
  94038. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  94039. cbits = bits;
  94040. }
  94041. goto break2;
  94042. }
  94043. else {
  94044. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  94045. uval <<= bits;
  94046. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94047. cbits = bits;
  94048. goto break2;
  94049. }
  94050. }
  94051. else {
  94052. /* in this case we're starting our read at a partial tail word;
  94053. * the reader has guaranteed that we have at least 'bits' bits
  94054. * available to read, which makes this case simpler.
  94055. */
  94056. uval <<= bits;
  94057. if(cbits) {
  94058. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94059. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94060. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94061. cbits += bits;
  94062. goto break2;
  94063. }
  94064. else {
  94065. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94066. cbits += bits;
  94067. goto break2;
  94068. }
  94069. }
  94070. }
  94071. break2:
  94072. /* compose the value */
  94073. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94074. /* are we done? */
  94075. --nvals;
  94076. if(nvals == 0) {
  94077. br->consumed_bits = cbits;
  94078. br->consumed_words = cwords;
  94079. return true;
  94080. }
  94081. uval = 0;
  94082. ++vals;
  94083. }
  94084. }
  94085. #else
  94086. {
  94087. unsigned i;
  94088. unsigned uval = 0;
  94089. /* try and get br->consumed_words and br->consumed_bits into register;
  94090. * must remember to flush them back to *br before calling other
  94091. * bitwriter functions that use them, and before returning */
  94092. register unsigned cwords;
  94093. register unsigned cbits;
  94094. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94095. FLAC__ASSERT(0 != br);
  94096. FLAC__ASSERT(0 != br->buffer);
  94097. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94098. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94099. FLAC__ASSERT(parameter < 32);
  94100. /* 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 */
  94101. if(nvals == 0)
  94102. return true;
  94103. cbits = br->consumed_bits;
  94104. cwords = br->consumed_words;
  94105. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94106. while(1) {
  94107. /* read unary part */
  94108. while(1) {
  94109. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94110. brword b = br->buffer[cwords] << cbits;
  94111. if(b) {
  94112. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94113. asm volatile (
  94114. "bsrl %1, %0;"
  94115. "notl %0;"
  94116. "andl $31, %0;"
  94117. : "=r"(i)
  94118. : "r"(b)
  94119. );
  94120. #else
  94121. i = COUNT_ZERO_MSBS(b);
  94122. #endif
  94123. uval += i;
  94124. cbits += i;
  94125. cbits++; /* skip over stop bit */
  94126. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94127. crc16_update_word_(br, br->buffer[cwords]);
  94128. cwords++;
  94129. cbits = 0;
  94130. }
  94131. goto break1;
  94132. }
  94133. else {
  94134. uval += FLAC__BITS_PER_WORD - cbits;
  94135. crc16_update_word_(br, br->buffer[cwords]);
  94136. cwords++;
  94137. cbits = 0;
  94138. /* didn't find stop bit yet, have to keep going... */
  94139. }
  94140. }
  94141. /* at this point we've eaten up all the whole words; have to try
  94142. * reading through any tail bytes before calling the read callback.
  94143. * this is a repeat of the above logic adjusted for the fact we
  94144. * don't have a whole word. note though if the client is feeding
  94145. * us data a byte at a time (unlikely), br->consumed_bits may not
  94146. * be zero.
  94147. */
  94148. if(br->bytes) {
  94149. const unsigned end = br->bytes * 8;
  94150. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94151. if(b) {
  94152. i = COUNT_ZERO_MSBS(b);
  94153. uval += i;
  94154. cbits += i;
  94155. cbits++; /* skip over stop bit */
  94156. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94157. goto break1;
  94158. }
  94159. else {
  94160. uval += end - cbits;
  94161. cbits += end;
  94162. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94163. /* didn't find stop bit yet, have to keep going... */
  94164. }
  94165. }
  94166. /* flush registers and read; bitreader_read_from_client_() does
  94167. * not touch br->consumed_bits at all but we still need to set
  94168. * it in case it fails and we have to return false.
  94169. */
  94170. br->consumed_bits = cbits;
  94171. br->consumed_words = cwords;
  94172. if(!bitreader_read_from_client_(br))
  94173. return false;
  94174. cwords = br->consumed_words;
  94175. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94176. /* + uval to offset our count by the # of unary bits already
  94177. * consumed before the read, because we will add these back
  94178. * in all at once at break1
  94179. */
  94180. }
  94181. break1:
  94182. ucbits -= uval;
  94183. ucbits--; /* account for stop bit */
  94184. /* read binary part */
  94185. FLAC__ASSERT(cwords <= br->words);
  94186. if(parameter) {
  94187. while(ucbits < parameter) {
  94188. /* flush registers and read; bitreader_read_from_client_() does
  94189. * not touch br->consumed_bits at all but we still need to set
  94190. * it in case it fails and we have to return false.
  94191. */
  94192. br->consumed_bits = cbits;
  94193. br->consumed_words = cwords;
  94194. if(!bitreader_read_from_client_(br))
  94195. return false;
  94196. cwords = br->consumed_words;
  94197. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94198. }
  94199. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94200. if(cbits) {
  94201. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94202. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94203. const brword word = br->buffer[cwords];
  94204. if(parameter < n) {
  94205. uval <<= parameter;
  94206. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94207. cbits += parameter;
  94208. }
  94209. else {
  94210. uval <<= n;
  94211. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94212. crc16_update_word_(br, word);
  94213. cwords++;
  94214. cbits = parameter - n;
  94215. 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 */
  94216. uval <<= cbits;
  94217. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94218. }
  94219. }
  94220. }
  94221. else {
  94222. cbits = parameter;
  94223. uval <<= parameter;
  94224. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94225. }
  94226. }
  94227. else {
  94228. /* in this case we're starting our read at a partial tail word;
  94229. * the reader has guaranteed that we have at least 'parameter'
  94230. * bits available to read, which makes this case simpler.
  94231. */
  94232. uval <<= parameter;
  94233. if(cbits) {
  94234. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94235. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94236. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94237. cbits += parameter;
  94238. }
  94239. else {
  94240. cbits = parameter;
  94241. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94242. }
  94243. }
  94244. }
  94245. ucbits -= parameter;
  94246. /* compose the value */
  94247. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94248. /* are we done? */
  94249. --nvals;
  94250. if(nvals == 0) {
  94251. br->consumed_bits = cbits;
  94252. br->consumed_words = cwords;
  94253. return true;
  94254. }
  94255. uval = 0;
  94256. ++vals;
  94257. }
  94258. }
  94259. #endif
  94260. #if 0 /* UNUSED */
  94261. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94262. {
  94263. FLAC__uint32 lsbs = 0, msbs = 0;
  94264. unsigned bit, uval, k;
  94265. FLAC__ASSERT(0 != br);
  94266. FLAC__ASSERT(0 != br->buffer);
  94267. k = FLAC__bitmath_ilog2(parameter);
  94268. /* read the unary MSBs and end bit */
  94269. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94270. return false;
  94271. /* read the binary LSBs */
  94272. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94273. return false;
  94274. if(parameter == 1u<<k) {
  94275. /* compose the value */
  94276. uval = (msbs << k) | lsbs;
  94277. }
  94278. else {
  94279. unsigned d = (1 << (k+1)) - parameter;
  94280. if(lsbs >= d) {
  94281. if(!FLAC__bitreader_read_bit(br, &bit))
  94282. return false;
  94283. lsbs <<= 1;
  94284. lsbs |= bit;
  94285. lsbs -= d;
  94286. }
  94287. /* compose the value */
  94288. uval = msbs * parameter + lsbs;
  94289. }
  94290. /* unfold unsigned to signed */
  94291. if(uval & 1)
  94292. *val = -((int)(uval >> 1)) - 1;
  94293. else
  94294. *val = (int)(uval >> 1);
  94295. return true;
  94296. }
  94297. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94298. {
  94299. FLAC__uint32 lsbs, msbs = 0;
  94300. unsigned bit, k;
  94301. FLAC__ASSERT(0 != br);
  94302. FLAC__ASSERT(0 != br->buffer);
  94303. k = FLAC__bitmath_ilog2(parameter);
  94304. /* read the unary MSBs and end bit */
  94305. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94306. return false;
  94307. /* read the binary LSBs */
  94308. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94309. return false;
  94310. if(parameter == 1u<<k) {
  94311. /* compose the value */
  94312. *val = (msbs << k) | lsbs;
  94313. }
  94314. else {
  94315. unsigned d = (1 << (k+1)) - parameter;
  94316. if(lsbs >= d) {
  94317. if(!FLAC__bitreader_read_bit(br, &bit))
  94318. return false;
  94319. lsbs <<= 1;
  94320. lsbs |= bit;
  94321. lsbs -= d;
  94322. }
  94323. /* compose the value */
  94324. *val = msbs * parameter + lsbs;
  94325. }
  94326. return true;
  94327. }
  94328. #endif /* UNUSED */
  94329. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94330. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94331. {
  94332. FLAC__uint32 v = 0;
  94333. FLAC__uint32 x;
  94334. unsigned i;
  94335. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94336. return false;
  94337. if(raw)
  94338. raw[(*rawlen)++] = (FLAC__byte)x;
  94339. if(!(x & 0x80)) { /* 0xxxxxxx */
  94340. v = x;
  94341. i = 0;
  94342. }
  94343. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94344. v = x & 0x1F;
  94345. i = 1;
  94346. }
  94347. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94348. v = x & 0x0F;
  94349. i = 2;
  94350. }
  94351. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94352. v = x & 0x07;
  94353. i = 3;
  94354. }
  94355. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94356. v = x & 0x03;
  94357. i = 4;
  94358. }
  94359. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94360. v = x & 0x01;
  94361. i = 5;
  94362. }
  94363. else {
  94364. *val = 0xffffffff;
  94365. return true;
  94366. }
  94367. for( ; i; i--) {
  94368. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94369. return false;
  94370. if(raw)
  94371. raw[(*rawlen)++] = (FLAC__byte)x;
  94372. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94373. *val = 0xffffffff;
  94374. return true;
  94375. }
  94376. v <<= 6;
  94377. v |= (x & 0x3F);
  94378. }
  94379. *val = v;
  94380. return true;
  94381. }
  94382. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94383. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94384. {
  94385. FLAC__uint64 v = 0;
  94386. FLAC__uint32 x;
  94387. unsigned i;
  94388. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94389. return false;
  94390. if(raw)
  94391. raw[(*rawlen)++] = (FLAC__byte)x;
  94392. if(!(x & 0x80)) { /* 0xxxxxxx */
  94393. v = x;
  94394. i = 0;
  94395. }
  94396. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94397. v = x & 0x1F;
  94398. i = 1;
  94399. }
  94400. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94401. v = x & 0x0F;
  94402. i = 2;
  94403. }
  94404. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94405. v = x & 0x07;
  94406. i = 3;
  94407. }
  94408. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94409. v = x & 0x03;
  94410. i = 4;
  94411. }
  94412. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94413. v = x & 0x01;
  94414. i = 5;
  94415. }
  94416. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94417. v = 0;
  94418. i = 6;
  94419. }
  94420. else {
  94421. *val = FLAC__U64L(0xffffffffffffffff);
  94422. return true;
  94423. }
  94424. for( ; i; i--) {
  94425. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94426. return false;
  94427. if(raw)
  94428. raw[(*rawlen)++] = (FLAC__byte)x;
  94429. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94430. *val = FLAC__U64L(0xffffffffffffffff);
  94431. return true;
  94432. }
  94433. v <<= 6;
  94434. v |= (x & 0x3F);
  94435. }
  94436. *val = v;
  94437. return true;
  94438. }
  94439. #endif
  94440. /*** End of inlined file: bitreader.c ***/
  94441. /*** Start of inlined file: bitwriter.c ***/
  94442. /*** Start of inlined file: juce_FlacHeader.h ***/
  94443. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94444. // tasks..
  94445. #define VERSION "1.2.1"
  94446. #define FLAC__NO_DLL 1
  94447. #if JUCE_MSVC
  94448. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94449. #endif
  94450. #if JUCE_MAC
  94451. #define FLAC__SYS_DARWIN 1
  94452. #endif
  94453. /*** End of inlined file: juce_FlacHeader.h ***/
  94454. #if JUCE_USE_FLAC
  94455. #if HAVE_CONFIG_H
  94456. # include <config.h>
  94457. #endif
  94458. #include <stdlib.h> /* for malloc() */
  94459. #include <string.h> /* for memcpy(), memset() */
  94460. #ifdef _MSC_VER
  94461. #include <winsock.h> /* for ntohl() */
  94462. #elif defined FLAC__SYS_DARWIN
  94463. #include <machine/endian.h> /* for ntohl() */
  94464. #elif defined __MINGW32__
  94465. #include <winsock.h> /* for ntohl() */
  94466. #else
  94467. #include <netinet/in.h> /* for ntohl() */
  94468. #endif
  94469. #if 0 /* UNUSED */
  94470. #endif
  94471. /*** Start of inlined file: bitwriter.h ***/
  94472. #ifndef FLAC__PRIVATE__BITWRITER_H
  94473. #define FLAC__PRIVATE__BITWRITER_H
  94474. #include <stdio.h> /* for FILE */
  94475. /*
  94476. * opaque structure definition
  94477. */
  94478. struct FLAC__BitWriter;
  94479. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94480. /*
  94481. * construction, deletion, initialization, etc functions
  94482. */
  94483. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94484. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94485. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94486. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94487. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94488. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94489. /*
  94490. * CRC functions
  94491. *
  94492. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94493. */
  94494. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94495. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94496. /*
  94497. * info functions
  94498. */
  94499. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94500. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94501. /*
  94502. * direct buffer access
  94503. *
  94504. * there may be no calls on the bitwriter between get and release.
  94505. * the bitwriter continues to own the returned buffer.
  94506. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94507. */
  94508. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94509. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94510. /*
  94511. * write functions
  94512. */
  94513. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94514. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94515. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94516. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94517. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94518. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94519. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94520. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94521. #if 0 /* UNUSED */
  94522. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94523. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94524. #endif
  94525. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94526. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94527. #if 0 /* UNUSED */
  94528. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94529. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94530. #endif
  94531. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94532. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94533. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94534. #endif
  94535. /*** End of inlined file: bitwriter.h ***/
  94536. /*** Start of inlined file: alloc.h ***/
  94537. #ifndef FLAC__SHARE__ALLOC_H
  94538. #define FLAC__SHARE__ALLOC_H
  94539. #if HAVE_CONFIG_H
  94540. # include <config.h>
  94541. #endif
  94542. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94543. * before #including this file, otherwise SIZE_MAX might not be defined
  94544. */
  94545. #include <limits.h> /* for SIZE_MAX */
  94546. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94547. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94548. #endif
  94549. #include <stdlib.h> /* for size_t, malloc(), etc */
  94550. #ifndef SIZE_MAX
  94551. # ifndef SIZE_T_MAX
  94552. # ifdef _MSC_VER
  94553. # define SIZE_T_MAX UINT_MAX
  94554. # else
  94555. # error
  94556. # endif
  94557. # endif
  94558. # define SIZE_MAX SIZE_T_MAX
  94559. #endif
  94560. #ifndef FLaC__INLINE
  94561. #define FLaC__INLINE
  94562. #endif
  94563. /* avoid malloc()ing 0 bytes, see:
  94564. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94565. */
  94566. static FLaC__INLINE void *safe_malloc_(size_t size)
  94567. {
  94568. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94569. if(!size)
  94570. size++;
  94571. return malloc(size);
  94572. }
  94573. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94574. {
  94575. if(!nmemb || !size)
  94576. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94577. return calloc(nmemb, size);
  94578. }
  94579. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94580. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94581. {
  94582. size2 += size1;
  94583. if(size2 < size1)
  94584. return 0;
  94585. return safe_malloc_(size2);
  94586. }
  94587. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94588. {
  94589. size2 += size1;
  94590. if(size2 < size1)
  94591. return 0;
  94592. size3 += size2;
  94593. if(size3 < size2)
  94594. return 0;
  94595. return safe_malloc_(size3);
  94596. }
  94597. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94598. {
  94599. size2 += size1;
  94600. if(size2 < size1)
  94601. return 0;
  94602. size3 += size2;
  94603. if(size3 < size2)
  94604. return 0;
  94605. size4 += size3;
  94606. if(size4 < size3)
  94607. return 0;
  94608. return safe_malloc_(size4);
  94609. }
  94610. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94611. #if 0
  94612. needs support for cases where sizeof(size_t) != 4
  94613. {
  94614. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94615. if(sizeof(size_t) == 4) {
  94616. if ((double)size1 * (double)size2 < 4294967296.0)
  94617. return malloc(size1*size2);
  94618. }
  94619. return 0;
  94620. }
  94621. #else
  94622. /* better? */
  94623. {
  94624. if(!size1 || !size2)
  94625. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94626. if(size1 > SIZE_MAX / size2)
  94627. return 0;
  94628. return malloc(size1*size2);
  94629. }
  94630. #endif
  94631. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94632. {
  94633. if(!size1 || !size2 || !size3)
  94634. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94635. if(size1 > SIZE_MAX / size2)
  94636. return 0;
  94637. size1 *= size2;
  94638. if(size1 > SIZE_MAX / size3)
  94639. return 0;
  94640. return malloc(size1*size3);
  94641. }
  94642. /* size1*size2 + size3 */
  94643. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94644. {
  94645. if(!size1 || !size2)
  94646. return safe_malloc_(size3);
  94647. if(size1 > SIZE_MAX / size2)
  94648. return 0;
  94649. return safe_malloc_add_2op_(size1*size2, size3);
  94650. }
  94651. /* size1 * (size2 + size3) */
  94652. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94653. {
  94654. if(!size1 || (!size2 && !size3))
  94655. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94656. size2 += size3;
  94657. if(size2 < size3)
  94658. return 0;
  94659. return safe_malloc_mul_2op_(size1, size2);
  94660. }
  94661. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94662. {
  94663. size2 += size1;
  94664. if(size2 < size1)
  94665. return 0;
  94666. return realloc(ptr, size2);
  94667. }
  94668. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94669. {
  94670. size2 += size1;
  94671. if(size2 < size1)
  94672. return 0;
  94673. size3 += size2;
  94674. if(size3 < size2)
  94675. return 0;
  94676. return realloc(ptr, size3);
  94677. }
  94678. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94679. {
  94680. size2 += size1;
  94681. if(size2 < size1)
  94682. return 0;
  94683. size3 += size2;
  94684. if(size3 < size2)
  94685. return 0;
  94686. size4 += size3;
  94687. if(size4 < size3)
  94688. return 0;
  94689. return realloc(ptr, size4);
  94690. }
  94691. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94692. {
  94693. if(!size1 || !size2)
  94694. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94695. if(size1 > SIZE_MAX / size2)
  94696. return 0;
  94697. return realloc(ptr, size1*size2);
  94698. }
  94699. /* size1 * (size2 + size3) */
  94700. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94701. {
  94702. if(!size1 || (!size2 && !size3))
  94703. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94704. size2 += size3;
  94705. if(size2 < size3)
  94706. return 0;
  94707. return safe_realloc_mul_2op_(ptr, size1, size2);
  94708. }
  94709. #endif
  94710. /*** End of inlined file: alloc.h ***/
  94711. /* Things should be fastest when this matches the machine word size */
  94712. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94713. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94714. typedef FLAC__uint32 bwword;
  94715. #define FLAC__BYTES_PER_WORD 4
  94716. #define FLAC__BITS_PER_WORD 32
  94717. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94718. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94719. #if WORDS_BIGENDIAN
  94720. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94721. #else
  94722. #ifdef _MSC_VER
  94723. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94724. #else
  94725. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94726. #endif
  94727. #endif
  94728. /*
  94729. * The default capacity here doesn't matter too much. The buffer always grows
  94730. * to hold whatever is written to it. Usually the encoder will stop adding at
  94731. * a frame or metadata block, then write that out and clear the buffer for the
  94732. * next one.
  94733. */
  94734. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94735. /* When growing, increment 4K at a time */
  94736. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94737. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94738. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94739. #ifdef min
  94740. #undef min
  94741. #endif
  94742. #define min(x,y) ((x)<(y)?(x):(y))
  94743. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94744. #ifdef _MSC_VER
  94745. #define FLAC__U64L(x) x
  94746. #else
  94747. #define FLAC__U64L(x) x##LLU
  94748. #endif
  94749. #ifndef FLaC__INLINE
  94750. #define FLaC__INLINE
  94751. #endif
  94752. struct FLAC__BitWriter {
  94753. bwword *buffer;
  94754. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94755. unsigned capacity; /* capacity of buffer in words */
  94756. unsigned words; /* # of complete words in buffer */
  94757. unsigned bits; /* # of used bits in accum */
  94758. };
  94759. /* * WATCHOUT: The current implementation only grows the buffer. */
  94760. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94761. {
  94762. unsigned new_capacity;
  94763. bwword *new_buffer;
  94764. FLAC__ASSERT(0 != bw);
  94765. FLAC__ASSERT(0 != bw->buffer);
  94766. /* calculate total words needed to store 'bits_to_add' additional bits */
  94767. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94768. /* it's possible (due to pessimism in the growth estimation that
  94769. * leads to this call) that we don't actually need to grow
  94770. */
  94771. if(bw->capacity >= new_capacity)
  94772. return true;
  94773. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94774. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94775. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94776. /* make sure we got everything right */
  94777. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94778. FLAC__ASSERT(new_capacity > bw->capacity);
  94779. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94780. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94781. if(new_buffer == 0)
  94782. return false;
  94783. bw->buffer = new_buffer;
  94784. bw->capacity = new_capacity;
  94785. return true;
  94786. }
  94787. /***********************************************************************
  94788. *
  94789. * Class constructor/destructor
  94790. *
  94791. ***********************************************************************/
  94792. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94793. {
  94794. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94795. /* note that calloc() sets all members to 0 for us */
  94796. return bw;
  94797. }
  94798. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94799. {
  94800. FLAC__ASSERT(0 != bw);
  94801. FLAC__bitwriter_free(bw);
  94802. free(bw);
  94803. }
  94804. /***********************************************************************
  94805. *
  94806. * Public class methods
  94807. *
  94808. ***********************************************************************/
  94809. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94810. {
  94811. FLAC__ASSERT(0 != bw);
  94812. bw->words = bw->bits = 0;
  94813. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94814. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94815. if(bw->buffer == 0)
  94816. return false;
  94817. return true;
  94818. }
  94819. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94820. {
  94821. FLAC__ASSERT(0 != bw);
  94822. if(0 != bw->buffer)
  94823. free(bw->buffer);
  94824. bw->buffer = 0;
  94825. bw->capacity = 0;
  94826. bw->words = bw->bits = 0;
  94827. }
  94828. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94829. {
  94830. bw->words = bw->bits = 0;
  94831. }
  94832. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94833. {
  94834. unsigned i, j;
  94835. if(bw == 0) {
  94836. fprintf(out, "bitwriter is NULL\n");
  94837. }
  94838. else {
  94839. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94840. for(i = 0; i < bw->words; i++) {
  94841. fprintf(out, "%08X: ", i);
  94842. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94843. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94844. fprintf(out, "\n");
  94845. }
  94846. if(bw->bits > 0) {
  94847. fprintf(out, "%08X: ", i);
  94848. for(j = 0; j < bw->bits; j++)
  94849. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94850. fprintf(out, "\n");
  94851. }
  94852. }
  94853. }
  94854. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94855. {
  94856. const FLAC__byte *buffer;
  94857. size_t bytes;
  94858. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94859. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94860. return false;
  94861. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94862. FLAC__bitwriter_release_buffer(bw);
  94863. return true;
  94864. }
  94865. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94866. {
  94867. const FLAC__byte *buffer;
  94868. size_t bytes;
  94869. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94870. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94871. return false;
  94872. *crc = FLAC__crc8(buffer, bytes);
  94873. FLAC__bitwriter_release_buffer(bw);
  94874. return true;
  94875. }
  94876. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94877. {
  94878. return ((bw->bits & 7) == 0);
  94879. }
  94880. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94881. {
  94882. return FLAC__TOTAL_BITS(bw);
  94883. }
  94884. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94885. {
  94886. FLAC__ASSERT((bw->bits & 7) == 0);
  94887. /* double protection */
  94888. if(bw->bits & 7)
  94889. return false;
  94890. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94891. if(bw->bits) {
  94892. FLAC__ASSERT(bw->words <= bw->capacity);
  94893. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94894. return false;
  94895. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94896. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94897. }
  94898. /* now we can just return what we have */
  94899. *buffer = (FLAC__byte*)bw->buffer;
  94900. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94901. return true;
  94902. }
  94903. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94904. {
  94905. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94906. * get-mode' flag could be added everywhere and then cleared here
  94907. */
  94908. (void)bw;
  94909. }
  94910. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94911. {
  94912. unsigned n;
  94913. FLAC__ASSERT(0 != bw);
  94914. FLAC__ASSERT(0 != bw->buffer);
  94915. if(bits == 0)
  94916. return true;
  94917. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94918. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94919. return false;
  94920. /* first part gets to word alignment */
  94921. if(bw->bits) {
  94922. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94923. bw->accum <<= n;
  94924. bits -= n;
  94925. bw->bits += n;
  94926. if(bw->bits == FLAC__BITS_PER_WORD) {
  94927. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94928. bw->bits = 0;
  94929. }
  94930. else
  94931. return true;
  94932. }
  94933. /* do whole words */
  94934. while(bits >= FLAC__BITS_PER_WORD) {
  94935. bw->buffer[bw->words++] = 0;
  94936. bits -= FLAC__BITS_PER_WORD;
  94937. }
  94938. /* do any leftovers */
  94939. if(bits > 0) {
  94940. bw->accum = 0;
  94941. bw->bits = bits;
  94942. }
  94943. return true;
  94944. }
  94945. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94946. {
  94947. register unsigned left;
  94948. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94949. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94950. FLAC__ASSERT(0 != bw);
  94951. FLAC__ASSERT(0 != bw->buffer);
  94952. FLAC__ASSERT(bits <= 32);
  94953. if(bits == 0)
  94954. return true;
  94955. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94956. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94957. return false;
  94958. left = FLAC__BITS_PER_WORD - bw->bits;
  94959. if(bits < left) {
  94960. bw->accum <<= bits;
  94961. bw->accum |= val;
  94962. bw->bits += bits;
  94963. }
  94964. 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 */
  94965. bw->accum <<= left;
  94966. bw->accum |= val >> (bw->bits = bits - left);
  94967. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94968. bw->accum = val;
  94969. }
  94970. else {
  94971. bw->accum = val;
  94972. bw->bits = 0;
  94973. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94974. }
  94975. return true;
  94976. }
  94977. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94978. {
  94979. /* zero-out unused bits */
  94980. if(bits < 32)
  94981. val &= (~(0xffffffff << bits));
  94982. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94983. }
  94984. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94985. {
  94986. /* this could be a little faster but it's not used for much */
  94987. if(bits > 32) {
  94988. return
  94989. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94990. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94991. }
  94992. else
  94993. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94994. }
  94995. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94996. {
  94997. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94998. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94999. return false;
  95000. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  95001. return false;
  95002. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  95003. return false;
  95004. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  95005. return false;
  95006. return true;
  95007. }
  95008. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  95009. {
  95010. unsigned i;
  95011. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  95012. for(i = 0; i < nvals; i++) {
  95013. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  95014. return false;
  95015. }
  95016. return true;
  95017. }
  95018. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  95019. {
  95020. if(val < 32)
  95021. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  95022. else
  95023. return
  95024. FLAC__bitwriter_write_zeroes(bw, val) &&
  95025. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  95026. }
  95027. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  95028. {
  95029. FLAC__uint32 uval;
  95030. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  95031. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95032. uval = (val<<1) ^ (val>>31);
  95033. return 1 + parameter + (uval >> parameter);
  95034. }
  95035. #if 0 /* UNUSED */
  95036. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  95037. {
  95038. unsigned bits, msbs, uval;
  95039. unsigned k;
  95040. FLAC__ASSERT(parameter > 0);
  95041. /* fold signed to unsigned */
  95042. if(val < 0)
  95043. uval = (unsigned)(((-(++val)) << 1) + 1);
  95044. else
  95045. uval = (unsigned)(val << 1);
  95046. k = FLAC__bitmath_ilog2(parameter);
  95047. if(parameter == 1u<<k) {
  95048. FLAC__ASSERT(k <= 30);
  95049. msbs = uval >> k;
  95050. bits = 1 + k + msbs;
  95051. }
  95052. else {
  95053. unsigned q, r, d;
  95054. d = (1 << (k+1)) - parameter;
  95055. q = uval / parameter;
  95056. r = uval - (q * parameter);
  95057. bits = 1 + q + k;
  95058. if(r >= d)
  95059. bits++;
  95060. }
  95061. return bits;
  95062. }
  95063. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95064. {
  95065. unsigned bits, msbs;
  95066. unsigned k;
  95067. FLAC__ASSERT(parameter > 0);
  95068. k = FLAC__bitmath_ilog2(parameter);
  95069. if(parameter == 1u<<k) {
  95070. FLAC__ASSERT(k <= 30);
  95071. msbs = uval >> k;
  95072. bits = 1 + k + msbs;
  95073. }
  95074. else {
  95075. unsigned q, r, d;
  95076. d = (1 << (k+1)) - parameter;
  95077. q = uval / parameter;
  95078. r = uval - (q * parameter);
  95079. bits = 1 + q + k;
  95080. if(r >= d)
  95081. bits++;
  95082. }
  95083. return bits;
  95084. }
  95085. #endif /* UNUSED */
  95086. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95087. {
  95088. unsigned total_bits, interesting_bits, msbs;
  95089. FLAC__uint32 uval, pattern;
  95090. FLAC__ASSERT(0 != bw);
  95091. FLAC__ASSERT(0 != bw->buffer);
  95092. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95093. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95094. uval = (val<<1) ^ (val>>31);
  95095. msbs = uval >> parameter;
  95096. interesting_bits = 1 + parameter;
  95097. total_bits = interesting_bits + msbs;
  95098. pattern = 1 << parameter; /* the unary end bit */
  95099. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95100. if(total_bits <= 32)
  95101. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95102. else
  95103. return
  95104. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95105. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95106. }
  95107. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95108. {
  95109. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95110. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95111. FLAC__uint32 uval;
  95112. unsigned left;
  95113. const unsigned lsbits = 1 + parameter;
  95114. unsigned msbits;
  95115. FLAC__ASSERT(0 != bw);
  95116. FLAC__ASSERT(0 != bw->buffer);
  95117. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95118. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95119. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95120. while(nvals) {
  95121. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95122. uval = (*vals<<1) ^ (*vals>>31);
  95123. msbits = uval >> parameter;
  95124. #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) */
  95125. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95126. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95127. bw->bits = bw->bits + msbits + lsbits;
  95128. uval |= mask1; /* set stop bit */
  95129. uval &= mask2; /* mask off unused top bits */
  95130. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95131. bw->accum <<= msbits;
  95132. bw->accum <<= lsbits;
  95133. bw->accum |= uval;
  95134. if(bw->bits == FLAC__BITS_PER_WORD) {
  95135. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95136. bw->bits = 0;
  95137. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95138. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95139. FLAC__ASSERT(bw->capacity == bw->words);
  95140. return false;
  95141. }
  95142. }
  95143. }
  95144. else {
  95145. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95146. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95147. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95148. bw->bits = bw->bits + msbits + lsbits;
  95149. uval |= mask1; /* set stop bit */
  95150. uval &= mask2; /* mask off unused top bits */
  95151. bw->accum <<= msbits + lsbits;
  95152. bw->accum |= uval;
  95153. }
  95154. else {
  95155. #endif
  95156. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95157. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95158. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95159. return false;
  95160. if(msbits) {
  95161. /* first part gets to word alignment */
  95162. if(bw->bits) {
  95163. left = FLAC__BITS_PER_WORD - bw->bits;
  95164. if(msbits < left) {
  95165. bw->accum <<= msbits;
  95166. bw->bits += msbits;
  95167. goto break1;
  95168. }
  95169. else {
  95170. bw->accum <<= left;
  95171. msbits -= left;
  95172. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95173. bw->bits = 0;
  95174. }
  95175. }
  95176. /* do whole words */
  95177. while(msbits >= FLAC__BITS_PER_WORD) {
  95178. bw->buffer[bw->words++] = 0;
  95179. msbits -= FLAC__BITS_PER_WORD;
  95180. }
  95181. /* do any leftovers */
  95182. if(msbits > 0) {
  95183. bw->accum = 0;
  95184. bw->bits = msbits;
  95185. }
  95186. }
  95187. break1:
  95188. uval |= mask1; /* set stop bit */
  95189. uval &= mask2; /* mask off unused top bits */
  95190. left = FLAC__BITS_PER_WORD - bw->bits;
  95191. if(lsbits < left) {
  95192. bw->accum <<= lsbits;
  95193. bw->accum |= uval;
  95194. bw->bits += lsbits;
  95195. }
  95196. else {
  95197. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95198. * be > lsbits (because of previous assertions) so it would have
  95199. * triggered the (lsbits<left) case above.
  95200. */
  95201. FLAC__ASSERT(bw->bits);
  95202. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95203. bw->accum <<= left;
  95204. bw->accum |= uval >> (bw->bits = lsbits - left);
  95205. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95206. bw->accum = uval;
  95207. }
  95208. #if 1
  95209. }
  95210. #endif
  95211. vals++;
  95212. nvals--;
  95213. }
  95214. return true;
  95215. }
  95216. #if 0 /* UNUSED */
  95217. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95218. {
  95219. unsigned total_bits, msbs, uval;
  95220. unsigned k;
  95221. FLAC__ASSERT(0 != bw);
  95222. FLAC__ASSERT(0 != bw->buffer);
  95223. FLAC__ASSERT(parameter > 0);
  95224. /* fold signed to unsigned */
  95225. if(val < 0)
  95226. uval = (unsigned)(((-(++val)) << 1) + 1);
  95227. else
  95228. uval = (unsigned)(val << 1);
  95229. k = FLAC__bitmath_ilog2(parameter);
  95230. if(parameter == 1u<<k) {
  95231. unsigned pattern;
  95232. FLAC__ASSERT(k <= 30);
  95233. msbs = uval >> k;
  95234. total_bits = 1 + k + msbs;
  95235. pattern = 1 << k; /* the unary end bit */
  95236. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95237. if(total_bits <= 32) {
  95238. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95239. return false;
  95240. }
  95241. else {
  95242. /* write the unary MSBs */
  95243. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95244. return false;
  95245. /* write the unary end bit and binary LSBs */
  95246. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95247. return false;
  95248. }
  95249. }
  95250. else {
  95251. unsigned q, r, d;
  95252. d = (1 << (k+1)) - parameter;
  95253. q = uval / parameter;
  95254. r = uval - (q * parameter);
  95255. /* write the unary MSBs */
  95256. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95257. return false;
  95258. /* write the unary end bit */
  95259. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95260. return false;
  95261. /* write the binary LSBs */
  95262. if(r >= d) {
  95263. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95264. return false;
  95265. }
  95266. else {
  95267. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95268. return false;
  95269. }
  95270. }
  95271. return true;
  95272. }
  95273. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95274. {
  95275. unsigned total_bits, msbs;
  95276. unsigned k;
  95277. FLAC__ASSERT(0 != bw);
  95278. FLAC__ASSERT(0 != bw->buffer);
  95279. FLAC__ASSERT(parameter > 0);
  95280. k = FLAC__bitmath_ilog2(parameter);
  95281. if(parameter == 1u<<k) {
  95282. unsigned pattern;
  95283. FLAC__ASSERT(k <= 30);
  95284. msbs = uval >> k;
  95285. total_bits = 1 + k + msbs;
  95286. pattern = 1 << k; /* the unary end bit */
  95287. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95288. if(total_bits <= 32) {
  95289. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95290. return false;
  95291. }
  95292. else {
  95293. /* write the unary MSBs */
  95294. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95295. return false;
  95296. /* write the unary end bit and binary LSBs */
  95297. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95298. return false;
  95299. }
  95300. }
  95301. else {
  95302. unsigned q, r, d;
  95303. d = (1 << (k+1)) - parameter;
  95304. q = uval / parameter;
  95305. r = uval - (q * parameter);
  95306. /* write the unary MSBs */
  95307. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95308. return false;
  95309. /* write the unary end bit */
  95310. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95311. return false;
  95312. /* write the binary LSBs */
  95313. if(r >= d) {
  95314. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95315. return false;
  95316. }
  95317. else {
  95318. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95319. return false;
  95320. }
  95321. }
  95322. return true;
  95323. }
  95324. #endif /* UNUSED */
  95325. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95326. {
  95327. FLAC__bool ok = 1;
  95328. FLAC__ASSERT(0 != bw);
  95329. FLAC__ASSERT(0 != bw->buffer);
  95330. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95331. if(val < 0x80) {
  95332. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95333. }
  95334. else if(val < 0x800) {
  95335. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95336. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95337. }
  95338. else if(val < 0x10000) {
  95339. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95340. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95341. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95342. }
  95343. else if(val < 0x200000) {
  95344. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95345. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95346. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95347. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95348. }
  95349. else if(val < 0x4000000) {
  95350. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95351. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95352. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95353. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95354. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95355. }
  95356. else {
  95357. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95358. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95359. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95360. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95361. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95362. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95363. }
  95364. return ok;
  95365. }
  95366. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95367. {
  95368. FLAC__bool ok = 1;
  95369. FLAC__ASSERT(0 != bw);
  95370. FLAC__ASSERT(0 != bw->buffer);
  95371. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95372. if(val < 0x80) {
  95373. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95374. }
  95375. else if(val < 0x800) {
  95376. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95377. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95378. }
  95379. else if(val < 0x10000) {
  95380. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95381. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95382. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95383. }
  95384. else if(val < 0x200000) {
  95385. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95386. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95387. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95388. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95389. }
  95390. else if(val < 0x4000000) {
  95391. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95392. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95393. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95394. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95395. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95396. }
  95397. else if(val < 0x80000000) {
  95398. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95399. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95400. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95401. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95402. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95403. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95404. }
  95405. else {
  95406. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95407. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95408. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95409. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95410. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95411. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95412. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95413. }
  95414. return ok;
  95415. }
  95416. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95417. {
  95418. /* 0-pad to byte boundary */
  95419. if(bw->bits & 7u)
  95420. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95421. else
  95422. return true;
  95423. }
  95424. #endif
  95425. /*** End of inlined file: bitwriter.c ***/
  95426. /*** Start of inlined file: cpu.c ***/
  95427. /*** Start of inlined file: juce_FlacHeader.h ***/
  95428. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95429. // tasks..
  95430. #define VERSION "1.2.1"
  95431. #define FLAC__NO_DLL 1
  95432. #if JUCE_MSVC
  95433. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95434. #endif
  95435. #if JUCE_MAC
  95436. #define FLAC__SYS_DARWIN 1
  95437. #endif
  95438. /*** End of inlined file: juce_FlacHeader.h ***/
  95439. #if JUCE_USE_FLAC
  95440. #if HAVE_CONFIG_H
  95441. # include <config.h>
  95442. #endif
  95443. #include <stdlib.h>
  95444. #include <stdio.h>
  95445. #if defined FLAC__CPU_IA32
  95446. # include <signal.h>
  95447. #elif defined FLAC__CPU_PPC
  95448. # if !defined FLAC__NO_ASM
  95449. # if defined FLAC__SYS_DARWIN
  95450. # include <sys/sysctl.h>
  95451. # include <mach/mach.h>
  95452. # include <mach/mach_host.h>
  95453. # include <mach/host_info.h>
  95454. # include <mach/machine.h>
  95455. # ifndef CPU_SUBTYPE_POWERPC_970
  95456. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95457. # endif
  95458. # else /* FLAC__SYS_DARWIN */
  95459. # include <signal.h>
  95460. # include <setjmp.h>
  95461. static sigjmp_buf jmpbuf;
  95462. static volatile sig_atomic_t canjump = 0;
  95463. static void sigill_handler (int sig)
  95464. {
  95465. if (!canjump) {
  95466. signal (sig, SIG_DFL);
  95467. raise (sig);
  95468. }
  95469. canjump = 0;
  95470. siglongjmp (jmpbuf, 1);
  95471. }
  95472. # endif /* FLAC__SYS_DARWIN */
  95473. # endif /* FLAC__NO_ASM */
  95474. #endif /* FLAC__CPU_PPC */
  95475. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95476. #include <sys/param.h>
  95477. #include <sys/sysctl.h>
  95478. #include <machine/cpu.h>
  95479. #endif
  95480. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95481. #include <sys/types.h>
  95482. #include <sys/sysctl.h>
  95483. #endif
  95484. #if defined(__APPLE__)
  95485. /* how to get sysctlbyname()? */
  95486. #endif
  95487. /* these are flags in EDX of CPUID AX=00000001 */
  95488. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95489. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95490. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95491. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95492. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95493. /* these are flags in ECX of CPUID AX=00000001 */
  95494. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95495. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95496. /* these are flags in EDX of CPUID AX=80000001 */
  95497. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95498. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95499. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95500. /*
  95501. * Extra stuff needed for detection of OS support for SSE on IA-32
  95502. */
  95503. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95504. # if defined(__linux__)
  95505. /*
  95506. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95507. * modify the return address to jump over the offending SSE instruction
  95508. * and also the operation following it that indicates the instruction
  95509. * executed successfully. In this way we use no global variables and
  95510. * stay thread-safe.
  95511. *
  95512. * 3 + 3 + 6:
  95513. * 3 bytes for "xorps xmm0,xmm0"
  95514. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95515. * 6 bytes extra in case our estimate is wrong
  95516. * 12 bytes puts us in the NOP "landing zone"
  95517. */
  95518. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95519. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95520. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95521. {
  95522. (void)signal;
  95523. sc.eip += 3 + 3 + 6;
  95524. }
  95525. # else
  95526. # include <sys/ucontext.h>
  95527. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95528. {
  95529. (void)signal, (void)si;
  95530. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95531. }
  95532. # endif
  95533. # elif defined(_MSC_VER)
  95534. # include <windows.h>
  95535. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95536. # ifdef USE_TRY_CATCH_FLAVOR
  95537. # else
  95538. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95539. {
  95540. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95541. ep->ContextRecord->Eip += 3 + 3 + 6;
  95542. return EXCEPTION_CONTINUE_EXECUTION;
  95543. }
  95544. return EXCEPTION_CONTINUE_SEARCH;
  95545. }
  95546. # endif
  95547. # endif
  95548. #endif
  95549. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95550. {
  95551. /*
  95552. * IA32-specific
  95553. */
  95554. #ifdef FLAC__CPU_IA32
  95555. info->type = FLAC__CPUINFO_TYPE_IA32;
  95556. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95557. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95558. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95559. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95560. info->data.ia32.cmov = false;
  95561. info->data.ia32.mmx = false;
  95562. info->data.ia32.fxsr = false;
  95563. info->data.ia32.sse = false;
  95564. info->data.ia32.sse2 = false;
  95565. info->data.ia32.sse3 = false;
  95566. info->data.ia32.ssse3 = false;
  95567. info->data.ia32._3dnow = false;
  95568. info->data.ia32.ext3dnow = false;
  95569. info->data.ia32.extmmx = false;
  95570. if(info->data.ia32.cpuid) {
  95571. /* http://www.sandpile.org/ia32/cpuid.htm */
  95572. FLAC__uint32 flags_edx, flags_ecx;
  95573. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95574. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95575. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95576. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95577. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95578. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95579. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95580. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95581. #ifdef FLAC__USE_3DNOW
  95582. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95583. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95584. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95585. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95586. #else
  95587. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95588. #endif
  95589. #ifdef DEBUG
  95590. fprintf(stderr, "CPU info (IA-32):\n");
  95591. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95592. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95593. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95594. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95595. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95596. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95597. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95598. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95599. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95600. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95601. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95602. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95603. #endif
  95604. /*
  95605. * now have to check for OS support of SSE/SSE2
  95606. */
  95607. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95608. #if defined FLAC__NO_SSE_OS
  95609. /* assume user knows better than us; turn it off */
  95610. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95611. #elif defined FLAC__SSE_OS
  95612. /* assume user knows better than us; leave as detected above */
  95613. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95614. int sse = 0;
  95615. size_t len;
  95616. /* at least one of these must work: */
  95617. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95618. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95619. if(!sse)
  95620. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95621. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95622. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95623. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95624. size_t len = sizeof(val);
  95625. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95626. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95627. else { /* double-check SSE2 */
  95628. mib[1] = CPU_SSE2;
  95629. len = sizeof(val);
  95630. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95631. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95632. }
  95633. # else
  95634. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95635. # endif
  95636. #elif defined(__linux__)
  95637. int sse = 0;
  95638. struct sigaction sigill_save;
  95639. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95640. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95641. #else
  95642. struct sigaction sigill_sse;
  95643. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95644. __sigemptyset(&sigill_sse.sa_mask);
  95645. 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 */
  95646. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95647. #endif
  95648. {
  95649. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95650. /* see sigill_handler_sse_os() for an explanation of the following: */
  95651. asm volatile (
  95652. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95653. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95654. "incl %0\n\t" /* SIGILL handler will jump over this */
  95655. /* landing zone */
  95656. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95657. "nop\n\t"
  95658. "nop\n\t"
  95659. "nop\n\t"
  95660. "nop\n\t"
  95661. "nop\n\t"
  95662. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95663. "nop\n\t"
  95664. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95665. : "=r"(sse)
  95666. : "r"(sse)
  95667. );
  95668. sigaction(SIGILL, &sigill_save, NULL);
  95669. }
  95670. if(!sse)
  95671. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95672. #elif defined(_MSC_VER)
  95673. # ifdef USE_TRY_CATCH_FLAVOR
  95674. _try {
  95675. __asm {
  95676. # if _MSC_VER <= 1200
  95677. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95678. _emit 0x0F
  95679. _emit 0x57
  95680. _emit 0xC0
  95681. # else
  95682. xorps xmm0,xmm0
  95683. # endif
  95684. }
  95685. }
  95686. _except(EXCEPTION_EXECUTE_HANDLER) {
  95687. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95688. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95689. }
  95690. # else
  95691. int sse = 0;
  95692. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95693. /* see GCC version above for explanation */
  95694. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95695. /* http://www.codeproject.com/cpp/gccasm.asp */
  95696. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95697. __asm {
  95698. # if _MSC_VER <= 1200
  95699. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95700. _emit 0x0F
  95701. _emit 0x57
  95702. _emit 0xC0
  95703. # else
  95704. xorps xmm0,xmm0
  95705. # endif
  95706. inc sse
  95707. nop
  95708. nop
  95709. nop
  95710. nop
  95711. nop
  95712. nop
  95713. nop
  95714. nop
  95715. nop
  95716. }
  95717. SetUnhandledExceptionFilter(save);
  95718. if(!sse)
  95719. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95720. # endif
  95721. #else
  95722. /* no way to test, disable to be safe */
  95723. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95724. #endif
  95725. #ifdef DEBUG
  95726. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95727. #endif
  95728. }
  95729. }
  95730. #else
  95731. info->use_asm = false;
  95732. #endif
  95733. /*
  95734. * PPC-specific
  95735. */
  95736. #elif defined FLAC__CPU_PPC
  95737. info->type = FLAC__CPUINFO_TYPE_PPC;
  95738. # if !defined FLAC__NO_ASM
  95739. info->use_asm = true;
  95740. # ifdef FLAC__USE_ALTIVEC
  95741. # if defined FLAC__SYS_DARWIN
  95742. {
  95743. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95744. size_t len = sizeof(val);
  95745. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95746. }
  95747. {
  95748. host_basic_info_data_t hostInfo;
  95749. mach_msg_type_number_t infoCount;
  95750. infoCount = HOST_BASIC_INFO_COUNT;
  95751. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95752. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95753. }
  95754. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95755. {
  95756. /* no Darwin, do it the brute-force way */
  95757. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95758. info->data.ppc.altivec = 0;
  95759. info->data.ppc.ppc64 = 0;
  95760. signal (SIGILL, sigill_handler);
  95761. canjump = 0;
  95762. if (!sigsetjmp (jmpbuf, 1)) {
  95763. canjump = 1;
  95764. asm volatile (
  95765. "mtspr 256, %0\n\t"
  95766. "vand %%v0, %%v0, %%v0"
  95767. :
  95768. : "r" (-1)
  95769. );
  95770. info->data.ppc.altivec = 1;
  95771. }
  95772. canjump = 0;
  95773. if (!sigsetjmp (jmpbuf, 1)) {
  95774. int x = 0;
  95775. canjump = 1;
  95776. /* PPC64 hardware implements the cntlzd instruction */
  95777. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95778. info->data.ppc.ppc64 = 1;
  95779. }
  95780. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95781. }
  95782. # endif
  95783. # else /* !FLAC__USE_ALTIVEC */
  95784. info->data.ppc.altivec = 0;
  95785. info->data.ppc.ppc64 = 0;
  95786. # endif
  95787. # else
  95788. info->use_asm = false;
  95789. # endif
  95790. /*
  95791. * unknown CPI
  95792. */
  95793. #else
  95794. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95795. info->use_asm = false;
  95796. #endif
  95797. }
  95798. #endif
  95799. /*** End of inlined file: cpu.c ***/
  95800. /*** Start of inlined file: crc.c ***/
  95801. /*** Start of inlined file: juce_FlacHeader.h ***/
  95802. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95803. // tasks..
  95804. #define VERSION "1.2.1"
  95805. #define FLAC__NO_DLL 1
  95806. #if JUCE_MSVC
  95807. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95808. #endif
  95809. #if JUCE_MAC
  95810. #define FLAC__SYS_DARWIN 1
  95811. #endif
  95812. /*** End of inlined file: juce_FlacHeader.h ***/
  95813. #if JUCE_USE_FLAC
  95814. #if HAVE_CONFIG_H
  95815. # include <config.h>
  95816. #endif
  95817. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95818. FLAC__byte const FLAC__crc8_table[256] = {
  95819. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95820. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95821. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95822. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95823. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95824. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95825. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95826. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95827. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95828. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95829. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95830. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95831. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95832. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95833. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95834. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95835. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95836. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95837. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95838. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95839. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95840. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95841. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95842. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95843. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95844. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95845. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95846. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95847. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95848. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95849. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95850. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95851. };
  95852. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95853. unsigned FLAC__crc16_table[256] = {
  95854. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95855. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95856. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95857. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95858. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95859. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95860. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95861. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95862. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95863. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95864. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95865. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95866. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95867. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95868. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95869. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95870. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95871. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95872. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95873. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95874. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95875. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95876. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95877. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95878. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95879. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95880. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95881. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95882. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95883. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95884. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95885. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95886. };
  95887. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95888. {
  95889. *crc = FLAC__crc8_table[*crc ^ data];
  95890. }
  95891. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95892. {
  95893. while(len--)
  95894. *crc = FLAC__crc8_table[*crc ^ *data++];
  95895. }
  95896. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95897. {
  95898. FLAC__uint8 crc = 0;
  95899. while(len--)
  95900. crc = FLAC__crc8_table[crc ^ *data++];
  95901. return crc;
  95902. }
  95903. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95904. {
  95905. unsigned crc = 0;
  95906. while(len--)
  95907. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95908. return crc;
  95909. }
  95910. #endif
  95911. /*** End of inlined file: crc.c ***/
  95912. /*** Start of inlined file: fixed.c ***/
  95913. /*** Start of inlined file: juce_FlacHeader.h ***/
  95914. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95915. // tasks..
  95916. #define VERSION "1.2.1"
  95917. #define FLAC__NO_DLL 1
  95918. #if JUCE_MSVC
  95919. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95920. #endif
  95921. #if JUCE_MAC
  95922. #define FLAC__SYS_DARWIN 1
  95923. #endif
  95924. /*** End of inlined file: juce_FlacHeader.h ***/
  95925. #if JUCE_USE_FLAC
  95926. #if HAVE_CONFIG_H
  95927. # include <config.h>
  95928. #endif
  95929. #include <math.h>
  95930. #include <string.h>
  95931. /*** Start of inlined file: fixed.h ***/
  95932. #ifndef FLAC__PRIVATE__FIXED_H
  95933. #define FLAC__PRIVATE__FIXED_H
  95934. #ifdef HAVE_CONFIG_H
  95935. #include <config.h>
  95936. #endif
  95937. /*** Start of inlined file: float.h ***/
  95938. #ifndef FLAC__PRIVATE__FLOAT_H
  95939. #define FLAC__PRIVATE__FLOAT_H
  95940. #ifdef HAVE_CONFIG_H
  95941. #include <config.h>
  95942. #endif
  95943. /*
  95944. * These typedefs make it easier to ensure that integer versions of
  95945. * the library really only contain integer operations. All the code
  95946. * in libFLAC should use FLAC__float and FLAC__double in place of
  95947. * float and double, and be protected by checks of the macro
  95948. * FLAC__INTEGER_ONLY_LIBRARY.
  95949. *
  95950. * FLAC__real is the basic floating point type used in LPC analysis.
  95951. */
  95952. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95953. typedef double FLAC__double;
  95954. typedef float FLAC__float;
  95955. /*
  95956. * WATCHOUT: changing FLAC__real will change the signatures of many
  95957. * functions that have assembly language equivalents and break them.
  95958. */
  95959. typedef float FLAC__real;
  95960. #else
  95961. /*
  95962. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95963. * for the integer part and lower 16 bits for the fractional part.
  95964. */
  95965. typedef FLAC__int32 FLAC__fixedpoint;
  95966. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95967. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95968. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95969. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95970. extern const FLAC__fixedpoint FLAC__FP_E;
  95971. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95972. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95973. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95974. /*
  95975. * FLAC__fixedpoint_log2()
  95976. * --------------------------------------------------------------------
  95977. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95978. * algorithm by Knuth for x >= 1.0
  95979. *
  95980. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95981. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95982. *
  95983. * 'precision' roughly limits the number of iterations that are done;
  95984. * use (unsigned)(-1) for maximum precision.
  95985. *
  95986. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95987. * function will punt and return 0.
  95988. *
  95989. * The return value will also have 'fracbits' fractional bits.
  95990. */
  95991. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95992. #endif
  95993. #endif
  95994. /*** End of inlined file: float.h ***/
  95995. /*** Start of inlined file: format.h ***/
  95996. #ifndef FLAC__PRIVATE__FORMAT_H
  95997. #define FLAC__PRIVATE__FORMAT_H
  95998. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95999. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  96000. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  96001. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  96002. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  96003. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  96004. #endif
  96005. /*** End of inlined file: format.h ***/
  96006. /*
  96007. * FLAC__fixed_compute_best_predictor()
  96008. * --------------------------------------------------------------------
  96009. * Compute the best fixed predictor and the expected bits-per-sample
  96010. * of the residual signal for each order. The _wide() version uses
  96011. * 64-bit integers which is statistically necessary when bits-per-
  96012. * sample + log2(blocksize) > 30
  96013. *
  96014. * IN data[0,data_len-1]
  96015. * IN data_len
  96016. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  96017. */
  96018. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96019. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96020. # ifndef FLAC__NO_ASM
  96021. # ifdef FLAC__CPU_IA32
  96022. # ifdef FLAC__HAS_NASM
  96023. 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]);
  96024. # endif
  96025. # endif
  96026. # endif
  96027. 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]);
  96028. #else
  96029. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96030. 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]);
  96031. #endif
  96032. /*
  96033. * FLAC__fixed_compute_residual()
  96034. * --------------------------------------------------------------------
  96035. * Compute the residual signal obtained from sutracting the predicted
  96036. * signal from the original.
  96037. *
  96038. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96039. * IN data_len length of original signal
  96040. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96041. * OUT residual[0,data_len-1] residual signal
  96042. */
  96043. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  96044. /*
  96045. * FLAC__fixed_restore_signal()
  96046. * --------------------------------------------------------------------
  96047. * Restore the original signal by summing the residual and the
  96048. * predictor.
  96049. *
  96050. * IN residual[0,data_len-1] residual signal
  96051. * IN data_len length of original signal
  96052. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96053. * *** IMPORTANT: the caller must pass in the historical samples:
  96054. * IN data[-order,-1] previously-reconstructed historical samples
  96055. * OUT data[0,data_len-1] original signal
  96056. */
  96057. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96058. #endif
  96059. /*** End of inlined file: fixed.h ***/
  96060. #ifndef M_LN2
  96061. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96062. #define M_LN2 0.69314718055994530942
  96063. #endif
  96064. #ifdef min
  96065. #undef min
  96066. #endif
  96067. #define min(x,y) ((x) < (y)? (x) : (y))
  96068. #ifdef local_abs
  96069. #undef local_abs
  96070. #endif
  96071. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96072. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96073. /* rbps stands for residual bits per sample
  96074. *
  96075. * (ln(2) * err)
  96076. * rbps = log (-----------)
  96077. * 2 ( n )
  96078. */
  96079. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96080. {
  96081. FLAC__uint32 rbps;
  96082. unsigned bits; /* the number of bits required to represent a number */
  96083. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96084. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96085. FLAC__ASSERT(err > 0);
  96086. FLAC__ASSERT(n > 0);
  96087. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96088. if(err <= n)
  96089. return 0;
  96090. /*
  96091. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96092. * These allow us later to know we won't lose too much precision in the
  96093. * fixed-point division (err<<fracbits)/n.
  96094. */
  96095. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96096. err <<= fracbits;
  96097. err /= n;
  96098. /* err now holds err/n with fracbits fractional bits */
  96099. /*
  96100. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96101. * our purposes.
  96102. */
  96103. FLAC__ASSERT(err > 0);
  96104. bits = FLAC__bitmath_ilog2(err)+1;
  96105. if(bits > 16) {
  96106. err >>= (bits-16);
  96107. fracbits -= (bits-16);
  96108. }
  96109. rbps = (FLAC__uint32)err;
  96110. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96111. rbps *= FLAC__FP_LN2;
  96112. fracbits += 16;
  96113. FLAC__ASSERT(fracbits >= 0);
  96114. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96115. {
  96116. const int f = fracbits & 3;
  96117. if(f) {
  96118. rbps >>= f;
  96119. fracbits -= f;
  96120. }
  96121. }
  96122. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96123. if(rbps == 0)
  96124. return 0;
  96125. /*
  96126. * The return value must have 16 fractional bits. Since the whole part
  96127. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96128. * must be >= -3, these assertion allows us to be able to shift rbps
  96129. * left if necessary to get 16 fracbits without losing any bits of the
  96130. * whole part of rbps.
  96131. *
  96132. * There is a slight chance due to accumulated error that the whole part
  96133. * will require 6 bits, so we use 6 in the assertion. Really though as
  96134. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96135. */
  96136. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96137. FLAC__ASSERT(fracbits >= -3);
  96138. /* now shift the decimal point into place */
  96139. if(fracbits < 16)
  96140. return rbps << (16-fracbits);
  96141. else if(fracbits > 16)
  96142. return rbps >> (fracbits-16);
  96143. else
  96144. return rbps;
  96145. }
  96146. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96147. {
  96148. FLAC__uint32 rbps;
  96149. unsigned bits; /* the number of bits required to represent a number */
  96150. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96151. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96152. FLAC__ASSERT(err > 0);
  96153. FLAC__ASSERT(n > 0);
  96154. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96155. if(err <= n)
  96156. return 0;
  96157. /*
  96158. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96159. * These allow us later to know we won't lose too much precision in the
  96160. * fixed-point division (err<<fracbits)/n.
  96161. */
  96162. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96163. err <<= fracbits;
  96164. err /= n;
  96165. /* err now holds err/n with fracbits fractional bits */
  96166. /*
  96167. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96168. * our purposes.
  96169. */
  96170. FLAC__ASSERT(err > 0);
  96171. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96172. if(bits > 16) {
  96173. err >>= (bits-16);
  96174. fracbits -= (bits-16);
  96175. }
  96176. rbps = (FLAC__uint32)err;
  96177. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96178. rbps *= FLAC__FP_LN2;
  96179. fracbits += 16;
  96180. FLAC__ASSERT(fracbits >= 0);
  96181. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96182. {
  96183. const int f = fracbits & 3;
  96184. if(f) {
  96185. rbps >>= f;
  96186. fracbits -= f;
  96187. }
  96188. }
  96189. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96190. if(rbps == 0)
  96191. return 0;
  96192. /*
  96193. * The return value must have 16 fractional bits. Since the whole part
  96194. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96195. * must be >= -3, these assertion allows us to be able to shift rbps
  96196. * left if necessary to get 16 fracbits without losing any bits of the
  96197. * whole part of rbps.
  96198. *
  96199. * There is a slight chance due to accumulated error that the whole part
  96200. * will require 6 bits, so we use 6 in the assertion. Really though as
  96201. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96202. */
  96203. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96204. FLAC__ASSERT(fracbits >= -3);
  96205. /* now shift the decimal point into place */
  96206. if(fracbits < 16)
  96207. return rbps << (16-fracbits);
  96208. else if(fracbits > 16)
  96209. return rbps >> (fracbits-16);
  96210. else
  96211. return rbps;
  96212. }
  96213. #endif
  96214. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96215. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96216. #else
  96217. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96218. #endif
  96219. {
  96220. FLAC__int32 last_error_0 = data[-1];
  96221. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96222. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96223. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96224. FLAC__int32 error, save;
  96225. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96226. unsigned i, order;
  96227. for(i = 0; i < data_len; i++) {
  96228. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96229. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96230. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96231. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96232. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96233. }
  96234. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96235. order = 0;
  96236. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96237. order = 1;
  96238. else if(total_error_2 < min(total_error_3, total_error_4))
  96239. order = 2;
  96240. else if(total_error_3 < total_error_4)
  96241. order = 3;
  96242. else
  96243. order = 4;
  96244. /* Estimate the expected number of bits per residual signal sample. */
  96245. /* 'total_error*' is linearly related to the variance of the residual */
  96246. /* signal, so we use it directly to compute E(|x|) */
  96247. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96248. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96249. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96250. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96251. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96252. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96253. 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);
  96254. 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);
  96255. 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);
  96256. 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);
  96257. 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);
  96258. #else
  96259. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96260. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96261. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96262. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96263. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96264. #endif
  96265. return order;
  96266. }
  96267. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96268. 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])
  96269. #else
  96270. 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])
  96271. #endif
  96272. {
  96273. FLAC__int32 last_error_0 = data[-1];
  96274. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96275. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96276. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96277. FLAC__int32 error, save;
  96278. /* total_error_* are 64-bits to avoid overflow when encoding
  96279. * erratic signals when the bits-per-sample and blocksize are
  96280. * large.
  96281. */
  96282. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96283. unsigned i, order;
  96284. for(i = 0; i < data_len; i++) {
  96285. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96286. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96287. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96288. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96289. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96290. }
  96291. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96292. order = 0;
  96293. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96294. order = 1;
  96295. else if(total_error_2 < min(total_error_3, total_error_4))
  96296. order = 2;
  96297. else if(total_error_3 < total_error_4)
  96298. order = 3;
  96299. else
  96300. order = 4;
  96301. /* Estimate the expected number of bits per residual signal sample. */
  96302. /* 'total_error*' is linearly related to the variance of the residual */
  96303. /* signal, so we use it directly to compute E(|x|) */
  96304. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96305. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96306. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96307. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96308. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96309. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96310. #if defined _MSC_VER || defined __MINGW32__
  96311. /* with MSVC you have to spoon feed it the casting */
  96312. 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);
  96313. 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);
  96314. 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);
  96315. 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);
  96316. 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);
  96317. #else
  96318. 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);
  96319. 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);
  96320. 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);
  96321. 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);
  96322. 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);
  96323. #endif
  96324. #else
  96325. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96326. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96327. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96328. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96329. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96330. #endif
  96331. return order;
  96332. }
  96333. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96334. {
  96335. const int idata_len = (int)data_len;
  96336. int i;
  96337. switch(order) {
  96338. case 0:
  96339. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96340. memcpy(residual, data, sizeof(residual[0])*data_len);
  96341. break;
  96342. case 1:
  96343. for(i = 0; i < idata_len; i++)
  96344. residual[i] = data[i] - data[i-1];
  96345. break;
  96346. case 2:
  96347. for(i = 0; i < idata_len; i++)
  96348. #if 1 /* OPT: may be faster with some compilers on some systems */
  96349. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96350. #else
  96351. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96352. #endif
  96353. break;
  96354. case 3:
  96355. for(i = 0; i < idata_len; i++)
  96356. #if 1 /* OPT: may be faster with some compilers on some systems */
  96357. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96358. #else
  96359. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96360. #endif
  96361. break;
  96362. case 4:
  96363. for(i = 0; i < idata_len; i++)
  96364. #if 1 /* OPT: may be faster with some compilers on some systems */
  96365. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96366. #else
  96367. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96368. #endif
  96369. break;
  96370. default:
  96371. FLAC__ASSERT(0);
  96372. }
  96373. }
  96374. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96375. {
  96376. int i, idata_len = (int)data_len;
  96377. switch(order) {
  96378. case 0:
  96379. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96380. memcpy(data, residual, sizeof(residual[0])*data_len);
  96381. break;
  96382. case 1:
  96383. for(i = 0; i < idata_len; i++)
  96384. data[i] = residual[i] + data[i-1];
  96385. break;
  96386. case 2:
  96387. for(i = 0; i < idata_len; i++)
  96388. #if 1 /* OPT: may be faster with some compilers on some systems */
  96389. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96390. #else
  96391. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96392. #endif
  96393. break;
  96394. case 3:
  96395. for(i = 0; i < idata_len; i++)
  96396. #if 1 /* OPT: may be faster with some compilers on some systems */
  96397. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96398. #else
  96399. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96400. #endif
  96401. break;
  96402. case 4:
  96403. for(i = 0; i < idata_len; i++)
  96404. #if 1 /* OPT: may be faster with some compilers on some systems */
  96405. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96406. #else
  96407. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96408. #endif
  96409. break;
  96410. default:
  96411. FLAC__ASSERT(0);
  96412. }
  96413. }
  96414. #endif
  96415. /*** End of inlined file: fixed.c ***/
  96416. /*** Start of inlined file: float.c ***/
  96417. /*** Start of inlined file: juce_FlacHeader.h ***/
  96418. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96419. // tasks..
  96420. #define VERSION "1.2.1"
  96421. #define FLAC__NO_DLL 1
  96422. #if JUCE_MSVC
  96423. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96424. #endif
  96425. #if JUCE_MAC
  96426. #define FLAC__SYS_DARWIN 1
  96427. #endif
  96428. /*** End of inlined file: juce_FlacHeader.h ***/
  96429. #if JUCE_USE_FLAC
  96430. #if HAVE_CONFIG_H
  96431. # include <config.h>
  96432. #endif
  96433. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96434. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96435. #ifdef _MSC_VER
  96436. #define FLAC__U64L(x) x
  96437. #else
  96438. #define FLAC__U64L(x) x##LLU
  96439. #endif
  96440. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96441. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96442. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96443. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96444. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96445. /* Lookup tables for Knuth's logarithm algorithm */
  96446. #define LOG2_LOOKUP_PRECISION 16
  96447. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96448. {
  96449. /*
  96450. * 0 fraction bits
  96451. */
  96452. /* undefined */ 0x00000000,
  96453. /* lg(2/1) = */ 0x00000001,
  96454. /* lg(4/3) = */ 0x00000000,
  96455. /* lg(8/7) = */ 0x00000000,
  96456. /* lg(16/15) = */ 0x00000000,
  96457. /* lg(32/31) = */ 0x00000000,
  96458. /* lg(64/63) = */ 0x00000000,
  96459. /* lg(128/127) = */ 0x00000000,
  96460. /* lg(256/255) = */ 0x00000000,
  96461. /* lg(512/511) = */ 0x00000000,
  96462. /* lg(1024/1023) = */ 0x00000000,
  96463. /* lg(2048/2047) = */ 0x00000000,
  96464. /* lg(4096/4095) = */ 0x00000000,
  96465. /* lg(8192/8191) = */ 0x00000000,
  96466. /* lg(16384/16383) = */ 0x00000000,
  96467. /* lg(32768/32767) = */ 0x00000000
  96468. },
  96469. {
  96470. /*
  96471. * 4 fraction bits
  96472. */
  96473. /* undefined */ 0x00000000,
  96474. /* lg(2/1) = */ 0x00000010,
  96475. /* lg(4/3) = */ 0x00000007,
  96476. /* lg(8/7) = */ 0x00000003,
  96477. /* lg(16/15) = */ 0x00000001,
  96478. /* lg(32/31) = */ 0x00000001,
  96479. /* lg(64/63) = */ 0x00000000,
  96480. /* lg(128/127) = */ 0x00000000,
  96481. /* lg(256/255) = */ 0x00000000,
  96482. /* lg(512/511) = */ 0x00000000,
  96483. /* lg(1024/1023) = */ 0x00000000,
  96484. /* lg(2048/2047) = */ 0x00000000,
  96485. /* lg(4096/4095) = */ 0x00000000,
  96486. /* lg(8192/8191) = */ 0x00000000,
  96487. /* lg(16384/16383) = */ 0x00000000,
  96488. /* lg(32768/32767) = */ 0x00000000
  96489. },
  96490. {
  96491. /*
  96492. * 8 fraction bits
  96493. */
  96494. /* undefined */ 0x00000000,
  96495. /* lg(2/1) = */ 0x00000100,
  96496. /* lg(4/3) = */ 0x0000006a,
  96497. /* lg(8/7) = */ 0x00000031,
  96498. /* lg(16/15) = */ 0x00000018,
  96499. /* lg(32/31) = */ 0x0000000c,
  96500. /* lg(64/63) = */ 0x00000006,
  96501. /* lg(128/127) = */ 0x00000003,
  96502. /* lg(256/255) = */ 0x00000001,
  96503. /* lg(512/511) = */ 0x00000001,
  96504. /* lg(1024/1023) = */ 0x00000000,
  96505. /* lg(2048/2047) = */ 0x00000000,
  96506. /* lg(4096/4095) = */ 0x00000000,
  96507. /* lg(8192/8191) = */ 0x00000000,
  96508. /* lg(16384/16383) = */ 0x00000000,
  96509. /* lg(32768/32767) = */ 0x00000000
  96510. },
  96511. {
  96512. /*
  96513. * 12 fraction bits
  96514. */
  96515. /* undefined */ 0x00000000,
  96516. /* lg(2/1) = */ 0x00001000,
  96517. /* lg(4/3) = */ 0x000006a4,
  96518. /* lg(8/7) = */ 0x00000315,
  96519. /* lg(16/15) = */ 0x0000017d,
  96520. /* lg(32/31) = */ 0x000000bc,
  96521. /* lg(64/63) = */ 0x0000005d,
  96522. /* lg(128/127) = */ 0x0000002e,
  96523. /* lg(256/255) = */ 0x00000017,
  96524. /* lg(512/511) = */ 0x0000000c,
  96525. /* lg(1024/1023) = */ 0x00000006,
  96526. /* lg(2048/2047) = */ 0x00000003,
  96527. /* lg(4096/4095) = */ 0x00000001,
  96528. /* lg(8192/8191) = */ 0x00000001,
  96529. /* lg(16384/16383) = */ 0x00000000,
  96530. /* lg(32768/32767) = */ 0x00000000
  96531. },
  96532. {
  96533. /*
  96534. * 16 fraction bits
  96535. */
  96536. /* undefined */ 0x00000000,
  96537. /* lg(2/1) = */ 0x00010000,
  96538. /* lg(4/3) = */ 0x00006a40,
  96539. /* lg(8/7) = */ 0x00003151,
  96540. /* lg(16/15) = */ 0x000017d6,
  96541. /* lg(32/31) = */ 0x00000bba,
  96542. /* lg(64/63) = */ 0x000005d1,
  96543. /* lg(128/127) = */ 0x000002e6,
  96544. /* lg(256/255) = */ 0x00000172,
  96545. /* lg(512/511) = */ 0x000000b9,
  96546. /* lg(1024/1023) = */ 0x0000005c,
  96547. /* lg(2048/2047) = */ 0x0000002e,
  96548. /* lg(4096/4095) = */ 0x00000017,
  96549. /* lg(8192/8191) = */ 0x0000000c,
  96550. /* lg(16384/16383) = */ 0x00000006,
  96551. /* lg(32768/32767) = */ 0x00000003
  96552. },
  96553. {
  96554. /*
  96555. * 20 fraction bits
  96556. */
  96557. /* undefined */ 0x00000000,
  96558. /* lg(2/1) = */ 0x00100000,
  96559. /* lg(4/3) = */ 0x0006a3fe,
  96560. /* lg(8/7) = */ 0x00031513,
  96561. /* lg(16/15) = */ 0x00017d60,
  96562. /* lg(32/31) = */ 0x0000bb9d,
  96563. /* lg(64/63) = */ 0x00005d10,
  96564. /* lg(128/127) = */ 0x00002e59,
  96565. /* lg(256/255) = */ 0x00001721,
  96566. /* lg(512/511) = */ 0x00000b8e,
  96567. /* lg(1024/1023) = */ 0x000005c6,
  96568. /* lg(2048/2047) = */ 0x000002e3,
  96569. /* lg(4096/4095) = */ 0x00000171,
  96570. /* lg(8192/8191) = */ 0x000000b9,
  96571. /* lg(16384/16383) = */ 0x0000005c,
  96572. /* lg(32768/32767) = */ 0x0000002e
  96573. },
  96574. {
  96575. /*
  96576. * 24 fraction bits
  96577. */
  96578. /* undefined */ 0x00000000,
  96579. /* lg(2/1) = */ 0x01000000,
  96580. /* lg(4/3) = */ 0x006a3fe6,
  96581. /* lg(8/7) = */ 0x00315130,
  96582. /* lg(16/15) = */ 0x0017d605,
  96583. /* lg(32/31) = */ 0x000bb9ca,
  96584. /* lg(64/63) = */ 0x0005d0fc,
  96585. /* lg(128/127) = */ 0x0002e58f,
  96586. /* lg(256/255) = */ 0x0001720e,
  96587. /* lg(512/511) = */ 0x0000b8d8,
  96588. /* lg(1024/1023) = */ 0x00005c61,
  96589. /* lg(2048/2047) = */ 0x00002e2d,
  96590. /* lg(4096/4095) = */ 0x00001716,
  96591. /* lg(8192/8191) = */ 0x00000b8b,
  96592. /* lg(16384/16383) = */ 0x000005c5,
  96593. /* lg(32768/32767) = */ 0x000002e3
  96594. },
  96595. {
  96596. /*
  96597. * 28 fraction bits
  96598. */
  96599. /* undefined */ 0x00000000,
  96600. /* lg(2/1) = */ 0x10000000,
  96601. /* lg(4/3) = */ 0x06a3fe5c,
  96602. /* lg(8/7) = */ 0x03151301,
  96603. /* lg(16/15) = */ 0x017d6049,
  96604. /* lg(32/31) = */ 0x00bb9ca6,
  96605. /* lg(64/63) = */ 0x005d0fba,
  96606. /* lg(128/127) = */ 0x002e58f7,
  96607. /* lg(256/255) = */ 0x001720da,
  96608. /* lg(512/511) = */ 0x000b8d87,
  96609. /* lg(1024/1023) = */ 0x0005c60b,
  96610. /* lg(2048/2047) = */ 0x0002e2d7,
  96611. /* lg(4096/4095) = */ 0x00017160,
  96612. /* lg(8192/8191) = */ 0x0000b8ad,
  96613. /* lg(16384/16383) = */ 0x00005c56,
  96614. /* lg(32768/32767) = */ 0x00002e2b
  96615. }
  96616. };
  96617. #if 0
  96618. static const FLAC__uint64 log2_lookup_wide[] = {
  96619. {
  96620. /*
  96621. * 32 fraction bits
  96622. */
  96623. /* undefined */ 0x00000000,
  96624. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96625. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96626. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96627. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96628. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96629. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96630. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96631. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96632. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96633. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96634. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96635. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96636. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96637. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96638. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96639. },
  96640. {
  96641. /*
  96642. * 48 fraction bits
  96643. */
  96644. /* undefined */ 0x00000000,
  96645. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96646. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96647. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96648. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96649. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96650. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96651. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96652. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96653. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96654. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96655. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96656. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96657. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96658. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96659. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96660. }
  96661. };
  96662. #endif
  96663. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96664. {
  96665. const FLAC__uint32 ONE = (1u << fracbits);
  96666. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96667. FLAC__ASSERT(fracbits < 32);
  96668. FLAC__ASSERT((fracbits & 0x3) == 0);
  96669. if(x < ONE)
  96670. return 0;
  96671. if(precision > LOG2_LOOKUP_PRECISION)
  96672. precision = LOG2_LOOKUP_PRECISION;
  96673. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96674. {
  96675. FLAC__uint32 y = 0;
  96676. FLAC__uint32 z = x >> 1, k = 1;
  96677. while (x > ONE && k < precision) {
  96678. if (x - z >= ONE) {
  96679. x -= z;
  96680. z = x >> k;
  96681. y += table[k];
  96682. }
  96683. else {
  96684. z >>= 1;
  96685. k++;
  96686. }
  96687. }
  96688. return y;
  96689. }
  96690. }
  96691. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96692. #endif
  96693. /*** End of inlined file: float.c ***/
  96694. /*** Start of inlined file: format.c ***/
  96695. /*** Start of inlined file: juce_FlacHeader.h ***/
  96696. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96697. // tasks..
  96698. #define VERSION "1.2.1"
  96699. #define FLAC__NO_DLL 1
  96700. #if JUCE_MSVC
  96701. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96702. #endif
  96703. #if JUCE_MAC
  96704. #define FLAC__SYS_DARWIN 1
  96705. #endif
  96706. /*** End of inlined file: juce_FlacHeader.h ***/
  96707. #if JUCE_USE_FLAC
  96708. #if HAVE_CONFIG_H
  96709. # include <config.h>
  96710. #endif
  96711. #include <stdio.h>
  96712. #include <stdlib.h> /* for qsort() */
  96713. #include <string.h> /* for memset() */
  96714. #ifndef FLaC__INLINE
  96715. #define FLaC__INLINE
  96716. #endif
  96717. #ifdef min
  96718. #undef min
  96719. #endif
  96720. #define min(a,b) ((a)<(b)?(a):(b))
  96721. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96722. #ifdef _MSC_VER
  96723. #define FLAC__U64L(x) x
  96724. #else
  96725. #define FLAC__U64L(x) x##LLU
  96726. #endif
  96727. /* VERSION should come from configure */
  96728. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96729. ;
  96730. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96731. /* yet one more hack because of MSVC6: */
  96732. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96733. #else
  96734. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96735. #endif
  96736. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96737. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96738. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96739. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96740. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96741. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96742. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96743. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96744. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96745. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96746. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96747. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96748. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96749. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96750. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96751. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96752. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96753. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96754. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96755. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96756. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96757. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96758. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96759. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96760. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96761. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96762. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96763. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96764. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96765. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96766. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96767. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96768. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96769. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96770. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96771. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96772. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96773. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96774. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96775. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96776. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96777. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96778. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96779. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96780. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96781. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96782. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96783. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96784. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96785. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96786. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96787. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96788. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96789. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96790. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96791. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96792. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96793. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96794. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96795. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96796. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96797. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96798. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96799. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96800. "PARTITIONED_RICE",
  96801. "PARTITIONED_RICE2"
  96802. };
  96803. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96804. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96805. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96806. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96807. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96808. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96809. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96810. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96811. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96812. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96813. "CONSTANT",
  96814. "VERBATIM",
  96815. "FIXED",
  96816. "LPC"
  96817. };
  96818. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96819. "INDEPENDENT",
  96820. "LEFT_SIDE",
  96821. "RIGHT_SIDE",
  96822. "MID_SIDE"
  96823. };
  96824. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96825. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96826. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96827. };
  96828. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96829. "STREAMINFO",
  96830. "PADDING",
  96831. "APPLICATION",
  96832. "SEEKTABLE",
  96833. "VORBIS_COMMENT",
  96834. "CUESHEET",
  96835. "PICTURE"
  96836. };
  96837. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96838. "Other",
  96839. "32x32 pixels 'file icon' (PNG only)",
  96840. "Other file icon",
  96841. "Cover (front)",
  96842. "Cover (back)",
  96843. "Leaflet page",
  96844. "Media (e.g. label side of CD)",
  96845. "Lead artist/lead performer/soloist",
  96846. "Artist/performer",
  96847. "Conductor",
  96848. "Band/Orchestra",
  96849. "Composer",
  96850. "Lyricist/text writer",
  96851. "Recording Location",
  96852. "During recording",
  96853. "During performance",
  96854. "Movie/video screen capture",
  96855. "A bright coloured fish",
  96856. "Illustration",
  96857. "Band/artist logotype",
  96858. "Publisher/Studio logotype"
  96859. };
  96860. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96861. {
  96862. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96863. return false;
  96864. }
  96865. else
  96866. return true;
  96867. }
  96868. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96869. {
  96870. if(
  96871. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96872. (
  96873. sample_rate >= (1u << 16) &&
  96874. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96875. )
  96876. ) {
  96877. return false;
  96878. }
  96879. else
  96880. return true;
  96881. }
  96882. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96883. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96884. {
  96885. unsigned i;
  96886. FLAC__uint64 prev_sample_number = 0;
  96887. FLAC__bool got_prev = false;
  96888. FLAC__ASSERT(0 != seek_table);
  96889. for(i = 0; i < seek_table->num_points; i++) {
  96890. if(got_prev) {
  96891. if(
  96892. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96893. seek_table->points[i].sample_number <= prev_sample_number
  96894. )
  96895. return false;
  96896. }
  96897. prev_sample_number = seek_table->points[i].sample_number;
  96898. got_prev = true;
  96899. }
  96900. return true;
  96901. }
  96902. /* used as the sort predicate for qsort() */
  96903. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96904. {
  96905. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96906. if(l->sample_number == r->sample_number)
  96907. return 0;
  96908. else if(l->sample_number < r->sample_number)
  96909. return -1;
  96910. else
  96911. return 1;
  96912. }
  96913. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96914. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96915. {
  96916. unsigned i, j;
  96917. FLAC__bool first;
  96918. FLAC__ASSERT(0 != seek_table);
  96919. /* sort the seekpoints */
  96920. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96921. /* uniquify the seekpoints */
  96922. first = true;
  96923. for(i = j = 0; i < seek_table->num_points; i++) {
  96924. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96925. if(!first) {
  96926. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96927. continue;
  96928. }
  96929. }
  96930. first = false;
  96931. seek_table->points[j++] = seek_table->points[i];
  96932. }
  96933. for(i = j; i < seek_table->num_points; i++) {
  96934. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96935. seek_table->points[i].stream_offset = 0;
  96936. seek_table->points[i].frame_samples = 0;
  96937. }
  96938. return j;
  96939. }
  96940. /*
  96941. * also disallows non-shortest-form encodings, c.f.
  96942. * http://www.unicode.org/versions/corrigendum1.html
  96943. * and a more clear explanation at the end of this section:
  96944. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96945. */
  96946. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96947. {
  96948. FLAC__ASSERT(0 != utf8);
  96949. if ((utf8[0] & 0x80) == 0) {
  96950. return 1;
  96951. }
  96952. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96953. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96954. return 0;
  96955. return 2;
  96956. }
  96957. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96958. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96959. return 0;
  96960. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96961. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96962. return 0;
  96963. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96964. return 0;
  96965. return 3;
  96966. }
  96967. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96968. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96969. return 0;
  96970. return 4;
  96971. }
  96972. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96973. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96974. return 0;
  96975. return 5;
  96976. }
  96977. 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) {
  96978. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96979. return 0;
  96980. return 6;
  96981. }
  96982. else {
  96983. return 0;
  96984. }
  96985. }
  96986. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96987. {
  96988. char c;
  96989. for(c = *name; c; c = *(++name))
  96990. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96991. return false;
  96992. return true;
  96993. }
  96994. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96995. {
  96996. if(length == (unsigned)(-1)) {
  96997. while(*value) {
  96998. unsigned n = utf8len_(value);
  96999. if(n == 0)
  97000. return false;
  97001. value += n;
  97002. }
  97003. }
  97004. else {
  97005. const FLAC__byte *end = value + length;
  97006. while(value < end) {
  97007. unsigned n = utf8len_(value);
  97008. if(n == 0)
  97009. return false;
  97010. value += n;
  97011. }
  97012. if(value != end)
  97013. return false;
  97014. }
  97015. return true;
  97016. }
  97017. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  97018. {
  97019. const FLAC__byte *s, *end;
  97020. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  97021. if(*s < 0x20 || *s > 0x7D)
  97022. return false;
  97023. }
  97024. if(s == end)
  97025. return false;
  97026. s++; /* skip '=' */
  97027. while(s < end) {
  97028. unsigned n = utf8len_(s);
  97029. if(n == 0)
  97030. return false;
  97031. s += n;
  97032. }
  97033. if(s != end)
  97034. return false;
  97035. return true;
  97036. }
  97037. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97038. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  97039. {
  97040. unsigned i, j;
  97041. if(check_cd_da_subset) {
  97042. if(cue_sheet->lead_in < 2 * 44100) {
  97043. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  97044. return false;
  97045. }
  97046. if(cue_sheet->lead_in % 588 != 0) {
  97047. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  97048. return false;
  97049. }
  97050. }
  97051. if(cue_sheet->num_tracks == 0) {
  97052. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97053. return false;
  97054. }
  97055. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97056. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97057. return false;
  97058. }
  97059. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97060. if(cue_sheet->tracks[i].number == 0) {
  97061. if(violation) *violation = "cue sheet may not have a track number 0";
  97062. return false;
  97063. }
  97064. if(check_cd_da_subset) {
  97065. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97066. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97067. return false;
  97068. }
  97069. }
  97070. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97071. if(violation) {
  97072. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97073. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97074. else
  97075. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97076. }
  97077. return false;
  97078. }
  97079. if(i < cue_sheet->num_tracks - 1) {
  97080. if(cue_sheet->tracks[i].num_indices == 0) {
  97081. if(violation) *violation = "cue sheet track must have at least one index point";
  97082. return false;
  97083. }
  97084. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97085. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97086. return false;
  97087. }
  97088. }
  97089. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97090. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97091. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97092. return false;
  97093. }
  97094. if(j > 0) {
  97095. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97096. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97097. return false;
  97098. }
  97099. }
  97100. }
  97101. }
  97102. return true;
  97103. }
  97104. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97105. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97106. {
  97107. char *p;
  97108. FLAC__byte *b;
  97109. for(p = picture->mime_type; *p; p++) {
  97110. if(*p < 0x20 || *p > 0x7e) {
  97111. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97112. return false;
  97113. }
  97114. }
  97115. for(b = picture->description; *b; ) {
  97116. unsigned n = utf8len_(b);
  97117. if(n == 0) {
  97118. if(violation) *violation = "description string must be valid UTF-8";
  97119. return false;
  97120. }
  97121. b += n;
  97122. }
  97123. return true;
  97124. }
  97125. /*
  97126. * These routines are private to libFLAC
  97127. */
  97128. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97129. {
  97130. return
  97131. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97132. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97133. blocksize,
  97134. predictor_order
  97135. );
  97136. }
  97137. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97138. {
  97139. unsigned max_rice_partition_order = 0;
  97140. while(!(blocksize & 1)) {
  97141. max_rice_partition_order++;
  97142. blocksize >>= 1;
  97143. }
  97144. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97145. }
  97146. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97147. {
  97148. unsigned max_rice_partition_order = limit;
  97149. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97150. max_rice_partition_order--;
  97151. FLAC__ASSERT(
  97152. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97153. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97154. );
  97155. return max_rice_partition_order;
  97156. }
  97157. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97158. {
  97159. FLAC__ASSERT(0 != object);
  97160. object->parameters = 0;
  97161. object->raw_bits = 0;
  97162. object->capacity_by_order = 0;
  97163. }
  97164. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97165. {
  97166. FLAC__ASSERT(0 != object);
  97167. if(0 != object->parameters)
  97168. free(object->parameters);
  97169. if(0 != object->raw_bits)
  97170. free(object->raw_bits);
  97171. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97172. }
  97173. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97174. {
  97175. FLAC__ASSERT(0 != object);
  97176. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97177. if(object->capacity_by_order < max_partition_order) {
  97178. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97179. return false;
  97180. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97181. return false;
  97182. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97183. object->capacity_by_order = max_partition_order;
  97184. }
  97185. return true;
  97186. }
  97187. #endif
  97188. /*** End of inlined file: format.c ***/
  97189. /*** Start of inlined file: lpc_flac.c ***/
  97190. /*** Start of inlined file: juce_FlacHeader.h ***/
  97191. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97192. // tasks..
  97193. #define VERSION "1.2.1"
  97194. #define FLAC__NO_DLL 1
  97195. #if JUCE_MSVC
  97196. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97197. #endif
  97198. #if JUCE_MAC
  97199. #define FLAC__SYS_DARWIN 1
  97200. #endif
  97201. /*** End of inlined file: juce_FlacHeader.h ***/
  97202. #if JUCE_USE_FLAC
  97203. #if HAVE_CONFIG_H
  97204. # include <config.h>
  97205. #endif
  97206. #include <math.h>
  97207. /*** Start of inlined file: lpc.h ***/
  97208. #ifndef FLAC__PRIVATE__LPC_H
  97209. #define FLAC__PRIVATE__LPC_H
  97210. #ifdef HAVE_CONFIG_H
  97211. #include <config.h>
  97212. #endif
  97213. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97214. /*
  97215. * FLAC__lpc_window_data()
  97216. * --------------------------------------------------------------------
  97217. * Applies the given window to the data.
  97218. * OPT: asm implementation
  97219. *
  97220. * IN in[0,data_len-1]
  97221. * IN window[0,data_len-1]
  97222. * OUT out[0,lag-1]
  97223. * IN data_len
  97224. */
  97225. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97226. /*
  97227. * FLAC__lpc_compute_autocorrelation()
  97228. * --------------------------------------------------------------------
  97229. * Compute the autocorrelation for lags between 0 and lag-1.
  97230. * Assumes data[] outside of [0,data_len-1] == 0.
  97231. * Asserts that lag > 0.
  97232. *
  97233. * IN data[0,data_len-1]
  97234. * IN data_len
  97235. * IN 0 < lag <= data_len
  97236. * OUT autoc[0,lag-1]
  97237. */
  97238. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97239. #ifndef FLAC__NO_ASM
  97240. # ifdef FLAC__CPU_IA32
  97241. # ifdef FLAC__HAS_NASM
  97242. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97243. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97244. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97245. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97246. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97247. # endif
  97248. # endif
  97249. #endif
  97250. /*
  97251. * FLAC__lpc_compute_lp_coefficients()
  97252. * --------------------------------------------------------------------
  97253. * Computes LP coefficients for orders 1..max_order.
  97254. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97255. * and there is no point in calculating a predictor.
  97256. *
  97257. * IN autoc[0,max_order] autocorrelation values
  97258. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97259. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97260. * *** IMPORTANT:
  97261. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97262. * OUT error[0,max_order-1] error for each order (more
  97263. * specifically, the variance of
  97264. * the error signal times # of
  97265. * samples in the signal)
  97266. *
  97267. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97268. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97269. * in lp_coeff[7][0,7], etc.
  97270. */
  97271. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97272. /*
  97273. * FLAC__lpc_quantize_coefficients()
  97274. * --------------------------------------------------------------------
  97275. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97276. * must be less than 32 (sizeof(FLAC__int32)*8).
  97277. *
  97278. * IN lp_coeff[0,order-1] LP coefficients
  97279. * IN order LP order
  97280. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97281. * desired precision (in bits, including sign
  97282. * bit) of largest coefficient
  97283. * OUT qlp_coeff[0,order-1] quantized coefficients
  97284. * OUT shift # of bits to shift right to get approximated
  97285. * LP coefficients. NOTE: could be negative.
  97286. * RETURN 0 => quantization OK
  97287. * 1 => coefficients require too much shifting for *shift to
  97288. * fit in the LPC subframe header. 'shift' is unset.
  97289. * 2 => coefficients are all zero, which is bad. 'shift' is
  97290. * unset.
  97291. */
  97292. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97293. /*
  97294. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97295. * --------------------------------------------------------------------
  97296. * Compute the residual signal obtained from sutracting the predicted
  97297. * signal from the original.
  97298. *
  97299. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97300. * IN data_len length of original signal
  97301. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97302. * IN order > 0 LP order
  97303. * IN lp_quantization quantization of LP coefficients in bits
  97304. * OUT residual[0,data_len-1] residual signal
  97305. */
  97306. 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[]);
  97307. 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[]);
  97308. #ifndef FLAC__NO_ASM
  97309. # ifdef FLAC__CPU_IA32
  97310. # ifdef FLAC__HAS_NASM
  97311. 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[]);
  97312. 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[]);
  97313. # endif
  97314. # endif
  97315. #endif
  97316. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97317. /*
  97318. * FLAC__lpc_restore_signal()
  97319. * --------------------------------------------------------------------
  97320. * Restore the original signal by summing the residual and the
  97321. * predictor.
  97322. *
  97323. * IN residual[0,data_len-1] residual signal
  97324. * IN data_len length of original signal
  97325. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97326. * IN order > 0 LP order
  97327. * IN lp_quantization quantization of LP coefficients in bits
  97328. * *** IMPORTANT: the caller must pass in the historical samples:
  97329. * IN data[-order,-1] previously-reconstructed historical samples
  97330. * OUT data[0,data_len-1] original signal
  97331. */
  97332. 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[]);
  97333. 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[]);
  97334. #ifndef FLAC__NO_ASM
  97335. # ifdef FLAC__CPU_IA32
  97336. # ifdef FLAC__HAS_NASM
  97337. 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[]);
  97338. 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[]);
  97339. # endif /* FLAC__HAS_NASM */
  97340. # elif defined FLAC__CPU_PPC
  97341. 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[]);
  97342. 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[]);
  97343. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97344. #endif /* FLAC__NO_ASM */
  97345. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97346. /*
  97347. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97348. * --------------------------------------------------------------------
  97349. * Compute the expected number of bits per residual signal sample
  97350. * based on the LP error (which is related to the residual variance).
  97351. *
  97352. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97353. * IN total_samples > 0 # of samples in residual signal
  97354. * RETURN expected bits per sample
  97355. */
  97356. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97357. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97358. /*
  97359. * FLAC__lpc_compute_best_order()
  97360. * --------------------------------------------------------------------
  97361. * Compute the best order from the array of signal errors returned
  97362. * during coefficient computation.
  97363. *
  97364. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97365. * IN max_order > 0 max LP order
  97366. * IN total_samples > 0 # of samples in residual signal
  97367. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97368. * (includes warmup sample size and quantized LP coefficient)
  97369. * RETURN [1,max_order] best order
  97370. */
  97371. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97372. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97373. #endif
  97374. /*** End of inlined file: lpc.h ***/
  97375. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97376. #include <stdio.h>
  97377. #endif
  97378. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97379. #ifndef M_LN2
  97380. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97381. #define M_LN2 0.69314718055994530942
  97382. #endif
  97383. /* OPT: #undef'ing this may improve the speed on some architectures */
  97384. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97385. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97386. {
  97387. unsigned i;
  97388. for(i = 0; i < data_len; i++)
  97389. out[i] = in[i] * window[i];
  97390. }
  97391. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97392. {
  97393. /* a readable, but slower, version */
  97394. #if 0
  97395. FLAC__real d;
  97396. unsigned i;
  97397. FLAC__ASSERT(lag > 0);
  97398. FLAC__ASSERT(lag <= data_len);
  97399. /*
  97400. * Technically we should subtract the mean first like so:
  97401. * for(i = 0; i < data_len; i++)
  97402. * data[i] -= mean;
  97403. * but it appears not to make enough of a difference to matter, and
  97404. * most signals are already closely centered around zero
  97405. */
  97406. while(lag--) {
  97407. for(i = lag, d = 0.0; i < data_len; i++)
  97408. d += data[i] * data[i - lag];
  97409. autoc[lag] = d;
  97410. }
  97411. #endif
  97412. /*
  97413. * this version tends to run faster because of better data locality
  97414. * ('data_len' is usually much larger than 'lag')
  97415. */
  97416. FLAC__real d;
  97417. unsigned sample, coeff;
  97418. const unsigned limit = data_len - lag;
  97419. FLAC__ASSERT(lag > 0);
  97420. FLAC__ASSERT(lag <= data_len);
  97421. for(coeff = 0; coeff < lag; coeff++)
  97422. autoc[coeff] = 0.0;
  97423. for(sample = 0; sample <= limit; sample++) {
  97424. d = data[sample];
  97425. for(coeff = 0; coeff < lag; coeff++)
  97426. autoc[coeff] += d * data[sample+coeff];
  97427. }
  97428. for(; sample < data_len; sample++) {
  97429. d = data[sample];
  97430. for(coeff = 0; coeff < data_len - sample; coeff++)
  97431. autoc[coeff] += d * data[sample+coeff];
  97432. }
  97433. }
  97434. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97435. {
  97436. unsigned i, j;
  97437. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97438. FLAC__ASSERT(0 != max_order);
  97439. FLAC__ASSERT(0 < *max_order);
  97440. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97441. FLAC__ASSERT(autoc[0] != 0.0);
  97442. err = autoc[0];
  97443. for(i = 0; i < *max_order; i++) {
  97444. /* Sum up this iteration's reflection coefficient. */
  97445. r = -autoc[i+1];
  97446. for(j = 0; j < i; j++)
  97447. r -= lpc[j] * autoc[i-j];
  97448. ref[i] = (r/=err);
  97449. /* Update LPC coefficients and total error. */
  97450. lpc[i]=r;
  97451. for(j = 0; j < (i>>1); j++) {
  97452. FLAC__double tmp = lpc[j];
  97453. lpc[j] += r * lpc[i-1-j];
  97454. lpc[i-1-j] += r * tmp;
  97455. }
  97456. if(i & 1)
  97457. lpc[j] += lpc[j] * r;
  97458. err *= (1.0 - r * r);
  97459. /* save this order */
  97460. for(j = 0; j <= i; j++)
  97461. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97462. error[i] = err;
  97463. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97464. if(err == 0.0) {
  97465. *max_order = i+1;
  97466. return;
  97467. }
  97468. }
  97469. }
  97470. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97471. {
  97472. unsigned i;
  97473. FLAC__double cmax;
  97474. FLAC__int32 qmax, qmin;
  97475. FLAC__ASSERT(precision > 0);
  97476. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97477. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97478. precision--;
  97479. qmax = 1 << precision;
  97480. qmin = -qmax;
  97481. qmax--;
  97482. /* calc cmax = max( |lp_coeff[i]| ) */
  97483. cmax = 0.0;
  97484. for(i = 0; i < order; i++) {
  97485. const FLAC__double d = fabs(lp_coeff[i]);
  97486. if(d > cmax)
  97487. cmax = d;
  97488. }
  97489. if(cmax <= 0.0) {
  97490. /* => coefficients are all 0, which means our constant-detect didn't work */
  97491. return 2;
  97492. }
  97493. else {
  97494. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97495. const int min_shiftlimit = -max_shiftlimit - 1;
  97496. int log2cmax;
  97497. (void)frexp(cmax, &log2cmax);
  97498. log2cmax--;
  97499. *shift = (int)precision - log2cmax - 1;
  97500. if(*shift > max_shiftlimit)
  97501. *shift = max_shiftlimit;
  97502. else if(*shift < min_shiftlimit)
  97503. return 1;
  97504. }
  97505. if(*shift >= 0) {
  97506. FLAC__double error = 0.0;
  97507. FLAC__int32 q;
  97508. for(i = 0; i < order; i++) {
  97509. error += lp_coeff[i] * (1 << *shift);
  97510. #if 1 /* unfortunately lround() is C99 */
  97511. if(error >= 0.0)
  97512. q = (FLAC__int32)(error + 0.5);
  97513. else
  97514. q = (FLAC__int32)(error - 0.5);
  97515. #else
  97516. q = lround(error);
  97517. #endif
  97518. #ifdef FLAC__OVERFLOW_DETECT
  97519. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97520. 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]);
  97521. else if(q < qmin)
  97522. 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]);
  97523. #endif
  97524. if(q > qmax)
  97525. q = qmax;
  97526. else if(q < qmin)
  97527. q = qmin;
  97528. error -= q;
  97529. qlp_coeff[i] = q;
  97530. }
  97531. }
  97532. /* negative shift is very rare but due to design flaw, negative shift is
  97533. * a NOP in the decoder, so it must be handled specially by scaling down
  97534. * coeffs
  97535. */
  97536. else {
  97537. const int nshift = -(*shift);
  97538. FLAC__double error = 0.0;
  97539. FLAC__int32 q;
  97540. #ifdef DEBUG
  97541. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97542. #endif
  97543. for(i = 0; i < order; i++) {
  97544. error += lp_coeff[i] / (1 << nshift);
  97545. #if 1 /* unfortunately lround() is C99 */
  97546. if(error >= 0.0)
  97547. q = (FLAC__int32)(error + 0.5);
  97548. else
  97549. q = (FLAC__int32)(error - 0.5);
  97550. #else
  97551. q = lround(error);
  97552. #endif
  97553. #ifdef FLAC__OVERFLOW_DETECT
  97554. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97555. 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]);
  97556. else if(q < qmin)
  97557. 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]);
  97558. #endif
  97559. if(q > qmax)
  97560. q = qmax;
  97561. else if(q < qmin)
  97562. q = qmin;
  97563. error -= q;
  97564. qlp_coeff[i] = q;
  97565. }
  97566. *shift = 0;
  97567. }
  97568. return 0;
  97569. }
  97570. 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[])
  97571. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97572. {
  97573. FLAC__int64 sumo;
  97574. unsigned i, j;
  97575. FLAC__int32 sum;
  97576. const FLAC__int32 *history;
  97577. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97578. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97579. for(i=0;i<order;i++)
  97580. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97581. fprintf(stderr,"\n");
  97582. #endif
  97583. FLAC__ASSERT(order > 0);
  97584. for(i = 0; i < data_len; i++) {
  97585. sumo = 0;
  97586. sum = 0;
  97587. history = data;
  97588. for(j = 0; j < order; j++) {
  97589. sum += qlp_coeff[j] * (*(--history));
  97590. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97591. #if defined _MSC_VER
  97592. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97593. 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);
  97594. #else
  97595. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97596. 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);
  97597. #endif
  97598. }
  97599. *(residual++) = *(data++) - (sum >> lp_quantization);
  97600. }
  97601. /* Here's a slower but clearer version:
  97602. for(i = 0; i < data_len; i++) {
  97603. sum = 0;
  97604. for(j = 0; j < order; j++)
  97605. sum += qlp_coeff[j] * data[i-j-1];
  97606. residual[i] = data[i] - (sum >> lp_quantization);
  97607. }
  97608. */
  97609. }
  97610. #else /* fully unrolled version for normal use */
  97611. {
  97612. int i;
  97613. FLAC__int32 sum;
  97614. FLAC__ASSERT(order > 0);
  97615. FLAC__ASSERT(order <= 32);
  97616. /*
  97617. * We do unique versions up to 12th order since that's the subset limit.
  97618. * Also they are roughly ordered to match frequency of occurrence to
  97619. * minimize branching.
  97620. */
  97621. if(order <= 12) {
  97622. if(order > 8) {
  97623. if(order > 10) {
  97624. if(order == 12) {
  97625. for(i = 0; i < (int)data_len; i++) {
  97626. sum = 0;
  97627. sum += qlp_coeff[11] * data[i-12];
  97628. sum += qlp_coeff[10] * data[i-11];
  97629. sum += qlp_coeff[9] * data[i-10];
  97630. sum += qlp_coeff[8] * data[i-9];
  97631. sum += qlp_coeff[7] * data[i-8];
  97632. sum += qlp_coeff[6] * data[i-7];
  97633. sum += qlp_coeff[5] * data[i-6];
  97634. sum += qlp_coeff[4] * data[i-5];
  97635. sum += qlp_coeff[3] * data[i-4];
  97636. sum += qlp_coeff[2] * data[i-3];
  97637. sum += qlp_coeff[1] * data[i-2];
  97638. sum += qlp_coeff[0] * data[i-1];
  97639. residual[i] = data[i] - (sum >> lp_quantization);
  97640. }
  97641. }
  97642. else { /* order == 11 */
  97643. for(i = 0; i < (int)data_len; i++) {
  97644. sum = 0;
  97645. sum += qlp_coeff[10] * data[i-11];
  97646. sum += qlp_coeff[9] * data[i-10];
  97647. sum += qlp_coeff[8] * data[i-9];
  97648. sum += qlp_coeff[7] * data[i-8];
  97649. sum += qlp_coeff[6] * data[i-7];
  97650. sum += qlp_coeff[5] * data[i-6];
  97651. sum += qlp_coeff[4] * data[i-5];
  97652. sum += qlp_coeff[3] * data[i-4];
  97653. sum += qlp_coeff[2] * data[i-3];
  97654. sum += qlp_coeff[1] * data[i-2];
  97655. sum += qlp_coeff[0] * data[i-1];
  97656. residual[i] = data[i] - (sum >> lp_quantization);
  97657. }
  97658. }
  97659. }
  97660. else {
  97661. if(order == 10) {
  97662. for(i = 0; i < (int)data_len; i++) {
  97663. sum = 0;
  97664. sum += qlp_coeff[9] * data[i-10];
  97665. sum += qlp_coeff[8] * data[i-9];
  97666. sum += qlp_coeff[7] * data[i-8];
  97667. sum += qlp_coeff[6] * data[i-7];
  97668. sum += qlp_coeff[5] * data[i-6];
  97669. sum += qlp_coeff[4] * data[i-5];
  97670. sum += qlp_coeff[3] * data[i-4];
  97671. sum += qlp_coeff[2] * data[i-3];
  97672. sum += qlp_coeff[1] * data[i-2];
  97673. sum += qlp_coeff[0] * data[i-1];
  97674. residual[i] = data[i] - (sum >> lp_quantization);
  97675. }
  97676. }
  97677. else { /* order == 9 */
  97678. for(i = 0; i < (int)data_len; i++) {
  97679. sum = 0;
  97680. sum += qlp_coeff[8] * data[i-9];
  97681. sum += qlp_coeff[7] * data[i-8];
  97682. sum += qlp_coeff[6] * data[i-7];
  97683. sum += qlp_coeff[5] * data[i-6];
  97684. sum += qlp_coeff[4] * data[i-5];
  97685. sum += qlp_coeff[3] * data[i-4];
  97686. sum += qlp_coeff[2] * data[i-3];
  97687. sum += qlp_coeff[1] * data[i-2];
  97688. sum += qlp_coeff[0] * data[i-1];
  97689. residual[i] = data[i] - (sum >> lp_quantization);
  97690. }
  97691. }
  97692. }
  97693. }
  97694. else if(order > 4) {
  97695. if(order > 6) {
  97696. if(order == 8) {
  97697. for(i = 0; i < (int)data_len; i++) {
  97698. sum = 0;
  97699. sum += qlp_coeff[7] * data[i-8];
  97700. sum += qlp_coeff[6] * data[i-7];
  97701. sum += qlp_coeff[5] * data[i-6];
  97702. sum += qlp_coeff[4] * data[i-5];
  97703. sum += qlp_coeff[3] * data[i-4];
  97704. sum += qlp_coeff[2] * data[i-3];
  97705. sum += qlp_coeff[1] * data[i-2];
  97706. sum += qlp_coeff[0] * data[i-1];
  97707. residual[i] = data[i] - (sum >> lp_quantization);
  97708. }
  97709. }
  97710. else { /* order == 7 */
  97711. for(i = 0; i < (int)data_len; i++) {
  97712. sum = 0;
  97713. sum += qlp_coeff[6] * data[i-7];
  97714. sum += qlp_coeff[5] * data[i-6];
  97715. sum += qlp_coeff[4] * data[i-5];
  97716. sum += qlp_coeff[3] * data[i-4];
  97717. sum += qlp_coeff[2] * data[i-3];
  97718. sum += qlp_coeff[1] * data[i-2];
  97719. sum += qlp_coeff[0] * data[i-1];
  97720. residual[i] = data[i] - (sum >> lp_quantization);
  97721. }
  97722. }
  97723. }
  97724. else {
  97725. if(order == 6) {
  97726. for(i = 0; i < (int)data_len; i++) {
  97727. sum = 0;
  97728. sum += qlp_coeff[5] * data[i-6];
  97729. sum += qlp_coeff[4] * data[i-5];
  97730. sum += qlp_coeff[3] * data[i-4];
  97731. sum += qlp_coeff[2] * data[i-3];
  97732. sum += qlp_coeff[1] * data[i-2];
  97733. sum += qlp_coeff[0] * data[i-1];
  97734. residual[i] = data[i] - (sum >> lp_quantization);
  97735. }
  97736. }
  97737. else { /* order == 5 */
  97738. for(i = 0; i < (int)data_len; i++) {
  97739. sum = 0;
  97740. sum += qlp_coeff[4] * data[i-5];
  97741. sum += qlp_coeff[3] * data[i-4];
  97742. sum += qlp_coeff[2] * data[i-3];
  97743. sum += qlp_coeff[1] * data[i-2];
  97744. sum += qlp_coeff[0] * data[i-1];
  97745. residual[i] = data[i] - (sum >> lp_quantization);
  97746. }
  97747. }
  97748. }
  97749. }
  97750. else {
  97751. if(order > 2) {
  97752. if(order == 4) {
  97753. for(i = 0; i < (int)data_len; i++) {
  97754. sum = 0;
  97755. sum += qlp_coeff[3] * data[i-4];
  97756. sum += qlp_coeff[2] * data[i-3];
  97757. sum += qlp_coeff[1] * data[i-2];
  97758. sum += qlp_coeff[0] * data[i-1];
  97759. residual[i] = data[i] - (sum >> lp_quantization);
  97760. }
  97761. }
  97762. else { /* order == 3 */
  97763. for(i = 0; i < (int)data_len; i++) {
  97764. sum = 0;
  97765. sum += qlp_coeff[2] * data[i-3];
  97766. sum += qlp_coeff[1] * data[i-2];
  97767. sum += qlp_coeff[0] * data[i-1];
  97768. residual[i] = data[i] - (sum >> lp_quantization);
  97769. }
  97770. }
  97771. }
  97772. else {
  97773. if(order == 2) {
  97774. for(i = 0; i < (int)data_len; i++) {
  97775. sum = 0;
  97776. sum += qlp_coeff[1] * data[i-2];
  97777. sum += qlp_coeff[0] * data[i-1];
  97778. residual[i] = data[i] - (sum >> lp_quantization);
  97779. }
  97780. }
  97781. else { /* order == 1 */
  97782. for(i = 0; i < (int)data_len; i++)
  97783. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97784. }
  97785. }
  97786. }
  97787. }
  97788. else { /* order > 12 */
  97789. for(i = 0; i < (int)data_len; i++) {
  97790. sum = 0;
  97791. switch(order) {
  97792. case 32: sum += qlp_coeff[31] * data[i-32];
  97793. case 31: sum += qlp_coeff[30] * data[i-31];
  97794. case 30: sum += qlp_coeff[29] * data[i-30];
  97795. case 29: sum += qlp_coeff[28] * data[i-29];
  97796. case 28: sum += qlp_coeff[27] * data[i-28];
  97797. case 27: sum += qlp_coeff[26] * data[i-27];
  97798. case 26: sum += qlp_coeff[25] * data[i-26];
  97799. case 25: sum += qlp_coeff[24] * data[i-25];
  97800. case 24: sum += qlp_coeff[23] * data[i-24];
  97801. case 23: sum += qlp_coeff[22] * data[i-23];
  97802. case 22: sum += qlp_coeff[21] * data[i-22];
  97803. case 21: sum += qlp_coeff[20] * data[i-21];
  97804. case 20: sum += qlp_coeff[19] * data[i-20];
  97805. case 19: sum += qlp_coeff[18] * data[i-19];
  97806. case 18: sum += qlp_coeff[17] * data[i-18];
  97807. case 17: sum += qlp_coeff[16] * data[i-17];
  97808. case 16: sum += qlp_coeff[15] * data[i-16];
  97809. case 15: sum += qlp_coeff[14] * data[i-15];
  97810. case 14: sum += qlp_coeff[13] * data[i-14];
  97811. case 13: sum += qlp_coeff[12] * data[i-13];
  97812. sum += qlp_coeff[11] * data[i-12];
  97813. sum += qlp_coeff[10] * data[i-11];
  97814. sum += qlp_coeff[ 9] * data[i-10];
  97815. sum += qlp_coeff[ 8] * data[i- 9];
  97816. sum += qlp_coeff[ 7] * data[i- 8];
  97817. sum += qlp_coeff[ 6] * data[i- 7];
  97818. sum += qlp_coeff[ 5] * data[i- 6];
  97819. sum += qlp_coeff[ 4] * data[i- 5];
  97820. sum += qlp_coeff[ 3] * data[i- 4];
  97821. sum += qlp_coeff[ 2] * data[i- 3];
  97822. sum += qlp_coeff[ 1] * data[i- 2];
  97823. sum += qlp_coeff[ 0] * data[i- 1];
  97824. }
  97825. residual[i] = data[i] - (sum >> lp_quantization);
  97826. }
  97827. }
  97828. }
  97829. #endif
  97830. 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[])
  97831. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97832. {
  97833. unsigned i, j;
  97834. FLAC__int64 sum;
  97835. const FLAC__int32 *history;
  97836. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97837. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97838. for(i=0;i<order;i++)
  97839. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97840. fprintf(stderr,"\n");
  97841. #endif
  97842. FLAC__ASSERT(order > 0);
  97843. for(i = 0; i < data_len; i++) {
  97844. sum = 0;
  97845. history = data;
  97846. for(j = 0; j < order; j++)
  97847. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97848. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97849. #if defined _MSC_VER
  97850. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97851. #else
  97852. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97853. #endif
  97854. break;
  97855. }
  97856. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97857. #if defined _MSC_VER
  97858. 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));
  97859. #else
  97860. 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)));
  97861. #endif
  97862. break;
  97863. }
  97864. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97865. }
  97866. }
  97867. #else /* fully unrolled version for normal use */
  97868. {
  97869. int i;
  97870. FLAC__int64 sum;
  97871. FLAC__ASSERT(order > 0);
  97872. FLAC__ASSERT(order <= 32);
  97873. /*
  97874. * We do unique versions up to 12th order since that's the subset limit.
  97875. * Also they are roughly ordered to match frequency of occurrence to
  97876. * minimize branching.
  97877. */
  97878. if(order <= 12) {
  97879. if(order > 8) {
  97880. if(order > 10) {
  97881. if(order == 12) {
  97882. for(i = 0; i < (int)data_len; i++) {
  97883. sum = 0;
  97884. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97885. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97886. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97887. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97888. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97889. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97890. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97891. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97892. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97893. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97894. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97895. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97896. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97897. }
  97898. }
  97899. else { /* order == 11 */
  97900. for(i = 0; i < (int)data_len; i++) {
  97901. sum = 0;
  97902. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97903. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97904. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97905. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97906. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97907. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97908. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97909. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97910. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97911. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97912. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97913. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97914. }
  97915. }
  97916. }
  97917. else {
  97918. if(order == 10) {
  97919. for(i = 0; i < (int)data_len; i++) {
  97920. sum = 0;
  97921. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97922. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97923. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97924. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97925. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97926. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97927. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97928. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97929. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97930. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97931. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97932. }
  97933. }
  97934. else { /* order == 9 */
  97935. for(i = 0; i < (int)data_len; i++) {
  97936. sum = 0;
  97937. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97938. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97939. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97940. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97941. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97942. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97943. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97944. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97945. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97946. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97947. }
  97948. }
  97949. }
  97950. }
  97951. else if(order > 4) {
  97952. if(order > 6) {
  97953. if(order == 8) {
  97954. for(i = 0; i < (int)data_len; i++) {
  97955. sum = 0;
  97956. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97957. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97958. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97959. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97960. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97961. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97962. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97963. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97964. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97965. }
  97966. }
  97967. else { /* order == 7 */
  97968. for(i = 0; i < (int)data_len; i++) {
  97969. sum = 0;
  97970. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97971. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97972. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97973. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97974. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97975. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97976. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97977. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97978. }
  97979. }
  97980. }
  97981. else {
  97982. if(order == 6) {
  97983. for(i = 0; i < (int)data_len; i++) {
  97984. sum = 0;
  97985. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97986. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97987. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97988. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97989. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97990. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97991. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97992. }
  97993. }
  97994. else { /* order == 5 */
  97995. for(i = 0; i < (int)data_len; i++) {
  97996. sum = 0;
  97997. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97998. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97999. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98000. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98001. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98002. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98003. }
  98004. }
  98005. }
  98006. }
  98007. else {
  98008. if(order > 2) {
  98009. if(order == 4) {
  98010. for(i = 0; i < (int)data_len; i++) {
  98011. sum = 0;
  98012. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98013. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98014. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98015. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98016. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98017. }
  98018. }
  98019. else { /* order == 3 */
  98020. for(i = 0; i < (int)data_len; i++) {
  98021. sum = 0;
  98022. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98023. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98024. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98025. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98026. }
  98027. }
  98028. }
  98029. else {
  98030. if(order == 2) {
  98031. for(i = 0; i < (int)data_len; i++) {
  98032. sum = 0;
  98033. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98034. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98035. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98036. }
  98037. }
  98038. else { /* order == 1 */
  98039. for(i = 0; i < (int)data_len; i++)
  98040. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98041. }
  98042. }
  98043. }
  98044. }
  98045. else { /* order > 12 */
  98046. for(i = 0; i < (int)data_len; i++) {
  98047. sum = 0;
  98048. switch(order) {
  98049. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98050. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98051. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98052. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98053. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98054. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98055. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98056. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98057. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98058. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98059. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98060. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98061. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98062. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98063. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98064. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98065. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98066. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98067. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98068. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98069. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98070. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98071. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98072. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98073. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98074. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98075. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98076. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98077. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98078. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98079. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98080. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98081. }
  98082. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98083. }
  98084. }
  98085. }
  98086. #endif
  98087. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98088. 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[])
  98089. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98090. {
  98091. FLAC__int64 sumo;
  98092. unsigned i, j;
  98093. FLAC__int32 sum;
  98094. const FLAC__int32 *r = residual, *history;
  98095. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98096. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98097. for(i=0;i<order;i++)
  98098. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98099. fprintf(stderr,"\n");
  98100. #endif
  98101. FLAC__ASSERT(order > 0);
  98102. for(i = 0; i < data_len; i++) {
  98103. sumo = 0;
  98104. sum = 0;
  98105. history = data;
  98106. for(j = 0; j < order; j++) {
  98107. sum += qlp_coeff[j] * (*(--history));
  98108. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98109. #if defined _MSC_VER
  98110. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98111. 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);
  98112. #else
  98113. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98114. 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);
  98115. #endif
  98116. }
  98117. *(data++) = *(r++) + (sum >> lp_quantization);
  98118. }
  98119. /* Here's a slower but clearer version:
  98120. for(i = 0; i < data_len; i++) {
  98121. sum = 0;
  98122. for(j = 0; j < order; j++)
  98123. sum += qlp_coeff[j] * data[i-j-1];
  98124. data[i] = residual[i] + (sum >> lp_quantization);
  98125. }
  98126. */
  98127. }
  98128. #else /* fully unrolled version for normal use */
  98129. {
  98130. int i;
  98131. FLAC__int32 sum;
  98132. FLAC__ASSERT(order > 0);
  98133. FLAC__ASSERT(order <= 32);
  98134. /*
  98135. * We do unique versions up to 12th order since that's the subset limit.
  98136. * Also they are roughly ordered to match frequency of occurrence to
  98137. * minimize branching.
  98138. */
  98139. if(order <= 12) {
  98140. if(order > 8) {
  98141. if(order > 10) {
  98142. if(order == 12) {
  98143. for(i = 0; i < (int)data_len; i++) {
  98144. sum = 0;
  98145. sum += qlp_coeff[11] * data[i-12];
  98146. sum += qlp_coeff[10] * data[i-11];
  98147. sum += qlp_coeff[9] * data[i-10];
  98148. sum += qlp_coeff[8] * data[i-9];
  98149. sum += qlp_coeff[7] * data[i-8];
  98150. sum += qlp_coeff[6] * data[i-7];
  98151. sum += qlp_coeff[5] * data[i-6];
  98152. sum += qlp_coeff[4] * data[i-5];
  98153. sum += qlp_coeff[3] * data[i-4];
  98154. sum += qlp_coeff[2] * data[i-3];
  98155. sum += qlp_coeff[1] * data[i-2];
  98156. sum += qlp_coeff[0] * data[i-1];
  98157. data[i] = residual[i] + (sum >> lp_quantization);
  98158. }
  98159. }
  98160. else { /* order == 11 */
  98161. for(i = 0; i < (int)data_len; i++) {
  98162. sum = 0;
  98163. sum += qlp_coeff[10] * data[i-11];
  98164. sum += qlp_coeff[9] * data[i-10];
  98165. sum += qlp_coeff[8] * data[i-9];
  98166. sum += qlp_coeff[7] * data[i-8];
  98167. sum += qlp_coeff[6] * data[i-7];
  98168. sum += qlp_coeff[5] * data[i-6];
  98169. sum += qlp_coeff[4] * data[i-5];
  98170. sum += qlp_coeff[3] * data[i-4];
  98171. sum += qlp_coeff[2] * data[i-3];
  98172. sum += qlp_coeff[1] * data[i-2];
  98173. sum += qlp_coeff[0] * data[i-1];
  98174. data[i] = residual[i] + (sum >> lp_quantization);
  98175. }
  98176. }
  98177. }
  98178. else {
  98179. if(order == 10) {
  98180. for(i = 0; i < (int)data_len; i++) {
  98181. sum = 0;
  98182. sum += qlp_coeff[9] * data[i-10];
  98183. sum += qlp_coeff[8] * data[i-9];
  98184. sum += qlp_coeff[7] * data[i-8];
  98185. sum += qlp_coeff[6] * data[i-7];
  98186. sum += qlp_coeff[5] * data[i-6];
  98187. sum += qlp_coeff[4] * data[i-5];
  98188. sum += qlp_coeff[3] * data[i-4];
  98189. sum += qlp_coeff[2] * data[i-3];
  98190. sum += qlp_coeff[1] * data[i-2];
  98191. sum += qlp_coeff[0] * data[i-1];
  98192. data[i] = residual[i] + (sum >> lp_quantization);
  98193. }
  98194. }
  98195. else { /* order == 9 */
  98196. for(i = 0; i < (int)data_len; i++) {
  98197. sum = 0;
  98198. sum += qlp_coeff[8] * data[i-9];
  98199. sum += qlp_coeff[7] * data[i-8];
  98200. sum += qlp_coeff[6] * data[i-7];
  98201. sum += qlp_coeff[5] * data[i-6];
  98202. sum += qlp_coeff[4] * data[i-5];
  98203. sum += qlp_coeff[3] * data[i-4];
  98204. sum += qlp_coeff[2] * data[i-3];
  98205. sum += qlp_coeff[1] * data[i-2];
  98206. sum += qlp_coeff[0] * data[i-1];
  98207. data[i] = residual[i] + (sum >> lp_quantization);
  98208. }
  98209. }
  98210. }
  98211. }
  98212. else if(order > 4) {
  98213. if(order > 6) {
  98214. if(order == 8) {
  98215. for(i = 0; i < (int)data_len; i++) {
  98216. sum = 0;
  98217. sum += qlp_coeff[7] * data[i-8];
  98218. sum += qlp_coeff[6] * data[i-7];
  98219. sum += qlp_coeff[5] * data[i-6];
  98220. sum += qlp_coeff[4] * data[i-5];
  98221. sum += qlp_coeff[3] * data[i-4];
  98222. sum += qlp_coeff[2] * data[i-3];
  98223. sum += qlp_coeff[1] * data[i-2];
  98224. sum += qlp_coeff[0] * data[i-1];
  98225. data[i] = residual[i] + (sum >> lp_quantization);
  98226. }
  98227. }
  98228. else { /* order == 7 */
  98229. for(i = 0; i < (int)data_len; i++) {
  98230. sum = 0;
  98231. sum += qlp_coeff[6] * data[i-7];
  98232. sum += qlp_coeff[5] * data[i-6];
  98233. sum += qlp_coeff[4] * data[i-5];
  98234. sum += qlp_coeff[3] * data[i-4];
  98235. sum += qlp_coeff[2] * data[i-3];
  98236. sum += qlp_coeff[1] * data[i-2];
  98237. sum += qlp_coeff[0] * data[i-1];
  98238. data[i] = residual[i] + (sum >> lp_quantization);
  98239. }
  98240. }
  98241. }
  98242. else {
  98243. if(order == 6) {
  98244. for(i = 0; i < (int)data_len; i++) {
  98245. sum = 0;
  98246. sum += qlp_coeff[5] * data[i-6];
  98247. sum += qlp_coeff[4] * data[i-5];
  98248. sum += qlp_coeff[3] * data[i-4];
  98249. sum += qlp_coeff[2] * data[i-3];
  98250. sum += qlp_coeff[1] * data[i-2];
  98251. sum += qlp_coeff[0] * data[i-1];
  98252. data[i] = residual[i] + (sum >> lp_quantization);
  98253. }
  98254. }
  98255. else { /* order == 5 */
  98256. for(i = 0; i < (int)data_len; i++) {
  98257. sum = 0;
  98258. sum += qlp_coeff[4] * data[i-5];
  98259. sum += qlp_coeff[3] * data[i-4];
  98260. sum += qlp_coeff[2] * data[i-3];
  98261. sum += qlp_coeff[1] * data[i-2];
  98262. sum += qlp_coeff[0] * data[i-1];
  98263. data[i] = residual[i] + (sum >> lp_quantization);
  98264. }
  98265. }
  98266. }
  98267. }
  98268. else {
  98269. if(order > 2) {
  98270. if(order == 4) {
  98271. for(i = 0; i < (int)data_len; i++) {
  98272. sum = 0;
  98273. sum += qlp_coeff[3] * data[i-4];
  98274. sum += qlp_coeff[2] * data[i-3];
  98275. sum += qlp_coeff[1] * data[i-2];
  98276. sum += qlp_coeff[0] * data[i-1];
  98277. data[i] = residual[i] + (sum >> lp_quantization);
  98278. }
  98279. }
  98280. else { /* order == 3 */
  98281. for(i = 0; i < (int)data_len; i++) {
  98282. sum = 0;
  98283. sum += qlp_coeff[2] * data[i-3];
  98284. sum += qlp_coeff[1] * data[i-2];
  98285. sum += qlp_coeff[0] * data[i-1];
  98286. data[i] = residual[i] + (sum >> lp_quantization);
  98287. }
  98288. }
  98289. }
  98290. else {
  98291. if(order == 2) {
  98292. for(i = 0; i < (int)data_len; i++) {
  98293. sum = 0;
  98294. sum += qlp_coeff[1] * data[i-2];
  98295. sum += qlp_coeff[0] * data[i-1];
  98296. data[i] = residual[i] + (sum >> lp_quantization);
  98297. }
  98298. }
  98299. else { /* order == 1 */
  98300. for(i = 0; i < (int)data_len; i++)
  98301. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98302. }
  98303. }
  98304. }
  98305. }
  98306. else { /* order > 12 */
  98307. for(i = 0; i < (int)data_len; i++) {
  98308. sum = 0;
  98309. switch(order) {
  98310. case 32: sum += qlp_coeff[31] * data[i-32];
  98311. case 31: sum += qlp_coeff[30] * data[i-31];
  98312. case 30: sum += qlp_coeff[29] * data[i-30];
  98313. case 29: sum += qlp_coeff[28] * data[i-29];
  98314. case 28: sum += qlp_coeff[27] * data[i-28];
  98315. case 27: sum += qlp_coeff[26] * data[i-27];
  98316. case 26: sum += qlp_coeff[25] * data[i-26];
  98317. case 25: sum += qlp_coeff[24] * data[i-25];
  98318. case 24: sum += qlp_coeff[23] * data[i-24];
  98319. case 23: sum += qlp_coeff[22] * data[i-23];
  98320. case 22: sum += qlp_coeff[21] * data[i-22];
  98321. case 21: sum += qlp_coeff[20] * data[i-21];
  98322. case 20: sum += qlp_coeff[19] * data[i-20];
  98323. case 19: sum += qlp_coeff[18] * data[i-19];
  98324. case 18: sum += qlp_coeff[17] * data[i-18];
  98325. case 17: sum += qlp_coeff[16] * data[i-17];
  98326. case 16: sum += qlp_coeff[15] * data[i-16];
  98327. case 15: sum += qlp_coeff[14] * data[i-15];
  98328. case 14: sum += qlp_coeff[13] * data[i-14];
  98329. case 13: sum += qlp_coeff[12] * data[i-13];
  98330. sum += qlp_coeff[11] * data[i-12];
  98331. sum += qlp_coeff[10] * data[i-11];
  98332. sum += qlp_coeff[ 9] * data[i-10];
  98333. sum += qlp_coeff[ 8] * data[i- 9];
  98334. sum += qlp_coeff[ 7] * data[i- 8];
  98335. sum += qlp_coeff[ 6] * data[i- 7];
  98336. sum += qlp_coeff[ 5] * data[i- 6];
  98337. sum += qlp_coeff[ 4] * data[i- 5];
  98338. sum += qlp_coeff[ 3] * data[i- 4];
  98339. sum += qlp_coeff[ 2] * data[i- 3];
  98340. sum += qlp_coeff[ 1] * data[i- 2];
  98341. sum += qlp_coeff[ 0] * data[i- 1];
  98342. }
  98343. data[i] = residual[i] + (sum >> lp_quantization);
  98344. }
  98345. }
  98346. }
  98347. #endif
  98348. 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[])
  98349. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98350. {
  98351. unsigned i, j;
  98352. FLAC__int64 sum;
  98353. const FLAC__int32 *r = residual, *history;
  98354. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98355. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98356. for(i=0;i<order;i++)
  98357. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98358. fprintf(stderr,"\n");
  98359. #endif
  98360. FLAC__ASSERT(order > 0);
  98361. for(i = 0; i < data_len; i++) {
  98362. sum = 0;
  98363. history = data;
  98364. for(j = 0; j < order; j++)
  98365. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98366. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98367. #ifdef _MSC_VER
  98368. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98369. #else
  98370. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98371. #endif
  98372. break;
  98373. }
  98374. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98375. #ifdef _MSC_VER
  98376. 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));
  98377. #else
  98378. 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)));
  98379. #endif
  98380. break;
  98381. }
  98382. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98383. }
  98384. }
  98385. #else /* fully unrolled version for normal use */
  98386. {
  98387. int i;
  98388. FLAC__int64 sum;
  98389. FLAC__ASSERT(order > 0);
  98390. FLAC__ASSERT(order <= 32);
  98391. /*
  98392. * We do unique versions up to 12th order since that's the subset limit.
  98393. * Also they are roughly ordered to match frequency of occurrence to
  98394. * minimize branching.
  98395. */
  98396. if(order <= 12) {
  98397. if(order > 8) {
  98398. if(order > 10) {
  98399. if(order == 12) {
  98400. for(i = 0; i < (int)data_len; i++) {
  98401. sum = 0;
  98402. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98403. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98404. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98405. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98406. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98407. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98408. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98409. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98410. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98411. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98412. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98413. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98414. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98415. }
  98416. }
  98417. else { /* order == 11 */
  98418. for(i = 0; i < (int)data_len; i++) {
  98419. sum = 0;
  98420. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98421. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98422. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98423. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98424. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98425. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98426. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98427. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98428. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98429. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98430. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98431. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98432. }
  98433. }
  98434. }
  98435. else {
  98436. if(order == 10) {
  98437. for(i = 0; i < (int)data_len; i++) {
  98438. sum = 0;
  98439. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98440. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98441. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98442. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98443. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98444. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98445. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98446. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98447. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98448. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98449. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98450. }
  98451. }
  98452. else { /* order == 9 */
  98453. for(i = 0; i < (int)data_len; i++) {
  98454. sum = 0;
  98455. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98456. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98457. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98458. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98459. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98460. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98461. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98462. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98463. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98464. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98465. }
  98466. }
  98467. }
  98468. }
  98469. else if(order > 4) {
  98470. if(order > 6) {
  98471. if(order == 8) {
  98472. for(i = 0; i < (int)data_len; i++) {
  98473. sum = 0;
  98474. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98475. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98476. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98477. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98478. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98479. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98480. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98481. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98482. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98483. }
  98484. }
  98485. else { /* order == 7 */
  98486. for(i = 0; i < (int)data_len; i++) {
  98487. sum = 0;
  98488. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98489. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98490. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98491. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98492. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98493. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98494. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98495. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98496. }
  98497. }
  98498. }
  98499. else {
  98500. if(order == 6) {
  98501. for(i = 0; i < (int)data_len; i++) {
  98502. sum = 0;
  98503. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98504. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98505. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98506. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98507. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98508. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98509. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98510. }
  98511. }
  98512. else { /* order == 5 */
  98513. for(i = 0; i < (int)data_len; i++) {
  98514. sum = 0;
  98515. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98516. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98517. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98518. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98519. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98520. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98521. }
  98522. }
  98523. }
  98524. }
  98525. else {
  98526. if(order > 2) {
  98527. if(order == 4) {
  98528. for(i = 0; i < (int)data_len; i++) {
  98529. sum = 0;
  98530. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98531. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98532. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98533. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98534. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98535. }
  98536. }
  98537. else { /* order == 3 */
  98538. for(i = 0; i < (int)data_len; i++) {
  98539. sum = 0;
  98540. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98541. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98542. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98543. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98544. }
  98545. }
  98546. }
  98547. else {
  98548. if(order == 2) {
  98549. for(i = 0; i < (int)data_len; i++) {
  98550. sum = 0;
  98551. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98552. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98553. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98554. }
  98555. }
  98556. else { /* order == 1 */
  98557. for(i = 0; i < (int)data_len; i++)
  98558. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98559. }
  98560. }
  98561. }
  98562. }
  98563. else { /* order > 12 */
  98564. for(i = 0; i < (int)data_len; i++) {
  98565. sum = 0;
  98566. switch(order) {
  98567. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98568. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98569. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98570. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98571. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98572. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98573. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98574. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98575. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98576. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98577. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98578. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98579. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98580. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98581. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98582. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98583. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98584. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98585. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98586. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98587. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98588. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98589. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98590. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98591. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98592. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98593. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98594. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98595. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98596. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98597. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98598. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98599. }
  98600. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98601. }
  98602. }
  98603. }
  98604. #endif
  98605. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98606. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98607. {
  98608. FLAC__double error_scale;
  98609. FLAC__ASSERT(total_samples > 0);
  98610. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98611. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98612. }
  98613. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98614. {
  98615. if(lpc_error > 0.0) {
  98616. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98617. if(bps >= 0.0)
  98618. return bps;
  98619. else
  98620. return 0.0;
  98621. }
  98622. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98623. return 1e32;
  98624. }
  98625. else {
  98626. return 0.0;
  98627. }
  98628. }
  98629. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98630. {
  98631. 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 */
  98632. FLAC__double bits, best_bits, error_scale;
  98633. FLAC__ASSERT(max_order > 0);
  98634. FLAC__ASSERT(total_samples > 0);
  98635. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98636. best_index = 0;
  98637. best_bits = (unsigned)(-1);
  98638. for(index = 0, order = 1; index < max_order; index++, order++) {
  98639. 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);
  98640. if(bits < best_bits) {
  98641. best_index = index;
  98642. best_bits = bits;
  98643. }
  98644. }
  98645. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98646. }
  98647. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98648. #endif
  98649. /*** End of inlined file: lpc_flac.c ***/
  98650. /*** Start of inlined file: md5.c ***/
  98651. /*** Start of inlined file: juce_FlacHeader.h ***/
  98652. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98653. // tasks..
  98654. #define VERSION "1.2.1"
  98655. #define FLAC__NO_DLL 1
  98656. #if JUCE_MSVC
  98657. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98658. #endif
  98659. #if JUCE_MAC
  98660. #define FLAC__SYS_DARWIN 1
  98661. #endif
  98662. /*** End of inlined file: juce_FlacHeader.h ***/
  98663. #if JUCE_USE_FLAC
  98664. #if HAVE_CONFIG_H
  98665. # include <config.h>
  98666. #endif
  98667. #include <stdlib.h> /* for malloc() */
  98668. #include <string.h> /* for memcpy() */
  98669. /*** Start of inlined file: md5.h ***/
  98670. #ifndef FLAC__PRIVATE__MD5_H
  98671. #define FLAC__PRIVATE__MD5_H
  98672. /*
  98673. * This is the header file for the MD5 message-digest algorithm.
  98674. * The algorithm is due to Ron Rivest. This code was
  98675. * written by Colin Plumb in 1993, no copyright is claimed.
  98676. * This code is in the public domain; do with it what you wish.
  98677. *
  98678. * Equivalent code is available from RSA Data Security, Inc.
  98679. * This code has been tested against that, and is equivalent,
  98680. * except that you don't need to include two pages of legalese
  98681. * with every copy.
  98682. *
  98683. * To compute the message digest of a chunk of bytes, declare an
  98684. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98685. * needed on buffers full of bytes, and then call MD5Final, which
  98686. * will fill a supplied 16-byte array with the digest.
  98687. *
  98688. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98689. * header definitions; now uses stuff from dpkg's config.h
  98690. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98691. * Still in the public domain.
  98692. *
  98693. * Josh Coalson: made some changes to integrate with libFLAC.
  98694. * Still in the public domain, with no warranty.
  98695. */
  98696. typedef struct {
  98697. FLAC__uint32 in[16];
  98698. FLAC__uint32 buf[4];
  98699. FLAC__uint32 bytes[2];
  98700. FLAC__byte *internal_buf;
  98701. size_t capacity;
  98702. } FLAC__MD5Context;
  98703. void FLAC__MD5Init(FLAC__MD5Context *context);
  98704. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98705. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98706. #endif
  98707. /*** End of inlined file: md5.h ***/
  98708. #ifndef FLaC__INLINE
  98709. #define FLaC__INLINE
  98710. #endif
  98711. /*
  98712. * This code implements the MD5 message-digest algorithm.
  98713. * The algorithm is due to Ron Rivest. This code was
  98714. * written by Colin Plumb in 1993, no copyright is claimed.
  98715. * This code is in the public domain; do with it what you wish.
  98716. *
  98717. * Equivalent code is available from RSA Data Security, Inc.
  98718. * This code has been tested against that, and is equivalent,
  98719. * except that you don't need to include two pages of legalese
  98720. * with every copy.
  98721. *
  98722. * To compute the message digest of a chunk of bytes, declare an
  98723. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98724. * needed on buffers full of bytes, and then call MD5Final, which
  98725. * will fill a supplied 16-byte array with the digest.
  98726. *
  98727. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98728. * definitions; now uses stuff from dpkg's config.h.
  98729. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98730. * Still in the public domain.
  98731. *
  98732. * Josh Coalson: made some changes to integrate with libFLAC.
  98733. * Still in the public domain.
  98734. */
  98735. /* The four core functions - F1 is optimized somewhat */
  98736. /* #define F1(x, y, z) (x & y | ~x & z) */
  98737. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98738. #define F2(x, y, z) F1(z, x, y)
  98739. #define F3(x, y, z) (x ^ y ^ z)
  98740. #define F4(x, y, z) (y ^ (x | ~z))
  98741. /* This is the central step in the MD5 algorithm. */
  98742. #define MD5STEP(f,w,x,y,z,in,s) \
  98743. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98744. /*
  98745. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98746. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98747. * the data and converts bytes into longwords for this routine.
  98748. */
  98749. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98750. {
  98751. register FLAC__uint32 a, b, c, d;
  98752. a = buf[0];
  98753. b = buf[1];
  98754. c = buf[2];
  98755. d = buf[3];
  98756. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98757. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98758. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98759. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98760. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98761. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98762. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98763. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98764. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98765. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98766. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98767. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98768. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98769. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98770. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98771. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98772. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98773. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98774. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98775. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98776. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98777. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98778. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98779. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98780. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98781. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98782. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98783. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98784. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98785. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98786. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98787. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98788. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98789. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98790. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98791. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98792. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98793. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98794. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98795. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98796. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98797. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98798. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98799. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98800. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98801. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98802. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98803. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98804. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98805. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98806. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98807. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98808. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98809. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98810. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98811. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98812. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98813. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98814. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98815. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98816. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98817. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98818. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98819. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98820. buf[0] += a;
  98821. buf[1] += b;
  98822. buf[2] += c;
  98823. buf[3] += d;
  98824. }
  98825. #if WORDS_BIGENDIAN
  98826. //@@@@@@ OPT: use bswap/intrinsics
  98827. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98828. {
  98829. register FLAC__uint32 x;
  98830. do {
  98831. x = *buf;
  98832. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98833. *buf++ = (x >> 16) | (x << 16);
  98834. } while (--words);
  98835. }
  98836. static void byteSwapX16(FLAC__uint32 *buf)
  98837. {
  98838. register FLAC__uint32 x;
  98839. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98840. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98841. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98842. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98843. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98844. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98845. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98846. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98847. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98848. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98849. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98850. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98851. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98852. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98853. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98854. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98855. }
  98856. #else
  98857. #define byteSwap(buf, words)
  98858. #define byteSwapX16(buf)
  98859. #endif
  98860. /*
  98861. * Update context to reflect the concatenation of another buffer full
  98862. * of bytes.
  98863. */
  98864. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98865. {
  98866. FLAC__uint32 t;
  98867. /* Update byte count */
  98868. t = ctx->bytes[0];
  98869. if ((ctx->bytes[0] = t + len) < t)
  98870. ctx->bytes[1]++; /* Carry from low to high */
  98871. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98872. if (t > len) {
  98873. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98874. return;
  98875. }
  98876. /* First chunk is an odd size */
  98877. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98878. byteSwapX16(ctx->in);
  98879. FLAC__MD5Transform(ctx->buf, ctx->in);
  98880. buf += t;
  98881. len -= t;
  98882. /* Process data in 64-byte chunks */
  98883. while (len >= 64) {
  98884. memcpy(ctx->in, buf, 64);
  98885. byteSwapX16(ctx->in);
  98886. FLAC__MD5Transform(ctx->buf, ctx->in);
  98887. buf += 64;
  98888. len -= 64;
  98889. }
  98890. /* Handle any remaining bytes of data. */
  98891. memcpy(ctx->in, buf, len);
  98892. }
  98893. /*
  98894. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98895. * initialization constants.
  98896. */
  98897. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98898. {
  98899. ctx->buf[0] = 0x67452301;
  98900. ctx->buf[1] = 0xefcdab89;
  98901. ctx->buf[2] = 0x98badcfe;
  98902. ctx->buf[3] = 0x10325476;
  98903. ctx->bytes[0] = 0;
  98904. ctx->bytes[1] = 0;
  98905. ctx->internal_buf = 0;
  98906. ctx->capacity = 0;
  98907. }
  98908. /*
  98909. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98910. * 1 0* (64-bit count of bits processed, MSB-first)
  98911. */
  98912. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98913. {
  98914. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98915. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98916. /* Set the first char of padding to 0x80. There is always room. */
  98917. *p++ = 0x80;
  98918. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98919. count = 56 - 1 - count;
  98920. if (count < 0) { /* Padding forces an extra block */
  98921. memset(p, 0, count + 8);
  98922. byteSwapX16(ctx->in);
  98923. FLAC__MD5Transform(ctx->buf, ctx->in);
  98924. p = (FLAC__byte *)ctx->in;
  98925. count = 56;
  98926. }
  98927. memset(p, 0, count);
  98928. byteSwap(ctx->in, 14);
  98929. /* Append length in bits and transform */
  98930. ctx->in[14] = ctx->bytes[0] << 3;
  98931. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98932. FLAC__MD5Transform(ctx->buf, ctx->in);
  98933. byteSwap(ctx->buf, 4);
  98934. memcpy(digest, ctx->buf, 16);
  98935. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98936. if(0 != ctx->internal_buf) {
  98937. free(ctx->internal_buf);
  98938. ctx->internal_buf = 0;
  98939. ctx->capacity = 0;
  98940. }
  98941. }
  98942. /*
  98943. * Convert the incoming audio signal to a byte stream
  98944. */
  98945. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98946. {
  98947. unsigned channel, sample;
  98948. register FLAC__int32 a_word;
  98949. register FLAC__byte *buf_ = buf;
  98950. #if WORDS_BIGENDIAN
  98951. #else
  98952. if(channels == 2 && bytes_per_sample == 2) {
  98953. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98954. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98955. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98956. *buf1_ = (FLAC__int16)signal[1][sample];
  98957. }
  98958. else if(channels == 1 && bytes_per_sample == 2) {
  98959. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98960. for(sample = 0; sample < samples; sample++)
  98961. *buf1_++ = (FLAC__int16)signal[0][sample];
  98962. }
  98963. else
  98964. #endif
  98965. if(bytes_per_sample == 2) {
  98966. if(channels == 2) {
  98967. for(sample = 0; sample < samples; sample++) {
  98968. a_word = signal[0][sample];
  98969. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98970. *buf_++ = (FLAC__byte)a_word;
  98971. a_word = signal[1][sample];
  98972. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98973. *buf_++ = (FLAC__byte)a_word;
  98974. }
  98975. }
  98976. else if(channels == 1) {
  98977. for(sample = 0; sample < samples; sample++) {
  98978. a_word = signal[0][sample];
  98979. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98980. *buf_++ = (FLAC__byte)a_word;
  98981. }
  98982. }
  98983. else {
  98984. for(sample = 0; sample < samples; sample++) {
  98985. for(channel = 0; channel < channels; channel++) {
  98986. a_word = signal[channel][sample];
  98987. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98988. *buf_++ = (FLAC__byte)a_word;
  98989. }
  98990. }
  98991. }
  98992. }
  98993. else if(bytes_per_sample == 3) {
  98994. if(channels == 2) {
  98995. for(sample = 0; sample < samples; sample++) {
  98996. a_word = signal[0][sample];
  98997. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98998. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98999. *buf_++ = (FLAC__byte)a_word;
  99000. a_word = signal[1][sample];
  99001. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99002. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99003. *buf_++ = (FLAC__byte)a_word;
  99004. }
  99005. }
  99006. else if(channels == 1) {
  99007. for(sample = 0; sample < samples; sample++) {
  99008. a_word = signal[0][sample];
  99009. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99010. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99011. *buf_++ = (FLAC__byte)a_word;
  99012. }
  99013. }
  99014. else {
  99015. for(sample = 0; sample < samples; sample++) {
  99016. for(channel = 0; channel < channels; channel++) {
  99017. a_word = signal[channel][sample];
  99018. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99019. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99020. *buf_++ = (FLAC__byte)a_word;
  99021. }
  99022. }
  99023. }
  99024. }
  99025. else if(bytes_per_sample == 1) {
  99026. if(channels == 2) {
  99027. for(sample = 0; sample < samples; sample++) {
  99028. a_word = signal[0][sample];
  99029. *buf_++ = (FLAC__byte)a_word;
  99030. a_word = signal[1][sample];
  99031. *buf_++ = (FLAC__byte)a_word;
  99032. }
  99033. }
  99034. else if(channels == 1) {
  99035. for(sample = 0; sample < samples; sample++) {
  99036. a_word = signal[0][sample];
  99037. *buf_++ = (FLAC__byte)a_word;
  99038. }
  99039. }
  99040. else {
  99041. for(sample = 0; sample < samples; sample++) {
  99042. for(channel = 0; channel < channels; channel++) {
  99043. a_word = signal[channel][sample];
  99044. *buf_++ = (FLAC__byte)a_word;
  99045. }
  99046. }
  99047. }
  99048. }
  99049. else { /* bytes_per_sample == 4, maybe optimize more later */
  99050. for(sample = 0; sample < samples; sample++) {
  99051. for(channel = 0; channel < channels; channel++) {
  99052. a_word = signal[channel][sample];
  99053. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99054. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99055. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99056. *buf_++ = (FLAC__byte)a_word;
  99057. }
  99058. }
  99059. }
  99060. }
  99061. /*
  99062. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99063. */
  99064. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99065. {
  99066. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99067. /* overflow check */
  99068. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99069. return false;
  99070. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99071. return false;
  99072. if(ctx->capacity < bytes_needed) {
  99073. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99074. if(0 == tmp) {
  99075. free(ctx->internal_buf);
  99076. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99077. return false;
  99078. }
  99079. ctx->internal_buf = tmp;
  99080. ctx->capacity = bytes_needed;
  99081. }
  99082. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99083. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99084. return true;
  99085. }
  99086. #endif
  99087. /*** End of inlined file: md5.c ***/
  99088. /*** Start of inlined file: memory.c ***/
  99089. /*** Start of inlined file: juce_FlacHeader.h ***/
  99090. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99091. // tasks..
  99092. #define VERSION "1.2.1"
  99093. #define FLAC__NO_DLL 1
  99094. #if JUCE_MSVC
  99095. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99096. #endif
  99097. #if JUCE_MAC
  99098. #define FLAC__SYS_DARWIN 1
  99099. #endif
  99100. /*** End of inlined file: juce_FlacHeader.h ***/
  99101. #if JUCE_USE_FLAC
  99102. #if HAVE_CONFIG_H
  99103. # include <config.h>
  99104. #endif
  99105. /*** Start of inlined file: memory.h ***/
  99106. #ifndef FLAC__PRIVATE__MEMORY_H
  99107. #define FLAC__PRIVATE__MEMORY_H
  99108. #ifdef HAVE_CONFIG_H
  99109. #include <config.h>
  99110. #endif
  99111. #include <stdlib.h> /* for size_t */
  99112. /* Returns the unaligned address returned by malloc.
  99113. * Use free() on this address to deallocate.
  99114. */
  99115. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99116. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99117. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99118. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99119. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99120. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99121. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99122. #endif
  99123. #endif
  99124. /*** End of inlined file: memory.h ***/
  99125. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99126. {
  99127. void *x;
  99128. FLAC__ASSERT(0 != aligned_address);
  99129. #ifdef FLAC__ALIGN_MALLOC_DATA
  99130. /* align on 32-byte (256-bit) boundary */
  99131. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99132. #ifdef SIZEOF_VOIDP
  99133. #if SIZEOF_VOIDP == 4
  99134. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99135. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99136. #elif SIZEOF_VOIDP == 8
  99137. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99138. #else
  99139. # error Unsupported sizeof(void*)
  99140. #endif
  99141. #else
  99142. /* there's got to be a better way to do this right for all archs */
  99143. if(sizeof(void*) == sizeof(unsigned))
  99144. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99145. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99146. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99147. else
  99148. return 0;
  99149. #endif
  99150. #else
  99151. x = safe_malloc_(bytes);
  99152. *aligned_address = x;
  99153. #endif
  99154. return x;
  99155. }
  99156. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99157. {
  99158. FLAC__int32 *pu; /* unaligned pointer */
  99159. union { /* union needed to comply with C99 pointer aliasing rules */
  99160. FLAC__int32 *pa; /* aligned pointer */
  99161. void *pv; /* aligned pointer alias */
  99162. } u;
  99163. FLAC__ASSERT(elements > 0);
  99164. FLAC__ASSERT(0 != unaligned_pointer);
  99165. FLAC__ASSERT(0 != aligned_pointer);
  99166. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99167. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99168. if(0 == pu) {
  99169. return false;
  99170. }
  99171. else {
  99172. if(*unaligned_pointer != 0)
  99173. free(*unaligned_pointer);
  99174. *unaligned_pointer = pu;
  99175. *aligned_pointer = u.pa;
  99176. return true;
  99177. }
  99178. }
  99179. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99180. {
  99181. FLAC__uint32 *pu; /* unaligned pointer */
  99182. union { /* union needed to comply with C99 pointer aliasing rules */
  99183. FLAC__uint32 *pa; /* aligned pointer */
  99184. void *pv; /* aligned pointer alias */
  99185. } u;
  99186. FLAC__ASSERT(elements > 0);
  99187. FLAC__ASSERT(0 != unaligned_pointer);
  99188. FLAC__ASSERT(0 != aligned_pointer);
  99189. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99190. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99191. if(0 == pu) {
  99192. return false;
  99193. }
  99194. else {
  99195. if(*unaligned_pointer != 0)
  99196. free(*unaligned_pointer);
  99197. *unaligned_pointer = pu;
  99198. *aligned_pointer = u.pa;
  99199. return true;
  99200. }
  99201. }
  99202. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99203. {
  99204. FLAC__uint64 *pu; /* unaligned pointer */
  99205. union { /* union needed to comply with C99 pointer aliasing rules */
  99206. FLAC__uint64 *pa; /* aligned pointer */
  99207. void *pv; /* aligned pointer alias */
  99208. } u;
  99209. FLAC__ASSERT(elements > 0);
  99210. FLAC__ASSERT(0 != unaligned_pointer);
  99211. FLAC__ASSERT(0 != aligned_pointer);
  99212. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99213. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99214. if(0 == pu) {
  99215. return false;
  99216. }
  99217. else {
  99218. if(*unaligned_pointer != 0)
  99219. free(*unaligned_pointer);
  99220. *unaligned_pointer = pu;
  99221. *aligned_pointer = u.pa;
  99222. return true;
  99223. }
  99224. }
  99225. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99226. {
  99227. unsigned *pu; /* unaligned pointer */
  99228. union { /* union needed to comply with C99 pointer aliasing rules */
  99229. unsigned *pa; /* aligned pointer */
  99230. void *pv; /* aligned pointer alias */
  99231. } u;
  99232. FLAC__ASSERT(elements > 0);
  99233. FLAC__ASSERT(0 != unaligned_pointer);
  99234. FLAC__ASSERT(0 != aligned_pointer);
  99235. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99236. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99237. if(0 == pu) {
  99238. return false;
  99239. }
  99240. else {
  99241. if(*unaligned_pointer != 0)
  99242. free(*unaligned_pointer);
  99243. *unaligned_pointer = pu;
  99244. *aligned_pointer = u.pa;
  99245. return true;
  99246. }
  99247. }
  99248. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99249. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99250. {
  99251. FLAC__real *pu; /* unaligned pointer */
  99252. union { /* union needed to comply with C99 pointer aliasing rules */
  99253. FLAC__real *pa; /* aligned pointer */
  99254. void *pv; /* aligned pointer alias */
  99255. } u;
  99256. FLAC__ASSERT(elements > 0);
  99257. FLAC__ASSERT(0 != unaligned_pointer);
  99258. FLAC__ASSERT(0 != aligned_pointer);
  99259. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99260. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99261. if(0 == pu) {
  99262. return false;
  99263. }
  99264. else {
  99265. if(*unaligned_pointer != 0)
  99266. free(*unaligned_pointer);
  99267. *unaligned_pointer = pu;
  99268. *aligned_pointer = u.pa;
  99269. return true;
  99270. }
  99271. }
  99272. #endif
  99273. #endif
  99274. /*** End of inlined file: memory.c ***/
  99275. /*** Start of inlined file: stream_decoder.c ***/
  99276. /*** Start of inlined file: juce_FlacHeader.h ***/
  99277. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99278. // tasks..
  99279. #define VERSION "1.2.1"
  99280. #define FLAC__NO_DLL 1
  99281. #if JUCE_MSVC
  99282. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99283. #endif
  99284. #if JUCE_MAC
  99285. #define FLAC__SYS_DARWIN 1
  99286. #endif
  99287. /*** End of inlined file: juce_FlacHeader.h ***/
  99288. #if JUCE_USE_FLAC
  99289. #if HAVE_CONFIG_H
  99290. # include <config.h>
  99291. #endif
  99292. #if defined _MSC_VER || defined __MINGW32__
  99293. #include <io.h> /* for _setmode() */
  99294. #include <fcntl.h> /* for _O_BINARY */
  99295. #endif
  99296. #if defined __CYGWIN__ || defined __EMX__
  99297. #include <io.h> /* for setmode(), O_BINARY */
  99298. #include <fcntl.h> /* for _O_BINARY */
  99299. #endif
  99300. #include <stdio.h>
  99301. #include <stdlib.h> /* for malloc() */
  99302. #include <string.h> /* for memset/memcpy() */
  99303. #include <sys/stat.h> /* for stat() */
  99304. #include <sys/types.h> /* for off_t */
  99305. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99306. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99307. #define fseeko fseek
  99308. #define ftello ftell
  99309. #endif
  99310. #endif
  99311. /*** Start of inlined file: stream_decoder.h ***/
  99312. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99313. #define FLAC__PROTECTED__STREAM_DECODER_H
  99314. #if FLAC__HAS_OGG
  99315. #include "include/private/ogg_decoder_aspect.h"
  99316. #endif
  99317. typedef struct FLAC__StreamDecoderProtected {
  99318. FLAC__StreamDecoderState state;
  99319. unsigned channels;
  99320. FLAC__ChannelAssignment channel_assignment;
  99321. unsigned bits_per_sample;
  99322. unsigned sample_rate; /* in Hz */
  99323. unsigned blocksize; /* in samples (per channel) */
  99324. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99325. #if FLAC__HAS_OGG
  99326. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99327. #endif
  99328. } FLAC__StreamDecoderProtected;
  99329. /*
  99330. * return the number of input bytes consumed
  99331. */
  99332. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99333. #endif
  99334. /*** End of inlined file: stream_decoder.h ***/
  99335. #ifdef max
  99336. #undef max
  99337. #endif
  99338. #define max(a,b) ((a)>(b)?(a):(b))
  99339. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99340. #ifdef _MSC_VER
  99341. #define FLAC__U64L(x) x
  99342. #else
  99343. #define FLAC__U64L(x) x##LLU
  99344. #endif
  99345. /* technically this should be in an "export.c" but this is convenient enough */
  99346. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99347. #if FLAC__HAS_OGG
  99348. 1
  99349. #else
  99350. 0
  99351. #endif
  99352. ;
  99353. /***********************************************************************
  99354. *
  99355. * Private static data
  99356. *
  99357. ***********************************************************************/
  99358. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99359. /***********************************************************************
  99360. *
  99361. * Private class method prototypes
  99362. *
  99363. ***********************************************************************/
  99364. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99365. static FILE *get_binary_stdin_(void);
  99366. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99367. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99368. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99369. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99370. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99371. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99372. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99373. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99374. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99375. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99376. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99377. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99378. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99379. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99380. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99381. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99382. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99383. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99384. 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);
  99385. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99386. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99387. #if FLAC__HAS_OGG
  99388. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99389. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99390. #endif
  99391. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99392. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99393. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99394. #if FLAC__HAS_OGG
  99395. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99396. #endif
  99397. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99398. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99399. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99400. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99401. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99402. /***********************************************************************
  99403. *
  99404. * Private class data
  99405. *
  99406. ***********************************************************************/
  99407. typedef struct FLAC__StreamDecoderPrivate {
  99408. #if FLAC__HAS_OGG
  99409. FLAC__bool is_ogg;
  99410. #endif
  99411. FLAC__StreamDecoderReadCallback read_callback;
  99412. FLAC__StreamDecoderSeekCallback seek_callback;
  99413. FLAC__StreamDecoderTellCallback tell_callback;
  99414. FLAC__StreamDecoderLengthCallback length_callback;
  99415. FLAC__StreamDecoderEofCallback eof_callback;
  99416. FLAC__StreamDecoderWriteCallback write_callback;
  99417. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99418. FLAC__StreamDecoderErrorCallback error_callback;
  99419. /* generic 32-bit datapath: */
  99420. 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[]);
  99421. /* generic 64-bit datapath: */
  99422. 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[]);
  99423. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99424. 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[]);
  99425. /* 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: */
  99426. 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[]);
  99427. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99428. void *client_data;
  99429. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99430. FLAC__BitReader *input;
  99431. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99432. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99433. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99434. unsigned output_capacity, output_channels;
  99435. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99436. FLAC__uint64 samples_decoded;
  99437. FLAC__bool has_stream_info, has_seek_table;
  99438. FLAC__StreamMetadata stream_info;
  99439. FLAC__StreamMetadata seek_table;
  99440. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99441. FLAC__byte *metadata_filter_ids;
  99442. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99443. FLAC__Frame frame;
  99444. FLAC__bool cached; /* true if there is a byte in lookahead */
  99445. FLAC__CPUInfo cpuinfo;
  99446. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99447. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99448. /* unaligned (original) pointers to allocated data */
  99449. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99450. 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 */
  99451. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99452. FLAC__bool is_seeking;
  99453. FLAC__MD5Context md5context;
  99454. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99455. /* (the rest of these are only used for seeking) */
  99456. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99457. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99458. FLAC__uint64 target_sample;
  99459. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99460. #if FLAC__HAS_OGG
  99461. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99462. #endif
  99463. } FLAC__StreamDecoderPrivate;
  99464. /***********************************************************************
  99465. *
  99466. * Public static class data
  99467. *
  99468. ***********************************************************************/
  99469. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99470. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99471. "FLAC__STREAM_DECODER_READ_METADATA",
  99472. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99473. "FLAC__STREAM_DECODER_READ_FRAME",
  99474. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99475. "FLAC__STREAM_DECODER_OGG_ERROR",
  99476. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99477. "FLAC__STREAM_DECODER_ABORTED",
  99478. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99479. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99480. };
  99481. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99482. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99483. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99484. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99485. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99486. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99487. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99488. };
  99489. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99490. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99491. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99492. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99493. };
  99494. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99495. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99496. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99497. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99498. };
  99499. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99500. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99501. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99502. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99503. };
  99504. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99505. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99506. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99507. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99508. };
  99509. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99510. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99511. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99512. };
  99513. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99514. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99515. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99516. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99517. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99518. };
  99519. /***********************************************************************
  99520. *
  99521. * Class constructor/destructor
  99522. *
  99523. ***********************************************************************/
  99524. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99525. {
  99526. FLAC__StreamDecoder *decoder;
  99527. unsigned i;
  99528. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99529. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99530. if(decoder == 0) {
  99531. return 0;
  99532. }
  99533. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99534. if(decoder->protected_ == 0) {
  99535. free(decoder);
  99536. return 0;
  99537. }
  99538. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99539. if(decoder->private_ == 0) {
  99540. free(decoder->protected_);
  99541. free(decoder);
  99542. return 0;
  99543. }
  99544. decoder->private_->input = FLAC__bitreader_new();
  99545. if(decoder->private_->input == 0) {
  99546. free(decoder->private_);
  99547. free(decoder->protected_);
  99548. free(decoder);
  99549. return 0;
  99550. }
  99551. decoder->private_->metadata_filter_ids_capacity = 16;
  99552. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99553. FLAC__bitreader_delete(decoder->private_->input);
  99554. free(decoder->private_);
  99555. free(decoder->protected_);
  99556. free(decoder);
  99557. return 0;
  99558. }
  99559. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99560. decoder->private_->output[i] = 0;
  99561. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99562. }
  99563. decoder->private_->output_capacity = 0;
  99564. decoder->private_->output_channels = 0;
  99565. decoder->private_->has_seek_table = false;
  99566. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99567. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99568. decoder->private_->file = 0;
  99569. set_defaults_dec(decoder);
  99570. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99571. return decoder;
  99572. }
  99573. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99574. {
  99575. unsigned i;
  99576. FLAC__ASSERT(0 != decoder);
  99577. FLAC__ASSERT(0 != decoder->protected_);
  99578. FLAC__ASSERT(0 != decoder->private_);
  99579. FLAC__ASSERT(0 != decoder->private_->input);
  99580. (void)FLAC__stream_decoder_finish(decoder);
  99581. if(0 != decoder->private_->metadata_filter_ids)
  99582. free(decoder->private_->metadata_filter_ids);
  99583. FLAC__bitreader_delete(decoder->private_->input);
  99584. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99585. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99586. free(decoder->private_);
  99587. free(decoder->protected_);
  99588. free(decoder);
  99589. }
  99590. /***********************************************************************
  99591. *
  99592. * Public class methods
  99593. *
  99594. ***********************************************************************/
  99595. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99596. FLAC__StreamDecoder *decoder,
  99597. FLAC__StreamDecoderReadCallback read_callback,
  99598. FLAC__StreamDecoderSeekCallback seek_callback,
  99599. FLAC__StreamDecoderTellCallback tell_callback,
  99600. FLAC__StreamDecoderLengthCallback length_callback,
  99601. FLAC__StreamDecoderEofCallback eof_callback,
  99602. FLAC__StreamDecoderWriteCallback write_callback,
  99603. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99604. FLAC__StreamDecoderErrorCallback error_callback,
  99605. void *client_data,
  99606. FLAC__bool is_ogg
  99607. )
  99608. {
  99609. FLAC__ASSERT(0 != decoder);
  99610. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99611. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99612. #if !FLAC__HAS_OGG
  99613. if(is_ogg)
  99614. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99615. #endif
  99616. if(
  99617. 0 == read_callback ||
  99618. 0 == write_callback ||
  99619. 0 == error_callback ||
  99620. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99621. )
  99622. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99623. #if FLAC__HAS_OGG
  99624. decoder->private_->is_ogg = is_ogg;
  99625. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99626. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99627. #endif
  99628. /*
  99629. * get the CPU info and set the function pointers
  99630. */
  99631. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99632. /* first default to the non-asm routines */
  99633. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99634. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99635. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99636. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99637. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99638. /* now override with asm where appropriate */
  99639. #ifndef FLAC__NO_ASM
  99640. if(decoder->private_->cpuinfo.use_asm) {
  99641. #ifdef FLAC__CPU_IA32
  99642. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99643. #ifdef FLAC__HAS_NASM
  99644. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99645. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99646. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99647. #endif
  99648. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99649. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99650. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99651. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99652. }
  99653. else {
  99654. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99655. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99656. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99657. }
  99658. #endif
  99659. #elif defined FLAC__CPU_PPC
  99660. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99661. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99662. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99663. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99664. }
  99665. #endif
  99666. }
  99667. #endif
  99668. /* from here on, errors are fatal */
  99669. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99670. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99671. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99672. }
  99673. decoder->private_->read_callback = read_callback;
  99674. decoder->private_->seek_callback = seek_callback;
  99675. decoder->private_->tell_callback = tell_callback;
  99676. decoder->private_->length_callback = length_callback;
  99677. decoder->private_->eof_callback = eof_callback;
  99678. decoder->private_->write_callback = write_callback;
  99679. decoder->private_->metadata_callback = metadata_callback;
  99680. decoder->private_->error_callback = error_callback;
  99681. decoder->private_->client_data = client_data;
  99682. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99683. decoder->private_->samples_decoded = 0;
  99684. decoder->private_->has_stream_info = false;
  99685. decoder->private_->cached = false;
  99686. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99687. decoder->private_->is_seeking = false;
  99688. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99689. if(!FLAC__stream_decoder_reset(decoder)) {
  99690. /* above call sets the state for us */
  99691. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99692. }
  99693. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99694. }
  99695. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99696. FLAC__StreamDecoder *decoder,
  99697. FLAC__StreamDecoderReadCallback read_callback,
  99698. FLAC__StreamDecoderSeekCallback seek_callback,
  99699. FLAC__StreamDecoderTellCallback tell_callback,
  99700. FLAC__StreamDecoderLengthCallback length_callback,
  99701. FLAC__StreamDecoderEofCallback eof_callback,
  99702. FLAC__StreamDecoderWriteCallback write_callback,
  99703. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99704. FLAC__StreamDecoderErrorCallback error_callback,
  99705. void *client_data
  99706. )
  99707. {
  99708. return init_stream_internal_dec(
  99709. decoder,
  99710. read_callback,
  99711. seek_callback,
  99712. tell_callback,
  99713. length_callback,
  99714. eof_callback,
  99715. write_callback,
  99716. metadata_callback,
  99717. error_callback,
  99718. client_data,
  99719. /*is_ogg=*/false
  99720. );
  99721. }
  99722. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99723. FLAC__StreamDecoder *decoder,
  99724. FLAC__StreamDecoderReadCallback read_callback,
  99725. FLAC__StreamDecoderSeekCallback seek_callback,
  99726. FLAC__StreamDecoderTellCallback tell_callback,
  99727. FLAC__StreamDecoderLengthCallback length_callback,
  99728. FLAC__StreamDecoderEofCallback eof_callback,
  99729. FLAC__StreamDecoderWriteCallback write_callback,
  99730. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99731. FLAC__StreamDecoderErrorCallback error_callback,
  99732. void *client_data
  99733. )
  99734. {
  99735. return init_stream_internal_dec(
  99736. decoder,
  99737. read_callback,
  99738. seek_callback,
  99739. tell_callback,
  99740. length_callback,
  99741. eof_callback,
  99742. write_callback,
  99743. metadata_callback,
  99744. error_callback,
  99745. client_data,
  99746. /*is_ogg=*/true
  99747. );
  99748. }
  99749. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99750. FLAC__StreamDecoder *decoder,
  99751. FILE *file,
  99752. FLAC__StreamDecoderWriteCallback write_callback,
  99753. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99754. FLAC__StreamDecoderErrorCallback error_callback,
  99755. void *client_data,
  99756. FLAC__bool is_ogg
  99757. )
  99758. {
  99759. FLAC__ASSERT(0 != decoder);
  99760. FLAC__ASSERT(0 != file);
  99761. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99762. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99763. if(0 == write_callback || 0 == error_callback)
  99764. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99765. /*
  99766. * To make sure that our file does not go unclosed after an error, we
  99767. * must assign the FILE pointer before any further error can occur in
  99768. * this routine.
  99769. */
  99770. if(file == stdin)
  99771. file = get_binary_stdin_(); /* just to be safe */
  99772. decoder->private_->file = file;
  99773. return init_stream_internal_dec(
  99774. decoder,
  99775. file_read_callback_dec,
  99776. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99777. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99778. decoder->private_->file == stdin? 0: file_length_callback_,
  99779. file_eof_callback_,
  99780. write_callback,
  99781. metadata_callback,
  99782. error_callback,
  99783. client_data,
  99784. is_ogg
  99785. );
  99786. }
  99787. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99788. FLAC__StreamDecoder *decoder,
  99789. FILE *file,
  99790. FLAC__StreamDecoderWriteCallback write_callback,
  99791. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99792. FLAC__StreamDecoderErrorCallback error_callback,
  99793. void *client_data
  99794. )
  99795. {
  99796. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99797. }
  99798. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99799. FLAC__StreamDecoder *decoder,
  99800. FILE *file,
  99801. FLAC__StreamDecoderWriteCallback write_callback,
  99802. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99803. FLAC__StreamDecoderErrorCallback error_callback,
  99804. void *client_data
  99805. )
  99806. {
  99807. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99808. }
  99809. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99810. FLAC__StreamDecoder *decoder,
  99811. const char *filename,
  99812. FLAC__StreamDecoderWriteCallback write_callback,
  99813. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99814. FLAC__StreamDecoderErrorCallback error_callback,
  99815. void *client_data,
  99816. FLAC__bool is_ogg
  99817. )
  99818. {
  99819. FILE *file;
  99820. FLAC__ASSERT(0 != decoder);
  99821. /*
  99822. * To make sure that our file does not go unclosed after an error, we
  99823. * have to do the same entrance checks here that are later performed
  99824. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99825. */
  99826. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99827. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99828. if(0 == write_callback || 0 == error_callback)
  99829. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99830. file = filename? fopen(filename, "rb") : stdin;
  99831. if(0 == file)
  99832. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99833. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99834. }
  99835. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99836. FLAC__StreamDecoder *decoder,
  99837. const char *filename,
  99838. FLAC__StreamDecoderWriteCallback write_callback,
  99839. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99840. FLAC__StreamDecoderErrorCallback error_callback,
  99841. void *client_data
  99842. )
  99843. {
  99844. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99845. }
  99846. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99847. FLAC__StreamDecoder *decoder,
  99848. const char *filename,
  99849. FLAC__StreamDecoderWriteCallback write_callback,
  99850. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99851. FLAC__StreamDecoderErrorCallback error_callback,
  99852. void *client_data
  99853. )
  99854. {
  99855. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99856. }
  99857. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99858. {
  99859. FLAC__bool md5_failed = false;
  99860. unsigned i;
  99861. FLAC__ASSERT(0 != decoder);
  99862. FLAC__ASSERT(0 != decoder->private_);
  99863. FLAC__ASSERT(0 != decoder->protected_);
  99864. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99865. return true;
  99866. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99867. * always call FLAC__MD5Final()
  99868. */
  99869. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99870. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99871. free(decoder->private_->seek_table.data.seek_table.points);
  99872. decoder->private_->seek_table.data.seek_table.points = 0;
  99873. decoder->private_->has_seek_table = false;
  99874. }
  99875. FLAC__bitreader_free(decoder->private_->input);
  99876. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99877. /* WATCHOUT:
  99878. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99879. * output arrays have a buffer of up to 3 zeroes in front
  99880. * (at negative indices) for alignment purposes; we use 4
  99881. * to keep the data well-aligned.
  99882. */
  99883. if(0 != decoder->private_->output[i]) {
  99884. free(decoder->private_->output[i]-4);
  99885. decoder->private_->output[i] = 0;
  99886. }
  99887. if(0 != decoder->private_->residual_unaligned[i]) {
  99888. free(decoder->private_->residual_unaligned[i]);
  99889. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99890. }
  99891. }
  99892. decoder->private_->output_capacity = 0;
  99893. decoder->private_->output_channels = 0;
  99894. #if FLAC__HAS_OGG
  99895. if(decoder->private_->is_ogg)
  99896. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99897. #endif
  99898. if(0 != decoder->private_->file) {
  99899. if(decoder->private_->file != stdin)
  99900. fclose(decoder->private_->file);
  99901. decoder->private_->file = 0;
  99902. }
  99903. if(decoder->private_->do_md5_checking) {
  99904. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99905. md5_failed = true;
  99906. }
  99907. decoder->private_->is_seeking = false;
  99908. set_defaults_dec(decoder);
  99909. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99910. return !md5_failed;
  99911. }
  99912. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99913. {
  99914. FLAC__ASSERT(0 != decoder);
  99915. FLAC__ASSERT(0 != decoder->private_);
  99916. FLAC__ASSERT(0 != decoder->protected_);
  99917. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99918. return false;
  99919. #if FLAC__HAS_OGG
  99920. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99921. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99922. return true;
  99923. #else
  99924. (void)value;
  99925. return false;
  99926. #endif
  99927. }
  99928. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99929. {
  99930. FLAC__ASSERT(0 != decoder);
  99931. FLAC__ASSERT(0 != decoder->protected_);
  99932. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99933. return false;
  99934. decoder->protected_->md5_checking = value;
  99935. return true;
  99936. }
  99937. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99938. {
  99939. FLAC__ASSERT(0 != decoder);
  99940. FLAC__ASSERT(0 != decoder->private_);
  99941. FLAC__ASSERT(0 != decoder->protected_);
  99942. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99943. /* double protection */
  99944. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99945. return false;
  99946. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99947. return false;
  99948. decoder->private_->metadata_filter[type] = true;
  99949. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99950. decoder->private_->metadata_filter_ids_count = 0;
  99951. return true;
  99952. }
  99953. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99954. {
  99955. FLAC__ASSERT(0 != decoder);
  99956. FLAC__ASSERT(0 != decoder->private_);
  99957. FLAC__ASSERT(0 != decoder->protected_);
  99958. FLAC__ASSERT(0 != id);
  99959. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99960. return false;
  99961. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99962. return true;
  99963. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99964. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99965. 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))) {
  99966. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99967. return false;
  99968. }
  99969. decoder->private_->metadata_filter_ids_capacity *= 2;
  99970. }
  99971. 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));
  99972. decoder->private_->metadata_filter_ids_count++;
  99973. return true;
  99974. }
  99975. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99976. {
  99977. unsigned i;
  99978. FLAC__ASSERT(0 != decoder);
  99979. FLAC__ASSERT(0 != decoder->private_);
  99980. FLAC__ASSERT(0 != decoder->protected_);
  99981. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99982. return false;
  99983. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99984. decoder->private_->metadata_filter[i] = true;
  99985. decoder->private_->metadata_filter_ids_count = 0;
  99986. return true;
  99987. }
  99988. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99989. {
  99990. FLAC__ASSERT(0 != decoder);
  99991. FLAC__ASSERT(0 != decoder->private_);
  99992. FLAC__ASSERT(0 != decoder->protected_);
  99993. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99994. /* double protection */
  99995. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99996. return false;
  99997. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99998. return false;
  99999. decoder->private_->metadata_filter[type] = false;
  100000. if(type == FLAC__METADATA_TYPE_APPLICATION)
  100001. decoder->private_->metadata_filter_ids_count = 0;
  100002. return true;
  100003. }
  100004. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  100005. {
  100006. FLAC__ASSERT(0 != decoder);
  100007. FLAC__ASSERT(0 != decoder->private_);
  100008. FLAC__ASSERT(0 != decoder->protected_);
  100009. FLAC__ASSERT(0 != id);
  100010. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100011. return false;
  100012. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  100013. return true;
  100014. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  100015. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  100016. 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))) {
  100017. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100018. return false;
  100019. }
  100020. decoder->private_->metadata_filter_ids_capacity *= 2;
  100021. }
  100022. 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));
  100023. decoder->private_->metadata_filter_ids_count++;
  100024. return true;
  100025. }
  100026. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  100027. {
  100028. FLAC__ASSERT(0 != decoder);
  100029. FLAC__ASSERT(0 != decoder->private_);
  100030. FLAC__ASSERT(0 != decoder->protected_);
  100031. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100032. return false;
  100033. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100034. decoder->private_->metadata_filter_ids_count = 0;
  100035. return true;
  100036. }
  100037. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  100038. {
  100039. FLAC__ASSERT(0 != decoder);
  100040. FLAC__ASSERT(0 != decoder->protected_);
  100041. return decoder->protected_->state;
  100042. }
  100043. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  100044. {
  100045. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  100046. }
  100047. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  100048. {
  100049. FLAC__ASSERT(0 != decoder);
  100050. FLAC__ASSERT(0 != decoder->protected_);
  100051. return decoder->protected_->md5_checking;
  100052. }
  100053. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100054. {
  100055. FLAC__ASSERT(0 != decoder);
  100056. FLAC__ASSERT(0 != decoder->protected_);
  100057. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100058. }
  100059. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100060. {
  100061. FLAC__ASSERT(0 != decoder);
  100062. FLAC__ASSERT(0 != decoder->protected_);
  100063. return decoder->protected_->channels;
  100064. }
  100065. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100066. {
  100067. FLAC__ASSERT(0 != decoder);
  100068. FLAC__ASSERT(0 != decoder->protected_);
  100069. return decoder->protected_->channel_assignment;
  100070. }
  100071. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100072. {
  100073. FLAC__ASSERT(0 != decoder);
  100074. FLAC__ASSERT(0 != decoder->protected_);
  100075. return decoder->protected_->bits_per_sample;
  100076. }
  100077. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100078. {
  100079. FLAC__ASSERT(0 != decoder);
  100080. FLAC__ASSERT(0 != decoder->protected_);
  100081. return decoder->protected_->sample_rate;
  100082. }
  100083. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100084. {
  100085. FLAC__ASSERT(0 != decoder);
  100086. FLAC__ASSERT(0 != decoder->protected_);
  100087. return decoder->protected_->blocksize;
  100088. }
  100089. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100090. {
  100091. FLAC__ASSERT(0 != decoder);
  100092. FLAC__ASSERT(0 != decoder->private_);
  100093. FLAC__ASSERT(0 != position);
  100094. #if FLAC__HAS_OGG
  100095. if(decoder->private_->is_ogg)
  100096. return false;
  100097. #endif
  100098. if(0 == decoder->private_->tell_callback)
  100099. return false;
  100100. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100101. return false;
  100102. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100103. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100104. return false;
  100105. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100106. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100107. return true;
  100108. }
  100109. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100110. {
  100111. FLAC__ASSERT(0 != decoder);
  100112. FLAC__ASSERT(0 != decoder->private_);
  100113. FLAC__ASSERT(0 != decoder->protected_);
  100114. decoder->private_->samples_decoded = 0;
  100115. decoder->private_->do_md5_checking = false;
  100116. #if FLAC__HAS_OGG
  100117. if(decoder->private_->is_ogg)
  100118. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100119. #endif
  100120. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100121. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100122. return false;
  100123. }
  100124. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100125. return true;
  100126. }
  100127. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100128. {
  100129. FLAC__ASSERT(0 != decoder);
  100130. FLAC__ASSERT(0 != decoder->private_);
  100131. FLAC__ASSERT(0 != decoder->protected_);
  100132. if(!FLAC__stream_decoder_flush(decoder)) {
  100133. /* above call sets the state for us */
  100134. return false;
  100135. }
  100136. #if FLAC__HAS_OGG
  100137. /*@@@ could go in !internal_reset_hack block below */
  100138. if(decoder->private_->is_ogg)
  100139. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100140. #endif
  100141. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100142. * (internal_reset_hack) don't try to rewind since we are already at
  100143. * the beginning of the stream and don't want to fail if the input is
  100144. * not seekable.
  100145. */
  100146. if(!decoder->private_->internal_reset_hack) {
  100147. if(decoder->private_->file == stdin)
  100148. return false; /* can't rewind stdin, reset fails */
  100149. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100150. return false; /* seekable and seek fails, reset fails */
  100151. }
  100152. else
  100153. decoder->private_->internal_reset_hack = false;
  100154. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100155. decoder->private_->has_stream_info = false;
  100156. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100157. free(decoder->private_->seek_table.data.seek_table.points);
  100158. decoder->private_->seek_table.data.seek_table.points = 0;
  100159. decoder->private_->has_seek_table = false;
  100160. }
  100161. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100162. /*
  100163. * This goes in reset() and not flush() because according to the spec, a
  100164. * fixed-blocksize stream must stay that way through the whole stream.
  100165. */
  100166. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100167. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100168. * is because md5 checking may be turned on to start and then turned off if
  100169. * a seek occurs. So we init the context here and finalize it in
  100170. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100171. * properly.
  100172. */
  100173. FLAC__MD5Init(&decoder->private_->md5context);
  100174. decoder->private_->first_frame_offset = 0;
  100175. decoder->private_->unparseable_frame_count = 0;
  100176. return true;
  100177. }
  100178. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100179. {
  100180. FLAC__bool got_a_frame;
  100181. FLAC__ASSERT(0 != decoder);
  100182. FLAC__ASSERT(0 != decoder->protected_);
  100183. while(1) {
  100184. switch(decoder->protected_->state) {
  100185. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100186. if(!find_metadata_(decoder))
  100187. return false; /* above function sets the status for us */
  100188. break;
  100189. case FLAC__STREAM_DECODER_READ_METADATA:
  100190. if(!read_metadata_(decoder))
  100191. return false; /* above function sets the status for us */
  100192. else
  100193. return true;
  100194. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100195. if(!frame_sync_(decoder))
  100196. return true; /* above function sets the status for us */
  100197. break;
  100198. case FLAC__STREAM_DECODER_READ_FRAME:
  100199. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100200. return false; /* above function sets the status for us */
  100201. if(got_a_frame)
  100202. return true; /* above function sets the status for us */
  100203. break;
  100204. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100205. case FLAC__STREAM_DECODER_ABORTED:
  100206. return true;
  100207. default:
  100208. FLAC__ASSERT(0);
  100209. return false;
  100210. }
  100211. }
  100212. }
  100213. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100214. {
  100215. FLAC__ASSERT(0 != decoder);
  100216. FLAC__ASSERT(0 != decoder->protected_);
  100217. while(1) {
  100218. switch(decoder->protected_->state) {
  100219. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100220. if(!find_metadata_(decoder))
  100221. return false; /* above function sets the status for us */
  100222. break;
  100223. case FLAC__STREAM_DECODER_READ_METADATA:
  100224. if(!read_metadata_(decoder))
  100225. return false; /* above function sets the status for us */
  100226. break;
  100227. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100228. case FLAC__STREAM_DECODER_READ_FRAME:
  100229. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100230. case FLAC__STREAM_DECODER_ABORTED:
  100231. return true;
  100232. default:
  100233. FLAC__ASSERT(0);
  100234. return false;
  100235. }
  100236. }
  100237. }
  100238. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100239. {
  100240. FLAC__bool dummy;
  100241. FLAC__ASSERT(0 != decoder);
  100242. FLAC__ASSERT(0 != decoder->protected_);
  100243. while(1) {
  100244. switch(decoder->protected_->state) {
  100245. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100246. if(!find_metadata_(decoder))
  100247. return false; /* above function sets the status for us */
  100248. break;
  100249. case FLAC__STREAM_DECODER_READ_METADATA:
  100250. if(!read_metadata_(decoder))
  100251. return false; /* above function sets the status for us */
  100252. break;
  100253. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100254. if(!frame_sync_(decoder))
  100255. return true; /* above function sets the status for us */
  100256. break;
  100257. case FLAC__STREAM_DECODER_READ_FRAME:
  100258. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100259. return false; /* above function sets the status for us */
  100260. break;
  100261. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100262. case FLAC__STREAM_DECODER_ABORTED:
  100263. return true;
  100264. default:
  100265. FLAC__ASSERT(0);
  100266. return false;
  100267. }
  100268. }
  100269. }
  100270. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100271. {
  100272. FLAC__bool got_a_frame;
  100273. FLAC__ASSERT(0 != decoder);
  100274. FLAC__ASSERT(0 != decoder->protected_);
  100275. while(1) {
  100276. switch(decoder->protected_->state) {
  100277. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100278. case FLAC__STREAM_DECODER_READ_METADATA:
  100279. return false; /* above function sets the status for us */
  100280. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100281. if(!frame_sync_(decoder))
  100282. return true; /* above function sets the status for us */
  100283. break;
  100284. case FLAC__STREAM_DECODER_READ_FRAME:
  100285. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100286. return false; /* above function sets the status for us */
  100287. if(got_a_frame)
  100288. return true; /* above function sets the status for us */
  100289. break;
  100290. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100291. case FLAC__STREAM_DECODER_ABORTED:
  100292. return true;
  100293. default:
  100294. FLAC__ASSERT(0);
  100295. return false;
  100296. }
  100297. }
  100298. }
  100299. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100300. {
  100301. FLAC__uint64 length;
  100302. FLAC__ASSERT(0 != decoder);
  100303. if(
  100304. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100305. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100306. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100307. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100308. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100309. )
  100310. return false;
  100311. if(0 == decoder->private_->seek_callback)
  100312. return false;
  100313. FLAC__ASSERT(decoder->private_->seek_callback);
  100314. FLAC__ASSERT(decoder->private_->tell_callback);
  100315. FLAC__ASSERT(decoder->private_->length_callback);
  100316. FLAC__ASSERT(decoder->private_->eof_callback);
  100317. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100318. return false;
  100319. decoder->private_->is_seeking = true;
  100320. /* turn off md5 checking if a seek is attempted */
  100321. decoder->private_->do_md5_checking = false;
  100322. /* 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) */
  100323. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100324. decoder->private_->is_seeking = false;
  100325. return false;
  100326. }
  100327. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100328. if(
  100329. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100330. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100331. ) {
  100332. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100333. /* above call sets the state for us */
  100334. decoder->private_->is_seeking = false;
  100335. return false;
  100336. }
  100337. /* check this again in case we didn't know total_samples the first time */
  100338. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100339. decoder->private_->is_seeking = false;
  100340. return false;
  100341. }
  100342. }
  100343. {
  100344. const FLAC__bool ok =
  100345. #if FLAC__HAS_OGG
  100346. decoder->private_->is_ogg?
  100347. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100348. #endif
  100349. seek_to_absolute_sample_(decoder, length, sample)
  100350. ;
  100351. decoder->private_->is_seeking = false;
  100352. return ok;
  100353. }
  100354. }
  100355. /***********************************************************************
  100356. *
  100357. * Protected class methods
  100358. *
  100359. ***********************************************************************/
  100360. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100361. {
  100362. FLAC__ASSERT(0 != decoder);
  100363. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100364. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100365. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100366. }
  100367. /***********************************************************************
  100368. *
  100369. * Private class methods
  100370. *
  100371. ***********************************************************************/
  100372. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100373. {
  100374. #if FLAC__HAS_OGG
  100375. decoder->private_->is_ogg = false;
  100376. #endif
  100377. decoder->private_->read_callback = 0;
  100378. decoder->private_->seek_callback = 0;
  100379. decoder->private_->tell_callback = 0;
  100380. decoder->private_->length_callback = 0;
  100381. decoder->private_->eof_callback = 0;
  100382. decoder->private_->write_callback = 0;
  100383. decoder->private_->metadata_callback = 0;
  100384. decoder->private_->error_callback = 0;
  100385. decoder->private_->client_data = 0;
  100386. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100387. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100388. decoder->private_->metadata_filter_ids_count = 0;
  100389. decoder->protected_->md5_checking = false;
  100390. #if FLAC__HAS_OGG
  100391. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100392. #endif
  100393. }
  100394. /*
  100395. * This will forcibly set stdin to binary mode (for OSes that require it)
  100396. */
  100397. FILE *get_binary_stdin_(void)
  100398. {
  100399. /* if something breaks here it is probably due to the presence or
  100400. * absence of an underscore before the identifiers 'setmode',
  100401. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100402. */
  100403. #if defined _MSC_VER || defined __MINGW32__
  100404. _setmode(_fileno(stdin), _O_BINARY);
  100405. #elif defined __CYGWIN__
  100406. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100407. setmode(_fileno(stdin), _O_BINARY);
  100408. #elif defined __EMX__
  100409. setmode(fileno(stdin), O_BINARY);
  100410. #endif
  100411. return stdin;
  100412. }
  100413. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100414. {
  100415. unsigned i;
  100416. FLAC__int32 *tmp;
  100417. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100418. return true;
  100419. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100420. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100421. if(0 != decoder->private_->output[i]) {
  100422. free(decoder->private_->output[i]-4);
  100423. decoder->private_->output[i] = 0;
  100424. }
  100425. if(0 != decoder->private_->residual_unaligned[i]) {
  100426. free(decoder->private_->residual_unaligned[i]);
  100427. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100428. }
  100429. }
  100430. for(i = 0; i < channels; i++) {
  100431. /* WATCHOUT:
  100432. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100433. * output arrays have a buffer of up to 3 zeroes in front
  100434. * (at negative indices) for alignment purposes; we use 4
  100435. * to keep the data well-aligned.
  100436. */
  100437. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100438. if(tmp == 0) {
  100439. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100440. return false;
  100441. }
  100442. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100443. decoder->private_->output[i] = tmp + 4;
  100444. /* WATCHOUT:
  100445. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100446. */
  100447. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100448. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100449. return false;
  100450. }
  100451. }
  100452. decoder->private_->output_capacity = size;
  100453. decoder->private_->output_channels = channels;
  100454. return true;
  100455. }
  100456. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100457. {
  100458. size_t i;
  100459. FLAC__ASSERT(0 != decoder);
  100460. FLAC__ASSERT(0 != decoder->private_);
  100461. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100462. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100463. return true;
  100464. return false;
  100465. }
  100466. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100467. {
  100468. FLAC__uint32 x;
  100469. unsigned i, id_;
  100470. FLAC__bool first = true;
  100471. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100472. for(i = id_ = 0; i < 4; ) {
  100473. if(decoder->private_->cached) {
  100474. x = (FLAC__uint32)decoder->private_->lookahead;
  100475. decoder->private_->cached = false;
  100476. }
  100477. else {
  100478. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100479. return false; /* read_callback_ sets the state for us */
  100480. }
  100481. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100482. first = true;
  100483. i++;
  100484. id_ = 0;
  100485. continue;
  100486. }
  100487. if(x == ID3V2_TAG_[id_]) {
  100488. id_++;
  100489. i = 0;
  100490. if(id_ == 3) {
  100491. if(!skip_id3v2_tag_(decoder))
  100492. return false; /* skip_id3v2_tag_ sets the state for us */
  100493. }
  100494. continue;
  100495. }
  100496. id_ = 0;
  100497. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100498. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100499. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100500. return false; /* read_callback_ sets the state for us */
  100501. /* 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 */
  100502. /* else we have to check if the second byte is the end of a sync code */
  100503. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100504. decoder->private_->lookahead = (FLAC__byte)x;
  100505. decoder->private_->cached = true;
  100506. }
  100507. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100508. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100509. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100510. return true;
  100511. }
  100512. }
  100513. i = 0;
  100514. if(first) {
  100515. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100516. first = false;
  100517. }
  100518. }
  100519. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100520. return true;
  100521. }
  100522. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100523. {
  100524. FLAC__bool is_last;
  100525. FLAC__uint32 i, x, type, length;
  100526. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100527. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100528. return false; /* read_callback_ sets the state for us */
  100529. is_last = x? true : false;
  100530. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100531. return false; /* read_callback_ sets the state for us */
  100532. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100533. return false; /* read_callback_ sets the state for us */
  100534. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100535. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100536. return false;
  100537. decoder->private_->has_stream_info = true;
  100538. 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))
  100539. decoder->private_->do_md5_checking = false;
  100540. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100541. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100542. }
  100543. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100544. if(!read_metadata_seektable_(decoder, is_last, length))
  100545. return false;
  100546. decoder->private_->has_seek_table = true;
  100547. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100548. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100549. }
  100550. else {
  100551. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100552. unsigned real_length = length;
  100553. FLAC__StreamMetadata block;
  100554. block.is_last = is_last;
  100555. block.type = (FLAC__MetadataType)type;
  100556. block.length = length;
  100557. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100558. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100559. return false; /* read_callback_ sets the state for us */
  100560. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100561. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100562. return false;
  100563. }
  100564. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100565. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100566. skip_it = !skip_it;
  100567. }
  100568. if(skip_it) {
  100569. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100570. return false; /* read_callback_ sets the state for us */
  100571. }
  100572. else {
  100573. switch(type) {
  100574. case FLAC__METADATA_TYPE_PADDING:
  100575. /* skip the padding bytes */
  100576. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100577. return false; /* read_callback_ sets the state for us */
  100578. break;
  100579. case FLAC__METADATA_TYPE_APPLICATION:
  100580. /* remember, we read the ID already */
  100581. if(real_length > 0) {
  100582. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100583. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100584. return false;
  100585. }
  100586. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100587. return false; /* read_callback_ sets the state for us */
  100588. }
  100589. else
  100590. block.data.application.data = 0;
  100591. break;
  100592. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100593. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100594. return false;
  100595. break;
  100596. case FLAC__METADATA_TYPE_CUESHEET:
  100597. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100598. return false;
  100599. break;
  100600. case FLAC__METADATA_TYPE_PICTURE:
  100601. if(!read_metadata_picture_(decoder, &block.data.picture))
  100602. return false;
  100603. break;
  100604. case FLAC__METADATA_TYPE_STREAMINFO:
  100605. case FLAC__METADATA_TYPE_SEEKTABLE:
  100606. FLAC__ASSERT(0);
  100607. break;
  100608. default:
  100609. if(real_length > 0) {
  100610. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100611. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100612. return false;
  100613. }
  100614. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100615. return false; /* read_callback_ sets the state for us */
  100616. }
  100617. else
  100618. block.data.unknown.data = 0;
  100619. break;
  100620. }
  100621. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100622. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100623. /* now we have to free any malloc()ed data in the block */
  100624. switch(type) {
  100625. case FLAC__METADATA_TYPE_PADDING:
  100626. break;
  100627. case FLAC__METADATA_TYPE_APPLICATION:
  100628. if(0 != block.data.application.data)
  100629. free(block.data.application.data);
  100630. break;
  100631. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100632. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100633. free(block.data.vorbis_comment.vendor_string.entry);
  100634. if(block.data.vorbis_comment.num_comments > 0)
  100635. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100636. if(0 != block.data.vorbis_comment.comments[i].entry)
  100637. free(block.data.vorbis_comment.comments[i].entry);
  100638. if(0 != block.data.vorbis_comment.comments)
  100639. free(block.data.vorbis_comment.comments);
  100640. break;
  100641. case FLAC__METADATA_TYPE_CUESHEET:
  100642. if(block.data.cue_sheet.num_tracks > 0)
  100643. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100644. if(0 != block.data.cue_sheet.tracks[i].indices)
  100645. free(block.data.cue_sheet.tracks[i].indices);
  100646. if(0 != block.data.cue_sheet.tracks)
  100647. free(block.data.cue_sheet.tracks);
  100648. break;
  100649. case FLAC__METADATA_TYPE_PICTURE:
  100650. if(0 != block.data.picture.mime_type)
  100651. free(block.data.picture.mime_type);
  100652. if(0 != block.data.picture.description)
  100653. free(block.data.picture.description);
  100654. if(0 != block.data.picture.data)
  100655. free(block.data.picture.data);
  100656. break;
  100657. case FLAC__METADATA_TYPE_STREAMINFO:
  100658. case FLAC__METADATA_TYPE_SEEKTABLE:
  100659. FLAC__ASSERT(0);
  100660. default:
  100661. if(0 != block.data.unknown.data)
  100662. free(block.data.unknown.data);
  100663. break;
  100664. }
  100665. }
  100666. }
  100667. if(is_last) {
  100668. /* if this fails, it's OK, it's just a hint for the seek routine */
  100669. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100670. decoder->private_->first_frame_offset = 0;
  100671. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100672. }
  100673. return true;
  100674. }
  100675. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100676. {
  100677. FLAC__uint32 x;
  100678. unsigned bits, used_bits = 0;
  100679. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100680. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100681. decoder->private_->stream_info.is_last = is_last;
  100682. decoder->private_->stream_info.length = length;
  100683. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100684. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100685. return false; /* read_callback_ sets the state for us */
  100686. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100687. used_bits += bits;
  100688. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100689. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100690. return false; /* read_callback_ sets the state for us */
  100691. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100692. used_bits += bits;
  100693. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100694. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100695. return false; /* read_callback_ sets the state for us */
  100696. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100697. used_bits += bits;
  100698. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100699. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100700. return false; /* read_callback_ sets the state for us */
  100701. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100702. used_bits += bits;
  100703. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100704. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100705. return false; /* read_callback_ sets the state for us */
  100706. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100707. used_bits += bits;
  100708. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100709. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100710. return false; /* read_callback_ sets the state for us */
  100711. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100712. used_bits += bits;
  100713. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100714. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100715. return false; /* read_callback_ sets the state for us */
  100716. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100717. used_bits += bits;
  100718. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100719. 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))
  100720. return false; /* read_callback_ sets the state for us */
  100721. used_bits += bits;
  100722. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100723. return false; /* read_callback_ sets the state for us */
  100724. used_bits += 16*8;
  100725. /* skip the rest of the block */
  100726. FLAC__ASSERT(used_bits % 8 == 0);
  100727. length -= (used_bits / 8);
  100728. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100729. return false; /* read_callback_ sets the state for us */
  100730. return true;
  100731. }
  100732. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100733. {
  100734. FLAC__uint32 i, x;
  100735. FLAC__uint64 xx;
  100736. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100737. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100738. decoder->private_->seek_table.is_last = is_last;
  100739. decoder->private_->seek_table.length = length;
  100740. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100741. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100742. 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)))) {
  100743. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100744. return false;
  100745. }
  100746. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100747. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100748. return false; /* read_callback_ sets the state for us */
  100749. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100750. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100751. return false; /* read_callback_ sets the state for us */
  100752. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100753. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100754. return false; /* read_callback_ sets the state for us */
  100755. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100756. }
  100757. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100758. /* if there is a partial point left, skip over it */
  100759. if(length > 0) {
  100760. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100761. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100762. return false; /* read_callback_ sets the state for us */
  100763. }
  100764. return true;
  100765. }
  100766. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100767. {
  100768. FLAC__uint32 i;
  100769. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100770. /* read vendor string */
  100771. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100772. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100773. return false; /* read_callback_ sets the state for us */
  100774. if(obj->vendor_string.length > 0) {
  100775. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100776. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100777. return false;
  100778. }
  100779. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100780. return false; /* read_callback_ sets the state for us */
  100781. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100782. }
  100783. else
  100784. obj->vendor_string.entry = 0;
  100785. /* read num comments */
  100786. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100787. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100788. return false; /* read_callback_ sets the state for us */
  100789. /* read comments */
  100790. if(obj->num_comments > 0) {
  100791. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100792. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100793. return false;
  100794. }
  100795. for(i = 0; i < obj->num_comments; i++) {
  100796. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100797. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100798. return false; /* read_callback_ sets the state for us */
  100799. if(obj->comments[i].length > 0) {
  100800. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100801. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100802. return false;
  100803. }
  100804. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100805. return false; /* read_callback_ sets the state for us */
  100806. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100807. }
  100808. else
  100809. obj->comments[i].entry = 0;
  100810. }
  100811. }
  100812. else {
  100813. obj->comments = 0;
  100814. }
  100815. return true;
  100816. }
  100817. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100818. {
  100819. FLAC__uint32 i, j, x;
  100820. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100821. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100822. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100823. 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))
  100824. return false; /* read_callback_ sets the state for us */
  100825. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100826. return false; /* read_callback_ sets the state for us */
  100827. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100828. return false; /* read_callback_ sets the state for us */
  100829. obj->is_cd = x? true : false;
  100830. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100831. return false; /* read_callback_ sets the state for us */
  100832. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100833. return false; /* read_callback_ sets the state for us */
  100834. obj->num_tracks = x;
  100835. if(obj->num_tracks > 0) {
  100836. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100837. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100838. return false;
  100839. }
  100840. for(i = 0; i < obj->num_tracks; i++) {
  100841. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100842. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100843. return false; /* read_callback_ sets the state for us */
  100844. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100845. return false; /* read_callback_ sets the state for us */
  100846. track->number = (FLAC__byte)x;
  100847. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100848. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100849. return false; /* read_callback_ sets the state for us */
  100850. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100851. return false; /* read_callback_ sets the state for us */
  100852. track->type = x;
  100853. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100854. return false; /* read_callback_ sets the state for us */
  100855. track->pre_emphasis = x;
  100856. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100857. return false; /* read_callback_ sets the state for us */
  100858. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100859. return false; /* read_callback_ sets the state for us */
  100860. track->num_indices = (FLAC__byte)x;
  100861. if(track->num_indices > 0) {
  100862. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100863. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100864. return false;
  100865. }
  100866. for(j = 0; j < track->num_indices; j++) {
  100867. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100868. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100869. return false; /* read_callback_ sets the state for us */
  100870. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100871. return false; /* read_callback_ sets the state for us */
  100872. index->number = (FLAC__byte)x;
  100873. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100874. return false; /* read_callback_ sets the state for us */
  100875. }
  100876. }
  100877. }
  100878. }
  100879. return true;
  100880. }
  100881. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100882. {
  100883. FLAC__uint32 x;
  100884. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100885. /* read type */
  100886. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100887. return false; /* read_callback_ sets the state for us */
  100888. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100889. /* read MIME type */
  100890. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100891. return false; /* read_callback_ sets the state for us */
  100892. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100893. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100894. return false;
  100895. }
  100896. if(x > 0) {
  100897. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100898. return false; /* read_callback_ sets the state for us */
  100899. }
  100900. obj->mime_type[x] = '\0';
  100901. /* read description */
  100902. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100903. return false; /* read_callback_ sets the state for us */
  100904. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100905. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100906. return false;
  100907. }
  100908. if(x > 0) {
  100909. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100910. return false; /* read_callback_ sets the state for us */
  100911. }
  100912. obj->description[x] = '\0';
  100913. /* read width */
  100914. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100915. return false; /* read_callback_ sets the state for us */
  100916. /* read height */
  100917. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100918. return false; /* read_callback_ sets the state for us */
  100919. /* read depth */
  100920. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100921. return false; /* read_callback_ sets the state for us */
  100922. /* read colors */
  100923. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100924. return false; /* read_callback_ sets the state for us */
  100925. /* read data */
  100926. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100927. return false; /* read_callback_ sets the state for us */
  100928. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100929. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100930. return false;
  100931. }
  100932. if(obj->data_length > 0) {
  100933. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100934. return false; /* read_callback_ sets the state for us */
  100935. }
  100936. return true;
  100937. }
  100938. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100939. {
  100940. FLAC__uint32 x;
  100941. unsigned i, skip;
  100942. /* skip the version and flags bytes */
  100943. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100944. return false; /* read_callback_ sets the state for us */
  100945. /* get the size (in bytes) to skip */
  100946. skip = 0;
  100947. for(i = 0; i < 4; i++) {
  100948. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100949. return false; /* read_callback_ sets the state for us */
  100950. skip <<= 7;
  100951. skip |= (x & 0x7f);
  100952. }
  100953. /* skip the rest of the tag */
  100954. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100955. return false; /* read_callback_ sets the state for us */
  100956. return true;
  100957. }
  100958. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100959. {
  100960. FLAC__uint32 x;
  100961. FLAC__bool first = true;
  100962. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100963. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100964. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100965. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100966. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100967. return true;
  100968. }
  100969. }
  100970. /* make sure we're byte aligned */
  100971. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100972. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100973. return false; /* read_callback_ sets the state for us */
  100974. }
  100975. while(1) {
  100976. if(decoder->private_->cached) {
  100977. x = (FLAC__uint32)decoder->private_->lookahead;
  100978. decoder->private_->cached = false;
  100979. }
  100980. else {
  100981. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100982. return false; /* read_callback_ sets the state for us */
  100983. }
  100984. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100985. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100986. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100987. return false; /* read_callback_ sets the state for us */
  100988. /* 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 */
  100989. /* else we have to check if the second byte is the end of a sync code */
  100990. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100991. decoder->private_->lookahead = (FLAC__byte)x;
  100992. decoder->private_->cached = true;
  100993. }
  100994. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100995. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100996. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100997. return true;
  100998. }
  100999. }
  101000. if(first) {
  101001. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101002. first = false;
  101003. }
  101004. }
  101005. return true;
  101006. }
  101007. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  101008. {
  101009. unsigned channel;
  101010. unsigned i;
  101011. FLAC__int32 mid, side;
  101012. unsigned frame_crc; /* the one we calculate from the input stream */
  101013. FLAC__uint32 x;
  101014. *got_a_frame = false;
  101015. /* init the CRC */
  101016. frame_crc = 0;
  101017. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  101018. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  101019. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  101020. if(!read_frame_header_(decoder))
  101021. return false;
  101022. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  101023. return true;
  101024. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  101025. return false;
  101026. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101027. /*
  101028. * first figure the correct bits-per-sample of the subframe
  101029. */
  101030. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  101031. switch(decoder->private_->frame.header.channel_assignment) {
  101032. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101033. /* no adjustment needed */
  101034. break;
  101035. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101036. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101037. if(channel == 1)
  101038. bps++;
  101039. break;
  101040. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101041. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101042. if(channel == 0)
  101043. bps++;
  101044. break;
  101045. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101046. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101047. if(channel == 1)
  101048. bps++;
  101049. break;
  101050. default:
  101051. FLAC__ASSERT(0);
  101052. }
  101053. /*
  101054. * now read it
  101055. */
  101056. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101057. return false;
  101058. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101059. return true;
  101060. }
  101061. if(!read_zero_padding_(decoder))
  101062. return false;
  101063. 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) */
  101064. return true;
  101065. /*
  101066. * Read the frame CRC-16 from the footer and check
  101067. */
  101068. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101069. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101070. return false; /* read_callback_ sets the state for us */
  101071. if(frame_crc == x) {
  101072. if(do_full_decode) {
  101073. /* Undo any special channel coding */
  101074. switch(decoder->private_->frame.header.channel_assignment) {
  101075. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101076. /* do nothing */
  101077. break;
  101078. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101079. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101080. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101081. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101082. break;
  101083. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101084. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101085. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101086. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101087. break;
  101088. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101089. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101090. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101091. #if 1
  101092. mid = decoder->private_->output[0][i];
  101093. side = decoder->private_->output[1][i];
  101094. mid <<= 1;
  101095. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101096. decoder->private_->output[0][i] = (mid + side) >> 1;
  101097. decoder->private_->output[1][i] = (mid - side) >> 1;
  101098. #else
  101099. /* OPT: without 'side' temp variable */
  101100. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101101. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101102. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101103. #endif
  101104. }
  101105. break;
  101106. default:
  101107. FLAC__ASSERT(0);
  101108. break;
  101109. }
  101110. }
  101111. }
  101112. else {
  101113. /* Bad frame, emit error and zero the output signal */
  101114. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101115. if(do_full_decode) {
  101116. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101117. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101118. }
  101119. }
  101120. }
  101121. *got_a_frame = true;
  101122. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101123. if(decoder->private_->next_fixed_block_size)
  101124. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101125. /* put the latest values into the public section of the decoder instance */
  101126. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101127. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101128. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101129. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101130. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101131. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101132. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101133. /* write it */
  101134. if(do_full_decode) {
  101135. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101136. return false;
  101137. }
  101138. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101139. return true;
  101140. }
  101141. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101142. {
  101143. FLAC__uint32 x;
  101144. FLAC__uint64 xx;
  101145. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101146. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101147. unsigned raw_header_len;
  101148. FLAC__bool is_unparseable = false;
  101149. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101150. /* init the raw header with the saved bits from synchronization */
  101151. raw_header[0] = decoder->private_->header_warmup[0];
  101152. raw_header[1] = decoder->private_->header_warmup[1];
  101153. raw_header_len = 2;
  101154. /* check to make sure that reserved bit is 0 */
  101155. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101156. is_unparseable = true;
  101157. /*
  101158. * Note that along the way as we read the header, we look for a sync
  101159. * code inside. If we find one it would indicate that our original
  101160. * sync was bad since there cannot be a sync code in a valid header.
  101161. *
  101162. * Three kinds of things can go wrong when reading the frame header:
  101163. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101164. * If we don't find a sync code, it can end up looking like we read
  101165. * a valid but unparseable header, until getting to the frame header
  101166. * CRC. Even then we could get a false positive on the CRC.
  101167. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101168. * future encoder).
  101169. * 3) We may be on a damaged frame which appears valid but unparseable.
  101170. *
  101171. * For all these reasons, we try and read a complete frame header as
  101172. * long as it seems valid, even if unparseable, up until the frame
  101173. * header CRC.
  101174. */
  101175. /*
  101176. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101177. */
  101178. for(i = 0; i < 2; i++) {
  101179. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101180. return false; /* read_callback_ sets the state for us */
  101181. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101182. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101183. decoder->private_->lookahead = (FLAC__byte)x;
  101184. decoder->private_->cached = true;
  101185. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101186. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101187. return true;
  101188. }
  101189. raw_header[raw_header_len++] = (FLAC__byte)x;
  101190. }
  101191. switch(x = raw_header[2] >> 4) {
  101192. case 0:
  101193. is_unparseable = true;
  101194. break;
  101195. case 1:
  101196. decoder->private_->frame.header.blocksize = 192;
  101197. break;
  101198. case 2:
  101199. case 3:
  101200. case 4:
  101201. case 5:
  101202. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101203. break;
  101204. case 6:
  101205. case 7:
  101206. blocksize_hint = x;
  101207. break;
  101208. case 8:
  101209. case 9:
  101210. case 10:
  101211. case 11:
  101212. case 12:
  101213. case 13:
  101214. case 14:
  101215. case 15:
  101216. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101217. break;
  101218. default:
  101219. FLAC__ASSERT(0);
  101220. break;
  101221. }
  101222. switch(x = raw_header[2] & 0x0f) {
  101223. case 0:
  101224. if(decoder->private_->has_stream_info)
  101225. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101226. else
  101227. is_unparseable = true;
  101228. break;
  101229. case 1:
  101230. decoder->private_->frame.header.sample_rate = 88200;
  101231. break;
  101232. case 2:
  101233. decoder->private_->frame.header.sample_rate = 176400;
  101234. break;
  101235. case 3:
  101236. decoder->private_->frame.header.sample_rate = 192000;
  101237. break;
  101238. case 4:
  101239. decoder->private_->frame.header.sample_rate = 8000;
  101240. break;
  101241. case 5:
  101242. decoder->private_->frame.header.sample_rate = 16000;
  101243. break;
  101244. case 6:
  101245. decoder->private_->frame.header.sample_rate = 22050;
  101246. break;
  101247. case 7:
  101248. decoder->private_->frame.header.sample_rate = 24000;
  101249. break;
  101250. case 8:
  101251. decoder->private_->frame.header.sample_rate = 32000;
  101252. break;
  101253. case 9:
  101254. decoder->private_->frame.header.sample_rate = 44100;
  101255. break;
  101256. case 10:
  101257. decoder->private_->frame.header.sample_rate = 48000;
  101258. break;
  101259. case 11:
  101260. decoder->private_->frame.header.sample_rate = 96000;
  101261. break;
  101262. case 12:
  101263. case 13:
  101264. case 14:
  101265. sample_rate_hint = x;
  101266. break;
  101267. case 15:
  101268. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101269. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101270. return true;
  101271. default:
  101272. FLAC__ASSERT(0);
  101273. }
  101274. x = (unsigned)(raw_header[3] >> 4);
  101275. if(x & 8) {
  101276. decoder->private_->frame.header.channels = 2;
  101277. switch(x & 7) {
  101278. case 0:
  101279. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101280. break;
  101281. case 1:
  101282. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101283. break;
  101284. case 2:
  101285. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101286. break;
  101287. default:
  101288. is_unparseable = true;
  101289. break;
  101290. }
  101291. }
  101292. else {
  101293. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101294. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101295. }
  101296. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101297. case 0:
  101298. if(decoder->private_->has_stream_info)
  101299. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101300. else
  101301. is_unparseable = true;
  101302. break;
  101303. case 1:
  101304. decoder->private_->frame.header.bits_per_sample = 8;
  101305. break;
  101306. case 2:
  101307. decoder->private_->frame.header.bits_per_sample = 12;
  101308. break;
  101309. case 4:
  101310. decoder->private_->frame.header.bits_per_sample = 16;
  101311. break;
  101312. case 5:
  101313. decoder->private_->frame.header.bits_per_sample = 20;
  101314. break;
  101315. case 6:
  101316. decoder->private_->frame.header.bits_per_sample = 24;
  101317. break;
  101318. case 3:
  101319. case 7:
  101320. is_unparseable = true;
  101321. break;
  101322. default:
  101323. FLAC__ASSERT(0);
  101324. break;
  101325. }
  101326. /* check to make sure that reserved bit is 0 */
  101327. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101328. is_unparseable = true;
  101329. /* read the frame's starting sample number (or frame number as the case may be) */
  101330. if(
  101331. raw_header[1] & 0x01 ||
  101332. /*@@@ 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 */
  101333. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101334. ) { /* variable blocksize */
  101335. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101336. return false; /* read_callback_ sets the state for us */
  101337. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101338. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101339. decoder->private_->cached = true;
  101340. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101341. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101342. return true;
  101343. }
  101344. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101345. decoder->private_->frame.header.number.sample_number = xx;
  101346. }
  101347. else { /* fixed blocksize */
  101348. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101349. return false; /* read_callback_ sets the state for us */
  101350. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101351. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101352. decoder->private_->cached = true;
  101353. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101354. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101355. return true;
  101356. }
  101357. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101358. decoder->private_->frame.header.number.frame_number = x;
  101359. }
  101360. if(blocksize_hint) {
  101361. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101362. return false; /* read_callback_ sets the state for us */
  101363. raw_header[raw_header_len++] = (FLAC__byte)x;
  101364. if(blocksize_hint == 7) {
  101365. FLAC__uint32 _x;
  101366. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101367. return false; /* read_callback_ sets the state for us */
  101368. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101369. x = (x << 8) | _x;
  101370. }
  101371. decoder->private_->frame.header.blocksize = x+1;
  101372. }
  101373. if(sample_rate_hint) {
  101374. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101375. return false; /* read_callback_ sets the state for us */
  101376. raw_header[raw_header_len++] = (FLAC__byte)x;
  101377. if(sample_rate_hint != 12) {
  101378. FLAC__uint32 _x;
  101379. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101380. return false; /* read_callback_ sets the state for us */
  101381. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101382. x = (x << 8) | _x;
  101383. }
  101384. if(sample_rate_hint == 12)
  101385. decoder->private_->frame.header.sample_rate = x*1000;
  101386. else if(sample_rate_hint == 13)
  101387. decoder->private_->frame.header.sample_rate = x;
  101388. else
  101389. decoder->private_->frame.header.sample_rate = x*10;
  101390. }
  101391. /* read the CRC-8 byte */
  101392. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101393. return false; /* read_callback_ sets the state for us */
  101394. crc8 = (FLAC__byte)x;
  101395. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101396. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101397. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101398. return true;
  101399. }
  101400. /* calculate the sample number from the frame number if needed */
  101401. decoder->private_->next_fixed_block_size = 0;
  101402. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101403. x = decoder->private_->frame.header.number.frame_number;
  101404. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101405. if(decoder->private_->fixed_block_size)
  101406. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101407. else if(decoder->private_->has_stream_info) {
  101408. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101409. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101410. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101411. }
  101412. else
  101413. is_unparseable = true;
  101414. }
  101415. else if(x == 0) {
  101416. decoder->private_->frame.header.number.sample_number = 0;
  101417. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101418. }
  101419. else {
  101420. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101421. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101422. }
  101423. }
  101424. if(is_unparseable) {
  101425. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101426. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101427. return true;
  101428. }
  101429. return true;
  101430. }
  101431. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101432. {
  101433. FLAC__uint32 x;
  101434. FLAC__bool wasted_bits;
  101435. unsigned i;
  101436. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101437. return false; /* read_callback_ sets the state for us */
  101438. wasted_bits = (x & 1);
  101439. x &= 0xfe;
  101440. if(wasted_bits) {
  101441. unsigned u;
  101442. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101443. return false; /* read_callback_ sets the state for us */
  101444. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101445. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101446. }
  101447. else
  101448. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101449. /*
  101450. * Lots of magic numbers here
  101451. */
  101452. if(x & 0x80) {
  101453. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101454. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101455. return true;
  101456. }
  101457. else if(x == 0) {
  101458. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101459. return false;
  101460. }
  101461. else if(x == 2) {
  101462. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101463. return false;
  101464. }
  101465. else if(x < 16) {
  101466. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101467. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101468. return true;
  101469. }
  101470. else if(x <= 24) {
  101471. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101472. return false;
  101473. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101474. return true;
  101475. }
  101476. else if(x < 64) {
  101477. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101478. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101479. return true;
  101480. }
  101481. else {
  101482. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101483. return false;
  101484. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101485. return true;
  101486. }
  101487. if(wasted_bits && do_full_decode) {
  101488. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101489. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101490. decoder->private_->output[channel][i] <<= x;
  101491. }
  101492. return true;
  101493. }
  101494. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101495. {
  101496. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101497. FLAC__int32 x;
  101498. unsigned i;
  101499. FLAC__int32 *output = decoder->private_->output[channel];
  101500. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101501. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101502. return false; /* read_callback_ sets the state for us */
  101503. subframe->value = x;
  101504. /* decode the subframe */
  101505. if(do_full_decode) {
  101506. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101507. output[i] = x;
  101508. }
  101509. return true;
  101510. }
  101511. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101512. {
  101513. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101514. FLAC__int32 i32;
  101515. FLAC__uint32 u32;
  101516. unsigned u;
  101517. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101518. subframe->residual = decoder->private_->residual[channel];
  101519. subframe->order = order;
  101520. /* read warm-up samples */
  101521. for(u = 0; u < order; u++) {
  101522. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101523. return false; /* read_callback_ sets the state for us */
  101524. subframe->warmup[u] = i32;
  101525. }
  101526. /* read entropy coding method info */
  101527. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101528. return false; /* read_callback_ sets the state for us */
  101529. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101530. switch(subframe->entropy_coding_method.type) {
  101531. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101532. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101533. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101534. return false; /* read_callback_ sets the state for us */
  101535. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101536. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101537. break;
  101538. default:
  101539. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101540. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101541. return true;
  101542. }
  101543. /* read residual */
  101544. switch(subframe->entropy_coding_method.type) {
  101545. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101546. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101547. 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))
  101548. return false;
  101549. break;
  101550. default:
  101551. FLAC__ASSERT(0);
  101552. }
  101553. /* decode the subframe */
  101554. if(do_full_decode) {
  101555. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101556. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101557. }
  101558. return true;
  101559. }
  101560. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101561. {
  101562. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101563. FLAC__int32 i32;
  101564. FLAC__uint32 u32;
  101565. unsigned u;
  101566. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101567. subframe->residual = decoder->private_->residual[channel];
  101568. subframe->order = order;
  101569. /* read warm-up samples */
  101570. for(u = 0; u < order; u++) {
  101571. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101572. return false; /* read_callback_ sets the state for us */
  101573. subframe->warmup[u] = i32;
  101574. }
  101575. /* read qlp coeff precision */
  101576. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101577. return false; /* read_callback_ sets the state for us */
  101578. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101579. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101580. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101581. return true;
  101582. }
  101583. subframe->qlp_coeff_precision = u32+1;
  101584. /* read qlp shift */
  101585. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101586. return false; /* read_callback_ sets the state for us */
  101587. subframe->quantization_level = i32;
  101588. /* read quantized lp coefficiencts */
  101589. for(u = 0; u < order; u++) {
  101590. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101591. return false; /* read_callback_ sets the state for us */
  101592. subframe->qlp_coeff[u] = i32;
  101593. }
  101594. /* read entropy coding method info */
  101595. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101596. return false; /* read_callback_ sets the state for us */
  101597. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101598. switch(subframe->entropy_coding_method.type) {
  101599. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101600. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101601. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101602. return false; /* read_callback_ sets the state for us */
  101603. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101604. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101605. break;
  101606. default:
  101607. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101608. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101609. return true;
  101610. }
  101611. /* read residual */
  101612. switch(subframe->entropy_coding_method.type) {
  101613. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101614. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101615. 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))
  101616. return false;
  101617. break;
  101618. default:
  101619. FLAC__ASSERT(0);
  101620. }
  101621. /* decode the subframe */
  101622. if(do_full_decode) {
  101623. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101624. /*@@@@@@ technically not pessimistic enough, should be more like
  101625. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101626. */
  101627. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101628. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101629. if(order <= 8)
  101630. 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);
  101631. else
  101632. 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);
  101633. }
  101634. else
  101635. 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);
  101636. else
  101637. 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);
  101638. }
  101639. return true;
  101640. }
  101641. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101642. {
  101643. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101644. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101645. unsigned i;
  101646. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101647. subframe->data = residual;
  101648. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101649. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101650. return false; /* read_callback_ sets the state for us */
  101651. residual[i] = x;
  101652. }
  101653. /* decode the subframe */
  101654. if(do_full_decode)
  101655. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101656. return true;
  101657. }
  101658. 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)
  101659. {
  101660. FLAC__uint32 rice_parameter;
  101661. int i;
  101662. unsigned partition, sample, u;
  101663. const unsigned partitions = 1u << partition_order;
  101664. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101665. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101666. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101667. /* sanity checks */
  101668. if(partition_order == 0) {
  101669. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101670. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101671. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101672. return true;
  101673. }
  101674. }
  101675. else {
  101676. if(partition_samples < predictor_order) {
  101677. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101678. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101679. return true;
  101680. }
  101681. }
  101682. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101683. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101684. return false;
  101685. }
  101686. sample = 0;
  101687. for(partition = 0; partition < partitions; partition++) {
  101688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101689. return false; /* read_callback_ sets the state for us */
  101690. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101691. if(rice_parameter < pesc) {
  101692. partitioned_rice_contents->raw_bits[partition] = 0;
  101693. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101694. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101695. return false; /* read_callback_ sets the state for us */
  101696. sample += u;
  101697. }
  101698. else {
  101699. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101700. return false; /* read_callback_ sets the state for us */
  101701. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101702. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101703. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101704. return false; /* read_callback_ sets the state for us */
  101705. residual[sample] = i;
  101706. }
  101707. }
  101708. }
  101709. return true;
  101710. }
  101711. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101712. {
  101713. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101714. FLAC__uint32 zero = 0;
  101715. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101716. return false; /* read_callback_ sets the state for us */
  101717. if(zero != 0) {
  101718. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101719. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101720. }
  101721. }
  101722. return true;
  101723. }
  101724. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101725. {
  101726. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101727. if(
  101728. #if FLAC__HAS_OGG
  101729. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101730. !decoder->private_->is_ogg &&
  101731. #endif
  101732. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101733. ) {
  101734. *bytes = 0;
  101735. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101736. return false;
  101737. }
  101738. else if(*bytes > 0) {
  101739. /* While seeking, it is possible for our seek to land in the
  101740. * middle of audio data that looks exactly like a frame header
  101741. * from a future version of an encoder. When that happens, our
  101742. * error callback will get an
  101743. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101744. * unparseable_frame_count. But there is a remote possibility
  101745. * that it is properly synced at such a "future-codec frame",
  101746. * so to make sure, we wait to see many "unparseable" errors in
  101747. * a row before bailing out.
  101748. */
  101749. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101750. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101751. return false;
  101752. }
  101753. else {
  101754. const FLAC__StreamDecoderReadStatus status =
  101755. #if FLAC__HAS_OGG
  101756. decoder->private_->is_ogg?
  101757. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101758. #endif
  101759. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101760. ;
  101761. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101762. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101763. return false;
  101764. }
  101765. else if(*bytes == 0) {
  101766. if(
  101767. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101768. (
  101769. #if FLAC__HAS_OGG
  101770. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101771. !decoder->private_->is_ogg &&
  101772. #endif
  101773. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101774. )
  101775. ) {
  101776. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101777. return false;
  101778. }
  101779. else
  101780. return true;
  101781. }
  101782. else
  101783. return true;
  101784. }
  101785. }
  101786. else {
  101787. /* abort to avoid a deadlock */
  101788. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101789. return false;
  101790. }
  101791. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101792. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101793. * and at the same time hit the end of the stream (for example, seeking
  101794. * to a point that is after the beginning of the last Ogg page). There
  101795. * is no way to report an Ogg sync loss through the callbacks (see note
  101796. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101797. * So to keep the decoder from stopping at this point we gate the call
  101798. * to the eof_callback and let the Ogg decoder aspect set the
  101799. * end-of-stream state when it is needed.
  101800. */
  101801. }
  101802. #if FLAC__HAS_OGG
  101803. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101804. {
  101805. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101806. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101807. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101808. /* we don't really have a way to handle lost sync via read
  101809. * callback so we'll let it pass and let the underlying
  101810. * FLAC decoder catch the error
  101811. */
  101812. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101813. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101814. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101815. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101816. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101817. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101818. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101819. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101820. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101821. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101822. default:
  101823. FLAC__ASSERT(0);
  101824. /* double protection */
  101825. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101826. }
  101827. }
  101828. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101829. {
  101830. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101831. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101832. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101833. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101834. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101835. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101836. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101837. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101838. default:
  101839. /* double protection: */
  101840. FLAC__ASSERT(0);
  101841. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101842. }
  101843. }
  101844. #endif
  101845. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101846. {
  101847. if(decoder->private_->is_seeking) {
  101848. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101849. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101850. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101851. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101852. #if FLAC__HAS_OGG
  101853. decoder->private_->got_a_frame = true;
  101854. #endif
  101855. decoder->private_->last_frame = *frame; /* save the frame */
  101856. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101857. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101858. /* kick out of seek mode */
  101859. decoder->private_->is_seeking = false;
  101860. /* shift out the samples before target_sample */
  101861. if(delta > 0) {
  101862. unsigned channel;
  101863. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101864. for(channel = 0; channel < frame->header.channels; channel++)
  101865. newbuffer[channel] = buffer[channel] + delta;
  101866. decoder->private_->last_frame.header.blocksize -= delta;
  101867. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101868. /* write the relevant samples */
  101869. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101870. }
  101871. else {
  101872. /* write the relevant samples */
  101873. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101874. }
  101875. }
  101876. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101877. }
  101878. /*
  101879. * If we never got STREAMINFO, turn off MD5 checking to save
  101880. * cycles since we don't have a sum to compare to anyway
  101881. */
  101882. if(!decoder->private_->has_stream_info)
  101883. decoder->private_->do_md5_checking = false;
  101884. if(decoder->private_->do_md5_checking) {
  101885. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101886. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101887. }
  101888. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101889. }
  101890. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101891. {
  101892. if(!decoder->private_->is_seeking)
  101893. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101894. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101895. decoder->private_->unparseable_frame_count++;
  101896. }
  101897. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101898. {
  101899. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101900. FLAC__int64 pos = -1;
  101901. int i;
  101902. unsigned approx_bytes_per_frame;
  101903. FLAC__bool first_seek = true;
  101904. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101905. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101906. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101907. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101908. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101909. /* take these from the current frame in case they've changed mid-stream */
  101910. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101911. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101912. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101913. /* use values from stream info if we didn't decode a frame */
  101914. if(channels == 0)
  101915. channels = decoder->private_->stream_info.data.stream_info.channels;
  101916. if(bps == 0)
  101917. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101918. /* we are just guessing here */
  101919. if(max_framesize > 0)
  101920. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101921. /*
  101922. * Check if it's a known fixed-blocksize stream. Note that though
  101923. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101924. * never get a STREAMINFO block when decoding so the value of
  101925. * min_blocksize might be zero.
  101926. */
  101927. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101928. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101929. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101930. }
  101931. else
  101932. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101933. /*
  101934. * First, we set an upper and lower bound on where in the
  101935. * stream we will search. For now we assume the worst case
  101936. * scenario, which is our best guess at the beginning of
  101937. * the first frame and end of the stream.
  101938. */
  101939. lower_bound = first_frame_offset;
  101940. lower_bound_sample = 0;
  101941. upper_bound = stream_length;
  101942. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101943. /*
  101944. * Now we refine the bounds if we have a seektable with
  101945. * suitable points. Note that according to the spec they
  101946. * must be ordered by ascending sample number.
  101947. *
  101948. * Note: to protect against invalid seek tables we will ignore points
  101949. * that have frame_samples==0 or sample_number>=total_samples
  101950. */
  101951. if(seek_table) {
  101952. FLAC__uint64 new_lower_bound = lower_bound;
  101953. FLAC__uint64 new_upper_bound = upper_bound;
  101954. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101955. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101956. /* find the closest seek point <= target_sample, if it exists */
  101957. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101958. if(
  101959. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101960. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101961. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101962. seek_table->points[i].sample_number <= target_sample
  101963. )
  101964. break;
  101965. }
  101966. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101967. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101968. new_lower_bound_sample = seek_table->points[i].sample_number;
  101969. }
  101970. /* find the closest seek point > target_sample, if it exists */
  101971. for(i = 0; i < (int)seek_table->num_points; i++) {
  101972. if(
  101973. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101974. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101975. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101976. seek_table->points[i].sample_number > target_sample
  101977. )
  101978. break;
  101979. }
  101980. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101981. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101982. new_upper_bound_sample = seek_table->points[i].sample_number;
  101983. }
  101984. /* final protection against unsorted seek tables; keep original values if bogus */
  101985. if(new_upper_bound >= new_lower_bound) {
  101986. lower_bound = new_lower_bound;
  101987. upper_bound = new_upper_bound;
  101988. lower_bound_sample = new_lower_bound_sample;
  101989. upper_bound_sample = new_upper_bound_sample;
  101990. }
  101991. }
  101992. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101993. /* there are 2 insidious ways that the following equality occurs, which
  101994. * we need to fix:
  101995. * 1) total_samples is 0 (unknown) and target_sample is 0
  101996. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101997. * exactly equal to the last seek point in the seek table; this
  101998. * means there is no seek point above it, and upper_bound_samples
  101999. * remains equal to the estimate (of target_samples) we made above
  102000. * in either case it does not hurt to move upper_bound_sample up by 1
  102001. */
  102002. if(upper_bound_sample == lower_bound_sample)
  102003. upper_bound_sample++;
  102004. decoder->private_->target_sample = target_sample;
  102005. while(1) {
  102006. /* check if the bounds are still ok */
  102007. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  102008. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102009. return false;
  102010. }
  102011. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102012. #if defined _MSC_VER || defined __MINGW32__
  102013. /* with VC++ you have to spoon feed it the casting */
  102014. 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;
  102015. #else
  102016. 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;
  102017. #endif
  102018. #else
  102019. /* a little less accurate: */
  102020. if(upper_bound - lower_bound < 0xffffffff)
  102021. 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;
  102022. else /* @@@ WATCHOUT, ~2TB limit */
  102023. 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;
  102024. #endif
  102025. if(pos >= (FLAC__int64)upper_bound)
  102026. pos = (FLAC__int64)upper_bound - 1;
  102027. if(pos < (FLAC__int64)lower_bound)
  102028. pos = (FLAC__int64)lower_bound;
  102029. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102030. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102031. return false;
  102032. }
  102033. if(!FLAC__stream_decoder_flush(decoder)) {
  102034. /* above call sets the state for us */
  102035. return false;
  102036. }
  102037. /* Now we need to get a frame. First we need to reset our
  102038. * unparseable_frame_count; if we get too many unparseable
  102039. * frames in a row, the read callback will return
  102040. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  102041. * FLAC__stream_decoder_process_single() to return false.
  102042. */
  102043. decoder->private_->unparseable_frame_count = 0;
  102044. if(!FLAC__stream_decoder_process_single(decoder)) {
  102045. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102046. return false;
  102047. }
  102048. /* our write callback will change the state when it gets to the target frame */
  102049. /* 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 */
  102050. #if 0
  102051. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  102052. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102053. break;
  102054. #endif
  102055. if(!decoder->private_->is_seeking)
  102056. break;
  102057. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102058. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102059. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102060. if (pos == (FLAC__int64)lower_bound) {
  102061. /* can't move back any more than the first frame, something is fatally wrong */
  102062. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102063. return false;
  102064. }
  102065. /* our last move backwards wasn't big enough, try again */
  102066. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102067. continue;
  102068. }
  102069. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102070. first_seek = false;
  102071. /* make sure we are not seeking in corrupted stream */
  102072. if (this_frame_sample < lower_bound_sample) {
  102073. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102074. return false;
  102075. }
  102076. /* we need to narrow the search */
  102077. if(target_sample < this_frame_sample) {
  102078. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102079. /*@@@@@@ what will decode position be if at end of stream? */
  102080. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102081. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102082. return false;
  102083. }
  102084. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102085. }
  102086. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102087. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102088. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102089. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102090. return false;
  102091. }
  102092. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102093. }
  102094. }
  102095. return true;
  102096. }
  102097. #if FLAC__HAS_OGG
  102098. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102099. {
  102100. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102101. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102102. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102103. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102104. FLAC__bool did_a_seek;
  102105. unsigned iteration = 0;
  102106. /* In the first iterations, we will calculate the target byte position
  102107. * by the distance from the target sample to left_sample and
  102108. * right_sample (let's call it "proportional search"). After that, we
  102109. * will switch to binary search.
  102110. */
  102111. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102112. /* We will switch to a linear search once our current sample is less
  102113. * than this number of samples ahead of the target sample
  102114. */
  102115. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102116. /* If the total number of samples is unknown, use a large value, and
  102117. * force binary search immediately.
  102118. */
  102119. if(right_sample == 0) {
  102120. right_sample = (FLAC__uint64)(-1);
  102121. BINARY_SEARCH_AFTER_ITERATION = 0;
  102122. }
  102123. decoder->private_->target_sample = target_sample;
  102124. for( ; ; iteration++) {
  102125. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102126. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102127. pos = (right_pos + left_pos) / 2;
  102128. }
  102129. else {
  102130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102131. #if defined _MSC_VER || defined __MINGW32__
  102132. /* with MSVC you have to spoon feed it the casting */
  102133. 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));
  102134. #else
  102135. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102136. #endif
  102137. #else
  102138. /* a little less accurate: */
  102139. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102140. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102141. else /* @@@ WATCHOUT, ~2TB limit */
  102142. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102143. #endif
  102144. /* @@@ TODO: might want to limit pos to some distance
  102145. * before EOF, to make sure we land before the last frame,
  102146. * thereby getting a this_frame_sample and so having a better
  102147. * estimate.
  102148. */
  102149. }
  102150. /* physical seek */
  102151. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102152. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102153. return false;
  102154. }
  102155. if(!FLAC__stream_decoder_flush(decoder)) {
  102156. /* above call sets the state for us */
  102157. return false;
  102158. }
  102159. did_a_seek = true;
  102160. }
  102161. else
  102162. did_a_seek = false;
  102163. decoder->private_->got_a_frame = false;
  102164. if(!FLAC__stream_decoder_process_single(decoder)) {
  102165. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102166. return false;
  102167. }
  102168. if(!decoder->private_->got_a_frame) {
  102169. if(did_a_seek) {
  102170. /* this can happen if we seek to a point after the last frame; we drop
  102171. * to binary search right away in this case to avoid any wasted
  102172. * iterations of proportional search.
  102173. */
  102174. right_pos = pos;
  102175. BINARY_SEARCH_AFTER_ITERATION = 0;
  102176. }
  102177. else {
  102178. /* this can probably only happen if total_samples is unknown and the
  102179. * target_sample is past the end of the stream
  102180. */
  102181. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102182. return false;
  102183. }
  102184. }
  102185. /* our write callback will change the state when it gets to the target frame */
  102186. else if(!decoder->private_->is_seeking) {
  102187. break;
  102188. }
  102189. else {
  102190. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102191. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102192. if (did_a_seek) {
  102193. if (this_frame_sample <= target_sample) {
  102194. /* The 'equal' case should not happen, since
  102195. * FLAC__stream_decoder_process_single()
  102196. * should recognize that it has hit the
  102197. * target sample and we would exit through
  102198. * the 'break' above.
  102199. */
  102200. FLAC__ASSERT(this_frame_sample != target_sample);
  102201. left_sample = this_frame_sample;
  102202. /* sanity check to avoid infinite loop */
  102203. if (left_pos == pos) {
  102204. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102205. return false;
  102206. }
  102207. left_pos = pos;
  102208. }
  102209. else if(this_frame_sample > target_sample) {
  102210. right_sample = this_frame_sample;
  102211. /* sanity check to avoid infinite loop */
  102212. if (right_pos == pos) {
  102213. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102214. return false;
  102215. }
  102216. right_pos = pos;
  102217. }
  102218. }
  102219. }
  102220. }
  102221. return true;
  102222. }
  102223. #endif
  102224. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102225. {
  102226. (void)client_data;
  102227. if(*bytes > 0) {
  102228. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102229. if(ferror(decoder->private_->file))
  102230. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102231. else if(*bytes == 0)
  102232. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102233. else
  102234. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102235. }
  102236. else
  102237. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102238. }
  102239. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102240. {
  102241. (void)client_data;
  102242. if(decoder->private_->file == stdin)
  102243. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102244. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102245. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102246. else
  102247. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102248. }
  102249. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102250. {
  102251. off_t pos;
  102252. (void)client_data;
  102253. if(decoder->private_->file == stdin)
  102254. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102255. else if((pos = ftello(decoder->private_->file)) < 0)
  102256. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102257. else {
  102258. *absolute_byte_offset = (FLAC__uint64)pos;
  102259. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102260. }
  102261. }
  102262. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102263. {
  102264. struct stat filestats;
  102265. (void)client_data;
  102266. if(decoder->private_->file == stdin)
  102267. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102268. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102269. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102270. else {
  102271. *stream_length = (FLAC__uint64)filestats.st_size;
  102272. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102273. }
  102274. }
  102275. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102276. {
  102277. (void)client_data;
  102278. return feof(decoder->private_->file)? true : false;
  102279. }
  102280. #endif
  102281. /*** End of inlined file: stream_decoder.c ***/
  102282. /*** Start of inlined file: stream_encoder.c ***/
  102283. /*** Start of inlined file: juce_FlacHeader.h ***/
  102284. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102285. // tasks..
  102286. #define VERSION "1.2.1"
  102287. #define FLAC__NO_DLL 1
  102288. #if JUCE_MSVC
  102289. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102290. #endif
  102291. #if JUCE_MAC
  102292. #define FLAC__SYS_DARWIN 1
  102293. #endif
  102294. /*** End of inlined file: juce_FlacHeader.h ***/
  102295. #if JUCE_USE_FLAC
  102296. #if HAVE_CONFIG_H
  102297. # include <config.h>
  102298. #endif
  102299. #if defined _MSC_VER || defined __MINGW32__
  102300. #include <io.h> /* for _setmode() */
  102301. #include <fcntl.h> /* for _O_BINARY */
  102302. #endif
  102303. #if defined __CYGWIN__ || defined __EMX__
  102304. #include <io.h> /* for setmode(), O_BINARY */
  102305. #include <fcntl.h> /* for _O_BINARY */
  102306. #endif
  102307. #include <limits.h>
  102308. #include <stdio.h>
  102309. #include <stdlib.h> /* for malloc() */
  102310. #include <string.h> /* for memcpy() */
  102311. #include <sys/types.h> /* for off_t */
  102312. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102313. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102314. #define fseeko fseek
  102315. #define ftello ftell
  102316. #endif
  102317. #endif
  102318. /*** Start of inlined file: stream_encoder.h ***/
  102319. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102320. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102321. #if FLAC__HAS_OGG
  102322. #include "private/ogg_encoder_aspect.h"
  102323. #endif
  102324. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102325. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102326. typedef enum {
  102327. FLAC__APODIZATION_BARTLETT,
  102328. FLAC__APODIZATION_BARTLETT_HANN,
  102329. FLAC__APODIZATION_BLACKMAN,
  102330. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102331. FLAC__APODIZATION_CONNES,
  102332. FLAC__APODIZATION_FLATTOP,
  102333. FLAC__APODIZATION_GAUSS,
  102334. FLAC__APODIZATION_HAMMING,
  102335. FLAC__APODIZATION_HANN,
  102336. FLAC__APODIZATION_KAISER_BESSEL,
  102337. FLAC__APODIZATION_NUTTALL,
  102338. FLAC__APODIZATION_RECTANGLE,
  102339. FLAC__APODIZATION_TRIANGLE,
  102340. FLAC__APODIZATION_TUKEY,
  102341. FLAC__APODIZATION_WELCH
  102342. } FLAC__ApodizationFunction;
  102343. typedef struct {
  102344. FLAC__ApodizationFunction type;
  102345. union {
  102346. struct {
  102347. FLAC__real stddev;
  102348. } gauss;
  102349. struct {
  102350. FLAC__real p;
  102351. } tukey;
  102352. } parameters;
  102353. } FLAC__ApodizationSpecification;
  102354. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102355. typedef struct FLAC__StreamEncoderProtected {
  102356. FLAC__StreamEncoderState state;
  102357. FLAC__bool verify;
  102358. FLAC__bool streamable_subset;
  102359. FLAC__bool do_md5;
  102360. FLAC__bool do_mid_side_stereo;
  102361. FLAC__bool loose_mid_side_stereo;
  102362. unsigned channels;
  102363. unsigned bits_per_sample;
  102364. unsigned sample_rate;
  102365. unsigned blocksize;
  102366. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102367. unsigned num_apodizations;
  102368. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102369. #endif
  102370. unsigned max_lpc_order;
  102371. unsigned qlp_coeff_precision;
  102372. FLAC__bool do_qlp_coeff_prec_search;
  102373. FLAC__bool do_exhaustive_model_search;
  102374. FLAC__bool do_escape_coding;
  102375. unsigned min_residual_partition_order;
  102376. unsigned max_residual_partition_order;
  102377. unsigned rice_parameter_search_dist;
  102378. FLAC__uint64 total_samples_estimate;
  102379. FLAC__StreamMetadata **metadata;
  102380. unsigned num_metadata_blocks;
  102381. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102382. #if FLAC__HAS_OGG
  102383. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102384. #endif
  102385. } FLAC__StreamEncoderProtected;
  102386. #endif
  102387. /*** End of inlined file: stream_encoder.h ***/
  102388. #if FLAC__HAS_OGG
  102389. #include "include/private/ogg_helper.h"
  102390. #include "include/private/ogg_mapping.h"
  102391. #endif
  102392. /*** Start of inlined file: stream_encoder_framing.h ***/
  102393. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102394. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102395. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102396. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102397. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102398. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102399. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102400. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102401. #endif
  102402. /*** End of inlined file: stream_encoder_framing.h ***/
  102403. /*** Start of inlined file: window.h ***/
  102404. #ifndef FLAC__PRIVATE__WINDOW_H
  102405. #define FLAC__PRIVATE__WINDOW_H
  102406. #ifdef HAVE_CONFIG_H
  102407. #include <config.h>
  102408. #endif
  102409. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102410. /*
  102411. * FLAC__window_*()
  102412. * --------------------------------------------------------------------
  102413. * Calculates window coefficients according to different apodization
  102414. * functions.
  102415. *
  102416. * OUT window[0,L-1]
  102417. * IN L (number of points in window)
  102418. */
  102419. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102420. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102421. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102422. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102423. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102424. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102425. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102426. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102427. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102428. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102429. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102430. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102431. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102432. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102433. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102434. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102435. #endif
  102436. /*** End of inlined file: window.h ***/
  102437. #ifndef FLaC__INLINE
  102438. #define FLaC__INLINE
  102439. #endif
  102440. #ifdef min
  102441. #undef min
  102442. #endif
  102443. #define min(x,y) ((x)<(y)?(x):(y))
  102444. #ifdef max
  102445. #undef max
  102446. #endif
  102447. #define max(x,y) ((x)>(y)?(x):(y))
  102448. /* Exact Rice codeword length calculation is off by default. The simple
  102449. * (and fast) estimation (of how many bits a residual value will be
  102450. * encoded with) in this encoder is very good, almost always yielding
  102451. * compression within 0.1% of exact calculation.
  102452. */
  102453. #undef EXACT_RICE_BITS_CALCULATION
  102454. /* Rice parameter searching is off by default. The simple (and fast)
  102455. * parameter estimation in this encoder is very good, almost always
  102456. * yielding compression within 0.1% of the optimal parameters.
  102457. */
  102458. #undef ENABLE_RICE_PARAMETER_SEARCH
  102459. typedef struct {
  102460. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102461. unsigned size; /* of each data[] in samples */
  102462. unsigned tail;
  102463. } verify_input_fifo;
  102464. typedef struct {
  102465. const FLAC__byte *data;
  102466. unsigned capacity;
  102467. unsigned bytes;
  102468. } verify_output;
  102469. typedef enum {
  102470. ENCODER_IN_MAGIC = 0,
  102471. ENCODER_IN_METADATA = 1,
  102472. ENCODER_IN_AUDIO = 2
  102473. } EncoderStateHint;
  102474. static struct CompressionLevels {
  102475. FLAC__bool do_mid_side_stereo;
  102476. FLAC__bool loose_mid_side_stereo;
  102477. unsigned max_lpc_order;
  102478. unsigned qlp_coeff_precision;
  102479. FLAC__bool do_qlp_coeff_prec_search;
  102480. FLAC__bool do_escape_coding;
  102481. FLAC__bool do_exhaustive_model_search;
  102482. unsigned min_residual_partition_order;
  102483. unsigned max_residual_partition_order;
  102484. unsigned rice_parameter_search_dist;
  102485. } compression_levels_[] = {
  102486. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102487. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102488. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102489. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102490. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102491. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102492. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102493. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102494. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102495. };
  102496. /***********************************************************************
  102497. *
  102498. * Private class method prototypes
  102499. *
  102500. ***********************************************************************/
  102501. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102502. static void free_(FLAC__StreamEncoder *encoder);
  102503. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102504. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102505. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102506. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102507. #if FLAC__HAS_OGG
  102508. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102509. #endif
  102510. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102511. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102512. static FLAC__bool process_subframe_(
  102513. FLAC__StreamEncoder *encoder,
  102514. unsigned min_partition_order,
  102515. unsigned max_partition_order,
  102516. const FLAC__FrameHeader *frame_header,
  102517. unsigned subframe_bps,
  102518. const FLAC__int32 integer_signal[],
  102519. FLAC__Subframe *subframe[2],
  102520. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102521. FLAC__int32 *residual[2],
  102522. unsigned *best_subframe,
  102523. unsigned *best_bits
  102524. );
  102525. static FLAC__bool add_subframe_(
  102526. FLAC__StreamEncoder *encoder,
  102527. unsigned blocksize,
  102528. unsigned subframe_bps,
  102529. const FLAC__Subframe *subframe,
  102530. FLAC__BitWriter *frame
  102531. );
  102532. static unsigned evaluate_constant_subframe_(
  102533. FLAC__StreamEncoder *encoder,
  102534. const FLAC__int32 signal,
  102535. unsigned blocksize,
  102536. unsigned subframe_bps,
  102537. FLAC__Subframe *subframe
  102538. );
  102539. static unsigned evaluate_fixed_subframe_(
  102540. FLAC__StreamEncoder *encoder,
  102541. const FLAC__int32 signal[],
  102542. FLAC__int32 residual[],
  102543. FLAC__uint64 abs_residual_partition_sums[],
  102544. unsigned raw_bits_per_partition[],
  102545. unsigned blocksize,
  102546. unsigned subframe_bps,
  102547. unsigned order,
  102548. unsigned rice_parameter,
  102549. unsigned rice_parameter_limit,
  102550. unsigned min_partition_order,
  102551. unsigned max_partition_order,
  102552. FLAC__bool do_escape_coding,
  102553. unsigned rice_parameter_search_dist,
  102554. FLAC__Subframe *subframe,
  102555. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102556. );
  102557. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102558. static unsigned evaluate_lpc_subframe_(
  102559. FLAC__StreamEncoder *encoder,
  102560. const FLAC__int32 signal[],
  102561. FLAC__int32 residual[],
  102562. FLAC__uint64 abs_residual_partition_sums[],
  102563. unsigned raw_bits_per_partition[],
  102564. const FLAC__real lp_coeff[],
  102565. unsigned blocksize,
  102566. unsigned subframe_bps,
  102567. unsigned order,
  102568. unsigned qlp_coeff_precision,
  102569. unsigned rice_parameter,
  102570. unsigned rice_parameter_limit,
  102571. unsigned min_partition_order,
  102572. unsigned max_partition_order,
  102573. FLAC__bool do_escape_coding,
  102574. unsigned rice_parameter_search_dist,
  102575. FLAC__Subframe *subframe,
  102576. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102577. );
  102578. #endif
  102579. static unsigned evaluate_verbatim_subframe_(
  102580. FLAC__StreamEncoder *encoder,
  102581. const FLAC__int32 signal[],
  102582. unsigned blocksize,
  102583. unsigned subframe_bps,
  102584. FLAC__Subframe *subframe
  102585. );
  102586. static unsigned find_best_partition_order_(
  102587. struct FLAC__StreamEncoderPrivate *private_,
  102588. const FLAC__int32 residual[],
  102589. FLAC__uint64 abs_residual_partition_sums[],
  102590. unsigned raw_bits_per_partition[],
  102591. unsigned residual_samples,
  102592. unsigned predictor_order,
  102593. unsigned rice_parameter,
  102594. unsigned rice_parameter_limit,
  102595. unsigned min_partition_order,
  102596. unsigned max_partition_order,
  102597. unsigned bps,
  102598. FLAC__bool do_escape_coding,
  102599. unsigned rice_parameter_search_dist,
  102600. FLAC__EntropyCodingMethod *best_ecm
  102601. );
  102602. static void precompute_partition_info_sums_(
  102603. const FLAC__int32 residual[],
  102604. FLAC__uint64 abs_residual_partition_sums[],
  102605. unsigned residual_samples,
  102606. unsigned predictor_order,
  102607. unsigned min_partition_order,
  102608. unsigned max_partition_order,
  102609. unsigned bps
  102610. );
  102611. static void precompute_partition_info_escapes_(
  102612. const FLAC__int32 residual[],
  102613. unsigned raw_bits_per_partition[],
  102614. unsigned residual_samples,
  102615. unsigned predictor_order,
  102616. unsigned min_partition_order,
  102617. unsigned max_partition_order
  102618. );
  102619. static FLAC__bool set_partitioned_rice_(
  102620. #ifdef EXACT_RICE_BITS_CALCULATION
  102621. const FLAC__int32 residual[],
  102622. #endif
  102623. const FLAC__uint64 abs_residual_partition_sums[],
  102624. const unsigned raw_bits_per_partition[],
  102625. const unsigned residual_samples,
  102626. const unsigned predictor_order,
  102627. const unsigned suggested_rice_parameter,
  102628. const unsigned rice_parameter_limit,
  102629. const unsigned rice_parameter_search_dist,
  102630. const unsigned partition_order,
  102631. const FLAC__bool search_for_escapes,
  102632. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102633. unsigned *bits
  102634. );
  102635. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102636. /* verify-related routines: */
  102637. static void append_to_verify_fifo_(
  102638. verify_input_fifo *fifo,
  102639. const FLAC__int32 * const input[],
  102640. unsigned input_offset,
  102641. unsigned channels,
  102642. unsigned wide_samples
  102643. );
  102644. static void append_to_verify_fifo_interleaved_(
  102645. verify_input_fifo *fifo,
  102646. const FLAC__int32 input[],
  102647. unsigned input_offset,
  102648. unsigned channels,
  102649. unsigned wide_samples
  102650. );
  102651. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102652. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102653. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102654. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102655. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102656. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102657. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102658. 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);
  102659. static FILE *get_binary_stdout_(void);
  102660. /***********************************************************************
  102661. *
  102662. * Private class data
  102663. *
  102664. ***********************************************************************/
  102665. typedef struct FLAC__StreamEncoderPrivate {
  102666. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102667. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102668. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102669. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102670. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102671. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102672. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102673. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102674. #endif
  102675. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102676. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102677. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102678. FLAC__int32 *residual_workspace_mid_side[2][2];
  102679. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102680. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102681. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102682. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102683. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102684. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102685. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102686. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102687. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102688. unsigned best_subframe_mid_side[2];
  102689. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102690. unsigned best_subframe_bits_mid_side[2];
  102691. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102692. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102693. FLAC__BitWriter *frame; /* the current frame being worked on */
  102694. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102695. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102696. FLAC__ChannelAssignment last_channel_assignment;
  102697. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102698. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102699. unsigned current_sample_number;
  102700. unsigned current_frame_number;
  102701. FLAC__MD5Context md5context;
  102702. FLAC__CPUInfo cpuinfo;
  102703. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102704. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102705. #else
  102706. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102707. #endif
  102708. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102709. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102710. 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[]);
  102711. 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[]);
  102712. 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[]);
  102713. #endif
  102714. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102715. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102716. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102717. FLAC__bool disable_constant_subframes;
  102718. FLAC__bool disable_fixed_subframes;
  102719. FLAC__bool disable_verbatim_subframes;
  102720. #if FLAC__HAS_OGG
  102721. FLAC__bool is_ogg;
  102722. #endif
  102723. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102724. FLAC__StreamEncoderSeekCallback seek_callback;
  102725. FLAC__StreamEncoderTellCallback tell_callback;
  102726. FLAC__StreamEncoderWriteCallback write_callback;
  102727. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102728. FLAC__StreamEncoderProgressCallback progress_callback;
  102729. void *client_data;
  102730. unsigned first_seekpoint_to_check;
  102731. FILE *file; /* only used when encoding to a file */
  102732. FLAC__uint64 bytes_written;
  102733. FLAC__uint64 samples_written;
  102734. unsigned frames_written;
  102735. unsigned total_frames_estimate;
  102736. /* unaligned (original) pointers to allocated data */
  102737. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102738. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102739. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102740. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102741. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102742. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102743. FLAC__real *windowed_signal_unaligned;
  102744. #endif
  102745. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102746. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102747. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102748. unsigned *raw_bits_per_partition_unaligned;
  102749. /*
  102750. * These fields have been moved here from private function local
  102751. * declarations merely to save stack space during encoding.
  102752. */
  102753. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102754. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102755. #endif
  102756. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102757. /*
  102758. * The data for the verify section
  102759. */
  102760. struct {
  102761. FLAC__StreamDecoder *decoder;
  102762. EncoderStateHint state_hint;
  102763. FLAC__bool needs_magic_hack;
  102764. verify_input_fifo input_fifo;
  102765. verify_output output;
  102766. struct {
  102767. FLAC__uint64 absolute_sample;
  102768. unsigned frame_number;
  102769. unsigned channel;
  102770. unsigned sample;
  102771. FLAC__int32 expected;
  102772. FLAC__int32 got;
  102773. } error_stats;
  102774. } verify;
  102775. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102776. } FLAC__StreamEncoderPrivate;
  102777. /***********************************************************************
  102778. *
  102779. * Public static class data
  102780. *
  102781. ***********************************************************************/
  102782. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102783. "FLAC__STREAM_ENCODER_OK",
  102784. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102785. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102786. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102787. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102788. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102789. "FLAC__STREAM_ENCODER_IO_ERROR",
  102790. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102791. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102792. };
  102793. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102794. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102795. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102796. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102797. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102798. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102799. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102800. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102801. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102802. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102803. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102804. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102805. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102806. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102807. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102808. };
  102809. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102810. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102811. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102812. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102813. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102814. };
  102815. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102816. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102817. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102818. };
  102819. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102820. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102821. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102822. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102823. };
  102824. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102825. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102826. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102827. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102828. };
  102829. /* Number of samples that will be overread to watch for end of stream. By
  102830. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102831. * always try to read blocksize+1 samples before encoding a block, so that
  102832. * even if the stream has a total sample count that is an integral multiple
  102833. * of the blocksize, we will still notice when we are encoding the last
  102834. * block. This is needed, for example, to correctly set the end-of-stream
  102835. * marker in Ogg FLAC.
  102836. *
  102837. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102838. * not really any reason to change it.
  102839. */
  102840. static const unsigned OVERREAD_ = 1;
  102841. /***********************************************************************
  102842. *
  102843. * Class constructor/destructor
  102844. *
  102845. */
  102846. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102847. {
  102848. FLAC__StreamEncoder *encoder;
  102849. unsigned i;
  102850. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102851. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102852. if(encoder == 0) {
  102853. return 0;
  102854. }
  102855. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102856. if(encoder->protected_ == 0) {
  102857. free(encoder);
  102858. return 0;
  102859. }
  102860. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102861. if(encoder->private_ == 0) {
  102862. free(encoder->protected_);
  102863. free(encoder);
  102864. return 0;
  102865. }
  102866. encoder->private_->frame = FLAC__bitwriter_new();
  102867. if(encoder->private_->frame == 0) {
  102868. free(encoder->private_);
  102869. free(encoder->protected_);
  102870. free(encoder);
  102871. return 0;
  102872. }
  102873. encoder->private_->file = 0;
  102874. set_defaults_enc(encoder);
  102875. encoder->private_->is_being_deleted = false;
  102876. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102877. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102878. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102879. }
  102880. for(i = 0; i < 2; i++) {
  102881. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102882. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102883. }
  102884. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102885. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102886. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102887. }
  102888. for(i = 0; i < 2; i++) {
  102889. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102890. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102891. }
  102892. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102893. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102894. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102895. }
  102896. for(i = 0; i < 2; i++) {
  102897. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102898. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102899. }
  102900. for(i = 0; i < 2; i++)
  102901. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102902. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102903. return encoder;
  102904. }
  102905. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102906. {
  102907. unsigned i;
  102908. FLAC__ASSERT(0 != encoder);
  102909. FLAC__ASSERT(0 != encoder->protected_);
  102910. FLAC__ASSERT(0 != encoder->private_);
  102911. FLAC__ASSERT(0 != encoder->private_->frame);
  102912. encoder->private_->is_being_deleted = true;
  102913. (void)FLAC__stream_encoder_finish(encoder);
  102914. if(0 != encoder->private_->verify.decoder)
  102915. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102916. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102917. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102918. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102919. }
  102920. for(i = 0; i < 2; i++) {
  102921. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102922. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102923. }
  102924. for(i = 0; i < 2; i++)
  102925. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102926. FLAC__bitwriter_delete(encoder->private_->frame);
  102927. free(encoder->private_);
  102928. free(encoder->protected_);
  102929. free(encoder);
  102930. }
  102931. /***********************************************************************
  102932. *
  102933. * Public class methods
  102934. *
  102935. ***********************************************************************/
  102936. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102937. FLAC__StreamEncoder *encoder,
  102938. FLAC__StreamEncoderReadCallback read_callback,
  102939. FLAC__StreamEncoderWriteCallback write_callback,
  102940. FLAC__StreamEncoderSeekCallback seek_callback,
  102941. FLAC__StreamEncoderTellCallback tell_callback,
  102942. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102943. void *client_data,
  102944. FLAC__bool is_ogg
  102945. )
  102946. {
  102947. unsigned i;
  102948. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102949. FLAC__ASSERT(0 != encoder);
  102950. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102951. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102952. #if !FLAC__HAS_OGG
  102953. if(is_ogg)
  102954. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102955. #endif
  102956. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102957. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102958. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102959. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102960. if(encoder->protected_->channels != 2) {
  102961. encoder->protected_->do_mid_side_stereo = false;
  102962. encoder->protected_->loose_mid_side_stereo = false;
  102963. }
  102964. else if(!encoder->protected_->do_mid_side_stereo)
  102965. encoder->protected_->loose_mid_side_stereo = false;
  102966. if(encoder->protected_->bits_per_sample >= 32)
  102967. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102968. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102969. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102970. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102971. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102972. if(encoder->protected_->blocksize == 0) {
  102973. if(encoder->protected_->max_lpc_order == 0)
  102974. encoder->protected_->blocksize = 1152;
  102975. else
  102976. encoder->protected_->blocksize = 4096;
  102977. }
  102978. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102979. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102980. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102981. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102982. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102983. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102984. if(encoder->protected_->qlp_coeff_precision == 0) {
  102985. if(encoder->protected_->bits_per_sample < 16) {
  102986. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102987. /* @@@ until then we'll make a guess */
  102988. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102989. }
  102990. else if(encoder->protected_->bits_per_sample == 16) {
  102991. if(encoder->protected_->blocksize <= 192)
  102992. encoder->protected_->qlp_coeff_precision = 7;
  102993. else if(encoder->protected_->blocksize <= 384)
  102994. encoder->protected_->qlp_coeff_precision = 8;
  102995. else if(encoder->protected_->blocksize <= 576)
  102996. encoder->protected_->qlp_coeff_precision = 9;
  102997. else if(encoder->protected_->blocksize <= 1152)
  102998. encoder->protected_->qlp_coeff_precision = 10;
  102999. else if(encoder->protected_->blocksize <= 2304)
  103000. encoder->protected_->qlp_coeff_precision = 11;
  103001. else if(encoder->protected_->blocksize <= 4608)
  103002. encoder->protected_->qlp_coeff_precision = 12;
  103003. else
  103004. encoder->protected_->qlp_coeff_precision = 13;
  103005. }
  103006. else {
  103007. if(encoder->protected_->blocksize <= 384)
  103008. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  103009. else if(encoder->protected_->blocksize <= 1152)
  103010. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  103011. else
  103012. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  103013. }
  103014. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  103015. }
  103016. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  103017. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  103018. if(encoder->protected_->streamable_subset) {
  103019. if(
  103020. encoder->protected_->blocksize != 192 &&
  103021. encoder->protected_->blocksize != 576 &&
  103022. encoder->protected_->blocksize != 1152 &&
  103023. encoder->protected_->blocksize != 2304 &&
  103024. encoder->protected_->blocksize != 4608 &&
  103025. encoder->protected_->blocksize != 256 &&
  103026. encoder->protected_->blocksize != 512 &&
  103027. encoder->protected_->blocksize != 1024 &&
  103028. encoder->protected_->blocksize != 2048 &&
  103029. encoder->protected_->blocksize != 4096 &&
  103030. encoder->protected_->blocksize != 8192 &&
  103031. encoder->protected_->blocksize != 16384
  103032. )
  103033. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103034. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  103035. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103036. if(
  103037. encoder->protected_->bits_per_sample != 8 &&
  103038. encoder->protected_->bits_per_sample != 12 &&
  103039. encoder->protected_->bits_per_sample != 16 &&
  103040. encoder->protected_->bits_per_sample != 20 &&
  103041. encoder->protected_->bits_per_sample != 24
  103042. )
  103043. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103044. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  103045. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103046. if(
  103047. encoder->protected_->sample_rate <= 48000 &&
  103048. (
  103049. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  103050. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  103051. )
  103052. ) {
  103053. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103054. }
  103055. }
  103056. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103057. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103058. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103059. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103060. #if FLAC__HAS_OGG
  103061. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103062. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103063. unsigned i;
  103064. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103065. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103066. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103067. for( ; i > 0; i--)
  103068. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103069. encoder->protected_->metadata[0] = vc;
  103070. break;
  103071. }
  103072. }
  103073. }
  103074. #endif
  103075. /* keep track of any SEEKTABLE block */
  103076. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103077. unsigned i;
  103078. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103079. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103080. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103081. break; /* take only the first one */
  103082. }
  103083. }
  103084. }
  103085. /* validate metadata */
  103086. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103087. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103088. metadata_has_seektable = false;
  103089. metadata_has_vorbis_comment = false;
  103090. metadata_picture_has_type1 = false;
  103091. metadata_picture_has_type2 = false;
  103092. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103093. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103094. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103095. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103096. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103097. if(metadata_has_seektable) /* only one is allowed */
  103098. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103099. metadata_has_seektable = true;
  103100. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103101. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103102. }
  103103. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103104. if(metadata_has_vorbis_comment) /* only one is allowed */
  103105. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103106. metadata_has_vorbis_comment = true;
  103107. }
  103108. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103109. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103110. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103111. }
  103112. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103113. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103114. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103115. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103116. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103117. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103118. metadata_picture_has_type1 = true;
  103119. /* standard icon must be 32x32 pixel PNG */
  103120. if(
  103121. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103122. (
  103123. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103124. m->data.picture.width != 32 ||
  103125. m->data.picture.height != 32
  103126. )
  103127. )
  103128. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103129. }
  103130. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103131. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103132. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103133. metadata_picture_has_type2 = true;
  103134. }
  103135. }
  103136. }
  103137. encoder->private_->input_capacity = 0;
  103138. for(i = 0; i < encoder->protected_->channels; i++) {
  103139. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103140. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103141. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103142. #endif
  103143. }
  103144. for(i = 0; i < 2; i++) {
  103145. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103146. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103147. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103148. #endif
  103149. }
  103150. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103151. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103152. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103153. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103154. #endif
  103155. for(i = 0; i < encoder->protected_->channels; i++) {
  103156. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103157. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103158. encoder->private_->best_subframe[i] = 0;
  103159. }
  103160. for(i = 0; i < 2; i++) {
  103161. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103162. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103163. encoder->private_->best_subframe_mid_side[i] = 0;
  103164. }
  103165. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103166. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103167. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103168. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103169. #else
  103170. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103171. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103172. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103173. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103174. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103175. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103176. 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);
  103177. #endif
  103178. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103179. encoder->private_->loose_mid_side_stereo_frames = 1;
  103180. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103181. encoder->private_->current_sample_number = 0;
  103182. encoder->private_->current_frame_number = 0;
  103183. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103184. 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? */
  103185. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103186. /*
  103187. * get the CPU info and set the function pointers
  103188. */
  103189. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103190. /* first default to the non-asm routines */
  103191. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103192. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103193. #endif
  103194. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103195. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103196. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103197. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103198. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103199. #endif
  103200. /* now override with asm where appropriate */
  103201. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103202. # ifndef FLAC__NO_ASM
  103203. if(encoder->private_->cpuinfo.use_asm) {
  103204. # ifdef FLAC__CPU_IA32
  103205. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103206. # ifdef FLAC__HAS_NASM
  103207. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103208. if(encoder->protected_->max_lpc_order < 4)
  103209. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103210. else if(encoder->protected_->max_lpc_order < 8)
  103211. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103212. else if(encoder->protected_->max_lpc_order < 12)
  103213. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103214. else
  103215. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103216. }
  103217. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103218. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103219. else
  103220. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103221. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103222. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103223. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103224. }
  103225. else {
  103226. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103227. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103228. }
  103229. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103230. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103231. # endif /* FLAC__HAS_NASM */
  103232. # endif /* FLAC__CPU_IA32 */
  103233. }
  103234. # endif /* !FLAC__NO_ASM */
  103235. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103236. /* finally override based on wide-ness if necessary */
  103237. if(encoder->private_->use_wide_by_block) {
  103238. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103239. }
  103240. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103241. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103242. #if FLAC__HAS_OGG
  103243. encoder->private_->is_ogg = is_ogg;
  103244. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103245. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103246. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103247. }
  103248. #endif
  103249. encoder->private_->read_callback = read_callback;
  103250. encoder->private_->write_callback = write_callback;
  103251. encoder->private_->seek_callback = seek_callback;
  103252. encoder->private_->tell_callback = tell_callback;
  103253. encoder->private_->metadata_callback = metadata_callback;
  103254. encoder->private_->client_data = client_data;
  103255. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103256. /* the above function sets the state for us in case of an error */
  103257. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103258. }
  103259. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103260. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103261. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103262. }
  103263. /*
  103264. * Set up the verify stuff if necessary
  103265. */
  103266. if(encoder->protected_->verify) {
  103267. /*
  103268. * First, set up the fifo which will hold the
  103269. * original signal to compare against
  103270. */
  103271. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103272. for(i = 0; i < encoder->protected_->channels; i++) {
  103273. 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))) {
  103274. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103275. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103276. }
  103277. }
  103278. encoder->private_->verify.input_fifo.tail = 0;
  103279. /*
  103280. * Now set up a stream decoder for verification
  103281. */
  103282. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103283. if(0 == encoder->private_->verify.decoder) {
  103284. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103285. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103286. }
  103287. 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) {
  103288. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103289. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103290. }
  103291. }
  103292. encoder->private_->verify.error_stats.absolute_sample = 0;
  103293. encoder->private_->verify.error_stats.frame_number = 0;
  103294. encoder->private_->verify.error_stats.channel = 0;
  103295. encoder->private_->verify.error_stats.sample = 0;
  103296. encoder->private_->verify.error_stats.expected = 0;
  103297. encoder->private_->verify.error_stats.got = 0;
  103298. /*
  103299. * These must be done before we write any metadata, because that
  103300. * calls the write_callback, which uses these values.
  103301. */
  103302. encoder->private_->first_seekpoint_to_check = 0;
  103303. encoder->private_->samples_written = 0;
  103304. encoder->protected_->streaminfo_offset = 0;
  103305. encoder->protected_->seektable_offset = 0;
  103306. encoder->protected_->audio_offset = 0;
  103307. /*
  103308. * write the stream header
  103309. */
  103310. if(encoder->protected_->verify)
  103311. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103312. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103313. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103314. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103315. }
  103316. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103317. /* the above function sets the state for us in case of an error */
  103318. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103319. }
  103320. /*
  103321. * write the STREAMINFO metadata block
  103322. */
  103323. if(encoder->protected_->verify)
  103324. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103325. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103326. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103327. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103328. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103329. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103330. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103331. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103332. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103333. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103334. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103335. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103336. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103337. if(encoder->protected_->do_md5)
  103338. FLAC__MD5Init(&encoder->private_->md5context);
  103339. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103340. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103341. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103342. }
  103343. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103344. /* the above function sets the state for us in case of an error */
  103345. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103346. }
  103347. /*
  103348. * Now that the STREAMINFO block is written, we can init this to an
  103349. * absurdly-high value...
  103350. */
  103351. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103352. /* ... and clear this to 0 */
  103353. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103354. /*
  103355. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103356. * if not, we will write an empty one (FLAC__add_metadata_block()
  103357. * automatically supplies the vendor string).
  103358. *
  103359. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103360. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103361. * true it will have already insured that the metadata list is properly
  103362. * ordered.)
  103363. */
  103364. if(!metadata_has_vorbis_comment) {
  103365. FLAC__StreamMetadata vorbis_comment;
  103366. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103367. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103368. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103369. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103370. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103371. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103372. vorbis_comment.data.vorbis_comment.comments = 0;
  103373. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103374. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103375. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103376. }
  103377. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103378. /* the above function sets the state for us in case of an error */
  103379. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103380. }
  103381. }
  103382. /*
  103383. * write the user's metadata blocks
  103384. */
  103385. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103386. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103387. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103388. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103389. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103390. }
  103391. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103392. /* the above function sets the state for us in case of an error */
  103393. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103394. }
  103395. }
  103396. /* now that all the metadata is written, we save the stream offset */
  103397. 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 */
  103398. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103399. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103400. }
  103401. if(encoder->protected_->verify)
  103402. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103403. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103404. }
  103405. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103406. FLAC__StreamEncoder *encoder,
  103407. FLAC__StreamEncoderWriteCallback write_callback,
  103408. FLAC__StreamEncoderSeekCallback seek_callback,
  103409. FLAC__StreamEncoderTellCallback tell_callback,
  103410. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103411. void *client_data
  103412. )
  103413. {
  103414. return init_stream_internal_enc(
  103415. encoder,
  103416. /*read_callback=*/0,
  103417. write_callback,
  103418. seek_callback,
  103419. tell_callback,
  103420. metadata_callback,
  103421. client_data,
  103422. /*is_ogg=*/false
  103423. );
  103424. }
  103425. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103426. FLAC__StreamEncoder *encoder,
  103427. FLAC__StreamEncoderReadCallback read_callback,
  103428. FLAC__StreamEncoderWriteCallback write_callback,
  103429. FLAC__StreamEncoderSeekCallback seek_callback,
  103430. FLAC__StreamEncoderTellCallback tell_callback,
  103431. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103432. void *client_data
  103433. )
  103434. {
  103435. return init_stream_internal_enc(
  103436. encoder,
  103437. read_callback,
  103438. write_callback,
  103439. seek_callback,
  103440. tell_callback,
  103441. metadata_callback,
  103442. client_data,
  103443. /*is_ogg=*/true
  103444. );
  103445. }
  103446. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103447. FLAC__StreamEncoder *encoder,
  103448. FILE *file,
  103449. FLAC__StreamEncoderProgressCallback progress_callback,
  103450. void *client_data,
  103451. FLAC__bool is_ogg
  103452. )
  103453. {
  103454. FLAC__StreamEncoderInitStatus init_status;
  103455. FLAC__ASSERT(0 != encoder);
  103456. FLAC__ASSERT(0 != file);
  103457. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103458. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103459. /* double protection */
  103460. if(file == 0) {
  103461. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103462. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103463. }
  103464. /*
  103465. * To make sure that our file does not go unclosed after an error, we
  103466. * must assign the FILE pointer before any further error can occur in
  103467. * this routine.
  103468. */
  103469. if(file == stdout)
  103470. file = get_binary_stdout_(); /* just to be safe */
  103471. encoder->private_->file = file;
  103472. encoder->private_->progress_callback = progress_callback;
  103473. encoder->private_->bytes_written = 0;
  103474. encoder->private_->samples_written = 0;
  103475. encoder->private_->frames_written = 0;
  103476. init_status = init_stream_internal_enc(
  103477. encoder,
  103478. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103479. file_write_callback_,
  103480. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103481. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103482. /*metadata_callback=*/0,
  103483. client_data,
  103484. is_ogg
  103485. );
  103486. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103487. /* the above function sets the state for us in case of an error */
  103488. return init_status;
  103489. }
  103490. {
  103491. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103492. FLAC__ASSERT(blocksize != 0);
  103493. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103494. }
  103495. return init_status;
  103496. }
  103497. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103498. FLAC__StreamEncoder *encoder,
  103499. FILE *file,
  103500. FLAC__StreamEncoderProgressCallback progress_callback,
  103501. void *client_data
  103502. )
  103503. {
  103504. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103505. }
  103506. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103507. FLAC__StreamEncoder *encoder,
  103508. FILE *file,
  103509. FLAC__StreamEncoderProgressCallback progress_callback,
  103510. void *client_data
  103511. )
  103512. {
  103513. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103514. }
  103515. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103516. FLAC__StreamEncoder *encoder,
  103517. const char *filename,
  103518. FLAC__StreamEncoderProgressCallback progress_callback,
  103519. void *client_data,
  103520. FLAC__bool is_ogg
  103521. )
  103522. {
  103523. FILE *file;
  103524. FLAC__ASSERT(0 != encoder);
  103525. /*
  103526. * To make sure that our file does not go unclosed after an error, we
  103527. * have to do the same entrance checks here that are later performed
  103528. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103529. */
  103530. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103531. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103532. file = filename? fopen(filename, "w+b") : stdout;
  103533. if(file == 0) {
  103534. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103535. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103536. }
  103537. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103538. }
  103539. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103540. FLAC__StreamEncoder *encoder,
  103541. const char *filename,
  103542. FLAC__StreamEncoderProgressCallback progress_callback,
  103543. void *client_data
  103544. )
  103545. {
  103546. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103547. }
  103548. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103549. FLAC__StreamEncoder *encoder,
  103550. const char *filename,
  103551. FLAC__StreamEncoderProgressCallback progress_callback,
  103552. void *client_data
  103553. )
  103554. {
  103555. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103556. }
  103557. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103558. {
  103559. FLAC__bool error = false;
  103560. FLAC__ASSERT(0 != encoder);
  103561. FLAC__ASSERT(0 != encoder->private_);
  103562. FLAC__ASSERT(0 != encoder->protected_);
  103563. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103564. return true;
  103565. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103566. if(encoder->private_->current_sample_number != 0) {
  103567. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103568. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103569. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103570. error = true;
  103571. }
  103572. }
  103573. if(encoder->protected_->do_md5)
  103574. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103575. if(!encoder->private_->is_being_deleted) {
  103576. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103577. if(encoder->private_->seek_callback) {
  103578. #if FLAC__HAS_OGG
  103579. if(encoder->private_->is_ogg)
  103580. update_ogg_metadata_(encoder);
  103581. else
  103582. #endif
  103583. update_metadata_(encoder);
  103584. /* check if an error occurred while updating metadata */
  103585. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103586. error = true;
  103587. }
  103588. if(encoder->private_->metadata_callback)
  103589. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103590. }
  103591. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103592. if(!error)
  103593. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103594. error = true;
  103595. }
  103596. }
  103597. if(0 != encoder->private_->file) {
  103598. if(encoder->private_->file != stdout)
  103599. fclose(encoder->private_->file);
  103600. encoder->private_->file = 0;
  103601. }
  103602. #if FLAC__HAS_OGG
  103603. if(encoder->private_->is_ogg)
  103604. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103605. #endif
  103606. free_(encoder);
  103607. set_defaults_enc(encoder);
  103608. if(!error)
  103609. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103610. return !error;
  103611. }
  103612. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103613. {
  103614. FLAC__ASSERT(0 != encoder);
  103615. FLAC__ASSERT(0 != encoder->private_);
  103616. FLAC__ASSERT(0 != encoder->protected_);
  103617. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103618. return false;
  103619. #if FLAC__HAS_OGG
  103620. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103621. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103622. return true;
  103623. #else
  103624. (void)value;
  103625. return false;
  103626. #endif
  103627. }
  103628. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103629. {
  103630. FLAC__ASSERT(0 != encoder);
  103631. FLAC__ASSERT(0 != encoder->private_);
  103632. FLAC__ASSERT(0 != encoder->protected_);
  103633. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103634. return false;
  103635. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103636. encoder->protected_->verify = value;
  103637. #endif
  103638. return true;
  103639. }
  103640. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103641. {
  103642. FLAC__ASSERT(0 != encoder);
  103643. FLAC__ASSERT(0 != encoder->private_);
  103644. FLAC__ASSERT(0 != encoder->protected_);
  103645. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103646. return false;
  103647. encoder->protected_->streamable_subset = value;
  103648. return true;
  103649. }
  103650. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103651. {
  103652. FLAC__ASSERT(0 != encoder);
  103653. FLAC__ASSERT(0 != encoder->private_);
  103654. FLAC__ASSERT(0 != encoder->protected_);
  103655. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103656. return false;
  103657. encoder->protected_->do_md5 = value;
  103658. return true;
  103659. }
  103660. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103661. {
  103662. FLAC__ASSERT(0 != encoder);
  103663. FLAC__ASSERT(0 != encoder->private_);
  103664. FLAC__ASSERT(0 != encoder->protected_);
  103665. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103666. return false;
  103667. encoder->protected_->channels = value;
  103668. return true;
  103669. }
  103670. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103671. {
  103672. FLAC__ASSERT(0 != encoder);
  103673. FLAC__ASSERT(0 != encoder->private_);
  103674. FLAC__ASSERT(0 != encoder->protected_);
  103675. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103676. return false;
  103677. encoder->protected_->bits_per_sample = value;
  103678. return true;
  103679. }
  103680. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103681. {
  103682. FLAC__ASSERT(0 != encoder);
  103683. FLAC__ASSERT(0 != encoder->private_);
  103684. FLAC__ASSERT(0 != encoder->protected_);
  103685. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103686. return false;
  103687. encoder->protected_->sample_rate = value;
  103688. return true;
  103689. }
  103690. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103691. {
  103692. FLAC__bool ok = true;
  103693. FLAC__ASSERT(0 != encoder);
  103694. FLAC__ASSERT(0 != encoder->private_);
  103695. FLAC__ASSERT(0 != encoder->protected_);
  103696. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103697. return false;
  103698. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103699. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103700. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103701. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103702. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103703. #if 0
  103704. /* was: */
  103705. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103706. /* but it's too hard to specify the string in a locale-specific way */
  103707. #else
  103708. encoder->protected_->num_apodizations = 1;
  103709. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103710. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103711. #endif
  103712. #endif
  103713. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103714. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103715. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103716. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103717. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103718. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103719. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103720. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103721. return ok;
  103722. }
  103723. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103724. {
  103725. FLAC__ASSERT(0 != encoder);
  103726. FLAC__ASSERT(0 != encoder->private_);
  103727. FLAC__ASSERT(0 != encoder->protected_);
  103728. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103729. return false;
  103730. encoder->protected_->blocksize = value;
  103731. return true;
  103732. }
  103733. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103734. {
  103735. FLAC__ASSERT(0 != encoder);
  103736. FLAC__ASSERT(0 != encoder->private_);
  103737. FLAC__ASSERT(0 != encoder->protected_);
  103738. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103739. return false;
  103740. encoder->protected_->do_mid_side_stereo = value;
  103741. return true;
  103742. }
  103743. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103744. {
  103745. FLAC__ASSERT(0 != encoder);
  103746. FLAC__ASSERT(0 != encoder->private_);
  103747. FLAC__ASSERT(0 != encoder->protected_);
  103748. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103749. return false;
  103750. encoder->protected_->loose_mid_side_stereo = value;
  103751. return true;
  103752. }
  103753. /*@@@@add to tests*/
  103754. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103755. {
  103756. FLAC__ASSERT(0 != encoder);
  103757. FLAC__ASSERT(0 != encoder->private_);
  103758. FLAC__ASSERT(0 != encoder->protected_);
  103759. FLAC__ASSERT(0 != specification);
  103760. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103761. return false;
  103762. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103763. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103764. #else
  103765. encoder->protected_->num_apodizations = 0;
  103766. while(1) {
  103767. const char *s = strchr(specification, ';');
  103768. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103769. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103770. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103771. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103772. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103773. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103774. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103775. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103776. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103777. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103778. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103779. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103780. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103781. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103782. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103783. if (stddev > 0.0 && stddev <= 0.5) {
  103784. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103785. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103786. }
  103787. }
  103788. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103789. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103790. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103791. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103792. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103793. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103794. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103795. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103796. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103797. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103798. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103799. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103800. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103801. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103802. if (p >= 0.0 && p <= 1.0) {
  103803. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103804. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103805. }
  103806. }
  103807. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103808. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103809. if (encoder->protected_->num_apodizations == 32)
  103810. break;
  103811. if (s)
  103812. specification = s+1;
  103813. else
  103814. break;
  103815. }
  103816. if(encoder->protected_->num_apodizations == 0) {
  103817. encoder->protected_->num_apodizations = 1;
  103818. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103819. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103820. }
  103821. #endif
  103822. return true;
  103823. }
  103824. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103825. {
  103826. FLAC__ASSERT(0 != encoder);
  103827. FLAC__ASSERT(0 != encoder->private_);
  103828. FLAC__ASSERT(0 != encoder->protected_);
  103829. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103830. return false;
  103831. encoder->protected_->max_lpc_order = value;
  103832. return true;
  103833. }
  103834. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103835. {
  103836. FLAC__ASSERT(0 != encoder);
  103837. FLAC__ASSERT(0 != encoder->private_);
  103838. FLAC__ASSERT(0 != encoder->protected_);
  103839. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103840. return false;
  103841. encoder->protected_->qlp_coeff_precision = value;
  103842. return true;
  103843. }
  103844. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103845. {
  103846. FLAC__ASSERT(0 != encoder);
  103847. FLAC__ASSERT(0 != encoder->private_);
  103848. FLAC__ASSERT(0 != encoder->protected_);
  103849. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103850. return false;
  103851. encoder->protected_->do_qlp_coeff_prec_search = value;
  103852. return true;
  103853. }
  103854. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103855. {
  103856. FLAC__ASSERT(0 != encoder);
  103857. FLAC__ASSERT(0 != encoder->private_);
  103858. FLAC__ASSERT(0 != encoder->protected_);
  103859. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103860. return false;
  103861. #if 0
  103862. /*@@@ deprecated: */
  103863. encoder->protected_->do_escape_coding = value;
  103864. #else
  103865. (void)value;
  103866. #endif
  103867. return true;
  103868. }
  103869. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103870. {
  103871. FLAC__ASSERT(0 != encoder);
  103872. FLAC__ASSERT(0 != encoder->private_);
  103873. FLAC__ASSERT(0 != encoder->protected_);
  103874. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103875. return false;
  103876. encoder->protected_->do_exhaustive_model_search = value;
  103877. return true;
  103878. }
  103879. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103880. {
  103881. FLAC__ASSERT(0 != encoder);
  103882. FLAC__ASSERT(0 != encoder->private_);
  103883. FLAC__ASSERT(0 != encoder->protected_);
  103884. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103885. return false;
  103886. encoder->protected_->min_residual_partition_order = value;
  103887. return true;
  103888. }
  103889. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103890. {
  103891. FLAC__ASSERT(0 != encoder);
  103892. FLAC__ASSERT(0 != encoder->private_);
  103893. FLAC__ASSERT(0 != encoder->protected_);
  103894. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103895. return false;
  103896. encoder->protected_->max_residual_partition_order = value;
  103897. return true;
  103898. }
  103899. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103900. {
  103901. FLAC__ASSERT(0 != encoder);
  103902. FLAC__ASSERT(0 != encoder->private_);
  103903. FLAC__ASSERT(0 != encoder->protected_);
  103904. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103905. return false;
  103906. #if 0
  103907. /*@@@ deprecated: */
  103908. encoder->protected_->rice_parameter_search_dist = value;
  103909. #else
  103910. (void)value;
  103911. #endif
  103912. return true;
  103913. }
  103914. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103915. {
  103916. FLAC__ASSERT(0 != encoder);
  103917. FLAC__ASSERT(0 != encoder->private_);
  103918. FLAC__ASSERT(0 != encoder->protected_);
  103919. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103920. return false;
  103921. encoder->protected_->total_samples_estimate = value;
  103922. return true;
  103923. }
  103924. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103925. {
  103926. FLAC__ASSERT(0 != encoder);
  103927. FLAC__ASSERT(0 != encoder->private_);
  103928. FLAC__ASSERT(0 != encoder->protected_);
  103929. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103930. return false;
  103931. if(0 == metadata)
  103932. num_blocks = 0;
  103933. if(0 == num_blocks)
  103934. metadata = 0;
  103935. /* realloc() does not do exactly what we want so... */
  103936. if(encoder->protected_->metadata) {
  103937. free(encoder->protected_->metadata);
  103938. encoder->protected_->metadata = 0;
  103939. encoder->protected_->num_metadata_blocks = 0;
  103940. }
  103941. if(num_blocks) {
  103942. FLAC__StreamMetadata **m;
  103943. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103944. return false;
  103945. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103946. encoder->protected_->metadata = m;
  103947. encoder->protected_->num_metadata_blocks = num_blocks;
  103948. }
  103949. #if FLAC__HAS_OGG
  103950. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103951. return false;
  103952. #endif
  103953. return true;
  103954. }
  103955. /*
  103956. * These three functions are not static, but not publically exposed in
  103957. * include/FLAC/ either. They are used by the test suite.
  103958. */
  103959. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103960. {
  103961. FLAC__ASSERT(0 != encoder);
  103962. FLAC__ASSERT(0 != encoder->private_);
  103963. FLAC__ASSERT(0 != encoder->protected_);
  103964. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103965. return false;
  103966. encoder->private_->disable_constant_subframes = value;
  103967. return true;
  103968. }
  103969. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103970. {
  103971. FLAC__ASSERT(0 != encoder);
  103972. FLAC__ASSERT(0 != encoder->private_);
  103973. FLAC__ASSERT(0 != encoder->protected_);
  103974. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103975. return false;
  103976. encoder->private_->disable_fixed_subframes = value;
  103977. return true;
  103978. }
  103979. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103980. {
  103981. FLAC__ASSERT(0 != encoder);
  103982. FLAC__ASSERT(0 != encoder->private_);
  103983. FLAC__ASSERT(0 != encoder->protected_);
  103984. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103985. return false;
  103986. encoder->private_->disable_verbatim_subframes = value;
  103987. return true;
  103988. }
  103989. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103990. {
  103991. FLAC__ASSERT(0 != encoder);
  103992. FLAC__ASSERT(0 != encoder->private_);
  103993. FLAC__ASSERT(0 != encoder->protected_);
  103994. return encoder->protected_->state;
  103995. }
  103996. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103997. {
  103998. FLAC__ASSERT(0 != encoder);
  103999. FLAC__ASSERT(0 != encoder->private_);
  104000. FLAC__ASSERT(0 != encoder->protected_);
  104001. if(encoder->protected_->verify)
  104002. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  104003. else
  104004. return FLAC__STREAM_DECODER_UNINITIALIZED;
  104005. }
  104006. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  104007. {
  104008. FLAC__ASSERT(0 != encoder);
  104009. FLAC__ASSERT(0 != encoder->private_);
  104010. FLAC__ASSERT(0 != encoder->protected_);
  104011. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  104012. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  104013. else
  104014. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  104015. }
  104016. 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)
  104017. {
  104018. FLAC__ASSERT(0 != encoder);
  104019. FLAC__ASSERT(0 != encoder->private_);
  104020. FLAC__ASSERT(0 != encoder->protected_);
  104021. if(0 != absolute_sample)
  104022. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  104023. if(0 != frame_number)
  104024. *frame_number = encoder->private_->verify.error_stats.frame_number;
  104025. if(0 != channel)
  104026. *channel = encoder->private_->verify.error_stats.channel;
  104027. if(0 != sample)
  104028. *sample = encoder->private_->verify.error_stats.sample;
  104029. if(0 != expected)
  104030. *expected = encoder->private_->verify.error_stats.expected;
  104031. if(0 != got)
  104032. *got = encoder->private_->verify.error_stats.got;
  104033. }
  104034. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  104035. {
  104036. FLAC__ASSERT(0 != encoder);
  104037. FLAC__ASSERT(0 != encoder->private_);
  104038. FLAC__ASSERT(0 != encoder->protected_);
  104039. return encoder->protected_->verify;
  104040. }
  104041. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  104042. {
  104043. FLAC__ASSERT(0 != encoder);
  104044. FLAC__ASSERT(0 != encoder->private_);
  104045. FLAC__ASSERT(0 != encoder->protected_);
  104046. return encoder->protected_->streamable_subset;
  104047. }
  104048. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  104049. {
  104050. FLAC__ASSERT(0 != encoder);
  104051. FLAC__ASSERT(0 != encoder->private_);
  104052. FLAC__ASSERT(0 != encoder->protected_);
  104053. return encoder->protected_->do_md5;
  104054. }
  104055. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104056. {
  104057. FLAC__ASSERT(0 != encoder);
  104058. FLAC__ASSERT(0 != encoder->private_);
  104059. FLAC__ASSERT(0 != encoder->protected_);
  104060. return encoder->protected_->channels;
  104061. }
  104062. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104063. {
  104064. FLAC__ASSERT(0 != encoder);
  104065. FLAC__ASSERT(0 != encoder->private_);
  104066. FLAC__ASSERT(0 != encoder->protected_);
  104067. return encoder->protected_->bits_per_sample;
  104068. }
  104069. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104070. {
  104071. FLAC__ASSERT(0 != encoder);
  104072. FLAC__ASSERT(0 != encoder->private_);
  104073. FLAC__ASSERT(0 != encoder->protected_);
  104074. return encoder->protected_->sample_rate;
  104075. }
  104076. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104077. {
  104078. FLAC__ASSERT(0 != encoder);
  104079. FLAC__ASSERT(0 != encoder->private_);
  104080. FLAC__ASSERT(0 != encoder->protected_);
  104081. return encoder->protected_->blocksize;
  104082. }
  104083. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104084. {
  104085. FLAC__ASSERT(0 != encoder);
  104086. FLAC__ASSERT(0 != encoder->private_);
  104087. FLAC__ASSERT(0 != encoder->protected_);
  104088. return encoder->protected_->do_mid_side_stereo;
  104089. }
  104090. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104091. {
  104092. FLAC__ASSERT(0 != encoder);
  104093. FLAC__ASSERT(0 != encoder->private_);
  104094. FLAC__ASSERT(0 != encoder->protected_);
  104095. return encoder->protected_->loose_mid_side_stereo;
  104096. }
  104097. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104098. {
  104099. FLAC__ASSERT(0 != encoder);
  104100. FLAC__ASSERT(0 != encoder->private_);
  104101. FLAC__ASSERT(0 != encoder->protected_);
  104102. return encoder->protected_->max_lpc_order;
  104103. }
  104104. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104105. {
  104106. FLAC__ASSERT(0 != encoder);
  104107. FLAC__ASSERT(0 != encoder->private_);
  104108. FLAC__ASSERT(0 != encoder->protected_);
  104109. return encoder->protected_->qlp_coeff_precision;
  104110. }
  104111. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104112. {
  104113. FLAC__ASSERT(0 != encoder);
  104114. FLAC__ASSERT(0 != encoder->private_);
  104115. FLAC__ASSERT(0 != encoder->protected_);
  104116. return encoder->protected_->do_qlp_coeff_prec_search;
  104117. }
  104118. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104119. {
  104120. FLAC__ASSERT(0 != encoder);
  104121. FLAC__ASSERT(0 != encoder->private_);
  104122. FLAC__ASSERT(0 != encoder->protected_);
  104123. return encoder->protected_->do_escape_coding;
  104124. }
  104125. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104126. {
  104127. FLAC__ASSERT(0 != encoder);
  104128. FLAC__ASSERT(0 != encoder->private_);
  104129. FLAC__ASSERT(0 != encoder->protected_);
  104130. return encoder->protected_->do_exhaustive_model_search;
  104131. }
  104132. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104133. {
  104134. FLAC__ASSERT(0 != encoder);
  104135. FLAC__ASSERT(0 != encoder->private_);
  104136. FLAC__ASSERT(0 != encoder->protected_);
  104137. return encoder->protected_->min_residual_partition_order;
  104138. }
  104139. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104140. {
  104141. FLAC__ASSERT(0 != encoder);
  104142. FLAC__ASSERT(0 != encoder->private_);
  104143. FLAC__ASSERT(0 != encoder->protected_);
  104144. return encoder->protected_->max_residual_partition_order;
  104145. }
  104146. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104147. {
  104148. FLAC__ASSERT(0 != encoder);
  104149. FLAC__ASSERT(0 != encoder->private_);
  104150. FLAC__ASSERT(0 != encoder->protected_);
  104151. return encoder->protected_->rice_parameter_search_dist;
  104152. }
  104153. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104154. {
  104155. FLAC__ASSERT(0 != encoder);
  104156. FLAC__ASSERT(0 != encoder->private_);
  104157. FLAC__ASSERT(0 != encoder->protected_);
  104158. return encoder->protected_->total_samples_estimate;
  104159. }
  104160. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104161. {
  104162. unsigned i, j = 0, channel;
  104163. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104164. FLAC__ASSERT(0 != encoder);
  104165. FLAC__ASSERT(0 != encoder->private_);
  104166. FLAC__ASSERT(0 != encoder->protected_);
  104167. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104168. do {
  104169. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104170. if(encoder->protected_->verify)
  104171. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104172. for(channel = 0; channel < channels; channel++)
  104173. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104174. if(encoder->protected_->do_mid_side_stereo) {
  104175. FLAC__ASSERT(channels == 2);
  104176. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104177. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104178. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104179. 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' ! */
  104180. }
  104181. }
  104182. else
  104183. j += n;
  104184. encoder->private_->current_sample_number += n;
  104185. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104186. if(encoder->private_->current_sample_number > blocksize) {
  104187. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104188. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104189. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104190. return false;
  104191. /* move unprocessed overread samples to beginnings of arrays */
  104192. for(channel = 0; channel < channels; channel++)
  104193. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104194. if(encoder->protected_->do_mid_side_stereo) {
  104195. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104196. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104197. }
  104198. encoder->private_->current_sample_number = 1;
  104199. }
  104200. } while(j < samples);
  104201. return true;
  104202. }
  104203. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104204. {
  104205. unsigned i, j, k, channel;
  104206. FLAC__int32 x, mid, side;
  104207. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104208. FLAC__ASSERT(0 != encoder);
  104209. FLAC__ASSERT(0 != encoder->private_);
  104210. FLAC__ASSERT(0 != encoder->protected_);
  104211. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104212. j = k = 0;
  104213. /*
  104214. * we have several flavors of the same basic loop, optimized for
  104215. * different conditions:
  104216. */
  104217. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104218. /*
  104219. * stereo coding: unroll channel loop
  104220. */
  104221. do {
  104222. if(encoder->protected_->verify)
  104223. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104224. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104225. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104226. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104227. x = buffer[k++];
  104228. encoder->private_->integer_signal[1][i] = x;
  104229. mid += x;
  104230. side -= x;
  104231. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104232. encoder->private_->integer_signal_mid_side[1][i] = side;
  104233. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104234. }
  104235. encoder->private_->current_sample_number = i;
  104236. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104237. if(i > blocksize) {
  104238. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104239. return false;
  104240. /* move unprocessed overread samples to beginnings of arrays */
  104241. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104242. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104243. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104244. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104245. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104246. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104247. encoder->private_->current_sample_number = 1;
  104248. }
  104249. } while(j < samples);
  104250. }
  104251. else {
  104252. /*
  104253. * independent channel coding: buffer each channel in inner loop
  104254. */
  104255. do {
  104256. if(encoder->protected_->verify)
  104257. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104258. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104259. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104260. for(channel = 0; channel < channels; channel++)
  104261. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104262. }
  104263. encoder->private_->current_sample_number = i;
  104264. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104265. if(i > blocksize) {
  104266. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104267. return false;
  104268. /* move unprocessed overread samples to beginnings of arrays */
  104269. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104270. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104271. for(channel = 0; channel < channels; channel++)
  104272. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104273. encoder->private_->current_sample_number = 1;
  104274. }
  104275. } while(j < samples);
  104276. }
  104277. return true;
  104278. }
  104279. /***********************************************************************
  104280. *
  104281. * Private class methods
  104282. *
  104283. ***********************************************************************/
  104284. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104285. {
  104286. FLAC__ASSERT(0 != encoder);
  104287. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104288. encoder->protected_->verify = true;
  104289. #else
  104290. encoder->protected_->verify = false;
  104291. #endif
  104292. encoder->protected_->streamable_subset = true;
  104293. encoder->protected_->do_md5 = true;
  104294. encoder->protected_->do_mid_side_stereo = false;
  104295. encoder->protected_->loose_mid_side_stereo = false;
  104296. encoder->protected_->channels = 2;
  104297. encoder->protected_->bits_per_sample = 16;
  104298. encoder->protected_->sample_rate = 44100;
  104299. encoder->protected_->blocksize = 0;
  104300. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104301. encoder->protected_->num_apodizations = 1;
  104302. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104303. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104304. #endif
  104305. encoder->protected_->max_lpc_order = 0;
  104306. encoder->protected_->qlp_coeff_precision = 0;
  104307. encoder->protected_->do_qlp_coeff_prec_search = false;
  104308. encoder->protected_->do_exhaustive_model_search = false;
  104309. encoder->protected_->do_escape_coding = false;
  104310. encoder->protected_->min_residual_partition_order = 0;
  104311. encoder->protected_->max_residual_partition_order = 0;
  104312. encoder->protected_->rice_parameter_search_dist = 0;
  104313. encoder->protected_->total_samples_estimate = 0;
  104314. encoder->protected_->metadata = 0;
  104315. encoder->protected_->num_metadata_blocks = 0;
  104316. encoder->private_->seek_table = 0;
  104317. encoder->private_->disable_constant_subframes = false;
  104318. encoder->private_->disable_fixed_subframes = false;
  104319. encoder->private_->disable_verbatim_subframes = false;
  104320. #if FLAC__HAS_OGG
  104321. encoder->private_->is_ogg = false;
  104322. #endif
  104323. encoder->private_->read_callback = 0;
  104324. encoder->private_->write_callback = 0;
  104325. encoder->private_->seek_callback = 0;
  104326. encoder->private_->tell_callback = 0;
  104327. encoder->private_->metadata_callback = 0;
  104328. encoder->private_->progress_callback = 0;
  104329. encoder->private_->client_data = 0;
  104330. #if FLAC__HAS_OGG
  104331. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104332. #endif
  104333. }
  104334. void free_(FLAC__StreamEncoder *encoder)
  104335. {
  104336. unsigned i, channel;
  104337. FLAC__ASSERT(0 != encoder);
  104338. if(encoder->protected_->metadata) {
  104339. free(encoder->protected_->metadata);
  104340. encoder->protected_->metadata = 0;
  104341. encoder->protected_->num_metadata_blocks = 0;
  104342. }
  104343. for(i = 0; i < encoder->protected_->channels; i++) {
  104344. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104345. free(encoder->private_->integer_signal_unaligned[i]);
  104346. encoder->private_->integer_signal_unaligned[i] = 0;
  104347. }
  104348. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104349. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104350. free(encoder->private_->real_signal_unaligned[i]);
  104351. encoder->private_->real_signal_unaligned[i] = 0;
  104352. }
  104353. #endif
  104354. }
  104355. for(i = 0; i < 2; i++) {
  104356. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104357. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104358. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104359. }
  104360. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104361. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104362. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104363. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104364. }
  104365. #endif
  104366. }
  104367. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104368. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104369. if(0 != encoder->private_->window_unaligned[i]) {
  104370. free(encoder->private_->window_unaligned[i]);
  104371. encoder->private_->window_unaligned[i] = 0;
  104372. }
  104373. }
  104374. if(0 != encoder->private_->windowed_signal_unaligned) {
  104375. free(encoder->private_->windowed_signal_unaligned);
  104376. encoder->private_->windowed_signal_unaligned = 0;
  104377. }
  104378. #endif
  104379. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104380. for(i = 0; i < 2; i++) {
  104381. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104382. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104383. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104384. }
  104385. }
  104386. }
  104387. for(channel = 0; channel < 2; channel++) {
  104388. for(i = 0; i < 2; i++) {
  104389. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104390. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104391. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104392. }
  104393. }
  104394. }
  104395. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104396. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104397. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104398. }
  104399. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104400. free(encoder->private_->raw_bits_per_partition_unaligned);
  104401. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104402. }
  104403. if(encoder->protected_->verify) {
  104404. for(i = 0; i < encoder->protected_->channels; i++) {
  104405. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104406. free(encoder->private_->verify.input_fifo.data[i]);
  104407. encoder->private_->verify.input_fifo.data[i] = 0;
  104408. }
  104409. }
  104410. }
  104411. FLAC__bitwriter_free(encoder->private_->frame);
  104412. }
  104413. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104414. {
  104415. FLAC__bool ok;
  104416. unsigned i, channel;
  104417. FLAC__ASSERT(new_blocksize > 0);
  104418. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104419. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104420. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104421. if(new_blocksize <= encoder->private_->input_capacity)
  104422. return true;
  104423. ok = true;
  104424. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104425. * requires that the input arrays (in our case the integer signals)
  104426. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104427. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104428. */
  104429. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104430. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104431. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104432. encoder->private_->integer_signal[i] += 4;
  104433. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104434. #if 0 /* @@@ currently unused */
  104435. if(encoder->protected_->max_lpc_order > 0)
  104436. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104437. #endif
  104438. #endif
  104439. }
  104440. for(i = 0; ok && i < 2; i++) {
  104441. 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]);
  104442. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104443. encoder->private_->integer_signal_mid_side[i] += 4;
  104444. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104445. #if 0 /* @@@ currently unused */
  104446. if(encoder->protected_->max_lpc_order > 0)
  104447. 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]);
  104448. #endif
  104449. #endif
  104450. }
  104451. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104452. if(ok && encoder->protected_->max_lpc_order > 0) {
  104453. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104454. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104455. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104456. }
  104457. #endif
  104458. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104459. for(i = 0; ok && i < 2; i++) {
  104460. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104461. }
  104462. }
  104463. for(channel = 0; ok && channel < 2; channel++) {
  104464. for(i = 0; ok && i < 2; i++) {
  104465. 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]);
  104466. }
  104467. }
  104468. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104469. /*@@@ 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) */
  104470. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104471. if(encoder->protected_->do_escape_coding)
  104472. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104473. /* now adjust the windows if the blocksize has changed */
  104474. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104475. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104476. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104477. switch(encoder->protected_->apodizations[i].type) {
  104478. case FLAC__APODIZATION_BARTLETT:
  104479. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104480. break;
  104481. case FLAC__APODIZATION_BARTLETT_HANN:
  104482. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104483. break;
  104484. case FLAC__APODIZATION_BLACKMAN:
  104485. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104486. break;
  104487. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104488. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104489. break;
  104490. case FLAC__APODIZATION_CONNES:
  104491. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104492. break;
  104493. case FLAC__APODIZATION_FLATTOP:
  104494. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104495. break;
  104496. case FLAC__APODIZATION_GAUSS:
  104497. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104498. break;
  104499. case FLAC__APODIZATION_HAMMING:
  104500. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104501. break;
  104502. case FLAC__APODIZATION_HANN:
  104503. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104504. break;
  104505. case FLAC__APODIZATION_KAISER_BESSEL:
  104506. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104507. break;
  104508. case FLAC__APODIZATION_NUTTALL:
  104509. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104510. break;
  104511. case FLAC__APODIZATION_RECTANGLE:
  104512. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104513. break;
  104514. case FLAC__APODIZATION_TRIANGLE:
  104515. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104516. break;
  104517. case FLAC__APODIZATION_TUKEY:
  104518. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104519. break;
  104520. case FLAC__APODIZATION_WELCH:
  104521. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104522. break;
  104523. default:
  104524. FLAC__ASSERT(0);
  104525. /* double protection */
  104526. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104527. break;
  104528. }
  104529. }
  104530. }
  104531. #endif
  104532. if(ok)
  104533. encoder->private_->input_capacity = new_blocksize;
  104534. else
  104535. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104536. return ok;
  104537. }
  104538. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104539. {
  104540. const FLAC__byte *buffer;
  104541. size_t bytes;
  104542. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104543. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104544. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104545. return false;
  104546. }
  104547. if(encoder->protected_->verify) {
  104548. encoder->private_->verify.output.data = buffer;
  104549. encoder->private_->verify.output.bytes = bytes;
  104550. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104551. encoder->private_->verify.needs_magic_hack = true;
  104552. }
  104553. else {
  104554. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104555. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104556. FLAC__bitwriter_clear(encoder->private_->frame);
  104557. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104558. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104559. return false;
  104560. }
  104561. }
  104562. }
  104563. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104564. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104565. FLAC__bitwriter_clear(encoder->private_->frame);
  104566. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104567. return false;
  104568. }
  104569. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104570. FLAC__bitwriter_clear(encoder->private_->frame);
  104571. if(samples > 0) {
  104572. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104573. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104574. }
  104575. return true;
  104576. }
  104577. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104578. {
  104579. FLAC__StreamEncoderWriteStatus status;
  104580. FLAC__uint64 output_position = 0;
  104581. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104582. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104583. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104584. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104585. }
  104586. /*
  104587. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104588. */
  104589. if(samples == 0) {
  104590. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104591. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104592. encoder->protected_->streaminfo_offset = output_position;
  104593. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104594. encoder->protected_->seektable_offset = output_position;
  104595. }
  104596. /*
  104597. * Mark the current seek point if hit (if audio_offset == 0 that
  104598. * means we're still writing metadata and haven't hit the first
  104599. * frame yet)
  104600. */
  104601. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104602. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104603. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104604. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104605. FLAC__uint64 test_sample;
  104606. unsigned i;
  104607. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104608. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104609. if(test_sample > frame_last_sample) {
  104610. break;
  104611. }
  104612. else if(test_sample >= frame_first_sample) {
  104613. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104614. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104615. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104616. encoder->private_->first_seekpoint_to_check++;
  104617. /* DO NOT: "break;" and here's why:
  104618. * The seektable template may contain more than one target
  104619. * sample for any given frame; we will keep looping, generating
  104620. * duplicate seekpoints for them, and we'll clean it up later,
  104621. * just before writing the seektable back to the metadata.
  104622. */
  104623. }
  104624. else {
  104625. encoder->private_->first_seekpoint_to_check++;
  104626. }
  104627. }
  104628. }
  104629. #if FLAC__HAS_OGG
  104630. if(encoder->private_->is_ogg) {
  104631. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104632. &encoder->protected_->ogg_encoder_aspect,
  104633. buffer,
  104634. bytes,
  104635. samples,
  104636. encoder->private_->current_frame_number,
  104637. is_last_block,
  104638. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104639. encoder,
  104640. encoder->private_->client_data
  104641. );
  104642. }
  104643. else
  104644. #endif
  104645. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104646. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104647. encoder->private_->bytes_written += bytes;
  104648. encoder->private_->samples_written += samples;
  104649. /* we keep a high watermark on the number of frames written because
  104650. * when the encoder goes back to write metadata, 'current_frame'
  104651. * will drop back to 0.
  104652. */
  104653. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104654. }
  104655. else
  104656. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104657. return status;
  104658. }
  104659. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104660. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104661. {
  104662. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104663. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104664. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104665. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104666. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104667. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104668. FLAC__StreamEncoderSeekStatus seek_status;
  104669. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104670. /* All this is based on intimate knowledge of the stream header
  104671. * layout, but a change to the header format that would break this
  104672. * would also break all streams encoded in the previous format.
  104673. */
  104674. /*
  104675. * Write MD5 signature
  104676. */
  104677. {
  104678. const unsigned md5_offset =
  104679. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104680. (
  104681. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104682. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104683. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104684. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104685. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104686. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104687. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104688. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104689. ) / 8;
  104690. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104691. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104692. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104693. return;
  104694. }
  104695. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104696. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104697. return;
  104698. }
  104699. }
  104700. /*
  104701. * Write total samples
  104702. */
  104703. {
  104704. const unsigned total_samples_byte_offset =
  104705. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104706. (
  104707. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104708. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104709. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104710. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104711. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104712. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104713. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104714. - 4
  104715. ) / 8;
  104716. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104717. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104718. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104719. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104720. b[4] = (FLAC__byte)(samples & 0xFF);
  104721. 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) {
  104722. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104723. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104724. return;
  104725. }
  104726. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104727. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104728. return;
  104729. }
  104730. }
  104731. /*
  104732. * Write min/max framesize
  104733. */
  104734. {
  104735. const unsigned min_framesize_offset =
  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. ) / 8;
  104741. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104742. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104743. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104744. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104745. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104746. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104747. 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) {
  104748. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104749. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104750. return;
  104751. }
  104752. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104753. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104754. return;
  104755. }
  104756. }
  104757. /*
  104758. * Write seektable
  104759. */
  104760. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104761. unsigned i;
  104762. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104763. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104764. 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) {
  104765. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104766. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104767. return;
  104768. }
  104769. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104770. FLAC__uint64 xx;
  104771. unsigned x;
  104772. xx = encoder->private_->seek_table->points[i].sample_number;
  104773. b[7] = (FLAC__byte)xx; xx >>= 8;
  104774. b[6] = (FLAC__byte)xx; xx >>= 8;
  104775. b[5] = (FLAC__byte)xx; xx >>= 8;
  104776. b[4] = (FLAC__byte)xx; xx >>= 8;
  104777. b[3] = (FLAC__byte)xx; xx >>= 8;
  104778. b[2] = (FLAC__byte)xx; xx >>= 8;
  104779. b[1] = (FLAC__byte)xx; xx >>= 8;
  104780. b[0] = (FLAC__byte)xx; xx >>= 8;
  104781. xx = encoder->private_->seek_table->points[i].stream_offset;
  104782. b[15] = (FLAC__byte)xx; xx >>= 8;
  104783. b[14] = (FLAC__byte)xx; xx >>= 8;
  104784. b[13] = (FLAC__byte)xx; xx >>= 8;
  104785. b[12] = (FLAC__byte)xx; xx >>= 8;
  104786. b[11] = (FLAC__byte)xx; xx >>= 8;
  104787. b[10] = (FLAC__byte)xx; xx >>= 8;
  104788. b[9] = (FLAC__byte)xx; xx >>= 8;
  104789. b[8] = (FLAC__byte)xx; xx >>= 8;
  104790. x = encoder->private_->seek_table->points[i].frame_samples;
  104791. b[17] = (FLAC__byte)x; x >>= 8;
  104792. b[16] = (FLAC__byte)x; x >>= 8;
  104793. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104794. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104795. return;
  104796. }
  104797. }
  104798. }
  104799. }
  104800. #if FLAC__HAS_OGG
  104801. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104802. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104803. {
  104804. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104805. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104806. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104807. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104808. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104809. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104810. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104811. FLAC__STREAM_SYNC_LENGTH
  104812. ;
  104813. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104814. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104815. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104816. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104817. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104818. ogg_page page;
  104819. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104820. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104821. /* Pre-check that client supports seeking, since we don't want the
  104822. * ogg_helper code to ever have to deal with this condition.
  104823. */
  104824. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104825. return;
  104826. /* All this is based on intimate knowledge of the stream header
  104827. * layout, but a change to the header format that would break this
  104828. * would also break all streams encoded in the previous format.
  104829. */
  104830. /**
  104831. ** Write STREAMINFO stats
  104832. **/
  104833. simple_ogg_page__init(&page);
  104834. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104835. simple_ogg_page__clear(&page);
  104836. return; /* state already set */
  104837. }
  104838. /*
  104839. * Write MD5 signature
  104840. */
  104841. {
  104842. const unsigned md5_offset =
  104843. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104844. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104845. (
  104846. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104847. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104848. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104849. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104850. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104851. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104852. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104853. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104854. ) / 8;
  104855. if(md5_offset + 16 > (unsigned)page.body_len) {
  104856. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104857. simple_ogg_page__clear(&page);
  104858. return;
  104859. }
  104860. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104861. }
  104862. /*
  104863. * Write total samples
  104864. */
  104865. {
  104866. const unsigned total_samples_byte_offset =
  104867. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104868. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104869. (
  104870. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104871. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104872. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104873. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104874. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104875. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104876. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104877. - 4
  104878. ) / 8;
  104879. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104880. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104881. simple_ogg_page__clear(&page);
  104882. return;
  104883. }
  104884. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104885. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104886. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104887. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104888. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104889. b[4] = (FLAC__byte)(samples & 0xFF);
  104890. memcpy(page.body + total_samples_byte_offset, b, 5);
  104891. }
  104892. /*
  104893. * Write min/max framesize
  104894. */
  104895. {
  104896. const unsigned min_framesize_offset =
  104897. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104898. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104899. (
  104900. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104901. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104902. ) / 8;
  104903. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104904. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104905. simple_ogg_page__clear(&page);
  104906. return;
  104907. }
  104908. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104909. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104910. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104911. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104912. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104913. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104914. memcpy(page.body + min_framesize_offset, b, 6);
  104915. }
  104916. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104917. simple_ogg_page__clear(&page);
  104918. return; /* state already set */
  104919. }
  104920. simple_ogg_page__clear(&page);
  104921. /*
  104922. * Write seektable
  104923. */
  104924. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104925. unsigned i;
  104926. FLAC__byte *p;
  104927. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104928. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104929. simple_ogg_page__init(&page);
  104930. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104931. simple_ogg_page__clear(&page);
  104932. return; /* state already set */
  104933. }
  104934. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104935. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104936. simple_ogg_page__clear(&page);
  104937. return;
  104938. }
  104939. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104940. FLAC__uint64 xx;
  104941. unsigned x;
  104942. xx = encoder->private_->seek_table->points[i].sample_number;
  104943. b[7] = (FLAC__byte)xx; xx >>= 8;
  104944. b[6] = (FLAC__byte)xx; xx >>= 8;
  104945. b[5] = (FLAC__byte)xx; xx >>= 8;
  104946. b[4] = (FLAC__byte)xx; xx >>= 8;
  104947. b[3] = (FLAC__byte)xx; xx >>= 8;
  104948. b[2] = (FLAC__byte)xx; xx >>= 8;
  104949. b[1] = (FLAC__byte)xx; xx >>= 8;
  104950. b[0] = (FLAC__byte)xx; xx >>= 8;
  104951. xx = encoder->private_->seek_table->points[i].stream_offset;
  104952. b[15] = (FLAC__byte)xx; xx >>= 8;
  104953. b[14] = (FLAC__byte)xx; xx >>= 8;
  104954. b[13] = (FLAC__byte)xx; xx >>= 8;
  104955. b[12] = (FLAC__byte)xx; xx >>= 8;
  104956. b[11] = (FLAC__byte)xx; xx >>= 8;
  104957. b[10] = (FLAC__byte)xx; xx >>= 8;
  104958. b[9] = (FLAC__byte)xx; xx >>= 8;
  104959. b[8] = (FLAC__byte)xx; xx >>= 8;
  104960. x = encoder->private_->seek_table->points[i].frame_samples;
  104961. b[17] = (FLAC__byte)x; x >>= 8;
  104962. b[16] = (FLAC__byte)x; x >>= 8;
  104963. memcpy(p, b, 18);
  104964. }
  104965. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104966. simple_ogg_page__clear(&page);
  104967. return; /* state already set */
  104968. }
  104969. simple_ogg_page__clear(&page);
  104970. }
  104971. }
  104972. #endif
  104973. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104974. {
  104975. FLAC__uint16 crc;
  104976. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104977. /*
  104978. * Accumulate raw signal to the MD5 signature
  104979. */
  104980. 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)) {
  104981. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104982. return false;
  104983. }
  104984. /*
  104985. * Process the frame header and subframes into the frame bitbuffer
  104986. */
  104987. if(!process_subframes_(encoder, is_fractional_block)) {
  104988. /* the above function sets the state for us in case of an error */
  104989. return false;
  104990. }
  104991. /*
  104992. * Zero-pad the frame to a byte_boundary
  104993. */
  104994. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104995. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104996. return false;
  104997. }
  104998. /*
  104999. * CRC-16 the whole thing
  105000. */
  105001. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  105002. if(
  105003. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  105004. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  105005. ) {
  105006. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  105007. return false;
  105008. }
  105009. /*
  105010. * Write it
  105011. */
  105012. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  105013. /* the above function sets the state for us in case of an error */
  105014. return false;
  105015. }
  105016. /*
  105017. * Get ready for the next frame
  105018. */
  105019. encoder->private_->current_sample_number = 0;
  105020. encoder->private_->current_frame_number++;
  105021. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  105022. return true;
  105023. }
  105024. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  105025. {
  105026. FLAC__FrameHeader frame_header;
  105027. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  105028. FLAC__bool do_independent, do_mid_side;
  105029. /*
  105030. * Calculate the min,max Rice partition orders
  105031. */
  105032. if(is_fractional_block) {
  105033. max_partition_order = 0;
  105034. }
  105035. else {
  105036. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  105037. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  105038. }
  105039. min_partition_order = min(min_partition_order, max_partition_order);
  105040. /*
  105041. * Setup the frame
  105042. */
  105043. frame_header.blocksize = encoder->protected_->blocksize;
  105044. frame_header.sample_rate = encoder->protected_->sample_rate;
  105045. frame_header.channels = encoder->protected_->channels;
  105046. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  105047. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  105048. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  105049. frame_header.number.frame_number = encoder->private_->current_frame_number;
  105050. /*
  105051. * Figure out what channel assignments to try
  105052. */
  105053. if(encoder->protected_->do_mid_side_stereo) {
  105054. if(encoder->protected_->loose_mid_side_stereo) {
  105055. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105056. do_independent = true;
  105057. do_mid_side = true;
  105058. }
  105059. else {
  105060. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105061. do_mid_side = !do_independent;
  105062. }
  105063. }
  105064. else {
  105065. do_independent = true;
  105066. do_mid_side = true;
  105067. }
  105068. }
  105069. else {
  105070. do_independent = true;
  105071. do_mid_side = false;
  105072. }
  105073. FLAC__ASSERT(do_independent || do_mid_side);
  105074. /*
  105075. * Check for wasted bits; set effective bps for each subframe
  105076. */
  105077. if(do_independent) {
  105078. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105079. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105080. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105081. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105082. }
  105083. }
  105084. if(do_mid_side) {
  105085. FLAC__ASSERT(encoder->protected_->channels == 2);
  105086. for(channel = 0; channel < 2; channel++) {
  105087. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105088. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105089. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105090. }
  105091. }
  105092. /*
  105093. * First do a normal encoding pass of each independent channel
  105094. */
  105095. if(do_independent) {
  105096. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105097. if(!
  105098. process_subframe_(
  105099. encoder,
  105100. min_partition_order,
  105101. max_partition_order,
  105102. &frame_header,
  105103. encoder->private_->subframe_bps[channel],
  105104. encoder->private_->integer_signal[channel],
  105105. encoder->private_->subframe_workspace_ptr[channel],
  105106. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105107. encoder->private_->residual_workspace[channel],
  105108. encoder->private_->best_subframe+channel,
  105109. encoder->private_->best_subframe_bits+channel
  105110. )
  105111. )
  105112. return false;
  105113. }
  105114. }
  105115. /*
  105116. * Now do mid and side channels if requested
  105117. */
  105118. if(do_mid_side) {
  105119. FLAC__ASSERT(encoder->protected_->channels == 2);
  105120. for(channel = 0; channel < 2; channel++) {
  105121. if(!
  105122. process_subframe_(
  105123. encoder,
  105124. min_partition_order,
  105125. max_partition_order,
  105126. &frame_header,
  105127. encoder->private_->subframe_bps_mid_side[channel],
  105128. encoder->private_->integer_signal_mid_side[channel],
  105129. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105130. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105131. encoder->private_->residual_workspace_mid_side[channel],
  105132. encoder->private_->best_subframe_mid_side+channel,
  105133. encoder->private_->best_subframe_bits_mid_side+channel
  105134. )
  105135. )
  105136. return false;
  105137. }
  105138. }
  105139. /*
  105140. * Compose the frame bitbuffer
  105141. */
  105142. if(do_mid_side) {
  105143. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105144. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105145. FLAC__ChannelAssignment channel_assignment;
  105146. FLAC__ASSERT(encoder->protected_->channels == 2);
  105147. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105148. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105149. }
  105150. else {
  105151. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105152. unsigned min_bits;
  105153. int ca;
  105154. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105155. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105156. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105157. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105158. FLAC__ASSERT(do_independent && do_mid_side);
  105159. /* We have to figure out which channel assignent results in the smallest frame */
  105160. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105161. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105162. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105163. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105164. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105165. min_bits = bits[channel_assignment];
  105166. for(ca = 1; ca <= 3; ca++) {
  105167. if(bits[ca] < min_bits) {
  105168. min_bits = bits[ca];
  105169. channel_assignment = (FLAC__ChannelAssignment)ca;
  105170. }
  105171. }
  105172. }
  105173. frame_header.channel_assignment = channel_assignment;
  105174. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105175. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105176. return false;
  105177. }
  105178. switch(channel_assignment) {
  105179. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105180. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105181. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105182. break;
  105183. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105184. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105185. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105186. break;
  105187. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105188. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105189. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105190. break;
  105191. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105192. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105193. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105194. break;
  105195. default:
  105196. FLAC__ASSERT(0);
  105197. }
  105198. switch(channel_assignment) {
  105199. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105200. left_bps = encoder->private_->subframe_bps [0];
  105201. right_bps = encoder->private_->subframe_bps [1];
  105202. break;
  105203. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105204. left_bps = encoder->private_->subframe_bps [0];
  105205. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105206. break;
  105207. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105208. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105209. right_bps = encoder->private_->subframe_bps [1];
  105210. break;
  105211. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105212. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105213. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105214. break;
  105215. default:
  105216. FLAC__ASSERT(0);
  105217. }
  105218. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105219. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105220. return false;
  105221. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105222. return false;
  105223. }
  105224. else {
  105225. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105226. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105227. return false;
  105228. }
  105229. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105230. 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)) {
  105231. /* the above function sets the state for us in case of an error */
  105232. return false;
  105233. }
  105234. }
  105235. }
  105236. if(encoder->protected_->loose_mid_side_stereo) {
  105237. encoder->private_->loose_mid_side_stereo_frame_count++;
  105238. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105239. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105240. }
  105241. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105242. return true;
  105243. }
  105244. FLAC__bool process_subframe_(
  105245. FLAC__StreamEncoder *encoder,
  105246. unsigned min_partition_order,
  105247. unsigned max_partition_order,
  105248. const FLAC__FrameHeader *frame_header,
  105249. unsigned subframe_bps,
  105250. const FLAC__int32 integer_signal[],
  105251. FLAC__Subframe *subframe[2],
  105252. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105253. FLAC__int32 *residual[2],
  105254. unsigned *best_subframe,
  105255. unsigned *best_bits
  105256. )
  105257. {
  105258. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105259. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105260. #else
  105261. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105262. #endif
  105263. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105264. FLAC__double lpc_residual_bits_per_sample;
  105265. 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 */
  105266. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105267. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105268. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105269. #endif
  105270. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105271. unsigned rice_parameter;
  105272. unsigned _candidate_bits, _best_bits;
  105273. unsigned _best_subframe;
  105274. /* only use RICE2 partitions if stream bps > 16 */
  105275. 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;
  105276. FLAC__ASSERT(frame_header->blocksize > 0);
  105277. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105278. _best_subframe = 0;
  105279. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105280. _best_bits = UINT_MAX;
  105281. else
  105282. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105283. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105284. unsigned signal_is_constant = false;
  105285. 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);
  105286. /* check for constant subframe */
  105287. if(
  105288. !encoder->private_->disable_constant_subframes &&
  105289. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105290. fixed_residual_bits_per_sample[1] == 0.0
  105291. #else
  105292. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105293. #endif
  105294. ) {
  105295. /* the above means it's possible all samples are the same value; now double-check it: */
  105296. unsigned i;
  105297. signal_is_constant = true;
  105298. for(i = 1; i < frame_header->blocksize; i++) {
  105299. if(integer_signal[0] != integer_signal[i]) {
  105300. signal_is_constant = false;
  105301. break;
  105302. }
  105303. }
  105304. }
  105305. if(signal_is_constant) {
  105306. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105307. if(_candidate_bits < _best_bits) {
  105308. _best_subframe = !_best_subframe;
  105309. _best_bits = _candidate_bits;
  105310. }
  105311. }
  105312. else {
  105313. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105314. /* encode fixed */
  105315. if(encoder->protected_->do_exhaustive_model_search) {
  105316. min_fixed_order = 0;
  105317. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105318. }
  105319. else {
  105320. min_fixed_order = max_fixed_order = guess_fixed_order;
  105321. }
  105322. if(max_fixed_order >= frame_header->blocksize)
  105323. max_fixed_order = frame_header->blocksize - 1;
  105324. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105325. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105326. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105327. continue; /* don't even try */
  105328. 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 */
  105329. #else
  105330. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105331. continue; /* don't even try */
  105332. 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 */
  105333. #endif
  105334. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105335. if(rice_parameter >= rice_parameter_limit) {
  105336. #ifdef DEBUG_VERBOSE
  105337. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105338. #endif
  105339. rice_parameter = rice_parameter_limit - 1;
  105340. }
  105341. _candidate_bits =
  105342. evaluate_fixed_subframe_(
  105343. encoder,
  105344. integer_signal,
  105345. residual[!_best_subframe],
  105346. encoder->private_->abs_residual_partition_sums,
  105347. encoder->private_->raw_bits_per_partition,
  105348. frame_header->blocksize,
  105349. subframe_bps,
  105350. fixed_order,
  105351. rice_parameter,
  105352. rice_parameter_limit,
  105353. min_partition_order,
  105354. max_partition_order,
  105355. encoder->protected_->do_escape_coding,
  105356. encoder->protected_->rice_parameter_search_dist,
  105357. subframe[!_best_subframe],
  105358. partitioned_rice_contents[!_best_subframe]
  105359. );
  105360. if(_candidate_bits < _best_bits) {
  105361. _best_subframe = !_best_subframe;
  105362. _best_bits = _candidate_bits;
  105363. }
  105364. }
  105365. }
  105366. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105367. /* encode lpc */
  105368. if(encoder->protected_->max_lpc_order > 0) {
  105369. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105370. max_lpc_order = frame_header->blocksize-1;
  105371. else
  105372. max_lpc_order = encoder->protected_->max_lpc_order;
  105373. if(max_lpc_order > 0) {
  105374. unsigned a;
  105375. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105376. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105377. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105378. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105379. if(autoc[0] != 0.0) {
  105380. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105381. if(encoder->protected_->do_exhaustive_model_search) {
  105382. min_lpc_order = 1;
  105383. }
  105384. else {
  105385. const unsigned guess_lpc_order =
  105386. FLAC__lpc_compute_best_order(
  105387. lpc_error,
  105388. max_lpc_order,
  105389. frame_header->blocksize,
  105390. subframe_bps + (
  105391. encoder->protected_->do_qlp_coeff_prec_search?
  105392. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105393. encoder->protected_->qlp_coeff_precision
  105394. )
  105395. );
  105396. min_lpc_order = max_lpc_order = guess_lpc_order;
  105397. }
  105398. if(max_lpc_order >= frame_header->blocksize)
  105399. max_lpc_order = frame_header->blocksize - 1;
  105400. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105401. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105402. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105403. continue; /* don't even try */
  105404. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105405. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105406. if(rice_parameter >= rice_parameter_limit) {
  105407. #ifdef DEBUG_VERBOSE
  105408. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105409. #endif
  105410. rice_parameter = rice_parameter_limit - 1;
  105411. }
  105412. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105413. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105414. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105415. if(subframe_bps <= 17) {
  105416. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105417. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105418. }
  105419. else
  105420. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105421. }
  105422. else {
  105423. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105424. }
  105425. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105426. _candidate_bits =
  105427. evaluate_lpc_subframe_(
  105428. encoder,
  105429. integer_signal,
  105430. residual[!_best_subframe],
  105431. encoder->private_->abs_residual_partition_sums,
  105432. encoder->private_->raw_bits_per_partition,
  105433. encoder->private_->lp_coeff[lpc_order-1],
  105434. frame_header->blocksize,
  105435. subframe_bps,
  105436. lpc_order,
  105437. qlp_coeff_precision,
  105438. rice_parameter,
  105439. rice_parameter_limit,
  105440. min_partition_order,
  105441. max_partition_order,
  105442. encoder->protected_->do_escape_coding,
  105443. encoder->protected_->rice_parameter_search_dist,
  105444. subframe[!_best_subframe],
  105445. partitioned_rice_contents[!_best_subframe]
  105446. );
  105447. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105448. if(_candidate_bits < _best_bits) {
  105449. _best_subframe = !_best_subframe;
  105450. _best_bits = _candidate_bits;
  105451. }
  105452. }
  105453. }
  105454. }
  105455. }
  105456. }
  105457. }
  105458. }
  105459. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105460. }
  105461. }
  105462. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105463. if(_best_bits == UINT_MAX) {
  105464. FLAC__ASSERT(_best_subframe == 0);
  105465. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105466. }
  105467. *best_subframe = _best_subframe;
  105468. *best_bits = _best_bits;
  105469. return true;
  105470. }
  105471. FLAC__bool add_subframe_(
  105472. FLAC__StreamEncoder *encoder,
  105473. unsigned blocksize,
  105474. unsigned subframe_bps,
  105475. const FLAC__Subframe *subframe,
  105476. FLAC__BitWriter *frame
  105477. )
  105478. {
  105479. switch(subframe->type) {
  105480. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105481. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105482. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105483. return false;
  105484. }
  105485. break;
  105486. case FLAC__SUBFRAME_TYPE_FIXED:
  105487. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105488. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105489. return false;
  105490. }
  105491. break;
  105492. case FLAC__SUBFRAME_TYPE_LPC:
  105493. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105494. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105495. return false;
  105496. }
  105497. break;
  105498. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105499. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105500. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105501. return false;
  105502. }
  105503. break;
  105504. default:
  105505. FLAC__ASSERT(0);
  105506. }
  105507. return true;
  105508. }
  105509. #define SPOTCHECK_ESTIMATE 0
  105510. #if SPOTCHECK_ESTIMATE
  105511. static void spotcheck_subframe_estimate_(
  105512. FLAC__StreamEncoder *encoder,
  105513. unsigned blocksize,
  105514. unsigned subframe_bps,
  105515. const FLAC__Subframe *subframe,
  105516. unsigned estimate
  105517. )
  105518. {
  105519. FLAC__bool ret;
  105520. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105521. if(frame == 0) {
  105522. fprintf(stderr, "EST: can't allocate frame\n");
  105523. return;
  105524. }
  105525. if(!FLAC__bitwriter_init(frame)) {
  105526. fprintf(stderr, "EST: can't init frame\n");
  105527. return;
  105528. }
  105529. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105530. FLAC__ASSERT(ret);
  105531. {
  105532. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105533. if(estimate != actual)
  105534. 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);
  105535. }
  105536. FLAC__bitwriter_delete(frame);
  105537. }
  105538. #endif
  105539. unsigned evaluate_constant_subframe_(
  105540. FLAC__StreamEncoder *encoder,
  105541. const FLAC__int32 signal,
  105542. unsigned blocksize,
  105543. unsigned subframe_bps,
  105544. FLAC__Subframe *subframe
  105545. )
  105546. {
  105547. unsigned estimate;
  105548. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105549. subframe->data.constant.value = signal;
  105550. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105551. #if SPOTCHECK_ESTIMATE
  105552. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105553. #else
  105554. (void)encoder, (void)blocksize;
  105555. #endif
  105556. return estimate;
  105557. }
  105558. unsigned evaluate_fixed_subframe_(
  105559. FLAC__StreamEncoder *encoder,
  105560. const FLAC__int32 signal[],
  105561. FLAC__int32 residual[],
  105562. FLAC__uint64 abs_residual_partition_sums[],
  105563. unsigned raw_bits_per_partition[],
  105564. unsigned blocksize,
  105565. unsigned subframe_bps,
  105566. unsigned order,
  105567. unsigned rice_parameter,
  105568. unsigned rice_parameter_limit,
  105569. unsigned min_partition_order,
  105570. unsigned max_partition_order,
  105571. FLAC__bool do_escape_coding,
  105572. unsigned rice_parameter_search_dist,
  105573. FLAC__Subframe *subframe,
  105574. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105575. )
  105576. {
  105577. unsigned i, residual_bits, estimate;
  105578. const unsigned residual_samples = blocksize - order;
  105579. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105580. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105581. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105582. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105583. subframe->data.fixed.residual = residual;
  105584. residual_bits =
  105585. find_best_partition_order_(
  105586. encoder->private_,
  105587. residual,
  105588. abs_residual_partition_sums,
  105589. raw_bits_per_partition,
  105590. residual_samples,
  105591. order,
  105592. rice_parameter,
  105593. rice_parameter_limit,
  105594. min_partition_order,
  105595. max_partition_order,
  105596. subframe_bps,
  105597. do_escape_coding,
  105598. rice_parameter_search_dist,
  105599. &subframe->data.fixed.entropy_coding_method
  105600. );
  105601. subframe->data.fixed.order = order;
  105602. for(i = 0; i < order; i++)
  105603. subframe->data.fixed.warmup[i] = signal[i];
  105604. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105605. #if SPOTCHECK_ESTIMATE
  105606. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105607. #endif
  105608. return estimate;
  105609. }
  105610. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105611. unsigned evaluate_lpc_subframe_(
  105612. FLAC__StreamEncoder *encoder,
  105613. const FLAC__int32 signal[],
  105614. FLAC__int32 residual[],
  105615. FLAC__uint64 abs_residual_partition_sums[],
  105616. unsigned raw_bits_per_partition[],
  105617. const FLAC__real lp_coeff[],
  105618. unsigned blocksize,
  105619. unsigned subframe_bps,
  105620. unsigned order,
  105621. unsigned qlp_coeff_precision,
  105622. unsigned rice_parameter,
  105623. unsigned rice_parameter_limit,
  105624. unsigned min_partition_order,
  105625. unsigned max_partition_order,
  105626. FLAC__bool do_escape_coding,
  105627. unsigned rice_parameter_search_dist,
  105628. FLAC__Subframe *subframe,
  105629. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105630. )
  105631. {
  105632. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105633. unsigned i, residual_bits, estimate;
  105634. int quantization, ret;
  105635. const unsigned residual_samples = blocksize - order;
  105636. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105637. if(subframe_bps <= 16) {
  105638. FLAC__ASSERT(order > 0);
  105639. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105640. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105641. }
  105642. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105643. if(ret != 0)
  105644. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105645. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105646. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105647. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105648. else
  105649. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105650. else
  105651. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105652. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105653. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105654. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105655. subframe->data.lpc.residual = residual;
  105656. residual_bits =
  105657. find_best_partition_order_(
  105658. encoder->private_,
  105659. residual,
  105660. abs_residual_partition_sums,
  105661. raw_bits_per_partition,
  105662. residual_samples,
  105663. order,
  105664. rice_parameter,
  105665. rice_parameter_limit,
  105666. min_partition_order,
  105667. max_partition_order,
  105668. subframe_bps,
  105669. do_escape_coding,
  105670. rice_parameter_search_dist,
  105671. &subframe->data.lpc.entropy_coding_method
  105672. );
  105673. subframe->data.lpc.order = order;
  105674. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105675. subframe->data.lpc.quantization_level = quantization;
  105676. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105677. for(i = 0; i < order; i++)
  105678. subframe->data.lpc.warmup[i] = signal[i];
  105679. 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;
  105680. #if SPOTCHECK_ESTIMATE
  105681. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105682. #endif
  105683. return estimate;
  105684. }
  105685. #endif
  105686. unsigned evaluate_verbatim_subframe_(
  105687. FLAC__StreamEncoder *encoder,
  105688. const FLAC__int32 signal[],
  105689. unsigned blocksize,
  105690. unsigned subframe_bps,
  105691. FLAC__Subframe *subframe
  105692. )
  105693. {
  105694. unsigned estimate;
  105695. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105696. subframe->data.verbatim.data = signal;
  105697. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105698. #if SPOTCHECK_ESTIMATE
  105699. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105700. #else
  105701. (void)encoder;
  105702. #endif
  105703. return estimate;
  105704. }
  105705. unsigned find_best_partition_order_(
  105706. FLAC__StreamEncoderPrivate *private_,
  105707. const FLAC__int32 residual[],
  105708. FLAC__uint64 abs_residual_partition_sums[],
  105709. unsigned raw_bits_per_partition[],
  105710. unsigned residual_samples,
  105711. unsigned predictor_order,
  105712. unsigned rice_parameter,
  105713. unsigned rice_parameter_limit,
  105714. unsigned min_partition_order,
  105715. unsigned max_partition_order,
  105716. unsigned bps,
  105717. FLAC__bool do_escape_coding,
  105718. unsigned rice_parameter_search_dist,
  105719. FLAC__EntropyCodingMethod *best_ecm
  105720. )
  105721. {
  105722. unsigned residual_bits, best_residual_bits = 0;
  105723. unsigned best_parameters_index = 0;
  105724. unsigned best_partition_order = 0;
  105725. const unsigned blocksize = residual_samples + predictor_order;
  105726. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105727. min_partition_order = min(min_partition_order, max_partition_order);
  105728. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105729. if(do_escape_coding)
  105730. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105731. {
  105732. int partition_order;
  105733. unsigned sum;
  105734. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105735. if(!
  105736. set_partitioned_rice_(
  105737. #ifdef EXACT_RICE_BITS_CALCULATION
  105738. residual,
  105739. #endif
  105740. abs_residual_partition_sums+sum,
  105741. raw_bits_per_partition+sum,
  105742. residual_samples,
  105743. predictor_order,
  105744. rice_parameter,
  105745. rice_parameter_limit,
  105746. rice_parameter_search_dist,
  105747. (unsigned)partition_order,
  105748. do_escape_coding,
  105749. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105750. &residual_bits
  105751. )
  105752. )
  105753. {
  105754. FLAC__ASSERT(best_residual_bits != 0);
  105755. break;
  105756. }
  105757. sum += 1u << partition_order;
  105758. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105759. best_residual_bits = residual_bits;
  105760. best_parameters_index = !best_parameters_index;
  105761. best_partition_order = partition_order;
  105762. }
  105763. }
  105764. }
  105765. best_ecm->data.partitioned_rice.order = best_partition_order;
  105766. {
  105767. /*
  105768. * We are allowed to de-const the pointer based on our special
  105769. * knowledge; it is const to the outside world.
  105770. */
  105771. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105772. unsigned partition;
  105773. /* save best parameters and raw_bits */
  105774. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105775. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105776. if(do_escape_coding)
  105777. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105778. /*
  105779. * Now need to check if the type should be changed to
  105780. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105781. * size of the rice parameters.
  105782. */
  105783. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105784. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105785. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105786. break;
  105787. }
  105788. }
  105789. }
  105790. return best_residual_bits;
  105791. }
  105792. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105793. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105794. const FLAC__int32 residual[],
  105795. FLAC__uint64 abs_residual_partition_sums[],
  105796. unsigned blocksize,
  105797. unsigned predictor_order,
  105798. unsigned min_partition_order,
  105799. unsigned max_partition_order
  105800. );
  105801. #endif
  105802. void precompute_partition_info_sums_(
  105803. const FLAC__int32 residual[],
  105804. FLAC__uint64 abs_residual_partition_sums[],
  105805. unsigned residual_samples,
  105806. unsigned predictor_order,
  105807. unsigned min_partition_order,
  105808. unsigned max_partition_order,
  105809. unsigned bps
  105810. )
  105811. {
  105812. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105813. unsigned partitions = 1u << max_partition_order;
  105814. FLAC__ASSERT(default_partition_samples > predictor_order);
  105815. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105816. /* slightly pessimistic but still catches all common cases */
  105817. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105818. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105819. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105820. return;
  105821. }
  105822. #endif
  105823. /* first do max_partition_order */
  105824. {
  105825. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105826. /* slightly pessimistic but still catches all common cases */
  105827. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105828. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105829. FLAC__uint32 abs_residual_partition_sum;
  105830. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105831. end += default_partition_samples;
  105832. abs_residual_partition_sum = 0;
  105833. for( ; residual_sample < end; residual_sample++)
  105834. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105835. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105836. }
  105837. }
  105838. else { /* have to pessimistically use 64 bits for accumulator */
  105839. FLAC__uint64 abs_residual_partition_sum;
  105840. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105841. end += default_partition_samples;
  105842. abs_residual_partition_sum = 0;
  105843. for( ; residual_sample < end; residual_sample++)
  105844. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105845. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105846. }
  105847. }
  105848. }
  105849. /* now merge partitions for lower orders */
  105850. {
  105851. unsigned from_partition = 0, to_partition = partitions;
  105852. int partition_order;
  105853. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105854. unsigned i;
  105855. partitions >>= 1;
  105856. for(i = 0; i < partitions; i++) {
  105857. abs_residual_partition_sums[to_partition++] =
  105858. abs_residual_partition_sums[from_partition ] +
  105859. abs_residual_partition_sums[from_partition+1];
  105860. from_partition += 2;
  105861. }
  105862. }
  105863. }
  105864. }
  105865. void precompute_partition_info_escapes_(
  105866. const FLAC__int32 residual[],
  105867. unsigned raw_bits_per_partition[],
  105868. unsigned residual_samples,
  105869. unsigned predictor_order,
  105870. unsigned min_partition_order,
  105871. unsigned max_partition_order
  105872. )
  105873. {
  105874. int partition_order;
  105875. unsigned from_partition, to_partition = 0;
  105876. const unsigned blocksize = residual_samples + predictor_order;
  105877. /* first do max_partition_order */
  105878. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105879. FLAC__int32 r;
  105880. FLAC__uint32 rmax;
  105881. unsigned partition, partition_sample, partition_samples, residual_sample;
  105882. const unsigned partitions = 1u << partition_order;
  105883. const unsigned default_partition_samples = blocksize >> partition_order;
  105884. FLAC__ASSERT(default_partition_samples > predictor_order);
  105885. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105886. partition_samples = default_partition_samples;
  105887. if(partition == 0)
  105888. partition_samples -= predictor_order;
  105889. rmax = 0;
  105890. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105891. r = residual[residual_sample++];
  105892. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105893. if(r < 0)
  105894. rmax |= ~r;
  105895. else
  105896. rmax |= r;
  105897. }
  105898. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105899. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105900. }
  105901. to_partition = partitions;
  105902. break; /*@@@ yuck, should remove the 'for' loop instead */
  105903. }
  105904. /* now merge partitions for lower orders */
  105905. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105906. unsigned m;
  105907. unsigned i;
  105908. const unsigned partitions = 1u << partition_order;
  105909. for(i = 0; i < partitions; i++) {
  105910. m = raw_bits_per_partition[from_partition];
  105911. from_partition++;
  105912. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105913. from_partition++;
  105914. to_partition++;
  105915. }
  105916. }
  105917. }
  105918. #ifdef EXACT_RICE_BITS_CALCULATION
  105919. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105920. const unsigned rice_parameter,
  105921. const unsigned partition_samples,
  105922. const FLAC__int32 *residual
  105923. )
  105924. {
  105925. unsigned i, partition_bits =
  105926. 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 */
  105927. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105928. ;
  105929. for(i = 0; i < partition_samples; i++)
  105930. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105931. return partition_bits;
  105932. }
  105933. #else
  105934. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105935. const unsigned rice_parameter,
  105936. const unsigned partition_samples,
  105937. const FLAC__uint64 abs_residual_partition_sum
  105938. )
  105939. {
  105940. return
  105941. 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 */
  105942. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105943. (
  105944. rice_parameter?
  105945. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105946. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105947. )
  105948. - (partition_samples >> 1)
  105949. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105950. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105951. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105952. * So the subtraction term tries to guess how many extra bits were contributed.
  105953. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105954. */
  105955. ;
  105956. }
  105957. #endif
  105958. FLAC__bool set_partitioned_rice_(
  105959. #ifdef EXACT_RICE_BITS_CALCULATION
  105960. const FLAC__int32 residual[],
  105961. #endif
  105962. const FLAC__uint64 abs_residual_partition_sums[],
  105963. const unsigned raw_bits_per_partition[],
  105964. const unsigned residual_samples,
  105965. const unsigned predictor_order,
  105966. const unsigned suggested_rice_parameter,
  105967. const unsigned rice_parameter_limit,
  105968. const unsigned rice_parameter_search_dist,
  105969. const unsigned partition_order,
  105970. const FLAC__bool search_for_escapes,
  105971. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105972. unsigned *bits
  105973. )
  105974. {
  105975. unsigned rice_parameter, partition_bits;
  105976. unsigned best_partition_bits, best_rice_parameter = 0;
  105977. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105978. unsigned *parameters, *raw_bits;
  105979. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105980. unsigned min_rice_parameter, max_rice_parameter;
  105981. #else
  105982. (void)rice_parameter_search_dist;
  105983. #endif
  105984. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105985. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105986. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105987. parameters = partitioned_rice_contents->parameters;
  105988. raw_bits = partitioned_rice_contents->raw_bits;
  105989. if(partition_order == 0) {
  105990. best_partition_bits = (unsigned)(-1);
  105991. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105992. if(rice_parameter_search_dist) {
  105993. if(suggested_rice_parameter < rice_parameter_search_dist)
  105994. min_rice_parameter = 0;
  105995. else
  105996. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105997. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105998. if(max_rice_parameter >= rice_parameter_limit) {
  105999. #ifdef DEBUG_VERBOSE
  106000. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  106001. #endif
  106002. max_rice_parameter = rice_parameter_limit - 1;
  106003. }
  106004. }
  106005. else
  106006. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  106007. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106008. #else
  106009. rice_parameter = suggested_rice_parameter;
  106010. #endif
  106011. #ifdef EXACT_RICE_BITS_CALCULATION
  106012. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  106013. #else
  106014. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  106015. #endif
  106016. if(partition_bits < best_partition_bits) {
  106017. best_rice_parameter = rice_parameter;
  106018. best_partition_bits = partition_bits;
  106019. }
  106020. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106021. }
  106022. #endif
  106023. if(search_for_escapes) {
  106024. 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;
  106025. if(partition_bits <= best_partition_bits) {
  106026. raw_bits[0] = raw_bits_per_partition[0];
  106027. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106028. best_partition_bits = partition_bits;
  106029. }
  106030. else
  106031. raw_bits[0] = 0;
  106032. }
  106033. parameters[0] = best_rice_parameter;
  106034. bits_ += best_partition_bits;
  106035. }
  106036. else {
  106037. unsigned partition, residual_sample;
  106038. unsigned partition_samples;
  106039. FLAC__uint64 mean, k;
  106040. const unsigned partitions = 1u << partition_order;
  106041. for(partition = residual_sample = 0; partition < partitions; partition++) {
  106042. partition_samples = (residual_samples+predictor_order) >> partition_order;
  106043. if(partition == 0) {
  106044. if(partition_samples <= predictor_order)
  106045. return false;
  106046. else
  106047. partition_samples -= predictor_order;
  106048. }
  106049. mean = abs_residual_partition_sums[partition];
  106050. /* we are basically calculating the size in bits of the
  106051. * average residual magnitude in the partition:
  106052. * rice_parameter = floor(log2(mean/partition_samples))
  106053. * 'mean' is not a good name for the variable, it is
  106054. * actually the sum of magnitudes of all residual values
  106055. * in the partition, so the actual mean is
  106056. * mean/partition_samples
  106057. */
  106058. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106059. ;
  106060. if(rice_parameter >= rice_parameter_limit) {
  106061. #ifdef DEBUG_VERBOSE
  106062. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106063. #endif
  106064. rice_parameter = rice_parameter_limit - 1;
  106065. }
  106066. best_partition_bits = (unsigned)(-1);
  106067. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106068. if(rice_parameter_search_dist) {
  106069. if(rice_parameter < rice_parameter_search_dist)
  106070. min_rice_parameter = 0;
  106071. else
  106072. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106073. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106074. if(max_rice_parameter >= rice_parameter_limit) {
  106075. #ifdef DEBUG_VERBOSE
  106076. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106077. #endif
  106078. max_rice_parameter = rice_parameter_limit - 1;
  106079. }
  106080. }
  106081. else
  106082. min_rice_parameter = max_rice_parameter = rice_parameter;
  106083. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106084. #endif
  106085. #ifdef EXACT_RICE_BITS_CALCULATION
  106086. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106087. #else
  106088. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106089. #endif
  106090. if(partition_bits < best_partition_bits) {
  106091. best_rice_parameter = rice_parameter;
  106092. best_partition_bits = partition_bits;
  106093. }
  106094. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106095. }
  106096. #endif
  106097. if(search_for_escapes) {
  106098. 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;
  106099. if(partition_bits <= best_partition_bits) {
  106100. raw_bits[partition] = raw_bits_per_partition[partition];
  106101. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106102. best_partition_bits = partition_bits;
  106103. }
  106104. else
  106105. raw_bits[partition] = 0;
  106106. }
  106107. parameters[partition] = best_rice_parameter;
  106108. bits_ += best_partition_bits;
  106109. residual_sample += partition_samples;
  106110. }
  106111. }
  106112. *bits = bits_;
  106113. return true;
  106114. }
  106115. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106116. {
  106117. unsigned i, shift;
  106118. FLAC__int32 x = 0;
  106119. for(i = 0; i < samples && !(x&1); i++)
  106120. x |= signal[i];
  106121. if(x == 0) {
  106122. shift = 0;
  106123. }
  106124. else {
  106125. for(shift = 0; !(x&1); shift++)
  106126. x >>= 1;
  106127. }
  106128. if(shift > 0) {
  106129. for(i = 0; i < samples; i++)
  106130. signal[i] >>= shift;
  106131. }
  106132. return shift;
  106133. }
  106134. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106135. {
  106136. unsigned channel;
  106137. for(channel = 0; channel < channels; channel++)
  106138. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106139. fifo->tail += wide_samples;
  106140. FLAC__ASSERT(fifo->tail <= fifo->size);
  106141. }
  106142. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106143. {
  106144. unsigned channel;
  106145. unsigned sample, wide_sample;
  106146. unsigned tail = fifo->tail;
  106147. sample = input_offset * channels;
  106148. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106149. for(channel = 0; channel < channels; channel++)
  106150. fifo->data[channel][tail] = input[sample++];
  106151. tail++;
  106152. }
  106153. fifo->tail = tail;
  106154. FLAC__ASSERT(fifo->tail <= fifo->size);
  106155. }
  106156. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106157. {
  106158. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106159. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106160. (void)decoder;
  106161. if(encoder->private_->verify.needs_magic_hack) {
  106162. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106163. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106164. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106165. encoder->private_->verify.needs_magic_hack = false;
  106166. }
  106167. else {
  106168. if(encoded_bytes == 0) {
  106169. /*
  106170. * If we get here, a FIFO underflow has occurred,
  106171. * which means there is a bug somewhere.
  106172. */
  106173. FLAC__ASSERT(0);
  106174. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106175. }
  106176. else if(encoded_bytes < *bytes)
  106177. *bytes = encoded_bytes;
  106178. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106179. encoder->private_->verify.output.data += *bytes;
  106180. encoder->private_->verify.output.bytes -= *bytes;
  106181. }
  106182. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106183. }
  106184. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106185. {
  106186. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106187. unsigned channel;
  106188. const unsigned channels = frame->header.channels;
  106189. const unsigned blocksize = frame->header.blocksize;
  106190. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106191. (void)decoder;
  106192. for(channel = 0; channel < channels; channel++) {
  106193. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106194. unsigned i, sample = 0;
  106195. FLAC__int32 expect = 0, got = 0;
  106196. for(i = 0; i < blocksize; i++) {
  106197. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106198. sample = i;
  106199. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106200. got = (FLAC__int32)buffer[channel][i];
  106201. break;
  106202. }
  106203. }
  106204. FLAC__ASSERT(i < blocksize);
  106205. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106206. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106207. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106208. encoder->private_->verify.error_stats.channel = channel;
  106209. encoder->private_->verify.error_stats.sample = sample;
  106210. encoder->private_->verify.error_stats.expected = expect;
  106211. encoder->private_->verify.error_stats.got = got;
  106212. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106213. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106214. }
  106215. }
  106216. /* dequeue the frame from the fifo */
  106217. encoder->private_->verify.input_fifo.tail -= blocksize;
  106218. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106219. for(channel = 0; channel < channels; channel++)
  106220. 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]));
  106221. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106222. }
  106223. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106224. {
  106225. (void)decoder, (void)metadata, (void)client_data;
  106226. }
  106227. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106228. {
  106229. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106230. (void)decoder, (void)status;
  106231. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106232. }
  106233. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106234. {
  106235. (void)client_data;
  106236. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106237. if (*bytes == 0) {
  106238. if (feof(encoder->private_->file))
  106239. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106240. else if (ferror(encoder->private_->file))
  106241. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106242. }
  106243. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106244. }
  106245. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106246. {
  106247. (void)client_data;
  106248. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106249. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106250. else
  106251. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106252. }
  106253. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106254. {
  106255. off_t offset;
  106256. (void)client_data;
  106257. offset = ftello(encoder->private_->file);
  106258. if(offset < 0) {
  106259. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106260. }
  106261. else {
  106262. *absolute_byte_offset = (FLAC__uint64)offset;
  106263. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106264. }
  106265. }
  106266. #ifdef FLAC__VALGRIND_TESTING
  106267. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106268. {
  106269. size_t ret = fwrite(ptr, size, nmemb, stream);
  106270. if(!ferror(stream))
  106271. fflush(stream);
  106272. return ret;
  106273. }
  106274. #else
  106275. #define local__fwrite fwrite
  106276. #endif
  106277. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106278. {
  106279. (void)client_data, (void)current_frame;
  106280. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106281. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106282. #if FLAC__HAS_OGG
  106283. /* We would like to be able to use 'samples > 0' in the
  106284. * clause here but currently because of the nature of our
  106285. * Ogg writing implementation, 'samples' is always 0 (see
  106286. * ogg_encoder_aspect.c). The downside is extra progress
  106287. * callbacks.
  106288. */
  106289. encoder->private_->is_ogg? true :
  106290. #endif
  106291. samples > 0
  106292. );
  106293. if(call_it) {
  106294. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106295. * because at this point in the callback chain, the stats
  106296. * have not been updated. Only after we return and control
  106297. * gets back to write_frame_() are the stats updated
  106298. */
  106299. 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);
  106300. }
  106301. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106302. }
  106303. else
  106304. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106305. }
  106306. /*
  106307. * This will forcibly set stdout to binary mode (for OSes that require it)
  106308. */
  106309. FILE *get_binary_stdout_(void)
  106310. {
  106311. /* if something breaks here it is probably due to the presence or
  106312. * absence of an underscore before the identifiers 'setmode',
  106313. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106314. */
  106315. #if defined _MSC_VER || defined __MINGW32__
  106316. _setmode(_fileno(stdout), _O_BINARY);
  106317. #elif defined __CYGWIN__
  106318. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106319. setmode(_fileno(stdout), _O_BINARY);
  106320. #elif defined __EMX__
  106321. setmode(fileno(stdout), O_BINARY);
  106322. #endif
  106323. return stdout;
  106324. }
  106325. #endif
  106326. /*** End of inlined file: stream_encoder.c ***/
  106327. /*** Start of inlined file: stream_encoder_framing.c ***/
  106328. /*** Start of inlined file: juce_FlacHeader.h ***/
  106329. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106330. // tasks..
  106331. #define VERSION "1.2.1"
  106332. #define FLAC__NO_DLL 1
  106333. #if JUCE_MSVC
  106334. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106335. #endif
  106336. #if JUCE_MAC
  106337. #define FLAC__SYS_DARWIN 1
  106338. #endif
  106339. /*** End of inlined file: juce_FlacHeader.h ***/
  106340. #if JUCE_USE_FLAC
  106341. #if HAVE_CONFIG_H
  106342. # include <config.h>
  106343. #endif
  106344. #include <stdio.h>
  106345. #include <string.h> /* for strlen() */
  106346. #ifdef max
  106347. #undef max
  106348. #endif
  106349. #define max(x,y) ((x)>(y)?(x):(y))
  106350. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106351. 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);
  106352. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106353. {
  106354. unsigned i, j;
  106355. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106356. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106357. return false;
  106358. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106359. return false;
  106360. /*
  106361. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106362. */
  106363. i = metadata->length;
  106364. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106365. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106366. i -= metadata->data.vorbis_comment.vendor_string.length;
  106367. i += vendor_string_length;
  106368. }
  106369. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106370. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106371. return false;
  106372. switch(metadata->type) {
  106373. case FLAC__METADATA_TYPE_STREAMINFO:
  106374. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106375. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106376. return false;
  106377. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106378. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106379. return false;
  106380. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106381. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106382. return false;
  106383. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106384. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106385. return false;
  106386. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106387. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106388. return false;
  106389. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106390. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106391. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106392. return false;
  106393. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106394. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106395. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106396. return false;
  106397. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106398. return false;
  106399. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106400. return false;
  106401. break;
  106402. case FLAC__METADATA_TYPE_PADDING:
  106403. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106404. return false;
  106405. break;
  106406. case FLAC__METADATA_TYPE_APPLICATION:
  106407. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106408. return false;
  106409. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106410. return false;
  106411. break;
  106412. case FLAC__METADATA_TYPE_SEEKTABLE:
  106413. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106414. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106415. return false;
  106416. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106417. return false;
  106418. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106419. return false;
  106420. }
  106421. break;
  106422. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106423. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106424. return false;
  106425. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106426. return false;
  106427. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106428. return false;
  106429. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106430. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106431. return false;
  106432. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106433. return false;
  106434. }
  106435. break;
  106436. case FLAC__METADATA_TYPE_CUESHEET:
  106437. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106438. 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))
  106439. return false;
  106440. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106441. return false;
  106442. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106443. return false;
  106444. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106445. return false;
  106446. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106447. return false;
  106448. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106449. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106450. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106451. return false;
  106452. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106453. return false;
  106454. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106455. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106456. return false;
  106457. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106458. return false;
  106459. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106460. return false;
  106461. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106462. return false;
  106463. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106464. return false;
  106465. for(j = 0; j < track->num_indices; j++) {
  106466. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106467. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106468. return false;
  106469. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106470. return false;
  106471. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106472. return false;
  106473. }
  106474. }
  106475. break;
  106476. case FLAC__METADATA_TYPE_PICTURE:
  106477. {
  106478. size_t len;
  106479. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106480. return false;
  106481. len = strlen(metadata->data.picture.mime_type);
  106482. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106483. return false;
  106484. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106485. return false;
  106486. len = strlen((const char *)metadata->data.picture.description);
  106487. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106488. return false;
  106489. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106490. return false;
  106491. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106492. return false;
  106493. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106494. return false;
  106495. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106496. return false;
  106497. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106498. return false;
  106499. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106500. return false;
  106501. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106502. return false;
  106503. }
  106504. break;
  106505. default:
  106506. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106507. return false;
  106508. break;
  106509. }
  106510. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106511. return true;
  106512. }
  106513. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106514. {
  106515. unsigned u, blocksize_hint, sample_rate_hint;
  106516. FLAC__byte crc;
  106517. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106518. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106519. return false;
  106520. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106521. return false;
  106522. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106523. return false;
  106524. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106525. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106526. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106527. blocksize_hint = 0;
  106528. switch(header->blocksize) {
  106529. case 192: u = 1; break;
  106530. case 576: u = 2; break;
  106531. case 1152: u = 3; break;
  106532. case 2304: u = 4; break;
  106533. case 4608: u = 5; break;
  106534. case 256: u = 8; break;
  106535. case 512: u = 9; break;
  106536. case 1024: u = 10; break;
  106537. case 2048: u = 11; break;
  106538. case 4096: u = 12; break;
  106539. case 8192: u = 13; break;
  106540. case 16384: u = 14; break;
  106541. case 32768: u = 15; break;
  106542. default:
  106543. if(header->blocksize <= 0x100)
  106544. blocksize_hint = u = 6;
  106545. else
  106546. blocksize_hint = u = 7;
  106547. break;
  106548. }
  106549. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106550. return false;
  106551. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106552. sample_rate_hint = 0;
  106553. switch(header->sample_rate) {
  106554. case 88200: u = 1; break;
  106555. case 176400: u = 2; break;
  106556. case 192000: u = 3; break;
  106557. case 8000: u = 4; break;
  106558. case 16000: u = 5; break;
  106559. case 22050: u = 6; break;
  106560. case 24000: u = 7; break;
  106561. case 32000: u = 8; break;
  106562. case 44100: u = 9; break;
  106563. case 48000: u = 10; break;
  106564. case 96000: u = 11; break;
  106565. default:
  106566. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106567. sample_rate_hint = u = 12;
  106568. else if(header->sample_rate % 10 == 0)
  106569. sample_rate_hint = u = 14;
  106570. else if(header->sample_rate <= 0xffff)
  106571. sample_rate_hint = u = 13;
  106572. else
  106573. u = 0;
  106574. break;
  106575. }
  106576. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106577. return false;
  106578. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106579. switch(header->channel_assignment) {
  106580. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106581. u = header->channels - 1;
  106582. break;
  106583. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106584. FLAC__ASSERT(header->channels == 2);
  106585. u = 8;
  106586. break;
  106587. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106588. FLAC__ASSERT(header->channels == 2);
  106589. u = 9;
  106590. break;
  106591. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106592. FLAC__ASSERT(header->channels == 2);
  106593. u = 10;
  106594. break;
  106595. default:
  106596. FLAC__ASSERT(0);
  106597. }
  106598. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106599. return false;
  106600. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106601. switch(header->bits_per_sample) {
  106602. case 8 : u = 1; break;
  106603. case 12: u = 2; break;
  106604. case 16: u = 4; break;
  106605. case 20: u = 5; break;
  106606. case 24: u = 6; break;
  106607. default: u = 0; break;
  106608. }
  106609. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106610. return false;
  106611. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106612. return false;
  106613. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106614. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106615. return false;
  106616. }
  106617. else {
  106618. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106619. return false;
  106620. }
  106621. if(blocksize_hint)
  106622. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106623. return false;
  106624. switch(sample_rate_hint) {
  106625. case 12:
  106626. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106627. return false;
  106628. break;
  106629. case 13:
  106630. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106631. return false;
  106632. break;
  106633. case 14:
  106634. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106635. return false;
  106636. break;
  106637. }
  106638. /* write the CRC */
  106639. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106640. return false;
  106641. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106642. return false;
  106643. return true;
  106644. }
  106645. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106646. {
  106647. FLAC__bool ok;
  106648. ok =
  106649. 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) &&
  106650. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106651. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106652. ;
  106653. return ok;
  106654. }
  106655. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106656. {
  106657. unsigned i;
  106658. 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))
  106659. return false;
  106660. if(wasted_bits)
  106661. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106662. return false;
  106663. for(i = 0; i < subframe->order; i++)
  106664. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106665. return false;
  106666. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106667. return false;
  106668. switch(subframe->entropy_coding_method.type) {
  106669. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106670. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106671. if(!add_residual_partitioned_rice_(
  106672. bw,
  106673. subframe->residual,
  106674. residual_samples,
  106675. subframe->order,
  106676. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106677. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106678. subframe->entropy_coding_method.data.partitioned_rice.order,
  106679. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106680. ))
  106681. return false;
  106682. break;
  106683. default:
  106684. FLAC__ASSERT(0);
  106685. }
  106686. return true;
  106687. }
  106688. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106689. {
  106690. unsigned i;
  106691. 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))
  106692. return false;
  106693. if(wasted_bits)
  106694. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106695. return false;
  106696. for(i = 0; i < subframe->order; i++)
  106697. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106698. return false;
  106699. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106700. return false;
  106701. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106702. return false;
  106703. for(i = 0; i < subframe->order; i++)
  106704. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106705. return false;
  106706. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106707. return false;
  106708. switch(subframe->entropy_coding_method.type) {
  106709. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106710. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106711. if(!add_residual_partitioned_rice_(
  106712. bw,
  106713. subframe->residual,
  106714. residual_samples,
  106715. subframe->order,
  106716. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106717. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106718. subframe->entropy_coding_method.data.partitioned_rice.order,
  106719. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106720. ))
  106721. return false;
  106722. break;
  106723. default:
  106724. FLAC__ASSERT(0);
  106725. }
  106726. return true;
  106727. }
  106728. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106729. {
  106730. unsigned i;
  106731. const FLAC__int32 *signal = subframe->data;
  106732. 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))
  106733. return false;
  106734. if(wasted_bits)
  106735. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106736. return false;
  106737. for(i = 0; i < samples; i++)
  106738. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106739. return false;
  106740. return true;
  106741. }
  106742. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106743. {
  106744. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106745. return false;
  106746. switch(method->type) {
  106747. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106748. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106749. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106750. return false;
  106751. break;
  106752. default:
  106753. FLAC__ASSERT(0);
  106754. }
  106755. return true;
  106756. }
  106757. 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)
  106758. {
  106759. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106760. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106761. if(partition_order == 0) {
  106762. unsigned i;
  106763. if(raw_bits[0] == 0) {
  106764. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106765. return false;
  106766. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106767. return false;
  106768. }
  106769. else {
  106770. FLAC__ASSERT(rice_parameters[0] == 0);
  106771. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106772. return false;
  106773. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106774. return false;
  106775. for(i = 0; i < residual_samples; i++) {
  106776. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106777. return false;
  106778. }
  106779. }
  106780. return true;
  106781. }
  106782. else {
  106783. unsigned i, j, k = 0, k_last = 0;
  106784. unsigned partition_samples;
  106785. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106786. for(i = 0; i < (1u<<partition_order); i++) {
  106787. partition_samples = default_partition_samples;
  106788. if(i == 0)
  106789. partition_samples -= predictor_order;
  106790. k += partition_samples;
  106791. if(raw_bits[i] == 0) {
  106792. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106793. return false;
  106794. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106795. return false;
  106796. }
  106797. else {
  106798. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106799. return false;
  106800. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106801. return false;
  106802. for(j = k_last; j < k; j++) {
  106803. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106804. return false;
  106805. }
  106806. }
  106807. k_last = k;
  106808. }
  106809. return true;
  106810. }
  106811. }
  106812. #endif
  106813. /*** End of inlined file: stream_encoder_framing.c ***/
  106814. /*** Start of inlined file: window_flac.c ***/
  106815. /*** Start of inlined file: juce_FlacHeader.h ***/
  106816. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106817. // tasks..
  106818. #define VERSION "1.2.1"
  106819. #define FLAC__NO_DLL 1
  106820. #if JUCE_MSVC
  106821. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106822. #endif
  106823. #if JUCE_MAC
  106824. #define FLAC__SYS_DARWIN 1
  106825. #endif
  106826. /*** End of inlined file: juce_FlacHeader.h ***/
  106827. #if JUCE_USE_FLAC
  106828. #if HAVE_CONFIG_H
  106829. # include <config.h>
  106830. #endif
  106831. #include <math.h>
  106832. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106833. #ifndef M_PI
  106834. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106835. #define M_PI 3.14159265358979323846
  106836. #endif
  106837. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106838. {
  106839. const FLAC__int32 N = L - 1;
  106840. FLAC__int32 n;
  106841. if (L & 1) {
  106842. for (n = 0; n <= N/2; n++)
  106843. window[n] = 2.0f * n / (float)N;
  106844. for (; n <= N; n++)
  106845. window[n] = 2.0f - 2.0f * n / (float)N;
  106846. }
  106847. else {
  106848. for (n = 0; n <= L/2-1; n++)
  106849. window[n] = 2.0f * n / (float)N;
  106850. for (; n <= N; n++)
  106851. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106852. }
  106853. }
  106854. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106855. {
  106856. const FLAC__int32 N = L - 1;
  106857. FLAC__int32 n;
  106858. for (n = 0; n < L; n++)
  106859. 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)));
  106860. }
  106861. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106862. {
  106863. const FLAC__int32 N = L - 1;
  106864. FLAC__int32 n;
  106865. for (n = 0; n < L; n++)
  106866. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106867. }
  106868. /* 4-term -92dB side-lobe */
  106869. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106870. {
  106871. const FLAC__int32 N = L - 1;
  106872. FLAC__int32 n;
  106873. for (n = 0; n <= N; n++)
  106874. 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));
  106875. }
  106876. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106877. {
  106878. const FLAC__int32 N = L - 1;
  106879. const double N2 = (double)N / 2.;
  106880. FLAC__int32 n;
  106881. for (n = 0; n <= N; n++) {
  106882. double k = ((double)n - N2) / N2;
  106883. k = 1.0f - k * k;
  106884. window[n] = (FLAC__real)(k * k);
  106885. }
  106886. }
  106887. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106888. {
  106889. const FLAC__int32 N = L - 1;
  106890. FLAC__int32 n;
  106891. for (n = 0; n < L; n++)
  106892. 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));
  106893. }
  106894. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106895. {
  106896. const FLAC__int32 N = L - 1;
  106897. const double N2 = (double)N / 2.;
  106898. FLAC__int32 n;
  106899. for (n = 0; n <= N; n++) {
  106900. const double k = ((double)n - N2) / (stddev * N2);
  106901. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106902. }
  106903. }
  106904. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106905. {
  106906. const FLAC__int32 N = L - 1;
  106907. FLAC__int32 n;
  106908. for (n = 0; n < L; n++)
  106909. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106910. }
  106911. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106912. {
  106913. const FLAC__int32 N = L - 1;
  106914. FLAC__int32 n;
  106915. for (n = 0; n < L; n++)
  106916. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106917. }
  106918. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106919. {
  106920. const FLAC__int32 N = L - 1;
  106921. FLAC__int32 n;
  106922. for (n = 0; n < L; n++)
  106923. 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));
  106924. }
  106925. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106926. {
  106927. const FLAC__int32 N = L - 1;
  106928. FLAC__int32 n;
  106929. for (n = 0; n < L; n++)
  106930. 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));
  106931. }
  106932. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106933. {
  106934. FLAC__int32 n;
  106935. for (n = 0; n < L; n++)
  106936. window[n] = 1.0f;
  106937. }
  106938. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106939. {
  106940. FLAC__int32 n;
  106941. if (L & 1) {
  106942. for (n = 1; n <= L+1/2; n++)
  106943. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106944. for (; n <= L; n++)
  106945. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106946. }
  106947. else {
  106948. for (n = 1; n <= L/2; n++)
  106949. window[n-1] = 2.0f * n / (float)L;
  106950. for (; n <= L; n++)
  106951. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106952. }
  106953. }
  106954. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106955. {
  106956. if (p <= 0.0)
  106957. FLAC__window_rectangle(window, L);
  106958. else if (p >= 1.0)
  106959. FLAC__window_hann(window, L);
  106960. else {
  106961. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106962. FLAC__int32 n;
  106963. /* start with rectangle... */
  106964. FLAC__window_rectangle(window, L);
  106965. /* ...replace ends with hann */
  106966. if (Np > 0) {
  106967. for (n = 0; n <= Np; n++) {
  106968. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106969. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106970. }
  106971. }
  106972. }
  106973. }
  106974. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106975. {
  106976. const FLAC__int32 N = L - 1;
  106977. const double N2 = (double)N / 2.;
  106978. FLAC__int32 n;
  106979. for (n = 0; n <= N; n++) {
  106980. const double k = ((double)n - N2) / N2;
  106981. window[n] = (FLAC__real)(1.0f - k * k);
  106982. }
  106983. }
  106984. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106985. #endif
  106986. /*** End of inlined file: window_flac.c ***/
  106987. #else
  106988. #include <FLAC/all.h>
  106989. #endif
  106990. }
  106991. #undef max
  106992. #undef min
  106993. BEGIN_JUCE_NAMESPACE
  106994. static const char* const flacFormatName = "FLAC file";
  106995. static const char* const flacExtensions[] = { ".flac", 0 };
  106996. class FlacReader : public AudioFormatReader
  106997. {
  106998. public:
  106999. FlacReader (InputStream* const in)
  107000. : AudioFormatReader (in, TRANS (flacFormatName)),
  107001. reservoir (2, 0),
  107002. reservoirStart (0),
  107003. samplesInReservoir (0),
  107004. scanningForLength (false)
  107005. {
  107006. using namespace FlacNamespace;
  107007. lengthInSamples = 0;
  107008. decoder = FLAC__stream_decoder_new();
  107009. ok = FLAC__stream_decoder_init_stream (decoder,
  107010. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  107011. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  107012. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  107013. if (ok)
  107014. {
  107015. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107016. if (lengthInSamples == 0 && sampleRate > 0)
  107017. {
  107018. // the length hasn't been stored in the metadata, so we'll need to
  107019. // work it out the length the hard way, by scanning the whole file..
  107020. scanningForLength = true;
  107021. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  107022. scanningForLength = false;
  107023. const int64 tempLength = lengthInSamples;
  107024. FLAC__stream_decoder_reset (decoder);
  107025. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107026. lengthInSamples = tempLength;
  107027. }
  107028. }
  107029. }
  107030. ~FlacReader()
  107031. {
  107032. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  107033. }
  107034. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  107035. {
  107036. sampleRate = info.sample_rate;
  107037. bitsPerSample = info.bits_per_sample;
  107038. lengthInSamples = (unsigned int) info.total_samples;
  107039. numChannels = info.channels;
  107040. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  107041. }
  107042. // returns the number of samples read
  107043. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  107044. int64 startSampleInFile, int numSamples)
  107045. {
  107046. using namespace FlacNamespace;
  107047. if (! ok)
  107048. return false;
  107049. while (numSamples > 0)
  107050. {
  107051. if (startSampleInFile >= reservoirStart
  107052. && startSampleInFile < reservoirStart + samplesInReservoir)
  107053. {
  107054. const int num = (int) jmin ((int64) numSamples,
  107055. reservoirStart + samplesInReservoir - startSampleInFile);
  107056. jassert (num > 0);
  107057. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107058. if (destSamples[i] != 0)
  107059. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107060. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107061. sizeof (int) * num);
  107062. startOffsetInDestBuffer += num;
  107063. startSampleInFile += num;
  107064. numSamples -= num;
  107065. }
  107066. else
  107067. {
  107068. if (startSampleInFile >= (int) lengthInSamples)
  107069. {
  107070. samplesInReservoir = 0;
  107071. }
  107072. else if (startSampleInFile < reservoirStart
  107073. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107074. {
  107075. // had some problems with flac crashing if the read pos is aligned more
  107076. // accurately than this. Probably fixed in newer versions of the library, though.
  107077. reservoirStart = (int) (startSampleInFile & ~511);
  107078. samplesInReservoir = 0;
  107079. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107080. }
  107081. else
  107082. {
  107083. reservoirStart += samplesInReservoir;
  107084. samplesInReservoir = 0;
  107085. FLAC__stream_decoder_process_single (decoder);
  107086. }
  107087. if (samplesInReservoir == 0)
  107088. break;
  107089. }
  107090. }
  107091. if (numSamples > 0)
  107092. {
  107093. for (int i = numDestChannels; --i >= 0;)
  107094. if (destSamples[i] != 0)
  107095. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107096. sizeof (int) * numSamples);
  107097. }
  107098. return true;
  107099. }
  107100. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107101. {
  107102. if (scanningForLength)
  107103. {
  107104. lengthInSamples += numSamples;
  107105. }
  107106. else
  107107. {
  107108. if (numSamples > reservoir.getNumSamples())
  107109. reservoir.setSize (numChannels, numSamples, false, false, true);
  107110. const int bitsToShift = 32 - bitsPerSample;
  107111. for (int i = 0; i < (int) numChannels; ++i)
  107112. {
  107113. const FlacNamespace::FLAC__int32* src = buffer[i];
  107114. int n = i;
  107115. while (src == 0 && n > 0)
  107116. src = buffer [--n];
  107117. if (src != 0)
  107118. {
  107119. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107120. for (int j = 0; j < numSamples; ++j)
  107121. dest[j] = src[j] << bitsToShift;
  107122. }
  107123. }
  107124. samplesInReservoir = numSamples;
  107125. }
  107126. }
  107127. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107128. {
  107129. using namespace FlacNamespace;
  107130. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107131. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107132. }
  107133. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107134. {
  107135. using namespace FlacNamespace;
  107136. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107137. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107138. }
  107139. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107140. {
  107141. using namespace FlacNamespace;
  107142. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107143. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107144. }
  107145. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107146. {
  107147. using namespace FlacNamespace;
  107148. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107149. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107150. }
  107151. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107152. {
  107153. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107154. }
  107155. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107156. const FlacNamespace::FLAC__Frame* frame,
  107157. const FlacNamespace::FLAC__int32* const buffer[],
  107158. void* client_data)
  107159. {
  107160. using namespace FlacNamespace;
  107161. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107162. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107163. }
  107164. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107165. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107166. void* client_data)
  107167. {
  107168. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107169. }
  107170. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107171. {
  107172. }
  107173. juce_UseDebuggingNewOperator
  107174. private:
  107175. FlacNamespace::FLAC__StreamDecoder* decoder;
  107176. AudioSampleBuffer reservoir;
  107177. int reservoirStart, samplesInReservoir;
  107178. bool ok, scanningForLength;
  107179. FlacReader (const FlacReader&);
  107180. FlacReader& operator= (const FlacReader&);
  107181. };
  107182. class FlacWriter : public AudioFormatWriter
  107183. {
  107184. public:
  107185. FlacWriter (OutputStream* const out, double sampleRate_,
  107186. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107187. : AudioFormatWriter (out, TRANS (flacFormatName),
  107188. sampleRate_, numChannels_, bitsPerSample_)
  107189. {
  107190. using namespace FlacNamespace;
  107191. encoder = FLAC__stream_encoder_new();
  107192. if (qualityOptionIndex > 0)
  107193. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107194. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107195. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107196. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107197. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107198. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107199. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107200. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107201. ok = FLAC__stream_encoder_init_stream (encoder,
  107202. encodeWriteCallback, encodeSeekCallback,
  107203. encodeTellCallback, encodeMetadataCallback,
  107204. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107205. }
  107206. ~FlacWriter()
  107207. {
  107208. if (ok)
  107209. {
  107210. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107211. output->flush();
  107212. }
  107213. else
  107214. {
  107215. output = 0; // to stop the base class deleting this, as it needs to be returned
  107216. // to the caller of createWriter()
  107217. }
  107218. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107219. }
  107220. bool write (const int** samplesToWrite, int numSamples)
  107221. {
  107222. using namespace FlacNamespace;
  107223. if (! ok)
  107224. return false;
  107225. int* buf[3];
  107226. const int bitsToShift = 32 - bitsPerSample;
  107227. if (bitsToShift > 0)
  107228. {
  107229. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107230. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107231. buf[0] = temp.getData();
  107232. buf[1] = temp.getData() + numSamples;
  107233. buf[2] = 0;
  107234. for (int i = numChannelsToWrite; --i >= 0;)
  107235. {
  107236. if (samplesToWrite[i] != 0)
  107237. {
  107238. for (int j = 0; j < numSamples; ++j)
  107239. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107240. }
  107241. }
  107242. samplesToWrite = const_cast<const int**> (buf);
  107243. }
  107244. return FLAC__stream_encoder_process (encoder,
  107245. (const FLAC__int32**) samplesToWrite,
  107246. numSamples) != 0;
  107247. }
  107248. bool writeData (const void* const data, const int size) const
  107249. {
  107250. return output->write (data, size);
  107251. }
  107252. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107253. {
  107254. using namespace FlacNamespace;
  107255. b += bytes;
  107256. for (int i = 0; i < bytes; ++i)
  107257. {
  107258. *(--b) = (FLAC__byte) (val & 0xff);
  107259. val >>= 8;
  107260. }
  107261. }
  107262. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107263. {
  107264. using namespace FlacNamespace;
  107265. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107266. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107267. const unsigned int channelsMinus1 = info.channels - 1;
  107268. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107269. packUint32 (info.min_blocksize, buffer, 2);
  107270. packUint32 (info.max_blocksize, buffer + 2, 2);
  107271. packUint32 (info.min_framesize, buffer + 4, 3);
  107272. packUint32 (info.max_framesize, buffer + 7, 3);
  107273. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107274. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107275. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107276. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107277. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107278. memcpy (buffer + 18, info.md5sum, 16);
  107279. const bool seekOk = output->setPosition (4);
  107280. (void) seekOk;
  107281. // if this fails, you've given it an output stream that can't seek! It needs
  107282. // to be able to seek back to write the header
  107283. jassert (seekOk);
  107284. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107285. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107286. }
  107287. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107288. const FlacNamespace::FLAC__byte buffer[],
  107289. size_t bytes,
  107290. unsigned int /*samples*/,
  107291. unsigned int /*current_frame*/,
  107292. void* client_data)
  107293. {
  107294. using namespace FlacNamespace;
  107295. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107296. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107297. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107298. }
  107299. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107300. {
  107301. using namespace FlacNamespace;
  107302. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107303. }
  107304. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107305. {
  107306. using namespace FlacNamespace;
  107307. if (client_data == 0)
  107308. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107309. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107310. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107311. }
  107312. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107313. {
  107314. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107315. }
  107316. juce_UseDebuggingNewOperator
  107317. bool ok;
  107318. private:
  107319. FlacNamespace::FLAC__StreamEncoder* encoder;
  107320. FlacWriter (const FlacWriter&);
  107321. FlacWriter& operator= (const FlacWriter&);
  107322. };
  107323. FlacAudioFormat::FlacAudioFormat()
  107324. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107325. {
  107326. }
  107327. FlacAudioFormat::~FlacAudioFormat()
  107328. {
  107329. }
  107330. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107331. {
  107332. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107333. return Array <int> (rates);
  107334. }
  107335. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107336. {
  107337. const int depths[] = { 16, 24, 0 };
  107338. return Array <int> (depths);
  107339. }
  107340. bool FlacAudioFormat::canDoStereo() { return true; }
  107341. bool FlacAudioFormat::canDoMono() { return true; }
  107342. bool FlacAudioFormat::isCompressed() { return true; }
  107343. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107344. const bool deleteStreamIfOpeningFails)
  107345. {
  107346. ScopedPointer<FlacReader> r (new FlacReader (in));
  107347. if (r->sampleRate != 0)
  107348. return r.release();
  107349. if (! deleteStreamIfOpeningFails)
  107350. r->input = 0;
  107351. return 0;
  107352. }
  107353. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107354. double sampleRate,
  107355. unsigned int numberOfChannels,
  107356. int bitsPerSample,
  107357. const StringPairArray& /*metadataValues*/,
  107358. int qualityOptionIndex)
  107359. {
  107360. if (getPossibleBitDepths().contains (bitsPerSample))
  107361. {
  107362. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107363. if (w->ok)
  107364. return w.release();
  107365. }
  107366. return 0;
  107367. }
  107368. END_JUCE_NAMESPACE
  107369. #endif
  107370. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107371. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107372. #if JUCE_USE_OGGVORBIS
  107373. #if JUCE_MAC
  107374. #define __MACOSX__ 1
  107375. #endif
  107376. namespace OggVorbisNamespace
  107377. {
  107378. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107379. /*** Start of inlined file: vorbisenc.h ***/
  107380. #ifndef _OV_ENC_H_
  107381. #define _OV_ENC_H_
  107382. #ifdef __cplusplus
  107383. extern "C"
  107384. {
  107385. #endif /* __cplusplus */
  107386. /*** Start of inlined file: codec.h ***/
  107387. #ifndef _vorbis_codec_h_
  107388. #define _vorbis_codec_h_
  107389. #ifdef __cplusplus
  107390. extern "C"
  107391. {
  107392. #endif /* __cplusplus */
  107393. /*** Start of inlined file: ogg.h ***/
  107394. #ifndef _OGG_H
  107395. #define _OGG_H
  107396. #ifdef __cplusplus
  107397. extern "C" {
  107398. #endif
  107399. /*** Start of inlined file: os_types.h ***/
  107400. #ifndef _OS_TYPES_H
  107401. #define _OS_TYPES_H
  107402. /* make it easy on the folks that want to compile the libs with a
  107403. different malloc than stdlib */
  107404. #define _ogg_malloc malloc
  107405. #define _ogg_calloc calloc
  107406. #define _ogg_realloc realloc
  107407. #define _ogg_free free
  107408. #if defined(_WIN32)
  107409. # if defined(__CYGWIN__)
  107410. # include <_G_config.h>
  107411. typedef _G_int64_t ogg_int64_t;
  107412. typedef _G_int32_t ogg_int32_t;
  107413. typedef _G_uint32_t ogg_uint32_t;
  107414. typedef _G_int16_t ogg_int16_t;
  107415. typedef _G_uint16_t ogg_uint16_t;
  107416. # elif defined(__MINGW32__)
  107417. typedef short ogg_int16_t;
  107418. typedef unsigned short ogg_uint16_t;
  107419. typedef int ogg_int32_t;
  107420. typedef unsigned int ogg_uint32_t;
  107421. typedef long long ogg_int64_t;
  107422. typedef unsigned long long ogg_uint64_t;
  107423. # elif defined(__MWERKS__)
  107424. typedef long long ogg_int64_t;
  107425. typedef int ogg_int32_t;
  107426. typedef unsigned int ogg_uint32_t;
  107427. typedef short ogg_int16_t;
  107428. typedef unsigned short ogg_uint16_t;
  107429. # else
  107430. /* MSVC/Borland */
  107431. typedef __int64 ogg_int64_t;
  107432. typedef __int32 ogg_int32_t;
  107433. typedef unsigned __int32 ogg_uint32_t;
  107434. typedef __int16 ogg_int16_t;
  107435. typedef unsigned __int16 ogg_uint16_t;
  107436. # endif
  107437. #elif defined(__MACOS__)
  107438. # include <sys/types.h>
  107439. typedef SInt16 ogg_int16_t;
  107440. typedef UInt16 ogg_uint16_t;
  107441. typedef SInt32 ogg_int32_t;
  107442. typedef UInt32 ogg_uint32_t;
  107443. typedef SInt64 ogg_int64_t;
  107444. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107445. # include <sys/types.h>
  107446. typedef int16_t ogg_int16_t;
  107447. typedef u_int16_t ogg_uint16_t;
  107448. typedef int32_t ogg_int32_t;
  107449. typedef u_int32_t ogg_uint32_t;
  107450. typedef int64_t ogg_int64_t;
  107451. #elif defined(__BEOS__)
  107452. /* Be */
  107453. # include <inttypes.h>
  107454. typedef int16_t ogg_int16_t;
  107455. typedef u_int16_t ogg_uint16_t;
  107456. typedef int32_t ogg_int32_t;
  107457. typedef u_int32_t ogg_uint32_t;
  107458. typedef int64_t ogg_int64_t;
  107459. #elif defined (__EMX__)
  107460. /* OS/2 GCC */
  107461. typedef short ogg_int16_t;
  107462. typedef unsigned short ogg_uint16_t;
  107463. typedef int ogg_int32_t;
  107464. typedef unsigned int ogg_uint32_t;
  107465. typedef long long ogg_int64_t;
  107466. #elif defined (DJGPP)
  107467. /* DJGPP */
  107468. typedef short ogg_int16_t;
  107469. typedef int ogg_int32_t;
  107470. typedef unsigned int ogg_uint32_t;
  107471. typedef long long ogg_int64_t;
  107472. #elif defined(R5900)
  107473. /* PS2 EE */
  107474. typedef long ogg_int64_t;
  107475. typedef int ogg_int32_t;
  107476. typedef unsigned ogg_uint32_t;
  107477. typedef short ogg_int16_t;
  107478. #elif defined(__SYMBIAN32__)
  107479. /* Symbian GCC */
  107480. typedef signed short ogg_int16_t;
  107481. typedef unsigned short ogg_uint16_t;
  107482. typedef signed int ogg_int32_t;
  107483. typedef unsigned int ogg_uint32_t;
  107484. typedef long long int ogg_int64_t;
  107485. #else
  107486. # include <sys/types.h>
  107487. /*** Start of inlined file: config_types.h ***/
  107488. #ifndef __CONFIG_TYPES_H__
  107489. #define __CONFIG_TYPES_H__
  107490. typedef int16_t ogg_int16_t;
  107491. typedef unsigned short ogg_uint16_t;
  107492. typedef int32_t ogg_int32_t;
  107493. typedef unsigned int ogg_uint32_t;
  107494. typedef int64_t ogg_int64_t;
  107495. #endif
  107496. /*** End of inlined file: config_types.h ***/
  107497. #endif
  107498. #endif /* _OS_TYPES_H */
  107499. /*** End of inlined file: os_types.h ***/
  107500. typedef struct {
  107501. long endbyte;
  107502. int endbit;
  107503. unsigned char *buffer;
  107504. unsigned char *ptr;
  107505. long storage;
  107506. } oggpack_buffer;
  107507. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107508. typedef struct {
  107509. unsigned char *header;
  107510. long header_len;
  107511. unsigned char *body;
  107512. long body_len;
  107513. } ogg_page;
  107514. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107515. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107516. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107517. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107518. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107519. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107520. }
  107521. /* ogg_stream_state contains the current encode/decode state of a logical
  107522. Ogg bitstream **********************************************************/
  107523. typedef struct {
  107524. unsigned char *body_data; /* bytes from packet bodies */
  107525. long body_storage; /* storage elements allocated */
  107526. long body_fill; /* elements stored; fill mark */
  107527. long body_returned; /* elements of fill returned */
  107528. int *lacing_vals; /* The values that will go to the segment table */
  107529. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107530. this way, but it is simple coupled to the
  107531. lacing fifo */
  107532. long lacing_storage;
  107533. long lacing_fill;
  107534. long lacing_packet;
  107535. long lacing_returned;
  107536. unsigned char header[282]; /* working space for header encode */
  107537. int header_fill;
  107538. int e_o_s; /* set when we have buffered the last packet in the
  107539. logical bitstream */
  107540. int b_o_s; /* set after we've written the initial page
  107541. of a logical bitstream */
  107542. long serialno;
  107543. long pageno;
  107544. ogg_int64_t packetno; /* sequence number for decode; the framing
  107545. knows where there's a hole in the data,
  107546. but we need coupling so that the codec
  107547. (which is in a seperate abstraction
  107548. layer) also knows about the gap */
  107549. ogg_int64_t granulepos;
  107550. } ogg_stream_state;
  107551. /* ogg_packet is used to encapsulate the data and metadata belonging
  107552. to a single raw Ogg/Vorbis packet *************************************/
  107553. typedef struct {
  107554. unsigned char *packet;
  107555. long bytes;
  107556. long b_o_s;
  107557. long e_o_s;
  107558. ogg_int64_t granulepos;
  107559. ogg_int64_t packetno; /* sequence number for decode; the framing
  107560. knows where there's a hole in the data,
  107561. but we need coupling so that the codec
  107562. (which is in a seperate abstraction
  107563. layer) also knows about the gap */
  107564. } ogg_packet;
  107565. typedef struct {
  107566. unsigned char *data;
  107567. int storage;
  107568. int fill;
  107569. int returned;
  107570. int unsynced;
  107571. int headerbytes;
  107572. int bodybytes;
  107573. } ogg_sync_state;
  107574. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107575. extern void oggpack_writeinit(oggpack_buffer *b);
  107576. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107577. extern void oggpack_writealign(oggpack_buffer *b);
  107578. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107579. extern void oggpack_reset(oggpack_buffer *b);
  107580. extern void oggpack_writeclear(oggpack_buffer *b);
  107581. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107582. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107583. extern long oggpack_look(oggpack_buffer *b,int bits);
  107584. extern long oggpack_look1(oggpack_buffer *b);
  107585. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107586. extern void oggpack_adv1(oggpack_buffer *b);
  107587. extern long oggpack_read(oggpack_buffer *b,int bits);
  107588. extern long oggpack_read1(oggpack_buffer *b);
  107589. extern long oggpack_bytes(oggpack_buffer *b);
  107590. extern long oggpack_bits(oggpack_buffer *b);
  107591. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107592. extern void oggpackB_writeinit(oggpack_buffer *b);
  107593. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107594. extern void oggpackB_writealign(oggpack_buffer *b);
  107595. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107596. extern void oggpackB_reset(oggpack_buffer *b);
  107597. extern void oggpackB_writeclear(oggpack_buffer *b);
  107598. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107599. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107600. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107601. extern long oggpackB_look1(oggpack_buffer *b);
  107602. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107603. extern void oggpackB_adv1(oggpack_buffer *b);
  107604. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107605. extern long oggpackB_read1(oggpack_buffer *b);
  107606. extern long oggpackB_bytes(oggpack_buffer *b);
  107607. extern long oggpackB_bits(oggpack_buffer *b);
  107608. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107609. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107610. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107611. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107612. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107613. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107614. extern int ogg_sync_init(ogg_sync_state *oy);
  107615. extern int ogg_sync_clear(ogg_sync_state *oy);
  107616. extern int ogg_sync_reset(ogg_sync_state *oy);
  107617. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107618. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107619. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107620. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107621. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107622. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107623. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107624. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107625. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107626. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107627. extern int ogg_stream_clear(ogg_stream_state *os);
  107628. extern int ogg_stream_reset(ogg_stream_state *os);
  107629. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107630. extern int ogg_stream_destroy(ogg_stream_state *os);
  107631. extern int ogg_stream_eos(ogg_stream_state *os);
  107632. extern void ogg_page_checksum_set(ogg_page *og);
  107633. extern int ogg_page_version(ogg_page *og);
  107634. extern int ogg_page_continued(ogg_page *og);
  107635. extern int ogg_page_bos(ogg_page *og);
  107636. extern int ogg_page_eos(ogg_page *og);
  107637. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107638. extern int ogg_page_serialno(ogg_page *og);
  107639. extern long ogg_page_pageno(ogg_page *og);
  107640. extern int ogg_page_packets(ogg_page *og);
  107641. extern void ogg_packet_clear(ogg_packet *op);
  107642. #ifdef __cplusplus
  107643. }
  107644. #endif
  107645. #endif /* _OGG_H */
  107646. /*** End of inlined file: ogg.h ***/
  107647. typedef struct vorbis_info{
  107648. int version;
  107649. int channels;
  107650. long rate;
  107651. /* The below bitrate declarations are *hints*.
  107652. Combinations of the three values carry the following implications:
  107653. all three set to the same value:
  107654. implies a fixed rate bitstream
  107655. only nominal set:
  107656. implies a VBR stream that averages the nominal bitrate. No hard
  107657. upper/lower limit
  107658. upper and or lower set:
  107659. implies a VBR bitstream that obeys the bitrate limits. nominal
  107660. may also be set to give a nominal rate.
  107661. none set:
  107662. the coder does not care to speculate.
  107663. */
  107664. long bitrate_upper;
  107665. long bitrate_nominal;
  107666. long bitrate_lower;
  107667. long bitrate_window;
  107668. void *codec_setup;
  107669. } vorbis_info;
  107670. /* vorbis_dsp_state buffers the current vorbis audio
  107671. analysis/synthesis state. The DSP state belongs to a specific
  107672. logical bitstream ****************************************************/
  107673. typedef struct vorbis_dsp_state{
  107674. int analysisp;
  107675. vorbis_info *vi;
  107676. float **pcm;
  107677. float **pcmret;
  107678. int pcm_storage;
  107679. int pcm_current;
  107680. int pcm_returned;
  107681. int preextrapolate;
  107682. int eofflag;
  107683. long lW;
  107684. long W;
  107685. long nW;
  107686. long centerW;
  107687. ogg_int64_t granulepos;
  107688. ogg_int64_t sequence;
  107689. ogg_int64_t glue_bits;
  107690. ogg_int64_t time_bits;
  107691. ogg_int64_t floor_bits;
  107692. ogg_int64_t res_bits;
  107693. void *backend_state;
  107694. } vorbis_dsp_state;
  107695. typedef struct vorbis_block{
  107696. /* necessary stream state for linking to the framing abstraction */
  107697. float **pcm; /* this is a pointer into local storage */
  107698. oggpack_buffer opb;
  107699. long lW;
  107700. long W;
  107701. long nW;
  107702. int pcmend;
  107703. int mode;
  107704. int eofflag;
  107705. ogg_int64_t granulepos;
  107706. ogg_int64_t sequence;
  107707. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107708. /* local storage to avoid remallocing; it's up to the mapping to
  107709. structure it */
  107710. void *localstore;
  107711. long localtop;
  107712. long localalloc;
  107713. long totaluse;
  107714. struct alloc_chain *reap;
  107715. /* bitmetrics for the frame */
  107716. long glue_bits;
  107717. long time_bits;
  107718. long floor_bits;
  107719. long res_bits;
  107720. void *internal;
  107721. } vorbis_block;
  107722. /* vorbis_block is a single block of data to be processed as part of
  107723. the analysis/synthesis stream; it belongs to a specific logical
  107724. bitstream, but is independant from other vorbis_blocks belonging to
  107725. that logical bitstream. *************************************************/
  107726. struct alloc_chain{
  107727. void *ptr;
  107728. struct alloc_chain *next;
  107729. };
  107730. /* vorbis_info contains all the setup information specific to the
  107731. specific compression/decompression mode in progress (eg,
  107732. psychoacoustic settings, channel setup, options, codebook
  107733. etc). vorbis_info and substructures are in backends.h.
  107734. *********************************************************************/
  107735. /* the comments are not part of vorbis_info so that vorbis_info can be
  107736. static storage */
  107737. typedef struct vorbis_comment{
  107738. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107739. whatever vendor is set to in encode */
  107740. char **user_comments;
  107741. int *comment_lengths;
  107742. int comments;
  107743. char *vendor;
  107744. } vorbis_comment;
  107745. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107746. and produce a packet (see docs/analysis.txt). The packet is then
  107747. coded into a framed OggSquish bitstream by the second layer (see
  107748. docs/framing.txt). Decode is the reverse process; we sync/frame
  107749. the bitstream and extract individual packets, then decode the
  107750. packet back into PCM audio.
  107751. The extra framing/packetizing is used in streaming formats, such as
  107752. files. Over the net (such as with UDP), the framing and
  107753. packetization aren't necessary as they're provided by the transport
  107754. and the streaming layer is not used */
  107755. /* Vorbis PRIMITIVES: general ***************************************/
  107756. extern void vorbis_info_init(vorbis_info *vi);
  107757. extern void vorbis_info_clear(vorbis_info *vi);
  107758. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107759. extern void vorbis_comment_init(vorbis_comment *vc);
  107760. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107761. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107762. const char *tag, char *contents);
  107763. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107764. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107765. extern void vorbis_comment_clear(vorbis_comment *vc);
  107766. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107767. extern int vorbis_block_clear(vorbis_block *vb);
  107768. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107769. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107770. ogg_int64_t granulepos);
  107771. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107772. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107773. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107774. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107775. vorbis_comment *vc,
  107776. ogg_packet *op,
  107777. ogg_packet *op_comm,
  107778. ogg_packet *op_code);
  107779. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107780. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107781. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107782. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107783. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107784. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107785. ogg_packet *op);
  107786. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107787. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107788. ogg_packet *op);
  107789. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107790. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107791. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107792. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107793. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107794. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107795. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107796. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107797. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107798. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107799. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107800. /* Vorbis ERRORS and return codes ***********************************/
  107801. #define OV_FALSE -1
  107802. #define OV_EOF -2
  107803. #define OV_HOLE -3
  107804. #define OV_EREAD -128
  107805. #define OV_EFAULT -129
  107806. #define OV_EIMPL -130
  107807. #define OV_EINVAL -131
  107808. #define OV_ENOTVORBIS -132
  107809. #define OV_EBADHEADER -133
  107810. #define OV_EVERSION -134
  107811. #define OV_ENOTAUDIO -135
  107812. #define OV_EBADPACKET -136
  107813. #define OV_EBADLINK -137
  107814. #define OV_ENOSEEK -138
  107815. #ifdef __cplusplus
  107816. }
  107817. #endif /* __cplusplus */
  107818. #endif
  107819. /*** End of inlined file: codec.h ***/
  107820. extern int vorbis_encode_init(vorbis_info *vi,
  107821. long channels,
  107822. long rate,
  107823. long max_bitrate,
  107824. long nominal_bitrate,
  107825. long min_bitrate);
  107826. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107827. long channels,
  107828. long rate,
  107829. long max_bitrate,
  107830. long nominal_bitrate,
  107831. long min_bitrate);
  107832. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107833. long channels,
  107834. long rate,
  107835. float quality /* quality level from 0. (lo) to 1. (hi) */
  107836. );
  107837. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107838. long channels,
  107839. long rate,
  107840. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107841. );
  107842. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107843. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107844. /* deprecated rate management supported only for compatability */
  107845. #define OV_ECTL_RATEMANAGE_GET 0x10
  107846. #define OV_ECTL_RATEMANAGE_SET 0x11
  107847. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107848. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107849. struct ovectl_ratemanage_arg {
  107850. int management_active;
  107851. long bitrate_hard_min;
  107852. long bitrate_hard_max;
  107853. double bitrate_hard_window;
  107854. long bitrate_av_lo;
  107855. long bitrate_av_hi;
  107856. double bitrate_av_window;
  107857. double bitrate_av_window_center;
  107858. };
  107859. /* new rate setup */
  107860. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107861. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107862. struct ovectl_ratemanage2_arg {
  107863. int management_active;
  107864. long bitrate_limit_min_kbps;
  107865. long bitrate_limit_max_kbps;
  107866. long bitrate_limit_reservoir_bits;
  107867. double bitrate_limit_reservoir_bias;
  107868. long bitrate_average_kbps;
  107869. double bitrate_average_damping;
  107870. };
  107871. #define OV_ECTL_LOWPASS_GET 0x20
  107872. #define OV_ECTL_LOWPASS_SET 0x21
  107873. #define OV_ECTL_IBLOCK_GET 0x30
  107874. #define OV_ECTL_IBLOCK_SET 0x31
  107875. #ifdef __cplusplus
  107876. }
  107877. #endif /* __cplusplus */
  107878. #endif
  107879. /*** End of inlined file: vorbisenc.h ***/
  107880. /*** Start of inlined file: vorbisfile.h ***/
  107881. #ifndef _OV_FILE_H_
  107882. #define _OV_FILE_H_
  107883. #ifdef __cplusplus
  107884. extern "C"
  107885. {
  107886. #endif /* __cplusplus */
  107887. #include <stdio.h>
  107888. /* The function prototypes for the callbacks are basically the same as for
  107889. * the stdio functions fread, fseek, fclose, ftell.
  107890. * The one difference is that the FILE * arguments have been replaced with
  107891. * a void * - this is to be used as a pointer to whatever internal data these
  107892. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107893. *
  107894. * If you use other functions, check the docs for these functions and return
  107895. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107896. * unseekable
  107897. */
  107898. typedef struct {
  107899. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107900. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107901. int (*close_func) (void *datasource);
  107902. long (*tell_func) (void *datasource);
  107903. } ov_callbacks;
  107904. #define NOTOPEN 0
  107905. #define PARTOPEN 1
  107906. #define OPENED 2
  107907. #define STREAMSET 3
  107908. #define INITSET 4
  107909. typedef struct OggVorbis_File {
  107910. void *datasource; /* Pointer to a FILE *, etc. */
  107911. int seekable;
  107912. ogg_int64_t offset;
  107913. ogg_int64_t end;
  107914. ogg_sync_state oy;
  107915. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107916. stream appears */
  107917. int links;
  107918. ogg_int64_t *offsets;
  107919. ogg_int64_t *dataoffsets;
  107920. long *serialnos;
  107921. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107922. compatability; x2 size, stores both
  107923. beginning and end values */
  107924. vorbis_info *vi;
  107925. vorbis_comment *vc;
  107926. /* Decoding working state local storage */
  107927. ogg_int64_t pcm_offset;
  107928. int ready_state;
  107929. long current_serialno;
  107930. int current_link;
  107931. double bittrack;
  107932. double samptrack;
  107933. ogg_stream_state os; /* take physical pages, weld into a logical
  107934. stream of packets */
  107935. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107936. vorbis_block vb; /* local working space for packet->PCM decode */
  107937. ov_callbacks callbacks;
  107938. } OggVorbis_File;
  107939. extern int ov_clear(OggVorbis_File *vf);
  107940. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107941. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107942. char *initial, long ibytes, ov_callbacks callbacks);
  107943. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107944. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107945. char *initial, long ibytes, ov_callbacks callbacks);
  107946. extern int ov_test_open(OggVorbis_File *vf);
  107947. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107948. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107949. extern long ov_streams(OggVorbis_File *vf);
  107950. extern long ov_seekable(OggVorbis_File *vf);
  107951. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107952. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107953. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107954. extern double ov_time_total(OggVorbis_File *vf,int i);
  107955. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107956. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107957. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107958. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107959. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107960. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107961. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107962. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107963. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107964. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107965. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107966. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107967. extern double ov_time_tell(OggVorbis_File *vf);
  107968. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107969. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107970. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107971. int *bitstream);
  107972. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107973. int bigendianp,int word,int sgned,int *bitstream);
  107974. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107975. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107976. extern int ov_halfrate_p(OggVorbis_File *vf);
  107977. #ifdef __cplusplus
  107978. }
  107979. #endif /* __cplusplus */
  107980. #endif
  107981. /*** End of inlined file: vorbisfile.h ***/
  107982. /*** Start of inlined file: bitwise.c ***/
  107983. /* We're 'LSb' endian; if we write a word but read individual bits,
  107984. then we'll read the lsb first */
  107985. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107986. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107987. // tasks..
  107988. #if JUCE_MSVC
  107989. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107990. #endif
  107991. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107992. #if JUCE_USE_OGGVORBIS
  107993. #include <string.h>
  107994. #include <stdlib.h>
  107995. #define BUFFER_INCREMENT 256
  107996. static const unsigned long mask[]=
  107997. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107998. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107999. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  108000. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  108001. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  108002. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  108003. 0x3fffffff,0x7fffffff,0xffffffff };
  108004. static const unsigned int mask8B[]=
  108005. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  108006. void oggpack_writeinit(oggpack_buffer *b){
  108007. memset(b,0,sizeof(*b));
  108008. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  108009. b->buffer[0]='\0';
  108010. b->storage=BUFFER_INCREMENT;
  108011. }
  108012. void oggpackB_writeinit(oggpack_buffer *b){
  108013. oggpack_writeinit(b);
  108014. }
  108015. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  108016. long bytes=bits>>3;
  108017. bits-=bytes*8;
  108018. b->ptr=b->buffer+bytes;
  108019. b->endbit=bits;
  108020. b->endbyte=bytes;
  108021. *b->ptr&=mask[bits];
  108022. }
  108023. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  108024. long bytes=bits>>3;
  108025. bits-=bytes*8;
  108026. b->ptr=b->buffer+bytes;
  108027. b->endbit=bits;
  108028. b->endbyte=bytes;
  108029. *b->ptr&=mask8B[bits];
  108030. }
  108031. /* Takes only up to 32 bits. */
  108032. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  108033. if(b->endbyte+4>=b->storage){
  108034. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108035. b->storage+=BUFFER_INCREMENT;
  108036. b->ptr=b->buffer+b->endbyte;
  108037. }
  108038. value&=mask[bits];
  108039. bits+=b->endbit;
  108040. b->ptr[0]|=value<<b->endbit;
  108041. if(bits>=8){
  108042. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  108043. if(bits>=16){
  108044. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  108045. if(bits>=24){
  108046. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  108047. if(bits>=32){
  108048. if(b->endbit)
  108049. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  108050. else
  108051. b->ptr[4]=0;
  108052. }
  108053. }
  108054. }
  108055. }
  108056. b->endbyte+=bits/8;
  108057. b->ptr+=bits/8;
  108058. b->endbit=bits&7;
  108059. }
  108060. /* Takes only up to 32 bits. */
  108061. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108062. if(b->endbyte+4>=b->storage){
  108063. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108064. b->storage+=BUFFER_INCREMENT;
  108065. b->ptr=b->buffer+b->endbyte;
  108066. }
  108067. value=(value&mask[bits])<<(32-bits);
  108068. bits+=b->endbit;
  108069. b->ptr[0]|=value>>(24+b->endbit);
  108070. if(bits>=8){
  108071. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108072. if(bits>=16){
  108073. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108074. if(bits>=24){
  108075. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108076. if(bits>=32){
  108077. if(b->endbit)
  108078. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108079. else
  108080. b->ptr[4]=0;
  108081. }
  108082. }
  108083. }
  108084. }
  108085. b->endbyte+=bits/8;
  108086. b->ptr+=bits/8;
  108087. b->endbit=bits&7;
  108088. }
  108089. void oggpack_writealign(oggpack_buffer *b){
  108090. int bits=8-b->endbit;
  108091. if(bits<8)
  108092. oggpack_write(b,0,bits);
  108093. }
  108094. void oggpackB_writealign(oggpack_buffer *b){
  108095. int bits=8-b->endbit;
  108096. if(bits<8)
  108097. oggpackB_write(b,0,bits);
  108098. }
  108099. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108100. void *source,
  108101. long bits,
  108102. void (*w)(oggpack_buffer *,
  108103. unsigned long,
  108104. int),
  108105. int msb){
  108106. unsigned char *ptr=(unsigned char *)source;
  108107. long bytes=bits/8;
  108108. bits-=bytes*8;
  108109. if(b->endbit){
  108110. int i;
  108111. /* unaligned copy. Do it the hard way. */
  108112. for(i=0;i<bytes;i++)
  108113. w(b,(unsigned long)(ptr[i]),8);
  108114. }else{
  108115. /* aligned block copy */
  108116. if(b->endbyte+bytes+1>=b->storage){
  108117. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108118. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108119. b->ptr=b->buffer+b->endbyte;
  108120. }
  108121. memmove(b->ptr,source,bytes);
  108122. b->ptr+=bytes;
  108123. b->endbyte+=bytes;
  108124. *b->ptr=0;
  108125. }
  108126. if(bits){
  108127. if(msb)
  108128. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108129. else
  108130. w(b,(unsigned long)(ptr[bytes]),bits);
  108131. }
  108132. }
  108133. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108134. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108135. }
  108136. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108137. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108138. }
  108139. void oggpack_reset(oggpack_buffer *b){
  108140. b->ptr=b->buffer;
  108141. b->buffer[0]=0;
  108142. b->endbit=b->endbyte=0;
  108143. }
  108144. void oggpackB_reset(oggpack_buffer *b){
  108145. oggpack_reset(b);
  108146. }
  108147. void oggpack_writeclear(oggpack_buffer *b){
  108148. _ogg_free(b->buffer);
  108149. memset(b,0,sizeof(*b));
  108150. }
  108151. void oggpackB_writeclear(oggpack_buffer *b){
  108152. oggpack_writeclear(b);
  108153. }
  108154. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108155. memset(b,0,sizeof(*b));
  108156. b->buffer=b->ptr=buf;
  108157. b->storage=bytes;
  108158. }
  108159. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108160. oggpack_readinit(b,buf,bytes);
  108161. }
  108162. /* Read in bits without advancing the bitptr; bits <= 32 */
  108163. long oggpack_look(oggpack_buffer *b,int bits){
  108164. unsigned long ret;
  108165. unsigned long m=mask[bits];
  108166. bits+=b->endbit;
  108167. if(b->endbyte+4>=b->storage){
  108168. /* not the main path */
  108169. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108170. }
  108171. ret=b->ptr[0]>>b->endbit;
  108172. if(bits>8){
  108173. ret|=b->ptr[1]<<(8-b->endbit);
  108174. if(bits>16){
  108175. ret|=b->ptr[2]<<(16-b->endbit);
  108176. if(bits>24){
  108177. ret|=b->ptr[3]<<(24-b->endbit);
  108178. if(bits>32 && b->endbit)
  108179. ret|=b->ptr[4]<<(32-b->endbit);
  108180. }
  108181. }
  108182. }
  108183. return(m&ret);
  108184. }
  108185. /* Read in bits without advancing the bitptr; bits <= 32 */
  108186. long oggpackB_look(oggpack_buffer *b,int bits){
  108187. unsigned long ret;
  108188. int m=32-bits;
  108189. bits+=b->endbit;
  108190. if(b->endbyte+4>=b->storage){
  108191. /* not the main path */
  108192. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108193. }
  108194. ret=b->ptr[0]<<(24+b->endbit);
  108195. if(bits>8){
  108196. ret|=b->ptr[1]<<(16+b->endbit);
  108197. if(bits>16){
  108198. ret|=b->ptr[2]<<(8+b->endbit);
  108199. if(bits>24){
  108200. ret|=b->ptr[3]<<(b->endbit);
  108201. if(bits>32 && b->endbit)
  108202. ret|=b->ptr[4]>>(8-b->endbit);
  108203. }
  108204. }
  108205. }
  108206. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108207. }
  108208. long oggpack_look1(oggpack_buffer *b){
  108209. if(b->endbyte>=b->storage)return(-1);
  108210. return((b->ptr[0]>>b->endbit)&1);
  108211. }
  108212. long oggpackB_look1(oggpack_buffer *b){
  108213. if(b->endbyte>=b->storage)return(-1);
  108214. return((b->ptr[0]>>(7-b->endbit))&1);
  108215. }
  108216. void oggpack_adv(oggpack_buffer *b,int bits){
  108217. bits+=b->endbit;
  108218. b->ptr+=bits/8;
  108219. b->endbyte+=bits/8;
  108220. b->endbit=bits&7;
  108221. }
  108222. void oggpackB_adv(oggpack_buffer *b,int bits){
  108223. oggpack_adv(b,bits);
  108224. }
  108225. void oggpack_adv1(oggpack_buffer *b){
  108226. if(++(b->endbit)>7){
  108227. b->endbit=0;
  108228. b->ptr++;
  108229. b->endbyte++;
  108230. }
  108231. }
  108232. void oggpackB_adv1(oggpack_buffer *b){
  108233. oggpack_adv1(b);
  108234. }
  108235. /* bits <= 32 */
  108236. long oggpack_read(oggpack_buffer *b,int bits){
  108237. long ret;
  108238. unsigned long m=mask[bits];
  108239. bits+=b->endbit;
  108240. if(b->endbyte+4>=b->storage){
  108241. /* not the main path */
  108242. ret=-1L;
  108243. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108244. }
  108245. ret=b->ptr[0]>>b->endbit;
  108246. if(bits>8){
  108247. ret|=b->ptr[1]<<(8-b->endbit);
  108248. if(bits>16){
  108249. ret|=b->ptr[2]<<(16-b->endbit);
  108250. if(bits>24){
  108251. ret|=b->ptr[3]<<(24-b->endbit);
  108252. if(bits>32 && b->endbit){
  108253. ret|=b->ptr[4]<<(32-b->endbit);
  108254. }
  108255. }
  108256. }
  108257. }
  108258. ret&=m;
  108259. overflow:
  108260. b->ptr+=bits/8;
  108261. b->endbyte+=bits/8;
  108262. b->endbit=bits&7;
  108263. return(ret);
  108264. }
  108265. /* bits <= 32 */
  108266. long oggpackB_read(oggpack_buffer *b,int bits){
  108267. long ret;
  108268. long m=32-bits;
  108269. bits+=b->endbit;
  108270. if(b->endbyte+4>=b->storage){
  108271. /* not the main path */
  108272. ret=-1L;
  108273. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108274. }
  108275. ret=b->ptr[0]<<(24+b->endbit);
  108276. if(bits>8){
  108277. ret|=b->ptr[1]<<(16+b->endbit);
  108278. if(bits>16){
  108279. ret|=b->ptr[2]<<(8+b->endbit);
  108280. if(bits>24){
  108281. ret|=b->ptr[3]<<(b->endbit);
  108282. if(bits>32 && b->endbit)
  108283. ret|=b->ptr[4]>>(8-b->endbit);
  108284. }
  108285. }
  108286. }
  108287. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108288. overflow:
  108289. b->ptr+=bits/8;
  108290. b->endbyte+=bits/8;
  108291. b->endbit=bits&7;
  108292. return(ret);
  108293. }
  108294. long oggpack_read1(oggpack_buffer *b){
  108295. long ret;
  108296. if(b->endbyte>=b->storage){
  108297. /* not the main path */
  108298. ret=-1L;
  108299. goto overflow;
  108300. }
  108301. ret=(b->ptr[0]>>b->endbit)&1;
  108302. overflow:
  108303. b->endbit++;
  108304. if(b->endbit>7){
  108305. b->endbit=0;
  108306. b->ptr++;
  108307. b->endbyte++;
  108308. }
  108309. return(ret);
  108310. }
  108311. long oggpackB_read1(oggpack_buffer *b){
  108312. long ret;
  108313. if(b->endbyte>=b->storage){
  108314. /* not the main path */
  108315. ret=-1L;
  108316. goto overflow;
  108317. }
  108318. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108319. overflow:
  108320. b->endbit++;
  108321. if(b->endbit>7){
  108322. b->endbit=0;
  108323. b->ptr++;
  108324. b->endbyte++;
  108325. }
  108326. return(ret);
  108327. }
  108328. long oggpack_bytes(oggpack_buffer *b){
  108329. return(b->endbyte+(b->endbit+7)/8);
  108330. }
  108331. long oggpack_bits(oggpack_buffer *b){
  108332. return(b->endbyte*8+b->endbit);
  108333. }
  108334. long oggpackB_bytes(oggpack_buffer *b){
  108335. return oggpack_bytes(b);
  108336. }
  108337. long oggpackB_bits(oggpack_buffer *b){
  108338. return oggpack_bits(b);
  108339. }
  108340. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108341. return(b->buffer);
  108342. }
  108343. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108344. return oggpack_get_buffer(b);
  108345. }
  108346. /* Self test of the bitwise routines; everything else is based on
  108347. them, so they damned well better be solid. */
  108348. #ifdef _V_SELFTEST
  108349. #include <stdio.h>
  108350. static int ilog(unsigned int v){
  108351. int ret=0;
  108352. while(v){
  108353. ret++;
  108354. v>>=1;
  108355. }
  108356. return(ret);
  108357. }
  108358. oggpack_buffer o;
  108359. oggpack_buffer r;
  108360. void report(char *in){
  108361. fprintf(stderr,"%s",in);
  108362. exit(1);
  108363. }
  108364. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108365. long bytes,i;
  108366. unsigned char *buffer;
  108367. oggpack_reset(&o);
  108368. for(i=0;i<vals;i++)
  108369. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108370. buffer=oggpack_get_buffer(&o);
  108371. bytes=oggpack_bytes(&o);
  108372. if(bytes!=compsize)report("wrong number of bytes!\n");
  108373. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108374. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108375. report("wrote incorrect value!\n");
  108376. }
  108377. oggpack_readinit(&r,buffer,bytes);
  108378. for(i=0;i<vals;i++){
  108379. int tbit=bits?bits:ilog(b[i]);
  108380. if(oggpack_look(&r,tbit)==-1)
  108381. report("out of data!\n");
  108382. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108383. report("looked at incorrect value!\n");
  108384. if(tbit==1)
  108385. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108386. report("looked at single bit incorrect value!\n");
  108387. if(tbit==1){
  108388. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108389. report("read incorrect single bit value!\n");
  108390. }else{
  108391. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108392. report("read incorrect value!\n");
  108393. }
  108394. }
  108395. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108396. }
  108397. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108398. long bytes,i;
  108399. unsigned char *buffer;
  108400. oggpackB_reset(&o);
  108401. for(i=0;i<vals;i++)
  108402. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108403. buffer=oggpackB_get_buffer(&o);
  108404. bytes=oggpackB_bytes(&o);
  108405. if(bytes!=compsize)report("wrong number of bytes!\n");
  108406. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108407. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108408. report("wrote incorrect value!\n");
  108409. }
  108410. oggpackB_readinit(&r,buffer,bytes);
  108411. for(i=0;i<vals;i++){
  108412. int tbit=bits?bits:ilog(b[i]);
  108413. if(oggpackB_look(&r,tbit)==-1)
  108414. report("out of data!\n");
  108415. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108416. report("looked at incorrect value!\n");
  108417. if(tbit==1)
  108418. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108419. report("looked at single bit incorrect value!\n");
  108420. if(tbit==1){
  108421. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108422. report("read incorrect single bit value!\n");
  108423. }else{
  108424. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108425. report("read incorrect value!\n");
  108426. }
  108427. }
  108428. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108429. }
  108430. int main(void){
  108431. unsigned char *buffer;
  108432. long bytes,i;
  108433. static unsigned long testbuffer1[]=
  108434. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108435. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108436. int test1size=43;
  108437. static unsigned long testbuffer2[]=
  108438. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108439. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108440. 85525151,0,12321,1,349528352};
  108441. int test2size=21;
  108442. static unsigned long testbuffer3[]=
  108443. {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,
  108444. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108445. int test3size=56;
  108446. static unsigned long large[]=
  108447. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108448. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108449. 85525151,0,12321,1,2146528352};
  108450. int onesize=33;
  108451. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108452. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108453. 223,4};
  108454. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108455. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108456. 245,251,128};
  108457. int twosize=6;
  108458. static int two[6]={61,255,255,251,231,29};
  108459. static int twoB[6]={247,63,255,253,249,120};
  108460. int threesize=54;
  108461. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108462. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108463. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108464. 100,52,4,14,18,86,77,1};
  108465. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108466. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108467. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108468. 200,20,254,4,58,106,176,144,0};
  108469. int foursize=38;
  108470. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108471. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108472. 28,2,133,0,1};
  108473. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108474. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108475. 129,10,4,32};
  108476. int fivesize=45;
  108477. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108478. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108479. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108480. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108481. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108482. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108483. int sixsize=7;
  108484. static int six[7]={17,177,170,242,169,19,148};
  108485. static int sixB[7]={136,141,85,79,149,200,41};
  108486. /* Test read/write together */
  108487. /* Later we test against pregenerated bitstreams */
  108488. oggpack_writeinit(&o);
  108489. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108490. cliptest(testbuffer1,test1size,0,one,onesize);
  108491. fprintf(stderr,"ok.");
  108492. fprintf(stderr,"\nNull bit call (LSb): ");
  108493. cliptest(testbuffer3,test3size,0,two,twosize);
  108494. fprintf(stderr,"ok.");
  108495. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108496. cliptest(testbuffer2,test2size,0,three,threesize);
  108497. fprintf(stderr,"ok.");
  108498. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108499. oggpack_reset(&o);
  108500. for(i=0;i<test2size;i++)
  108501. oggpack_write(&o,large[i],32);
  108502. buffer=oggpack_get_buffer(&o);
  108503. bytes=oggpack_bytes(&o);
  108504. oggpack_readinit(&r,buffer,bytes);
  108505. for(i=0;i<test2size;i++){
  108506. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108507. if(oggpack_look(&r,32)!=large[i]){
  108508. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108509. oggpack_look(&r,32),large[i]);
  108510. report("read incorrect value!\n");
  108511. }
  108512. oggpack_adv(&r,32);
  108513. }
  108514. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108515. fprintf(stderr,"ok.");
  108516. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108517. cliptest(testbuffer1,test1size,7,four,foursize);
  108518. fprintf(stderr,"ok.");
  108519. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108520. cliptest(testbuffer2,test2size,17,five,fivesize);
  108521. fprintf(stderr,"ok.");
  108522. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108523. cliptest(testbuffer3,test3size,1,six,sixsize);
  108524. fprintf(stderr,"ok.");
  108525. fprintf(stderr,"\nTesting read past end (LSb): ");
  108526. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108527. for(i=0;i<64;i++){
  108528. if(oggpack_read(&r,1)!=0){
  108529. fprintf(stderr,"failed; got -1 prematurely.\n");
  108530. exit(1);
  108531. }
  108532. }
  108533. if(oggpack_look(&r,1)!=-1 ||
  108534. oggpack_read(&r,1)!=-1){
  108535. fprintf(stderr,"failed; read past end without -1.\n");
  108536. exit(1);
  108537. }
  108538. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108539. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108540. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108541. exit(1);
  108542. }
  108543. if(oggpack_look(&r,18)!=0 ||
  108544. oggpack_look(&r,18)!=0){
  108545. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108546. exit(1);
  108547. }
  108548. if(oggpack_look(&r,19)!=-1 ||
  108549. oggpack_look(&r,19)!=-1){
  108550. fprintf(stderr,"failed; read past end without -1.\n");
  108551. exit(1);
  108552. }
  108553. if(oggpack_look(&r,32)!=-1 ||
  108554. oggpack_look(&r,32)!=-1){
  108555. fprintf(stderr,"failed; read past end without -1.\n");
  108556. exit(1);
  108557. }
  108558. oggpack_writeclear(&o);
  108559. fprintf(stderr,"ok.\n");
  108560. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108561. /* Test read/write together */
  108562. /* Later we test against pregenerated bitstreams */
  108563. oggpackB_writeinit(&o);
  108564. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108565. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108566. fprintf(stderr,"ok.");
  108567. fprintf(stderr,"\nNull bit call (MSb): ");
  108568. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108569. fprintf(stderr,"ok.");
  108570. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108571. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108572. fprintf(stderr,"ok.");
  108573. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108574. oggpackB_reset(&o);
  108575. for(i=0;i<test2size;i++)
  108576. oggpackB_write(&o,large[i],32);
  108577. buffer=oggpackB_get_buffer(&o);
  108578. bytes=oggpackB_bytes(&o);
  108579. oggpackB_readinit(&r,buffer,bytes);
  108580. for(i=0;i<test2size;i++){
  108581. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108582. if(oggpackB_look(&r,32)!=large[i]){
  108583. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108584. oggpackB_look(&r,32),large[i]);
  108585. report("read incorrect value!\n");
  108586. }
  108587. oggpackB_adv(&r,32);
  108588. }
  108589. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108590. fprintf(stderr,"ok.");
  108591. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108592. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108593. fprintf(stderr,"ok.");
  108594. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108595. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108596. fprintf(stderr,"ok.");
  108597. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108598. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108599. fprintf(stderr,"ok.");
  108600. fprintf(stderr,"\nTesting read past end (MSb): ");
  108601. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108602. for(i=0;i<64;i++){
  108603. if(oggpackB_read(&r,1)!=0){
  108604. fprintf(stderr,"failed; got -1 prematurely.\n");
  108605. exit(1);
  108606. }
  108607. }
  108608. if(oggpackB_look(&r,1)!=-1 ||
  108609. oggpackB_read(&r,1)!=-1){
  108610. fprintf(stderr,"failed; read past end without -1.\n");
  108611. exit(1);
  108612. }
  108613. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108614. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108615. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108616. exit(1);
  108617. }
  108618. if(oggpackB_look(&r,18)!=0 ||
  108619. oggpackB_look(&r,18)!=0){
  108620. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108621. exit(1);
  108622. }
  108623. if(oggpackB_look(&r,19)!=-1 ||
  108624. oggpackB_look(&r,19)!=-1){
  108625. fprintf(stderr,"failed; read past end without -1.\n");
  108626. exit(1);
  108627. }
  108628. if(oggpackB_look(&r,32)!=-1 ||
  108629. oggpackB_look(&r,32)!=-1){
  108630. fprintf(stderr,"failed; read past end without -1.\n");
  108631. exit(1);
  108632. }
  108633. oggpackB_writeclear(&o);
  108634. fprintf(stderr,"ok.\n\n");
  108635. return(0);
  108636. }
  108637. #endif /* _V_SELFTEST */
  108638. #undef BUFFER_INCREMENT
  108639. #endif
  108640. /*** End of inlined file: bitwise.c ***/
  108641. /*** Start of inlined file: framing.c ***/
  108642. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108643. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108644. // tasks..
  108645. #if JUCE_MSVC
  108646. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108647. #endif
  108648. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108649. #if JUCE_USE_OGGVORBIS
  108650. #include <stdlib.h>
  108651. #include <string.h>
  108652. /* A complete description of Ogg framing exists in docs/framing.html */
  108653. int ogg_page_version(ogg_page *og){
  108654. return((int)(og->header[4]));
  108655. }
  108656. int ogg_page_continued(ogg_page *og){
  108657. return((int)(og->header[5]&0x01));
  108658. }
  108659. int ogg_page_bos(ogg_page *og){
  108660. return((int)(og->header[5]&0x02));
  108661. }
  108662. int ogg_page_eos(ogg_page *og){
  108663. return((int)(og->header[5]&0x04));
  108664. }
  108665. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108666. unsigned char *page=og->header;
  108667. ogg_int64_t granulepos=page[13]&(0xff);
  108668. granulepos= (granulepos<<8)|(page[12]&0xff);
  108669. granulepos= (granulepos<<8)|(page[11]&0xff);
  108670. granulepos= (granulepos<<8)|(page[10]&0xff);
  108671. granulepos= (granulepos<<8)|(page[9]&0xff);
  108672. granulepos= (granulepos<<8)|(page[8]&0xff);
  108673. granulepos= (granulepos<<8)|(page[7]&0xff);
  108674. granulepos= (granulepos<<8)|(page[6]&0xff);
  108675. return(granulepos);
  108676. }
  108677. int ogg_page_serialno(ogg_page *og){
  108678. return(og->header[14] |
  108679. (og->header[15]<<8) |
  108680. (og->header[16]<<16) |
  108681. (og->header[17]<<24));
  108682. }
  108683. long ogg_page_pageno(ogg_page *og){
  108684. return(og->header[18] |
  108685. (og->header[19]<<8) |
  108686. (og->header[20]<<16) |
  108687. (og->header[21]<<24));
  108688. }
  108689. /* returns the number of packets that are completed on this page (if
  108690. the leading packet is begun on a previous page, but ends on this
  108691. page, it's counted */
  108692. /* NOTE:
  108693. If a page consists of a packet begun on a previous page, and a new
  108694. packet begun (but not completed) on this page, the return will be:
  108695. ogg_page_packets(page) ==1,
  108696. ogg_page_continued(page) !=0
  108697. If a page happens to be a single packet that was begun on a
  108698. previous page, and spans to the next page (in the case of a three or
  108699. more page packet), the return will be:
  108700. ogg_page_packets(page) ==0,
  108701. ogg_page_continued(page) !=0
  108702. */
  108703. int ogg_page_packets(ogg_page *og){
  108704. int i,n=og->header[26],count=0;
  108705. for(i=0;i<n;i++)
  108706. if(og->header[27+i]<255)count++;
  108707. return(count);
  108708. }
  108709. #if 0
  108710. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108711. use the static init below) */
  108712. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108713. int i;
  108714. unsigned long r;
  108715. r = index << 24;
  108716. for (i=0; i<8; i++)
  108717. if (r & 0x80000000UL)
  108718. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108719. polynomial, although we use an
  108720. unreflected alg and an init/final
  108721. of 0, not 0xffffffff */
  108722. else
  108723. r<<=1;
  108724. return (r & 0xffffffffUL);
  108725. }
  108726. #endif
  108727. static const ogg_uint32_t crc_lookup[256]={
  108728. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108729. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108730. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108731. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108732. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108733. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108734. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108735. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108736. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108737. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108738. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108739. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108740. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108741. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108742. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108743. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108744. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108745. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108746. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108747. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108748. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108749. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108750. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108751. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108752. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108753. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108754. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108755. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108756. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108757. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108758. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108759. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108760. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108761. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108762. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108763. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108764. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108765. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108766. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108767. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108768. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108769. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108770. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108771. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108772. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108773. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108774. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108775. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108776. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108777. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108778. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108779. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108780. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108781. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108782. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108783. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108784. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108785. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108786. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108787. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108788. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108789. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108790. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108791. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108792. /* init the encode/decode logical stream state */
  108793. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108794. if(os){
  108795. memset(os,0,sizeof(*os));
  108796. os->body_storage=16*1024;
  108797. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108798. os->lacing_storage=1024;
  108799. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108800. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108801. os->serialno=serialno;
  108802. return(0);
  108803. }
  108804. return(-1);
  108805. }
  108806. /* _clear does not free os, only the non-flat storage within */
  108807. int ogg_stream_clear(ogg_stream_state *os){
  108808. if(os){
  108809. if(os->body_data)_ogg_free(os->body_data);
  108810. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108811. if(os->granule_vals)_ogg_free(os->granule_vals);
  108812. memset(os,0,sizeof(*os));
  108813. }
  108814. return(0);
  108815. }
  108816. int ogg_stream_destroy(ogg_stream_state *os){
  108817. if(os){
  108818. ogg_stream_clear(os);
  108819. _ogg_free(os);
  108820. }
  108821. return(0);
  108822. }
  108823. /* Helpers for ogg_stream_encode; this keeps the structure and
  108824. what's happening fairly clear */
  108825. static void _os_body_expand(ogg_stream_state *os,int needed){
  108826. if(os->body_storage<=os->body_fill+needed){
  108827. os->body_storage+=(needed+1024);
  108828. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108829. }
  108830. }
  108831. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108832. if(os->lacing_storage<=os->lacing_fill+needed){
  108833. os->lacing_storage+=(needed+32);
  108834. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108835. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108836. }
  108837. }
  108838. /* checksum the page */
  108839. /* Direct table CRC; note that this will be faster in the future if we
  108840. perform the checksum silmultaneously with other copies */
  108841. void ogg_page_checksum_set(ogg_page *og){
  108842. if(og){
  108843. ogg_uint32_t crc_reg=0;
  108844. int i;
  108845. /* safety; needed for API behavior, but not framing code */
  108846. og->header[22]=0;
  108847. og->header[23]=0;
  108848. og->header[24]=0;
  108849. og->header[25]=0;
  108850. for(i=0;i<og->header_len;i++)
  108851. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108852. for(i=0;i<og->body_len;i++)
  108853. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108854. og->header[22]=(unsigned char)(crc_reg&0xff);
  108855. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108856. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108857. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108858. }
  108859. }
  108860. /* submit data to the internal buffer of the framing engine */
  108861. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108862. int lacing_vals=op->bytes/255+1,i;
  108863. if(os->body_returned){
  108864. /* advance packet data according to the body_returned pointer. We
  108865. had to keep it around to return a pointer into the buffer last
  108866. call */
  108867. os->body_fill-=os->body_returned;
  108868. if(os->body_fill)
  108869. memmove(os->body_data,os->body_data+os->body_returned,
  108870. os->body_fill);
  108871. os->body_returned=0;
  108872. }
  108873. /* make sure we have the buffer storage */
  108874. _os_body_expand(os,op->bytes);
  108875. _os_lacing_expand(os,lacing_vals);
  108876. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108877. the liability of overly clean abstraction for the time being. It
  108878. will actually be fairly easy to eliminate the extra copy in the
  108879. future */
  108880. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108881. os->body_fill+=op->bytes;
  108882. /* Store lacing vals for this packet */
  108883. for(i=0;i<lacing_vals-1;i++){
  108884. os->lacing_vals[os->lacing_fill+i]=255;
  108885. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108886. }
  108887. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108888. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108889. /* flag the first segment as the beginning of the packet */
  108890. os->lacing_vals[os->lacing_fill]|= 0x100;
  108891. os->lacing_fill+=lacing_vals;
  108892. /* for the sake of completeness */
  108893. os->packetno++;
  108894. if(op->e_o_s)os->e_o_s=1;
  108895. return(0);
  108896. }
  108897. /* This will flush remaining packets into a page (returning nonzero),
  108898. even if there is not enough data to trigger a flush normally
  108899. (undersized page). If there are no packets or partial packets to
  108900. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108901. try to flush a normal sized page like ogg_stream_pageout; a call to
  108902. ogg_stream_flush does not guarantee that all packets have flushed.
  108903. Only a return value of 0 from ogg_stream_flush indicates all packet
  108904. data is flushed into pages.
  108905. since ogg_stream_flush will flush the last page in a stream even if
  108906. it's undersized, you almost certainly want to use ogg_stream_pageout
  108907. (and *not* ogg_stream_flush) unless you specifically need to flush
  108908. an page regardless of size in the middle of a stream. */
  108909. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108910. int i;
  108911. int vals=0;
  108912. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108913. int bytes=0;
  108914. long acc=0;
  108915. ogg_int64_t granule_pos=-1;
  108916. if(maxvals==0)return(0);
  108917. /* construct a page */
  108918. /* decide how many segments to include */
  108919. /* If this is the initial header case, the first page must only include
  108920. the initial header packet */
  108921. if(os->b_o_s==0){ /* 'initial header page' case */
  108922. granule_pos=0;
  108923. for(vals=0;vals<maxvals;vals++){
  108924. if((os->lacing_vals[vals]&0x0ff)<255){
  108925. vals++;
  108926. break;
  108927. }
  108928. }
  108929. }else{
  108930. for(vals=0;vals<maxvals;vals++){
  108931. if(acc>4096)break;
  108932. acc+=os->lacing_vals[vals]&0x0ff;
  108933. if((os->lacing_vals[vals]&0xff)<255)
  108934. granule_pos=os->granule_vals[vals];
  108935. }
  108936. }
  108937. /* construct the header in temp storage */
  108938. memcpy(os->header,"OggS",4);
  108939. /* stream structure version */
  108940. os->header[4]=0x00;
  108941. /* continued packet flag? */
  108942. os->header[5]=0x00;
  108943. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108944. /* first page flag? */
  108945. if(os->b_o_s==0)os->header[5]|=0x02;
  108946. /* last page flag? */
  108947. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108948. os->b_o_s=1;
  108949. /* 64 bits of PCM position */
  108950. for(i=6;i<14;i++){
  108951. os->header[i]=(unsigned char)(granule_pos&0xff);
  108952. granule_pos>>=8;
  108953. }
  108954. /* 32 bits of stream serial number */
  108955. {
  108956. long serialno=os->serialno;
  108957. for(i=14;i<18;i++){
  108958. os->header[i]=(unsigned char)(serialno&0xff);
  108959. serialno>>=8;
  108960. }
  108961. }
  108962. /* 32 bits of page counter (we have both counter and page header
  108963. because this val can roll over) */
  108964. if(os->pageno==-1)os->pageno=0; /* because someone called
  108965. stream_reset; this would be a
  108966. strange thing to do in an
  108967. encode stream, but it has
  108968. plausible uses */
  108969. {
  108970. long pageno=os->pageno++;
  108971. for(i=18;i<22;i++){
  108972. os->header[i]=(unsigned char)(pageno&0xff);
  108973. pageno>>=8;
  108974. }
  108975. }
  108976. /* zero for computation; filled in later */
  108977. os->header[22]=0;
  108978. os->header[23]=0;
  108979. os->header[24]=0;
  108980. os->header[25]=0;
  108981. /* segment table */
  108982. os->header[26]=(unsigned char)(vals&0xff);
  108983. for(i=0;i<vals;i++)
  108984. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108985. /* set pointers in the ogg_page struct */
  108986. og->header=os->header;
  108987. og->header_len=os->header_fill=vals+27;
  108988. og->body=os->body_data+os->body_returned;
  108989. og->body_len=bytes;
  108990. /* advance the lacing data and set the body_returned pointer */
  108991. os->lacing_fill-=vals;
  108992. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108993. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108994. os->body_returned+=bytes;
  108995. /* calculate the checksum */
  108996. ogg_page_checksum_set(og);
  108997. /* done */
  108998. return(1);
  108999. }
  109000. /* This constructs pages from buffered packet segments. The pointers
  109001. returned are to static buffers; do not free. The returned buffers are
  109002. good only until the next call (using the same ogg_stream_state) */
  109003. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  109004. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  109005. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  109006. os->lacing_fill>=255 || /* 'segment table full' case */
  109007. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  109008. return(ogg_stream_flush(os,og));
  109009. }
  109010. /* not enough data to construct a page and not end of stream */
  109011. return(0);
  109012. }
  109013. int ogg_stream_eos(ogg_stream_state *os){
  109014. return os->e_o_s;
  109015. }
  109016. /* DECODING PRIMITIVES: packet streaming layer **********************/
  109017. /* This has two layers to place more of the multi-serialno and paging
  109018. control in the application's hands. First, we expose a data buffer
  109019. using ogg_sync_buffer(). The app either copies into the
  109020. buffer, or passes it directly to read(), etc. We then call
  109021. ogg_sync_wrote() to tell how many bytes we just added.
  109022. Pages are returned (pointers into the buffer in ogg_sync_state)
  109023. by ogg_sync_pageout(). The page is then submitted to
  109024. ogg_stream_pagein() along with the appropriate
  109025. ogg_stream_state* (ie, matching serialno). We then get raw
  109026. packets out calling ogg_stream_packetout() with a
  109027. ogg_stream_state. */
  109028. /* initialize the struct to a known state */
  109029. int ogg_sync_init(ogg_sync_state *oy){
  109030. if(oy){
  109031. memset(oy,0,sizeof(*oy));
  109032. }
  109033. return(0);
  109034. }
  109035. /* clear non-flat storage within */
  109036. int ogg_sync_clear(ogg_sync_state *oy){
  109037. if(oy){
  109038. if(oy->data)_ogg_free(oy->data);
  109039. ogg_sync_init(oy);
  109040. }
  109041. return(0);
  109042. }
  109043. int ogg_sync_destroy(ogg_sync_state *oy){
  109044. if(oy){
  109045. ogg_sync_clear(oy);
  109046. _ogg_free(oy);
  109047. }
  109048. return(0);
  109049. }
  109050. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  109051. /* first, clear out any space that has been previously returned */
  109052. if(oy->returned){
  109053. oy->fill-=oy->returned;
  109054. if(oy->fill>0)
  109055. memmove(oy->data,oy->data+oy->returned,oy->fill);
  109056. oy->returned=0;
  109057. }
  109058. if(size>oy->storage-oy->fill){
  109059. /* We need to extend the internal buffer */
  109060. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  109061. if(oy->data)
  109062. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109063. else
  109064. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109065. oy->storage=newsize;
  109066. }
  109067. /* expose a segment at least as large as requested at the fill mark */
  109068. return((char *)oy->data+oy->fill);
  109069. }
  109070. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109071. if(oy->fill+bytes>oy->storage)return(-1);
  109072. oy->fill+=bytes;
  109073. return(0);
  109074. }
  109075. /* sync the stream. This is meant to be useful for finding page
  109076. boundaries.
  109077. return values for this:
  109078. -n) skipped n bytes
  109079. 0) page not ready; more data (no bytes skipped)
  109080. n) page synced at current location; page length n bytes
  109081. */
  109082. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109083. unsigned char *page=oy->data+oy->returned;
  109084. unsigned char *next;
  109085. long bytes=oy->fill-oy->returned;
  109086. if(oy->headerbytes==0){
  109087. int headerbytes,i;
  109088. if(bytes<27)return(0); /* not enough for a header */
  109089. /* verify capture pattern */
  109090. if(memcmp(page,"OggS",4))goto sync_fail;
  109091. headerbytes=page[26]+27;
  109092. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109093. /* count up body length in the segment table */
  109094. for(i=0;i<page[26];i++)
  109095. oy->bodybytes+=page[27+i];
  109096. oy->headerbytes=headerbytes;
  109097. }
  109098. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109099. /* The whole test page is buffered. Verify the checksum */
  109100. {
  109101. /* Grab the checksum bytes, set the header field to zero */
  109102. char chksum[4];
  109103. ogg_page log;
  109104. memcpy(chksum,page+22,4);
  109105. memset(page+22,0,4);
  109106. /* set up a temp page struct and recompute the checksum */
  109107. log.header=page;
  109108. log.header_len=oy->headerbytes;
  109109. log.body=page+oy->headerbytes;
  109110. log.body_len=oy->bodybytes;
  109111. ogg_page_checksum_set(&log);
  109112. /* Compare */
  109113. if(memcmp(chksum,page+22,4)){
  109114. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109115. at all) */
  109116. /* replace the computed checksum with the one actually read in */
  109117. memcpy(page+22,chksum,4);
  109118. /* Bad checksum. Lose sync */
  109119. goto sync_fail;
  109120. }
  109121. }
  109122. /* yes, have a whole page all ready to go */
  109123. {
  109124. unsigned char *page=oy->data+oy->returned;
  109125. long bytes;
  109126. if(og){
  109127. og->header=page;
  109128. og->header_len=oy->headerbytes;
  109129. og->body=page+oy->headerbytes;
  109130. og->body_len=oy->bodybytes;
  109131. }
  109132. oy->unsynced=0;
  109133. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109134. oy->headerbytes=0;
  109135. oy->bodybytes=0;
  109136. return(bytes);
  109137. }
  109138. sync_fail:
  109139. oy->headerbytes=0;
  109140. oy->bodybytes=0;
  109141. /* search for possible capture */
  109142. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109143. if(!next)
  109144. next=oy->data+oy->fill;
  109145. oy->returned=next-oy->data;
  109146. return(-(next-page));
  109147. }
  109148. /* sync the stream and get a page. Keep trying until we find a page.
  109149. Supress 'sync errors' after reporting the first.
  109150. return values:
  109151. -1) recapture (hole in data)
  109152. 0) need more data
  109153. 1) page returned
  109154. Returns pointers into buffered data; invalidated by next call to
  109155. _stream, _clear, _init, or _buffer */
  109156. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109157. /* all we need to do is verify a page at the head of the stream
  109158. buffer. If it doesn't verify, we look for the next potential
  109159. frame */
  109160. for(;;){
  109161. long ret=ogg_sync_pageseek(oy,og);
  109162. if(ret>0){
  109163. /* have a page */
  109164. return(1);
  109165. }
  109166. if(ret==0){
  109167. /* need more data */
  109168. return(0);
  109169. }
  109170. /* head did not start a synced page... skipped some bytes */
  109171. if(!oy->unsynced){
  109172. oy->unsynced=1;
  109173. return(-1);
  109174. }
  109175. /* loop. keep looking */
  109176. }
  109177. }
  109178. /* add the incoming page to the stream state; we decompose the page
  109179. into packet segments here as well. */
  109180. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109181. unsigned char *header=og->header;
  109182. unsigned char *body=og->body;
  109183. long bodysize=og->body_len;
  109184. int segptr=0;
  109185. int version=ogg_page_version(og);
  109186. int continued=ogg_page_continued(og);
  109187. int bos=ogg_page_bos(og);
  109188. int eos=ogg_page_eos(og);
  109189. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109190. int serialno=ogg_page_serialno(og);
  109191. long pageno=ogg_page_pageno(og);
  109192. int segments=header[26];
  109193. /* clean up 'returned data' */
  109194. {
  109195. long lr=os->lacing_returned;
  109196. long br=os->body_returned;
  109197. /* body data */
  109198. if(br){
  109199. os->body_fill-=br;
  109200. if(os->body_fill)
  109201. memmove(os->body_data,os->body_data+br,os->body_fill);
  109202. os->body_returned=0;
  109203. }
  109204. if(lr){
  109205. /* segment table */
  109206. if(os->lacing_fill-lr){
  109207. memmove(os->lacing_vals,os->lacing_vals+lr,
  109208. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109209. memmove(os->granule_vals,os->granule_vals+lr,
  109210. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109211. }
  109212. os->lacing_fill-=lr;
  109213. os->lacing_packet-=lr;
  109214. os->lacing_returned=0;
  109215. }
  109216. }
  109217. /* check the serial number */
  109218. if(serialno!=os->serialno)return(-1);
  109219. if(version>0)return(-1);
  109220. _os_lacing_expand(os,segments+1);
  109221. /* are we in sequence? */
  109222. if(pageno!=os->pageno){
  109223. int i;
  109224. /* unroll previous partial packet (if any) */
  109225. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109226. os->body_fill-=os->lacing_vals[i]&0xff;
  109227. os->lacing_fill=os->lacing_packet;
  109228. /* make a note of dropped data in segment table */
  109229. if(os->pageno!=-1){
  109230. os->lacing_vals[os->lacing_fill++]=0x400;
  109231. os->lacing_packet++;
  109232. }
  109233. }
  109234. /* are we a 'continued packet' page? If so, we may need to skip
  109235. some segments */
  109236. if(continued){
  109237. if(os->lacing_fill<1 ||
  109238. os->lacing_vals[os->lacing_fill-1]==0x400){
  109239. bos=0;
  109240. for(;segptr<segments;segptr++){
  109241. int val=header[27+segptr];
  109242. body+=val;
  109243. bodysize-=val;
  109244. if(val<255){
  109245. segptr++;
  109246. break;
  109247. }
  109248. }
  109249. }
  109250. }
  109251. if(bodysize){
  109252. _os_body_expand(os,bodysize);
  109253. memcpy(os->body_data+os->body_fill,body,bodysize);
  109254. os->body_fill+=bodysize;
  109255. }
  109256. {
  109257. int saved=-1;
  109258. while(segptr<segments){
  109259. int val=header[27+segptr];
  109260. os->lacing_vals[os->lacing_fill]=val;
  109261. os->granule_vals[os->lacing_fill]=-1;
  109262. if(bos){
  109263. os->lacing_vals[os->lacing_fill]|=0x100;
  109264. bos=0;
  109265. }
  109266. if(val<255)saved=os->lacing_fill;
  109267. os->lacing_fill++;
  109268. segptr++;
  109269. if(val<255)os->lacing_packet=os->lacing_fill;
  109270. }
  109271. /* set the granulepos on the last granuleval of the last full packet */
  109272. if(saved!=-1){
  109273. os->granule_vals[saved]=granulepos;
  109274. }
  109275. }
  109276. if(eos){
  109277. os->e_o_s=1;
  109278. if(os->lacing_fill>0)
  109279. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109280. }
  109281. os->pageno=pageno+1;
  109282. return(0);
  109283. }
  109284. /* clear things to an initial state. Good to call, eg, before seeking */
  109285. int ogg_sync_reset(ogg_sync_state *oy){
  109286. oy->fill=0;
  109287. oy->returned=0;
  109288. oy->unsynced=0;
  109289. oy->headerbytes=0;
  109290. oy->bodybytes=0;
  109291. return(0);
  109292. }
  109293. int ogg_stream_reset(ogg_stream_state *os){
  109294. os->body_fill=0;
  109295. os->body_returned=0;
  109296. os->lacing_fill=0;
  109297. os->lacing_packet=0;
  109298. os->lacing_returned=0;
  109299. os->header_fill=0;
  109300. os->e_o_s=0;
  109301. os->b_o_s=0;
  109302. os->pageno=-1;
  109303. os->packetno=0;
  109304. os->granulepos=0;
  109305. return(0);
  109306. }
  109307. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109308. ogg_stream_reset(os);
  109309. os->serialno=serialno;
  109310. return(0);
  109311. }
  109312. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109313. /* The last part of decode. We have the stream broken into packet
  109314. segments. Now we need to group them into packets (or return the
  109315. out of sync markers) */
  109316. int ptr=os->lacing_returned;
  109317. if(os->lacing_packet<=ptr)return(0);
  109318. if(os->lacing_vals[ptr]&0x400){
  109319. /* we need to tell the codec there's a gap; it might need to
  109320. handle previous packet dependencies. */
  109321. os->lacing_returned++;
  109322. os->packetno++;
  109323. return(-1);
  109324. }
  109325. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109326. to ask if there's a whole packet
  109327. waiting */
  109328. /* Gather the whole packet. We'll have no holes or a partial packet */
  109329. {
  109330. int size=os->lacing_vals[ptr]&0xff;
  109331. int bytes=size;
  109332. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109333. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109334. while(size==255){
  109335. int val=os->lacing_vals[++ptr];
  109336. size=val&0xff;
  109337. if(val&0x200)eos=0x200;
  109338. bytes+=size;
  109339. }
  109340. if(op){
  109341. op->e_o_s=eos;
  109342. op->b_o_s=bos;
  109343. op->packet=os->body_data+os->body_returned;
  109344. op->packetno=os->packetno;
  109345. op->granulepos=os->granule_vals[ptr];
  109346. op->bytes=bytes;
  109347. }
  109348. if(adv){
  109349. os->body_returned+=bytes;
  109350. os->lacing_returned=ptr+1;
  109351. os->packetno++;
  109352. }
  109353. }
  109354. return(1);
  109355. }
  109356. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109357. return _packetout(os,op,1);
  109358. }
  109359. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109360. return _packetout(os,op,0);
  109361. }
  109362. void ogg_packet_clear(ogg_packet *op) {
  109363. _ogg_free(op->packet);
  109364. memset(op, 0, sizeof(*op));
  109365. }
  109366. #ifdef _V_SELFTEST
  109367. #include <stdio.h>
  109368. ogg_stream_state os_en, os_de;
  109369. ogg_sync_state oy;
  109370. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109371. long j;
  109372. static int sequence=0;
  109373. static int lastno=0;
  109374. if(op->bytes!=len){
  109375. fprintf(stderr,"incorrect packet length!\n");
  109376. exit(1);
  109377. }
  109378. if(op->granulepos!=pos){
  109379. fprintf(stderr,"incorrect packet position!\n");
  109380. exit(1);
  109381. }
  109382. /* packet number just follows sequence/gap; adjust the input number
  109383. for that */
  109384. if(no==0){
  109385. sequence=0;
  109386. }else{
  109387. sequence++;
  109388. if(no>lastno+1)
  109389. sequence++;
  109390. }
  109391. lastno=no;
  109392. if(op->packetno!=sequence){
  109393. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109394. (long)(op->packetno),sequence);
  109395. exit(1);
  109396. }
  109397. /* Test data */
  109398. for(j=0;j<op->bytes;j++)
  109399. if(op->packet[j]!=((j+no)&0xff)){
  109400. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109401. j,op->packet[j],(j+no)&0xff);
  109402. exit(1);
  109403. }
  109404. }
  109405. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109406. long j;
  109407. /* Test data */
  109408. for(j=0;j<og->body_len;j++)
  109409. if(og->body[j]!=data[j]){
  109410. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109411. j,data[j],og->body[j]);
  109412. exit(1);
  109413. }
  109414. /* Test header */
  109415. for(j=0;j<og->header_len;j++){
  109416. if(og->header[j]!=header[j]){
  109417. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109418. for(j=0;j<header[26]+27;j++)
  109419. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109420. fprintf(stderr,"\n");
  109421. exit(1);
  109422. }
  109423. }
  109424. if(og->header_len!=header[26]+27){
  109425. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109426. og->header_len,header[26]+27);
  109427. exit(1);
  109428. }
  109429. }
  109430. void print_header(ogg_page *og){
  109431. int j;
  109432. fprintf(stderr,"\nHEADER:\n");
  109433. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109434. og->header[0],og->header[1],og->header[2],og->header[3],
  109435. (int)og->header[4],(int)og->header[5]);
  109436. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109437. (og->header[9]<<24)|(og->header[8]<<16)|
  109438. (og->header[7]<<8)|og->header[6],
  109439. (og->header[17]<<24)|(og->header[16]<<16)|
  109440. (og->header[15]<<8)|og->header[14],
  109441. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109442. (og->header[19]<<8)|og->header[18]);
  109443. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109444. (int)og->header[22],(int)og->header[23],
  109445. (int)og->header[24],(int)og->header[25],
  109446. (int)og->header[26]);
  109447. for(j=27;j<og->header_len;j++)
  109448. fprintf(stderr,"%d ",(int)og->header[j]);
  109449. fprintf(stderr,")\n\n");
  109450. }
  109451. void copy_page(ogg_page *og){
  109452. unsigned char *temp=_ogg_malloc(og->header_len);
  109453. memcpy(temp,og->header,og->header_len);
  109454. og->header=temp;
  109455. temp=_ogg_malloc(og->body_len);
  109456. memcpy(temp,og->body,og->body_len);
  109457. og->body=temp;
  109458. }
  109459. void free_page(ogg_page *og){
  109460. _ogg_free (og->header);
  109461. _ogg_free (og->body);
  109462. }
  109463. void error(void){
  109464. fprintf(stderr,"error!\n");
  109465. exit(1);
  109466. }
  109467. /* 17 only */
  109468. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109469. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109470. 0x01,0x02,0x03,0x04,0,0,0,0,
  109471. 0x15,0xed,0xec,0x91,
  109472. 1,
  109473. 17};
  109474. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109475. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109476. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109477. 0x01,0x02,0x03,0x04,0,0,0,0,
  109478. 0x59,0x10,0x6c,0x2c,
  109479. 1,
  109480. 17};
  109481. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109482. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109483. 0x01,0x02,0x03,0x04,1,0,0,0,
  109484. 0x89,0x33,0x85,0xce,
  109485. 13,
  109486. 254,255,0,255,1,255,245,255,255,0,
  109487. 255,255,90};
  109488. /* nil packets; beginning,middle,end */
  109489. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109490. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109491. 0x01,0x02,0x03,0x04,0,0,0,0,
  109492. 0xff,0x7b,0x23,0x17,
  109493. 1,
  109494. 0};
  109495. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109496. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109497. 0x01,0x02,0x03,0x04,1,0,0,0,
  109498. 0x5c,0x3f,0x66,0xcb,
  109499. 17,
  109500. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109501. 255,255,90,0};
  109502. /* large initial packet */
  109503. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109504. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109505. 0x01,0x02,0x03,0x04,0,0,0,0,
  109506. 0x01,0x27,0x31,0xaa,
  109507. 18,
  109508. 255,255,255,255,255,255,255,255,
  109509. 255,255,255,255,255,255,255,255,255,10};
  109510. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109511. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109512. 0x01,0x02,0x03,0x04,1,0,0,0,
  109513. 0x7f,0x4e,0x8a,0xd2,
  109514. 4,
  109515. 255,4,255,0};
  109516. /* continuing packet test */
  109517. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109518. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109519. 0x01,0x02,0x03,0x04,0,0,0,0,
  109520. 0xff,0x7b,0x23,0x17,
  109521. 1,
  109522. 0};
  109523. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109524. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109525. 0x01,0x02,0x03,0x04,1,0,0,0,
  109526. 0x54,0x05,0x51,0xc8,
  109527. 17,
  109528. 255,255,255,255,255,255,255,255,
  109529. 255,255,255,255,255,255,255,255,255};
  109530. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109531. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109532. 0x01,0x02,0x03,0x04,2,0,0,0,
  109533. 0xc8,0xc3,0xcb,0xed,
  109534. 5,
  109535. 10,255,4,255,0};
  109536. /* page with the 255 segment limit */
  109537. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109538. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109539. 0x01,0x02,0x03,0x04,0,0,0,0,
  109540. 0xff,0x7b,0x23,0x17,
  109541. 1,
  109542. 0};
  109543. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109544. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109545. 0x01,0x02,0x03,0x04,1,0,0,0,
  109546. 0xed,0x2a,0x2e,0xa7,
  109547. 255,
  109548. 10,10,10,10,10,10,10,10,
  109549. 10,10,10,10,10,10,10,10,
  109550. 10,10,10,10,10,10,10,10,
  109551. 10,10,10,10,10,10,10,10,
  109552. 10,10,10,10,10,10,10,10,
  109553. 10,10,10,10,10,10,10,10,
  109554. 10,10,10,10,10,10,10,10,
  109555. 10,10,10,10,10,10,10,10,
  109556. 10,10,10,10,10,10,10,10,
  109557. 10,10,10,10,10,10,10,10,
  109558. 10,10,10,10,10,10,10,10,
  109559. 10,10,10,10,10,10,10,10,
  109560. 10,10,10,10,10,10,10,10,
  109561. 10,10,10,10,10,10,10,10,
  109562. 10,10,10,10,10,10,10,10,
  109563. 10,10,10,10,10,10,10,10,
  109564. 10,10,10,10,10,10,10,10,
  109565. 10,10,10,10,10,10,10,10,
  109566. 10,10,10,10,10,10,10,10,
  109567. 10,10,10,10,10,10,10,10,
  109568. 10,10,10,10,10,10,10,10,
  109569. 10,10,10,10,10,10,10,10,
  109570. 10,10,10,10,10,10,10,10,
  109571. 10,10,10,10,10,10,10,10,
  109572. 10,10,10,10,10,10,10,10,
  109573. 10,10,10,10,10,10,10,10,
  109574. 10,10,10,10,10,10,10,10,
  109575. 10,10,10,10,10,10,10,10,
  109576. 10,10,10,10,10,10,10,10,
  109577. 10,10,10,10,10,10,10,10,
  109578. 10,10,10,10,10,10,10,10,
  109579. 10,10,10,10,10,10,10};
  109580. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109581. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109582. 0x01,0x02,0x03,0x04,2,0,0,0,
  109583. 0x6c,0x3b,0x82,0x3d,
  109584. 1,
  109585. 50};
  109586. /* packet that overspans over an entire page */
  109587. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109588. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109589. 0x01,0x02,0x03,0x04,0,0,0,0,
  109590. 0xff,0x7b,0x23,0x17,
  109591. 1,
  109592. 0};
  109593. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109594. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109595. 0x01,0x02,0x03,0x04,1,0,0,0,
  109596. 0x3c,0xd9,0x4d,0x3f,
  109597. 17,
  109598. 100,255,255,255,255,255,255,255,255,
  109599. 255,255,255,255,255,255,255,255};
  109600. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109601. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109602. 0x01,0x02,0x03,0x04,2,0,0,0,
  109603. 0x01,0xd2,0xe5,0xe5,
  109604. 17,
  109605. 255,255,255,255,255,255,255,255,
  109606. 255,255,255,255,255,255,255,255,255};
  109607. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109608. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109609. 0x01,0x02,0x03,0x04,3,0,0,0,
  109610. 0xef,0xdd,0x88,0xde,
  109611. 7,
  109612. 255,255,75,255,4,255,0};
  109613. /* packet that overspans over an entire page */
  109614. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109615. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109616. 0x01,0x02,0x03,0x04,0,0,0,0,
  109617. 0xff,0x7b,0x23,0x17,
  109618. 1,
  109619. 0};
  109620. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109621. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109622. 0x01,0x02,0x03,0x04,1,0,0,0,
  109623. 0x3c,0xd9,0x4d,0x3f,
  109624. 17,
  109625. 100,255,255,255,255,255,255,255,255,
  109626. 255,255,255,255,255,255,255,255};
  109627. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109628. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109629. 0x01,0x02,0x03,0x04,2,0,0,0,
  109630. 0xd4,0xe0,0x60,0xe5,
  109631. 1,0};
  109632. void test_pack(const int *pl, const int **headers, int byteskip,
  109633. int pageskip, int packetskip){
  109634. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109635. long inptr=0;
  109636. long outptr=0;
  109637. long deptr=0;
  109638. long depacket=0;
  109639. long granule_pos=7,pageno=0;
  109640. int i,j,packets,pageout=pageskip;
  109641. int eosflag=0;
  109642. int bosflag=0;
  109643. int byteskipcount=0;
  109644. ogg_stream_reset(&os_en);
  109645. ogg_stream_reset(&os_de);
  109646. ogg_sync_reset(&oy);
  109647. for(packets=0;packets<packetskip;packets++)
  109648. depacket+=pl[packets];
  109649. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109650. for(i=0;i<packets;i++){
  109651. /* construct a test packet */
  109652. ogg_packet op;
  109653. int len=pl[i];
  109654. op.packet=data+inptr;
  109655. op.bytes=len;
  109656. op.e_o_s=(pl[i+1]<0?1:0);
  109657. op.granulepos=granule_pos;
  109658. granule_pos+=1024;
  109659. for(j=0;j<len;j++)data[inptr++]=i+j;
  109660. /* submit the test packet */
  109661. ogg_stream_packetin(&os_en,&op);
  109662. /* retrieve any finished pages */
  109663. {
  109664. ogg_page og;
  109665. while(ogg_stream_pageout(&os_en,&og)){
  109666. /* We have a page. Check it carefully */
  109667. fprintf(stderr,"%ld, ",pageno);
  109668. if(headers[pageno]==NULL){
  109669. fprintf(stderr,"coded too many pages!\n");
  109670. exit(1);
  109671. }
  109672. check_page(data+outptr,headers[pageno],&og);
  109673. outptr+=og.body_len;
  109674. pageno++;
  109675. if(pageskip){
  109676. bosflag=1;
  109677. pageskip--;
  109678. deptr+=og.body_len;
  109679. }
  109680. /* have a complete page; submit it to sync/decode */
  109681. {
  109682. ogg_page og_de;
  109683. ogg_packet op_de,op_de2;
  109684. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109685. char *next=buf;
  109686. byteskipcount+=og.header_len;
  109687. if(byteskipcount>byteskip){
  109688. memcpy(next,og.header,byteskipcount-byteskip);
  109689. next+=byteskipcount-byteskip;
  109690. byteskipcount=byteskip;
  109691. }
  109692. byteskipcount+=og.body_len;
  109693. if(byteskipcount>byteskip){
  109694. memcpy(next,og.body,byteskipcount-byteskip);
  109695. next+=byteskipcount-byteskip;
  109696. byteskipcount=byteskip;
  109697. }
  109698. ogg_sync_wrote(&oy,next-buf);
  109699. while(1){
  109700. int ret=ogg_sync_pageout(&oy,&og_de);
  109701. if(ret==0)break;
  109702. if(ret<0)continue;
  109703. /* got a page. Happy happy. Verify that it's good. */
  109704. fprintf(stderr,"(%ld), ",pageout);
  109705. check_page(data+deptr,headers[pageout],&og_de);
  109706. deptr+=og_de.body_len;
  109707. pageout++;
  109708. /* submit it to deconstitution */
  109709. ogg_stream_pagein(&os_de,&og_de);
  109710. /* packets out? */
  109711. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109712. ogg_stream_packetpeek(&os_de,NULL);
  109713. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109714. /* verify peek and out match */
  109715. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109716. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109717. depacket);
  109718. exit(1);
  109719. }
  109720. /* verify the packet! */
  109721. /* check data */
  109722. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109723. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109724. depacket);
  109725. exit(1);
  109726. }
  109727. /* check bos flag */
  109728. if(bosflag==0 && op_de.b_o_s==0){
  109729. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109730. exit(1);
  109731. }
  109732. if(bosflag && op_de.b_o_s){
  109733. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109734. exit(1);
  109735. }
  109736. bosflag=1;
  109737. depacket+=op_de.bytes;
  109738. /* check eos flag */
  109739. if(eosflag){
  109740. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109741. exit(1);
  109742. }
  109743. if(op_de.e_o_s)eosflag=1;
  109744. /* check granulepos flag */
  109745. if(op_de.granulepos!=-1){
  109746. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109747. }
  109748. }
  109749. }
  109750. }
  109751. }
  109752. }
  109753. }
  109754. _ogg_free(data);
  109755. if(headers[pageno]!=NULL){
  109756. fprintf(stderr,"did not write last page!\n");
  109757. exit(1);
  109758. }
  109759. if(headers[pageout]!=NULL){
  109760. fprintf(stderr,"did not decode last page!\n");
  109761. exit(1);
  109762. }
  109763. if(inptr!=outptr){
  109764. fprintf(stderr,"encoded page data incomplete!\n");
  109765. exit(1);
  109766. }
  109767. if(inptr!=deptr){
  109768. fprintf(stderr,"decoded page data incomplete!\n");
  109769. exit(1);
  109770. }
  109771. if(inptr!=depacket){
  109772. fprintf(stderr,"decoded packet data incomplete!\n");
  109773. exit(1);
  109774. }
  109775. if(!eosflag){
  109776. fprintf(stderr,"Never got a packet with EOS set!\n");
  109777. exit(1);
  109778. }
  109779. fprintf(stderr,"ok.\n");
  109780. }
  109781. int main(void){
  109782. ogg_stream_init(&os_en,0x04030201);
  109783. ogg_stream_init(&os_de,0x04030201);
  109784. ogg_sync_init(&oy);
  109785. /* Exercise each code path in the framing code. Also verify that
  109786. the checksums are working. */
  109787. {
  109788. /* 17 only */
  109789. const int packets[]={17, -1};
  109790. const int *headret[]={head1_0,NULL};
  109791. fprintf(stderr,"testing single page encoding... ");
  109792. test_pack(packets,headret,0,0,0);
  109793. }
  109794. {
  109795. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109796. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109797. const int *headret[]={head1_1,head2_1,NULL};
  109798. fprintf(stderr,"testing basic page encoding... ");
  109799. test_pack(packets,headret,0,0,0);
  109800. }
  109801. {
  109802. /* nil packets; beginning,middle,end */
  109803. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109804. const int *headret[]={head1_2,head2_2,NULL};
  109805. fprintf(stderr,"testing basic nil packets... ");
  109806. test_pack(packets,headret,0,0,0);
  109807. }
  109808. {
  109809. /* large initial packet */
  109810. const int packets[]={4345,259,255,-1};
  109811. const int *headret[]={head1_3,head2_3,NULL};
  109812. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109813. test_pack(packets,headret,0,0,0);
  109814. }
  109815. {
  109816. /* continuing packet test */
  109817. const int packets[]={0,4345,259,255,-1};
  109818. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109819. fprintf(stderr,"testing single packet page span... ");
  109820. test_pack(packets,headret,0,0,0);
  109821. }
  109822. /* page with the 255 segment limit */
  109823. {
  109824. const int packets[]={0,10,10,10,10,10,10,10,10,
  109825. 10,10,10,10,10,10,10,10,
  109826. 10,10,10,10,10,10,10,10,
  109827. 10,10,10,10,10,10,10,10,
  109828. 10,10,10,10,10,10,10,10,
  109829. 10,10,10,10,10,10,10,10,
  109830. 10,10,10,10,10,10,10,10,
  109831. 10,10,10,10,10,10,10,10,
  109832. 10,10,10,10,10,10,10,10,
  109833. 10,10,10,10,10,10,10,10,
  109834. 10,10,10,10,10,10,10,10,
  109835. 10,10,10,10,10,10,10,10,
  109836. 10,10,10,10,10,10,10,10,
  109837. 10,10,10,10,10,10,10,10,
  109838. 10,10,10,10,10,10,10,10,
  109839. 10,10,10,10,10,10,10,10,
  109840. 10,10,10,10,10,10,10,10,
  109841. 10,10,10,10,10,10,10,10,
  109842. 10,10,10,10,10,10,10,10,
  109843. 10,10,10,10,10,10,10,10,
  109844. 10,10,10,10,10,10,10,10,
  109845. 10,10,10,10,10,10,10,10,
  109846. 10,10,10,10,10,10,10,10,
  109847. 10,10,10,10,10,10,10,10,
  109848. 10,10,10,10,10,10,10,10,
  109849. 10,10,10,10,10,10,10,10,
  109850. 10,10,10,10,10,10,10,10,
  109851. 10,10,10,10,10,10,10,10,
  109852. 10,10,10,10,10,10,10,10,
  109853. 10,10,10,10,10,10,10,10,
  109854. 10,10,10,10,10,10,10,10,
  109855. 10,10,10,10,10,10,10,50,-1};
  109856. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109857. fprintf(stderr,"testing max packet segments... ");
  109858. test_pack(packets,headret,0,0,0);
  109859. }
  109860. {
  109861. /* packet that overspans over an entire page */
  109862. const int packets[]={0,100,9000,259,255,-1};
  109863. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109864. fprintf(stderr,"testing very large packets... ");
  109865. test_pack(packets,headret,0,0,0);
  109866. }
  109867. {
  109868. /* test for the libogg 1.1.1 resync in large continuation bug
  109869. found by Josh Coalson) */
  109870. const int packets[]={0,100,9000,259,255,-1};
  109871. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109872. fprintf(stderr,"testing continuation resync in very large packets... ");
  109873. test_pack(packets,headret,100,2,3);
  109874. }
  109875. {
  109876. /* term only page. why not? */
  109877. const int packets[]={0,100,4080,-1};
  109878. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109879. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109880. test_pack(packets,headret,0,0,0);
  109881. }
  109882. {
  109883. /* build a bunch of pages for testing */
  109884. unsigned char *data=_ogg_malloc(1024*1024);
  109885. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109886. int inptr=0,i,j;
  109887. ogg_page og[5];
  109888. ogg_stream_reset(&os_en);
  109889. for(i=0;pl[i]!=-1;i++){
  109890. ogg_packet op;
  109891. int len=pl[i];
  109892. op.packet=data+inptr;
  109893. op.bytes=len;
  109894. op.e_o_s=(pl[i+1]<0?1:0);
  109895. op.granulepos=(i+1)*1000;
  109896. for(j=0;j<len;j++)data[inptr++]=i+j;
  109897. ogg_stream_packetin(&os_en,&op);
  109898. }
  109899. _ogg_free(data);
  109900. /* retrieve finished pages */
  109901. for(i=0;i<5;i++){
  109902. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109903. fprintf(stderr,"Too few pages output building sync tests!\n");
  109904. exit(1);
  109905. }
  109906. copy_page(&og[i]);
  109907. }
  109908. /* Test lost pages on pagein/packetout: no rollback */
  109909. {
  109910. ogg_page temp;
  109911. ogg_packet test;
  109912. fprintf(stderr,"Testing loss of pages... ");
  109913. ogg_sync_reset(&oy);
  109914. ogg_stream_reset(&os_de);
  109915. for(i=0;i<5;i++){
  109916. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109917. og[i].header_len);
  109918. ogg_sync_wrote(&oy,og[i].header_len);
  109919. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109920. ogg_sync_wrote(&oy,og[i].body_len);
  109921. }
  109922. ogg_sync_pageout(&oy,&temp);
  109923. ogg_stream_pagein(&os_de,&temp);
  109924. ogg_sync_pageout(&oy,&temp);
  109925. ogg_stream_pagein(&os_de,&temp);
  109926. ogg_sync_pageout(&oy,&temp);
  109927. /* skip */
  109928. ogg_sync_pageout(&oy,&temp);
  109929. ogg_stream_pagein(&os_de,&temp);
  109930. /* do we get the expected results/packets? */
  109931. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109932. checkpacket(&test,0,0,0);
  109933. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109934. checkpacket(&test,100,1,-1);
  109935. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109936. checkpacket(&test,4079,2,3000);
  109937. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109938. fprintf(stderr,"Error: loss of page did not return error\n");
  109939. exit(1);
  109940. }
  109941. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109942. checkpacket(&test,76,5,-1);
  109943. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109944. checkpacket(&test,34,6,-1);
  109945. fprintf(stderr,"ok.\n");
  109946. }
  109947. /* Test lost pages on pagein/packetout: rollback with continuation */
  109948. {
  109949. ogg_page temp;
  109950. ogg_packet test;
  109951. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109952. ogg_sync_reset(&oy);
  109953. ogg_stream_reset(&os_de);
  109954. for(i=0;i<5;i++){
  109955. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109956. og[i].header_len);
  109957. ogg_sync_wrote(&oy,og[i].header_len);
  109958. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109959. ogg_sync_wrote(&oy,og[i].body_len);
  109960. }
  109961. ogg_sync_pageout(&oy,&temp);
  109962. ogg_stream_pagein(&os_de,&temp);
  109963. ogg_sync_pageout(&oy,&temp);
  109964. ogg_stream_pagein(&os_de,&temp);
  109965. ogg_sync_pageout(&oy,&temp);
  109966. ogg_stream_pagein(&os_de,&temp);
  109967. ogg_sync_pageout(&oy,&temp);
  109968. /* skip */
  109969. ogg_sync_pageout(&oy,&temp);
  109970. ogg_stream_pagein(&os_de,&temp);
  109971. /* do we get the expected results/packets? */
  109972. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109973. checkpacket(&test,0,0,0);
  109974. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109975. checkpacket(&test,100,1,-1);
  109976. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109977. checkpacket(&test,4079,2,3000);
  109978. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109979. checkpacket(&test,2956,3,4000);
  109980. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109981. fprintf(stderr,"Error: loss of page did not return error\n");
  109982. exit(1);
  109983. }
  109984. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109985. checkpacket(&test,300,13,14000);
  109986. fprintf(stderr,"ok.\n");
  109987. }
  109988. /* the rest only test sync */
  109989. {
  109990. ogg_page og_de;
  109991. /* Test fractional page inputs: incomplete capture */
  109992. fprintf(stderr,"Testing sync on partial inputs... ");
  109993. ogg_sync_reset(&oy);
  109994. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109995. 3);
  109996. ogg_sync_wrote(&oy,3);
  109997. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109998. /* Test fractional page inputs: incomplete fixed header */
  109999. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  110000. 20);
  110001. ogg_sync_wrote(&oy,20);
  110002. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110003. /* Test fractional page inputs: incomplete header */
  110004. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  110005. 5);
  110006. ogg_sync_wrote(&oy,5);
  110007. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110008. /* Test fractional page inputs: incomplete body */
  110009. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  110010. og[1].header_len-28);
  110011. ogg_sync_wrote(&oy,og[1].header_len-28);
  110012. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110013. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  110014. ogg_sync_wrote(&oy,1000);
  110015. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110016. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  110017. og[1].body_len-1000);
  110018. ogg_sync_wrote(&oy,og[1].body_len-1000);
  110019. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110020. fprintf(stderr,"ok.\n");
  110021. }
  110022. /* Test fractional page inputs: page + incomplete capture */
  110023. {
  110024. ogg_page og_de;
  110025. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  110026. ogg_sync_reset(&oy);
  110027. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110028. og[1].header_len);
  110029. ogg_sync_wrote(&oy,og[1].header_len);
  110030. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110031. og[1].body_len);
  110032. ogg_sync_wrote(&oy,og[1].body_len);
  110033. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110034. 20);
  110035. ogg_sync_wrote(&oy,20);
  110036. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110037. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110038. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  110039. og[1].header_len-20);
  110040. ogg_sync_wrote(&oy,og[1].header_len-20);
  110041. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110042. og[1].body_len);
  110043. ogg_sync_wrote(&oy,og[1].body_len);
  110044. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110045. fprintf(stderr,"ok.\n");
  110046. }
  110047. /* Test recapture: garbage + page */
  110048. {
  110049. ogg_page og_de;
  110050. fprintf(stderr,"Testing search for capture... ");
  110051. ogg_sync_reset(&oy);
  110052. /* 'garbage' */
  110053. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110054. og[1].body_len);
  110055. ogg_sync_wrote(&oy,og[1].body_len);
  110056. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110057. og[1].header_len);
  110058. ogg_sync_wrote(&oy,og[1].header_len);
  110059. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110060. og[1].body_len);
  110061. ogg_sync_wrote(&oy,og[1].body_len);
  110062. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110063. 20);
  110064. ogg_sync_wrote(&oy,20);
  110065. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110066. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110067. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110068. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110069. og[2].header_len-20);
  110070. ogg_sync_wrote(&oy,og[2].header_len-20);
  110071. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110072. og[2].body_len);
  110073. ogg_sync_wrote(&oy,og[2].body_len);
  110074. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110075. fprintf(stderr,"ok.\n");
  110076. }
  110077. /* Test recapture: page + garbage + page */
  110078. {
  110079. ogg_page og_de;
  110080. fprintf(stderr,"Testing recapture... ");
  110081. ogg_sync_reset(&oy);
  110082. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110083. og[1].header_len);
  110084. ogg_sync_wrote(&oy,og[1].header_len);
  110085. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110086. og[1].body_len);
  110087. ogg_sync_wrote(&oy,og[1].body_len);
  110088. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110089. og[2].header_len);
  110090. ogg_sync_wrote(&oy,og[2].header_len);
  110091. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110092. og[2].header_len);
  110093. ogg_sync_wrote(&oy,og[2].header_len);
  110094. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110095. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110096. og[2].body_len-5);
  110097. ogg_sync_wrote(&oy,og[2].body_len-5);
  110098. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110099. og[3].header_len);
  110100. ogg_sync_wrote(&oy,og[3].header_len);
  110101. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110102. og[3].body_len);
  110103. ogg_sync_wrote(&oy,og[3].body_len);
  110104. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110105. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110106. fprintf(stderr,"ok.\n");
  110107. }
  110108. /* Free page data that was previously copied */
  110109. {
  110110. for(i=0;i<5;i++){
  110111. free_page(&og[i]);
  110112. }
  110113. }
  110114. }
  110115. return(0);
  110116. }
  110117. #endif
  110118. #endif
  110119. /*** End of inlined file: framing.c ***/
  110120. /*** Start of inlined file: analysis.c ***/
  110121. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110122. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110123. // tasks..
  110124. #if JUCE_MSVC
  110125. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110126. #endif
  110127. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110128. #if JUCE_USE_OGGVORBIS
  110129. #include <stdio.h>
  110130. #include <string.h>
  110131. #include <math.h>
  110132. /*** Start of inlined file: codec_internal.h ***/
  110133. #ifndef _V_CODECI_H_
  110134. #define _V_CODECI_H_
  110135. /*** Start of inlined file: envelope.h ***/
  110136. #ifndef _V_ENVELOPE_
  110137. #define _V_ENVELOPE_
  110138. /*** Start of inlined file: mdct.h ***/
  110139. #ifndef _OGG_mdct_H_
  110140. #define _OGG_mdct_H_
  110141. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110142. #ifdef MDCT_INTEGERIZED
  110143. #define DATA_TYPE int
  110144. #define REG_TYPE register int
  110145. #define TRIGBITS 14
  110146. #define cPI3_8 6270
  110147. #define cPI2_8 11585
  110148. #define cPI1_8 15137
  110149. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110150. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110151. #define HALVE(x) ((x)>>1)
  110152. #else
  110153. #define DATA_TYPE float
  110154. #define REG_TYPE float
  110155. #define cPI3_8 .38268343236508977175F
  110156. #define cPI2_8 .70710678118654752441F
  110157. #define cPI1_8 .92387953251128675613F
  110158. #define FLOAT_CONV(x) (x)
  110159. #define MULT_NORM(x) (x)
  110160. #define HALVE(x) ((x)*.5f)
  110161. #endif
  110162. typedef struct {
  110163. int n;
  110164. int log2n;
  110165. DATA_TYPE *trig;
  110166. int *bitrev;
  110167. DATA_TYPE scale;
  110168. } mdct_lookup;
  110169. extern void mdct_init(mdct_lookup *lookup,int n);
  110170. extern void mdct_clear(mdct_lookup *l);
  110171. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110172. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110173. #endif
  110174. /*** End of inlined file: mdct.h ***/
  110175. #define VE_PRE 16
  110176. #define VE_WIN 4
  110177. #define VE_POST 2
  110178. #define VE_AMP (VE_PRE+VE_POST-1)
  110179. #define VE_BANDS 7
  110180. #define VE_NEARDC 15
  110181. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110182. #define VE_MAXSTRETCH 12 /* one-third full block */
  110183. typedef struct {
  110184. float ampbuf[VE_AMP];
  110185. int ampptr;
  110186. float nearDC[VE_NEARDC];
  110187. float nearDC_acc;
  110188. float nearDC_partialacc;
  110189. int nearptr;
  110190. } envelope_filter_state;
  110191. typedef struct {
  110192. int begin;
  110193. int end;
  110194. float *window;
  110195. float total;
  110196. } envelope_band;
  110197. typedef struct {
  110198. int ch;
  110199. int winlength;
  110200. int searchstep;
  110201. float minenergy;
  110202. mdct_lookup mdct;
  110203. float *mdct_win;
  110204. envelope_band band[VE_BANDS];
  110205. envelope_filter_state *filter;
  110206. int stretch;
  110207. int *mark;
  110208. long storage;
  110209. long current;
  110210. long curmark;
  110211. long cursor;
  110212. } envelope_lookup;
  110213. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110214. extern void _ve_envelope_clear(envelope_lookup *e);
  110215. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110216. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110217. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110218. #endif
  110219. /*** End of inlined file: envelope.h ***/
  110220. /*** Start of inlined file: codebook.h ***/
  110221. #ifndef _V_CODEBOOK_H_
  110222. #define _V_CODEBOOK_H_
  110223. /* This structure encapsulates huffman and VQ style encoding books; it
  110224. doesn't do anything specific to either.
  110225. valuelist/quantlist are nonNULL (and q_* significant) only if
  110226. there's entry->value mapping to be done.
  110227. If encode-side mapping must be done (and thus the entry needs to be
  110228. hunted), the auxiliary encode pointer will point to a decision
  110229. tree. This is true of both VQ and huffman, but is mostly useful
  110230. with VQ.
  110231. */
  110232. typedef struct static_codebook{
  110233. long dim; /* codebook dimensions (elements per vector) */
  110234. long entries; /* codebook entries */
  110235. long *lengthlist; /* codeword lengths in bits */
  110236. /* mapping ***************************************************************/
  110237. int maptype; /* 0=none
  110238. 1=implicitly populated values from map column
  110239. 2=listed arbitrary values */
  110240. /* The below does a linear, single monotonic sequence mapping. */
  110241. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110242. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110243. int q_quant; /* bits: 0 < quant <= 16 */
  110244. int q_sequencep; /* bitflag */
  110245. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110246. map == 2: list of dim*entries quantized entry vals
  110247. */
  110248. /* encode helpers ********************************************************/
  110249. struct encode_aux_nearestmatch *nearest_tree;
  110250. struct encode_aux_threshmatch *thresh_tree;
  110251. struct encode_aux_pigeonhole *pigeon_tree;
  110252. int allocedp;
  110253. } static_codebook;
  110254. /* this structures an arbitrary trained book to quickly find the
  110255. nearest cell match */
  110256. typedef struct encode_aux_nearestmatch{
  110257. /* pre-calculated partitioning tree */
  110258. long *ptr0;
  110259. long *ptr1;
  110260. long *p; /* decision points (each is an entry) */
  110261. long *q; /* decision points (each is an entry) */
  110262. long aux; /* number of tree entries */
  110263. long alloc;
  110264. } encode_aux_nearestmatch;
  110265. /* assumes a maptype of 1; encode side only, so that's OK */
  110266. typedef struct encode_aux_threshmatch{
  110267. float *quantthresh;
  110268. long *quantmap;
  110269. int quantvals;
  110270. int threshvals;
  110271. } encode_aux_threshmatch;
  110272. typedef struct encode_aux_pigeonhole{
  110273. float min;
  110274. float del;
  110275. int mapentries;
  110276. int quantvals;
  110277. long *pigeonmap;
  110278. long fittotal;
  110279. long *fitlist;
  110280. long *fitmap;
  110281. long *fitlength;
  110282. } encode_aux_pigeonhole;
  110283. typedef struct codebook{
  110284. long dim; /* codebook dimensions (elements per vector) */
  110285. long entries; /* codebook entries */
  110286. long used_entries; /* populated codebook entries */
  110287. const static_codebook *c;
  110288. /* for encode, the below are entry-ordered, fully populated */
  110289. /* for decode, the below are ordered by bitreversed codeword and only
  110290. used entries are populated */
  110291. float *valuelist; /* list of dim*entries actual entry values */
  110292. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110293. int *dec_index; /* only used if sparseness collapsed */
  110294. char *dec_codelengths;
  110295. ogg_uint32_t *dec_firsttable;
  110296. int dec_firsttablen;
  110297. int dec_maxlength;
  110298. } codebook;
  110299. extern void vorbis_staticbook_clear(static_codebook *b);
  110300. extern void vorbis_staticbook_destroy(static_codebook *b);
  110301. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110302. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110303. extern void vorbis_book_clear(codebook *b);
  110304. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110305. extern float *_book_logdist(const static_codebook *b,float *vals);
  110306. extern float _float32_unpack(long val);
  110307. extern long _float32_pack(float val);
  110308. extern int _best(codebook *book, float *a, int step);
  110309. extern int _ilog(unsigned int v);
  110310. extern long _book_maptype1_quantvals(const static_codebook *b);
  110311. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110312. extern long vorbis_book_codeword(codebook *book,int entry);
  110313. extern long vorbis_book_codelen(codebook *book,int entry);
  110314. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110315. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110316. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110317. extern int vorbis_book_errorv(codebook *book, float *a);
  110318. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110319. oggpack_buffer *b);
  110320. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110321. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110322. oggpack_buffer *b,int n);
  110323. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110324. oggpack_buffer *b,int n);
  110325. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110326. oggpack_buffer *b,int n);
  110327. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110328. long off,int ch,
  110329. oggpack_buffer *b,int n);
  110330. #endif
  110331. /*** End of inlined file: codebook.h ***/
  110332. #define BLOCKTYPE_IMPULSE 0
  110333. #define BLOCKTYPE_PADDING 1
  110334. #define BLOCKTYPE_TRANSITION 0
  110335. #define BLOCKTYPE_LONG 1
  110336. #define PACKETBLOBS 15
  110337. typedef struct vorbis_block_internal{
  110338. float **pcmdelay; /* this is a pointer into local storage */
  110339. float ampmax;
  110340. int blocktype;
  110341. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110342. blob [PACKETBLOBS/2] points to
  110343. the oggpack_buffer in the
  110344. main vorbis_block */
  110345. } vorbis_block_internal;
  110346. typedef void vorbis_look_floor;
  110347. typedef void vorbis_look_residue;
  110348. typedef void vorbis_look_transform;
  110349. /* mode ************************************************************/
  110350. typedef struct {
  110351. int blockflag;
  110352. int windowtype;
  110353. int transformtype;
  110354. int mapping;
  110355. } vorbis_info_mode;
  110356. typedef void vorbis_info_floor;
  110357. typedef void vorbis_info_residue;
  110358. typedef void vorbis_info_mapping;
  110359. /*** Start of inlined file: psy.h ***/
  110360. #ifndef _V_PSY_H_
  110361. #define _V_PSY_H_
  110362. /*** Start of inlined file: smallft.h ***/
  110363. #ifndef _V_SMFT_H_
  110364. #define _V_SMFT_H_
  110365. typedef struct {
  110366. int n;
  110367. float *trigcache;
  110368. int *splitcache;
  110369. } drft_lookup;
  110370. extern void drft_forward(drft_lookup *l,float *data);
  110371. extern void drft_backward(drft_lookup *l,float *data);
  110372. extern void drft_init(drft_lookup *l,int n);
  110373. extern void drft_clear(drft_lookup *l);
  110374. #endif
  110375. /*** End of inlined file: smallft.h ***/
  110376. /*** Start of inlined file: backends.h ***/
  110377. /* this is exposed up here because we need it for static modes.
  110378. Lookups for each backend aren't exposed because there's no reason
  110379. to do so */
  110380. #ifndef _vorbis_backend_h_
  110381. #define _vorbis_backend_h_
  110382. /* this would all be simpler/shorter with templates, but.... */
  110383. /* Floor backend generic *****************************************/
  110384. typedef struct{
  110385. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110386. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110387. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110388. void (*free_info) (vorbis_info_floor *);
  110389. void (*free_look) (vorbis_look_floor *);
  110390. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110391. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110392. void *buffer,float *);
  110393. } vorbis_func_floor;
  110394. typedef struct{
  110395. int order;
  110396. long rate;
  110397. long barkmap;
  110398. int ampbits;
  110399. int ampdB;
  110400. int numbooks; /* <= 16 */
  110401. int books[16];
  110402. float lessthan; /* encode-only config setting hacks for libvorbis */
  110403. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110404. } vorbis_info_floor0;
  110405. #define VIF_POSIT 63
  110406. #define VIF_CLASS 16
  110407. #define VIF_PARTS 31
  110408. typedef struct{
  110409. int partitions; /* 0 to 31 */
  110410. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110411. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110412. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110413. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110414. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110415. int mult; /* 1 2 3 or 4 */
  110416. int postlist[VIF_POSIT+2]; /* first two implicit */
  110417. /* encode side analysis parameters */
  110418. float maxover;
  110419. float maxunder;
  110420. float maxerr;
  110421. float twofitweight;
  110422. float twofitatten;
  110423. int n;
  110424. } vorbis_info_floor1;
  110425. /* Residue backend generic *****************************************/
  110426. typedef struct{
  110427. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110428. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110429. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110430. vorbis_info_residue *);
  110431. void (*free_info) (vorbis_info_residue *);
  110432. void (*free_look) (vorbis_look_residue *);
  110433. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110434. float **,int *,int);
  110435. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110436. vorbis_look_residue *,
  110437. float **,float **,int *,int,long **);
  110438. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110439. float **,int *,int);
  110440. } vorbis_func_residue;
  110441. typedef struct vorbis_info_residue0{
  110442. /* block-partitioned VQ coded straight residue */
  110443. long begin;
  110444. long end;
  110445. /* first stage (lossless partitioning) */
  110446. int grouping; /* group n vectors per partition */
  110447. int partitions; /* possible codebooks for a partition */
  110448. int groupbook; /* huffbook for partitioning */
  110449. int secondstages[64]; /* expanded out to pointers in lookup */
  110450. int booklist[256]; /* list of second stage books */
  110451. float classmetric1[64];
  110452. float classmetric2[64];
  110453. } vorbis_info_residue0;
  110454. /* Mapping backend generic *****************************************/
  110455. typedef struct{
  110456. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110457. oggpack_buffer *);
  110458. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110459. void (*free_info) (vorbis_info_mapping *);
  110460. int (*forward) (struct vorbis_block *vb);
  110461. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110462. } vorbis_func_mapping;
  110463. typedef struct vorbis_info_mapping0{
  110464. int submaps; /* <= 16 */
  110465. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110466. int floorsubmap[16]; /* [mux] submap to floors */
  110467. int residuesubmap[16]; /* [mux] submap to residue */
  110468. int coupling_steps;
  110469. int coupling_mag[256];
  110470. int coupling_ang[256];
  110471. } vorbis_info_mapping0;
  110472. #endif
  110473. /*** End of inlined file: backends.h ***/
  110474. #ifndef EHMER_MAX
  110475. #define EHMER_MAX 56
  110476. #endif
  110477. /* psychoacoustic setup ********************************************/
  110478. #define P_BANDS 17 /* 62Hz to 16kHz */
  110479. #define P_LEVELS 8 /* 30dB to 100dB */
  110480. #define P_LEVEL_0 30. /* 30 dB */
  110481. #define P_NOISECURVES 3
  110482. #define NOISE_COMPAND_LEVELS 40
  110483. typedef struct vorbis_info_psy{
  110484. int blockflag;
  110485. float ath_adjatt;
  110486. float ath_maxatt;
  110487. float tone_masteratt[P_NOISECURVES];
  110488. float tone_centerboost;
  110489. float tone_decay;
  110490. float tone_abs_limit;
  110491. float toneatt[P_BANDS];
  110492. int noisemaskp;
  110493. float noisemaxsupp;
  110494. float noisewindowlo;
  110495. float noisewindowhi;
  110496. int noisewindowlomin;
  110497. int noisewindowhimin;
  110498. int noisewindowfixed;
  110499. float noiseoff[P_NOISECURVES][P_BANDS];
  110500. float noisecompand[NOISE_COMPAND_LEVELS];
  110501. float max_curve_dB;
  110502. int normal_channel_p;
  110503. int normal_point_p;
  110504. int normal_start;
  110505. int normal_partition;
  110506. double normal_thresh;
  110507. } vorbis_info_psy;
  110508. typedef struct{
  110509. int eighth_octave_lines;
  110510. /* for block long/short tuning; encode only */
  110511. float preecho_thresh[VE_BANDS];
  110512. float postecho_thresh[VE_BANDS];
  110513. float stretch_penalty;
  110514. float preecho_minenergy;
  110515. float ampmax_att_per_sec;
  110516. /* channel coupling config */
  110517. int coupling_pkHz[PACKETBLOBS];
  110518. int coupling_pointlimit[2][PACKETBLOBS];
  110519. int coupling_prepointamp[PACKETBLOBS];
  110520. int coupling_postpointamp[PACKETBLOBS];
  110521. int sliding_lowpass[2][PACKETBLOBS];
  110522. } vorbis_info_psy_global;
  110523. typedef struct {
  110524. float ampmax;
  110525. int channels;
  110526. vorbis_info_psy_global *gi;
  110527. int coupling_pointlimit[2][P_NOISECURVES];
  110528. } vorbis_look_psy_global;
  110529. typedef struct {
  110530. int n;
  110531. struct vorbis_info_psy *vi;
  110532. float ***tonecurves;
  110533. float **noiseoffset;
  110534. float *ath;
  110535. long *octave; /* in n.ocshift format */
  110536. long *bark;
  110537. long firstoc;
  110538. long shiftoc;
  110539. int eighth_octave_lines; /* power of two, please */
  110540. int total_octave_lines;
  110541. long rate; /* cache it */
  110542. float m_val; /* Masking compensation value */
  110543. } vorbis_look_psy;
  110544. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110545. vorbis_info_psy_global *gi,int n,long rate);
  110546. extern void _vp_psy_clear(vorbis_look_psy *p);
  110547. extern void *_vi_psy_dup(void *source);
  110548. extern void _vi_psy_free(vorbis_info_psy *i);
  110549. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110550. extern void _vp_remove_floor(vorbis_look_psy *p,
  110551. float *mdct,
  110552. int *icodedflr,
  110553. float *residue,
  110554. int sliding_lowpass);
  110555. extern void _vp_noisemask(vorbis_look_psy *p,
  110556. float *logmdct,
  110557. float *logmask);
  110558. extern void _vp_tonemask(vorbis_look_psy *p,
  110559. float *logfft,
  110560. float *logmask,
  110561. float global_specmax,
  110562. float local_specmax);
  110563. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110564. float *noise,
  110565. float *tone,
  110566. int offset_select,
  110567. float *logmask,
  110568. float *mdct,
  110569. float *logmdct);
  110570. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110571. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110572. vorbis_info_psy_global *g,
  110573. vorbis_look_psy *p,
  110574. vorbis_info_mapping0 *vi,
  110575. float **mdct);
  110576. extern void _vp_couple(int blobno,
  110577. vorbis_info_psy_global *g,
  110578. vorbis_look_psy *p,
  110579. vorbis_info_mapping0 *vi,
  110580. float **res,
  110581. float **mag_memo,
  110582. int **mag_sort,
  110583. int **ifloor,
  110584. int *nonzero,
  110585. int sliding_lowpass);
  110586. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110587. float *in,float *out,int *sortedindex);
  110588. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110589. float *magnitudes,int *sortedindex);
  110590. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110591. vorbis_look_psy *p,
  110592. vorbis_info_mapping0 *vi,
  110593. float **mags);
  110594. extern void hf_reduction(vorbis_info_psy_global *g,
  110595. vorbis_look_psy *p,
  110596. vorbis_info_mapping0 *vi,
  110597. float **mdct);
  110598. #endif
  110599. /*** End of inlined file: psy.h ***/
  110600. /*** Start of inlined file: bitrate.h ***/
  110601. #ifndef _V_BITRATE_H_
  110602. #define _V_BITRATE_H_
  110603. /*** Start of inlined file: os.h ***/
  110604. #ifndef _OS_H
  110605. #define _OS_H
  110606. /********************************************************************
  110607. * *
  110608. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110609. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110610. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110611. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110612. * *
  110613. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110614. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110615. * *
  110616. ********************************************************************
  110617. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110618. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110619. ********************************************************************/
  110620. #ifdef HAVE_CONFIG_H
  110621. #include "config.h"
  110622. #endif
  110623. #include <math.h>
  110624. /*** Start of inlined file: misc.h ***/
  110625. #ifndef _V_RANDOM_H_
  110626. #define _V_RANDOM_H_
  110627. extern int analysis_noisy;
  110628. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110629. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110630. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110631. ogg_int64_t off);
  110632. #ifdef DEBUG_MALLOC
  110633. #define _VDBG_GRAPHFILE "malloc.m"
  110634. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110635. extern void _VDBG_free(void *ptr,char *file,long line);
  110636. #ifndef MISC_C
  110637. #undef _ogg_malloc
  110638. #undef _ogg_calloc
  110639. #undef _ogg_realloc
  110640. #undef _ogg_free
  110641. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110642. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110643. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110644. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110645. #endif
  110646. #endif
  110647. #endif
  110648. /*** End of inlined file: misc.h ***/
  110649. #ifndef _V_IFDEFJAIL_H_
  110650. # define _V_IFDEFJAIL_H_
  110651. # ifdef __GNUC__
  110652. # define STIN static __inline__
  110653. # elif _WIN32
  110654. # define STIN static __inline
  110655. # else
  110656. # define STIN static
  110657. # endif
  110658. #ifdef DJGPP
  110659. # define rint(x) (floor((x)+0.5f))
  110660. #endif
  110661. #ifndef M_PI
  110662. # define M_PI (3.1415926536f)
  110663. #endif
  110664. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110665. # include <malloc.h>
  110666. # define rint(x) (floor((x)+0.5f))
  110667. # define NO_FLOAT_MATH_LIB
  110668. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110669. #endif
  110670. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110671. void *_alloca(size_t size);
  110672. # define alloca _alloca
  110673. #endif
  110674. #ifndef FAST_HYPOT
  110675. # define FAST_HYPOT hypot
  110676. #endif
  110677. #endif
  110678. #ifdef HAVE_ALLOCA_H
  110679. # include <alloca.h>
  110680. #endif
  110681. #ifdef USE_MEMORY_H
  110682. # include <memory.h>
  110683. #endif
  110684. #ifndef min
  110685. # define min(x,y) ((x)>(y)?(y):(x))
  110686. #endif
  110687. #ifndef max
  110688. # define max(x,y) ((x)<(y)?(y):(x))
  110689. #endif
  110690. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110691. # define VORBIS_FPU_CONTROL
  110692. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110693. Because of encapsulation constraints (GCC can't see inside the asm
  110694. block and so we end up doing stupid things like a store/load that
  110695. is collectively a noop), we do it this way */
  110696. /* we must set up the fpu before this works!! */
  110697. typedef ogg_int16_t vorbis_fpu_control;
  110698. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110699. ogg_int16_t ret;
  110700. ogg_int16_t temp;
  110701. __asm__ __volatile__("fnstcw %0\n\t"
  110702. "movw %0,%%dx\n\t"
  110703. "orw $62463,%%dx\n\t"
  110704. "movw %%dx,%1\n\t"
  110705. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110706. *fpu=ret;
  110707. }
  110708. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110709. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110710. }
  110711. /* assumes the FPU is in round mode! */
  110712. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110713. we get extra fst/fld to
  110714. truncate precision */
  110715. int i;
  110716. __asm__("fistl %0": "=m"(i) : "t"(f));
  110717. return(i);
  110718. }
  110719. #endif
  110720. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110721. # define VORBIS_FPU_CONTROL
  110722. typedef ogg_int16_t vorbis_fpu_control;
  110723. static __inline int vorbis_ftoi(double f){
  110724. int i;
  110725. __asm{
  110726. fld f
  110727. fistp i
  110728. }
  110729. return i;
  110730. }
  110731. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110732. }
  110733. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110734. }
  110735. #endif
  110736. #ifndef VORBIS_FPU_CONTROL
  110737. typedef int vorbis_fpu_control;
  110738. static int vorbis_ftoi(double f){
  110739. return (int)(f+.5);
  110740. }
  110741. /* We don't have special code for this compiler/arch, so do it the slow way */
  110742. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110743. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110744. #endif
  110745. #endif /* _OS_H */
  110746. /*** End of inlined file: os.h ***/
  110747. /* encode side bitrate tracking */
  110748. typedef struct bitrate_manager_state {
  110749. int managed;
  110750. long avg_reservoir;
  110751. long minmax_reservoir;
  110752. long avg_bitsper;
  110753. long min_bitsper;
  110754. long max_bitsper;
  110755. long short_per_long;
  110756. double avgfloat;
  110757. vorbis_block *vb;
  110758. int choice;
  110759. } bitrate_manager_state;
  110760. typedef struct bitrate_manager_info{
  110761. long avg_rate;
  110762. long min_rate;
  110763. long max_rate;
  110764. long reservoir_bits;
  110765. double reservoir_bias;
  110766. double slew_damp;
  110767. } bitrate_manager_info;
  110768. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110769. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110770. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110771. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110772. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110773. #endif
  110774. /*** End of inlined file: bitrate.h ***/
  110775. static int ilog(unsigned int v){
  110776. int ret=0;
  110777. while(v){
  110778. ret++;
  110779. v>>=1;
  110780. }
  110781. return(ret);
  110782. }
  110783. static int ilog2(unsigned int v){
  110784. int ret=0;
  110785. if(v)--v;
  110786. while(v){
  110787. ret++;
  110788. v>>=1;
  110789. }
  110790. return(ret);
  110791. }
  110792. typedef struct private_state {
  110793. /* local lookup storage */
  110794. envelope_lookup *ve; /* envelope lookup */
  110795. int window[2];
  110796. vorbis_look_transform **transform[2]; /* block, type */
  110797. drft_lookup fft_look[2];
  110798. int modebits;
  110799. vorbis_look_floor **flr;
  110800. vorbis_look_residue **residue;
  110801. vorbis_look_psy *psy;
  110802. vorbis_look_psy_global *psy_g_look;
  110803. /* local storage, only used on the encoding side. This way the
  110804. application does not need to worry about freeing some packets'
  110805. memory and not others'; packet storage is always tracked.
  110806. Cleared next call to a _dsp_ function */
  110807. unsigned char *header;
  110808. unsigned char *header1;
  110809. unsigned char *header2;
  110810. bitrate_manager_state bms;
  110811. ogg_int64_t sample_count;
  110812. } private_state;
  110813. /* codec_setup_info contains all the setup information specific to the
  110814. specific compression/decompression mode in progress (eg,
  110815. psychoacoustic settings, channel setup, options, codebook
  110816. etc).
  110817. *********************************************************************/
  110818. /*** Start of inlined file: highlevel.h ***/
  110819. typedef struct highlevel_byblocktype {
  110820. double tone_mask_setting;
  110821. double tone_peaklimit_setting;
  110822. double noise_bias_setting;
  110823. double noise_compand_setting;
  110824. } highlevel_byblocktype;
  110825. typedef struct highlevel_encode_setup {
  110826. void *setup;
  110827. int set_in_stone;
  110828. double base_setting;
  110829. double long_setting;
  110830. double short_setting;
  110831. double impulse_noisetune;
  110832. int managed;
  110833. long bitrate_min;
  110834. long bitrate_av;
  110835. double bitrate_av_damp;
  110836. long bitrate_max;
  110837. long bitrate_reservoir;
  110838. double bitrate_reservoir_bias;
  110839. int impulse_block_p;
  110840. int noise_normalize_p;
  110841. double stereo_point_setting;
  110842. double lowpass_kHz;
  110843. double ath_floating_dB;
  110844. double ath_absolute_dB;
  110845. double amplitude_track_dBpersec;
  110846. double trigger_setting;
  110847. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110848. } highlevel_encode_setup;
  110849. /*** End of inlined file: highlevel.h ***/
  110850. typedef struct codec_setup_info {
  110851. /* Vorbis supports only short and long blocks, but allows the
  110852. encoder to choose the sizes */
  110853. long blocksizes[2];
  110854. /* modes are the primary means of supporting on-the-fly different
  110855. blocksizes, different channel mappings (LR or M/A),
  110856. different residue backends, etc. Each mode consists of a
  110857. blocksize flag and a mapping (along with the mapping setup */
  110858. int modes;
  110859. int maps;
  110860. int floors;
  110861. int residues;
  110862. int books;
  110863. int psys; /* encode only */
  110864. vorbis_info_mode *mode_param[64];
  110865. int map_type[64];
  110866. vorbis_info_mapping *map_param[64];
  110867. int floor_type[64];
  110868. vorbis_info_floor *floor_param[64];
  110869. int residue_type[64];
  110870. vorbis_info_residue *residue_param[64];
  110871. static_codebook *book_param[256];
  110872. codebook *fullbooks;
  110873. vorbis_info_psy *psy_param[4]; /* encode only */
  110874. vorbis_info_psy_global psy_g_param;
  110875. bitrate_manager_info bi;
  110876. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110877. highly redundant structure, but
  110878. improves clarity of program flow. */
  110879. int halfrate_flag; /* painless downsample for decode */
  110880. } codec_setup_info;
  110881. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110882. extern void _vp_global_free(vorbis_look_psy_global *look);
  110883. #endif
  110884. /*** End of inlined file: codec_internal.h ***/
  110885. /*** Start of inlined file: registry.h ***/
  110886. #ifndef _V_REG_H_
  110887. #define _V_REG_H_
  110888. #define VI_TRANSFORMB 1
  110889. #define VI_WINDOWB 1
  110890. #define VI_TIMEB 1
  110891. #define VI_FLOORB 2
  110892. #define VI_RESB 3
  110893. #define VI_MAPB 1
  110894. extern vorbis_func_floor *_floor_P[];
  110895. extern vorbis_func_residue *_residue_P[];
  110896. extern vorbis_func_mapping *_mapping_P[];
  110897. #endif
  110898. /*** End of inlined file: registry.h ***/
  110899. /*** Start of inlined file: scales.h ***/
  110900. #ifndef _V_SCALES_H_
  110901. #define _V_SCALES_H_
  110902. #include <math.h>
  110903. /* 20log10(x) */
  110904. #define VORBIS_IEEE_FLOAT32 1
  110905. #ifdef VORBIS_IEEE_FLOAT32
  110906. static float unitnorm(float x){
  110907. union {
  110908. ogg_uint32_t i;
  110909. float f;
  110910. } ix;
  110911. ix.f = x;
  110912. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110913. return ix.f;
  110914. }
  110915. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110916. static float todB(const float *x){
  110917. union {
  110918. ogg_uint32_t i;
  110919. float f;
  110920. } ix;
  110921. ix.f = *x;
  110922. ix.i = ix.i&0x7fffffff;
  110923. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110924. }
  110925. #define todB_nn(x) todB(x)
  110926. #else
  110927. static float unitnorm(float x){
  110928. if(x<0)return(-1.f);
  110929. return(1.f);
  110930. }
  110931. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110932. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110933. #endif
  110934. #define fromdB(x) (exp((x)*.11512925f))
  110935. /* The bark scale equations are approximations, since the original
  110936. table was somewhat hand rolled. The below are chosen to have the
  110937. best possible fit to the rolled tables, thus their somewhat odd
  110938. appearance (these are more accurate and over a longer range than
  110939. the oft-quoted bark equations found in the texts I have). The
  110940. approximations are valid from 0 - 30kHz (nyquist) or so.
  110941. all f in Hz, z in Bark */
  110942. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110943. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110944. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110945. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110946. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110947. 0.0 */
  110948. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110949. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110950. #endif
  110951. /*** End of inlined file: scales.h ***/
  110952. int analysis_noisy=1;
  110953. /* decides between modes, dispatches to the appropriate mapping. */
  110954. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110955. int ret,i;
  110956. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110957. vb->glue_bits=0;
  110958. vb->time_bits=0;
  110959. vb->floor_bits=0;
  110960. vb->res_bits=0;
  110961. /* first things first. Make sure encode is ready */
  110962. for(i=0;i<PACKETBLOBS;i++)
  110963. oggpack_reset(vbi->packetblob[i]);
  110964. /* we only have one mapping type (0), and we let the mapping code
  110965. itself figure out what soft mode to use. This allows easier
  110966. bitrate management */
  110967. if((ret=_mapping_P[0]->forward(vb)))
  110968. return(ret);
  110969. if(op){
  110970. if(vorbis_bitrate_managed(vb))
  110971. /* The app is using a bitmanaged mode... but not using the
  110972. bitrate management interface. */
  110973. return(OV_EINVAL);
  110974. op->packet=oggpack_get_buffer(&vb->opb);
  110975. op->bytes=oggpack_bytes(&vb->opb);
  110976. op->b_o_s=0;
  110977. op->e_o_s=vb->eofflag;
  110978. op->granulepos=vb->granulepos;
  110979. op->packetno=vb->sequence; /* for sake of completeness */
  110980. }
  110981. return(0);
  110982. }
  110983. /* there was no great place to put this.... */
  110984. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110985. int j;
  110986. FILE *of;
  110987. char buffer[80];
  110988. /* if(i==5870){*/
  110989. sprintf(buffer,"%s_%d.m",base,i);
  110990. of=fopen(buffer,"w");
  110991. if(!of)perror("failed to open data dump file");
  110992. for(j=0;j<n;j++){
  110993. if(bark){
  110994. float b=toBARK((4000.f*j/n)+.25);
  110995. fprintf(of,"%f ",b);
  110996. }else
  110997. if(off!=0)
  110998. fprintf(of,"%f ",(double)(j+off)/8000.);
  110999. else
  111000. fprintf(of,"%f ",(double)j);
  111001. if(dB){
  111002. float val;
  111003. if(v[j]==0.)
  111004. val=-140.;
  111005. else
  111006. val=todB(v+j);
  111007. fprintf(of,"%f\n",val);
  111008. }else{
  111009. fprintf(of,"%f\n",v[j]);
  111010. }
  111011. }
  111012. fclose(of);
  111013. /* } */
  111014. }
  111015. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  111016. ogg_int64_t off){
  111017. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  111018. }
  111019. #endif
  111020. /*** End of inlined file: analysis.c ***/
  111021. /*** Start of inlined file: bitrate.c ***/
  111022. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111023. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111024. // tasks..
  111025. #if JUCE_MSVC
  111026. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111027. #endif
  111028. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111029. #if JUCE_USE_OGGVORBIS
  111030. #include <stdlib.h>
  111031. #include <string.h>
  111032. #include <math.h>
  111033. /* compute bitrate tracking setup */
  111034. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  111035. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111036. bitrate_manager_info *bi=&ci->bi;
  111037. memset(bm,0,sizeof(*bm));
  111038. if(bi && (bi->reservoir_bits>0)){
  111039. long ratesamples=vi->rate;
  111040. int halfsamples=ci->blocksizes[0]>>1;
  111041. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  111042. bm->managed=1;
  111043. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  111044. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  111045. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  111046. bm->avgfloat=PACKETBLOBS/2;
  111047. /* not a necessary fix, but one that leads to a more balanced
  111048. typical initialization */
  111049. {
  111050. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111051. bm->minmax_reservoir=desired_fill;
  111052. bm->avg_reservoir=desired_fill;
  111053. }
  111054. }
  111055. }
  111056. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  111057. memset(bm,0,sizeof(*bm));
  111058. return;
  111059. }
  111060. int vorbis_bitrate_managed(vorbis_block *vb){
  111061. vorbis_dsp_state *vd=vb->vd;
  111062. private_state *b=(private_state*)vd->backend_state;
  111063. bitrate_manager_state *bm=&b->bms;
  111064. if(bm && bm->managed)return(1);
  111065. return(0);
  111066. }
  111067. /* finish taking in the block we just processed */
  111068. int vorbis_bitrate_addblock(vorbis_block *vb){
  111069. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111070. vorbis_dsp_state *vd=vb->vd;
  111071. private_state *b=(private_state*)vd->backend_state;
  111072. bitrate_manager_state *bm=&b->bms;
  111073. vorbis_info *vi=vd->vi;
  111074. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111075. bitrate_manager_info *bi=&ci->bi;
  111076. int choice=rint(bm->avgfloat);
  111077. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111078. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111079. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111080. int samples=ci->blocksizes[vb->W]>>1;
  111081. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111082. if(!bm->managed){
  111083. /* not a bitrate managed stream, but for API simplicity, we'll
  111084. buffer the packet to keep the code path clean */
  111085. if(bm->vb)return(-1); /* one has been submitted without
  111086. being claimed */
  111087. bm->vb=vb;
  111088. return(0);
  111089. }
  111090. bm->vb=vb;
  111091. /* look ahead for avg floater */
  111092. if(bm->avg_bitsper>0){
  111093. double slew=0.;
  111094. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111095. double slewlimit= 15./bi->slew_damp;
  111096. /* choosing a new floater:
  111097. if we're over target, we slew down
  111098. if we're under target, we slew up
  111099. choose slew as follows: look through packetblobs of this frame
  111100. and set slew as the first in the appropriate direction that
  111101. gives us the slew we want. This may mean no slew if delta is
  111102. already favorable.
  111103. Then limit slew to slew max */
  111104. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111105. while(choice>0 && this_bits>avg_target_bits &&
  111106. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111107. choice--;
  111108. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111109. }
  111110. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111111. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111112. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111113. choice++;
  111114. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111115. }
  111116. }
  111117. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111118. if(slew<-slewlimit)slew=-slewlimit;
  111119. if(slew>slewlimit)slew=slewlimit;
  111120. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111121. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111122. }
  111123. /* enforce min(if used) on the current floater (if used) */
  111124. if(bm->min_bitsper>0){
  111125. /* do we need to force the bitrate up? */
  111126. if(this_bits<min_target_bits){
  111127. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111128. choice++;
  111129. if(choice>=PACKETBLOBS)break;
  111130. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111131. }
  111132. }
  111133. }
  111134. /* enforce max (if used) on the current floater (if used) */
  111135. if(bm->max_bitsper>0){
  111136. /* do we need to force the bitrate down? */
  111137. if(this_bits>max_target_bits){
  111138. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111139. choice--;
  111140. if(choice<0)break;
  111141. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111142. }
  111143. }
  111144. }
  111145. /* Choice of packetblobs now made based on floater, and min/max
  111146. requirements. Now boundary check extreme choices */
  111147. if(choice<0){
  111148. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111149. frame will need to be truncated */
  111150. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111151. bm->choice=choice=0;
  111152. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111153. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111154. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111155. }
  111156. }else{
  111157. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111158. if(choice>=PACKETBLOBS)
  111159. choice=PACKETBLOBS-1;
  111160. bm->choice=choice;
  111161. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111162. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111163. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111164. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111165. }
  111166. /* now we have the final packet and the final packet size. Update statistics */
  111167. /* min and max reservoir */
  111168. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111169. if(max_target_bits>0 && this_bits>max_target_bits){
  111170. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111171. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111172. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111173. }else{
  111174. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111175. if(bm->minmax_reservoir>desired_fill){
  111176. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111177. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111178. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111179. }else{
  111180. bm->minmax_reservoir=desired_fill;
  111181. }
  111182. }else{
  111183. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111184. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111185. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111186. }else{
  111187. bm->minmax_reservoir=desired_fill;
  111188. }
  111189. }
  111190. }
  111191. }
  111192. /* avg reservoir */
  111193. if(bm->avg_bitsper>0){
  111194. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111195. bm->avg_reservoir+=this_bits-avg_target_bits;
  111196. }
  111197. return(0);
  111198. }
  111199. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111200. private_state *b=(private_state*)vd->backend_state;
  111201. bitrate_manager_state *bm=&b->bms;
  111202. vorbis_block *vb=bm->vb;
  111203. int choice=PACKETBLOBS/2;
  111204. if(!vb)return 0;
  111205. if(op){
  111206. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111207. if(vorbis_bitrate_managed(vb))
  111208. choice=bm->choice;
  111209. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111210. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111211. op->b_o_s=0;
  111212. op->e_o_s=vb->eofflag;
  111213. op->granulepos=vb->granulepos;
  111214. op->packetno=vb->sequence; /* for sake of completeness */
  111215. }
  111216. bm->vb=0;
  111217. return(1);
  111218. }
  111219. #endif
  111220. /*** End of inlined file: bitrate.c ***/
  111221. /*** Start of inlined file: block.c ***/
  111222. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111223. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111224. // tasks..
  111225. #if JUCE_MSVC
  111226. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111227. #endif
  111228. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111229. #if JUCE_USE_OGGVORBIS
  111230. #include <stdio.h>
  111231. #include <stdlib.h>
  111232. #include <string.h>
  111233. /*** Start of inlined file: window.h ***/
  111234. #ifndef _V_WINDOW_
  111235. #define _V_WINDOW_
  111236. extern float *_vorbis_window_get(int n);
  111237. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111238. int lW,int W,int nW);
  111239. #endif
  111240. /*** End of inlined file: window.h ***/
  111241. /*** Start of inlined file: lpc.h ***/
  111242. #ifndef _V_LPC_H_
  111243. #define _V_LPC_H_
  111244. /* simple linear scale LPC code */
  111245. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111246. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111247. float *data,long n);
  111248. #endif
  111249. /*** End of inlined file: lpc.h ***/
  111250. /* pcm accumulator examples (not exhaustive):
  111251. <-------------- lW ---------------->
  111252. <--------------- W ---------------->
  111253. : .....|..... _______________ |
  111254. : .''' | '''_--- | |\ |
  111255. :.....''' |_____--- '''......| | \_______|
  111256. :.................|__________________|_______|__|______|
  111257. |<------ Sl ------>| > Sr < |endW
  111258. |beginSl |endSl | |endSr
  111259. |beginW |endlW |beginSr
  111260. |< lW >|
  111261. <--------------- W ---------------->
  111262. | | .. ______________ |
  111263. | | ' `/ | ---_ |
  111264. |___.'___/`. | ---_____|
  111265. |_______|__|_______|_________________|
  111266. | >|Sl|< |<------ Sr ----->|endW
  111267. | | |endSl |beginSr |endSr
  111268. |beginW | |endlW
  111269. mult[0] |beginSl mult[n]
  111270. <-------------- lW ----------------->
  111271. |<--W-->|
  111272. : .............. ___ | |
  111273. : .''' |`/ \ | |
  111274. :.....''' |/`....\|...|
  111275. :.........................|___|___|___|
  111276. |Sl |Sr |endW
  111277. | | |endSr
  111278. | |beginSr
  111279. | |endSl
  111280. |beginSl
  111281. |beginW
  111282. */
  111283. /* block abstraction setup *********************************************/
  111284. #ifndef WORD_ALIGN
  111285. #define WORD_ALIGN 8
  111286. #endif
  111287. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111288. int i;
  111289. memset(vb,0,sizeof(*vb));
  111290. vb->vd=v;
  111291. vb->localalloc=0;
  111292. vb->localstore=NULL;
  111293. if(v->analysisp){
  111294. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111295. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111296. vbi->ampmax=-9999;
  111297. for(i=0;i<PACKETBLOBS;i++){
  111298. if(i==PACKETBLOBS/2){
  111299. vbi->packetblob[i]=&vb->opb;
  111300. }else{
  111301. vbi->packetblob[i]=
  111302. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111303. }
  111304. oggpack_writeinit(vbi->packetblob[i]);
  111305. }
  111306. }
  111307. return(0);
  111308. }
  111309. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111310. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111311. if(bytes+vb->localtop>vb->localalloc){
  111312. /* can't just _ogg_realloc... there are outstanding pointers */
  111313. if(vb->localstore){
  111314. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111315. vb->totaluse+=vb->localtop;
  111316. link->next=vb->reap;
  111317. link->ptr=vb->localstore;
  111318. vb->reap=link;
  111319. }
  111320. /* highly conservative */
  111321. vb->localalloc=bytes;
  111322. vb->localstore=_ogg_malloc(vb->localalloc);
  111323. vb->localtop=0;
  111324. }
  111325. {
  111326. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111327. vb->localtop+=bytes;
  111328. return ret;
  111329. }
  111330. }
  111331. /* reap the chain, pull the ripcord */
  111332. void _vorbis_block_ripcord(vorbis_block *vb){
  111333. /* reap the chain */
  111334. struct alloc_chain *reap=vb->reap;
  111335. while(reap){
  111336. struct alloc_chain *next=reap->next;
  111337. _ogg_free(reap->ptr);
  111338. memset(reap,0,sizeof(*reap));
  111339. _ogg_free(reap);
  111340. reap=next;
  111341. }
  111342. /* consolidate storage */
  111343. if(vb->totaluse){
  111344. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111345. vb->localalloc+=vb->totaluse;
  111346. vb->totaluse=0;
  111347. }
  111348. /* pull the ripcord */
  111349. vb->localtop=0;
  111350. vb->reap=NULL;
  111351. }
  111352. int vorbis_block_clear(vorbis_block *vb){
  111353. int i;
  111354. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111355. _vorbis_block_ripcord(vb);
  111356. if(vb->localstore)_ogg_free(vb->localstore);
  111357. if(vbi){
  111358. for(i=0;i<PACKETBLOBS;i++){
  111359. oggpack_writeclear(vbi->packetblob[i]);
  111360. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111361. }
  111362. _ogg_free(vbi);
  111363. }
  111364. memset(vb,0,sizeof(*vb));
  111365. return(0);
  111366. }
  111367. /* Analysis side code, but directly related to blocking. Thus it's
  111368. here and not in analysis.c (which is for analysis transforms only).
  111369. The init is here because some of it is shared */
  111370. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111371. int i;
  111372. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111373. private_state *b=NULL;
  111374. int hs;
  111375. if(ci==NULL) return 1;
  111376. hs=ci->halfrate_flag;
  111377. memset(v,0,sizeof(*v));
  111378. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111379. v->vi=vi;
  111380. b->modebits=ilog2(ci->modes);
  111381. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111382. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111383. /* MDCT is tranform 0 */
  111384. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111385. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111386. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111387. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111388. /* Vorbis I uses only window type 0 */
  111389. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111390. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111391. if(encp){ /* encode/decode differ here */
  111392. /* analysis always needs an fft */
  111393. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111394. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111395. /* finish the codebooks */
  111396. if(!ci->fullbooks){
  111397. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111398. for(i=0;i<ci->books;i++)
  111399. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111400. }
  111401. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111402. for(i=0;i<ci->psys;i++){
  111403. _vp_psy_init(b->psy+i,
  111404. ci->psy_param[i],
  111405. &ci->psy_g_param,
  111406. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111407. vi->rate);
  111408. }
  111409. v->analysisp=1;
  111410. }else{
  111411. /* finish the codebooks */
  111412. if(!ci->fullbooks){
  111413. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111414. for(i=0;i<ci->books;i++){
  111415. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111416. /* decode codebooks are now standalone after init */
  111417. vorbis_staticbook_destroy(ci->book_param[i]);
  111418. ci->book_param[i]=NULL;
  111419. }
  111420. }
  111421. }
  111422. /* initialize the storage vectors. blocksize[1] is small for encode,
  111423. but the correct size for decode */
  111424. v->pcm_storage=ci->blocksizes[1];
  111425. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111426. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111427. {
  111428. int i;
  111429. for(i=0;i<vi->channels;i++)
  111430. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111431. }
  111432. /* all 1 (large block) or 0 (small block) */
  111433. /* explicitly set for the sake of clarity */
  111434. v->lW=0; /* previous window size */
  111435. v->W=0; /* current window size */
  111436. /* all vector indexes */
  111437. v->centerW=ci->blocksizes[1]/2;
  111438. v->pcm_current=v->centerW;
  111439. /* initialize all the backend lookups */
  111440. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111441. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111442. for(i=0;i<ci->floors;i++)
  111443. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111444. look(v,ci->floor_param[i]);
  111445. for(i=0;i<ci->residues;i++)
  111446. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111447. look(v,ci->residue_param[i]);
  111448. return 0;
  111449. }
  111450. /* arbitrary settings and spec-mandated numbers get filled in here */
  111451. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111452. private_state *b=NULL;
  111453. if(_vds_shared_init(v,vi,1))return 1;
  111454. b=(private_state*)v->backend_state;
  111455. b->psy_g_look=_vp_global_look(vi);
  111456. /* Initialize the envelope state storage */
  111457. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111458. _ve_envelope_init(b->ve,vi);
  111459. vorbis_bitrate_init(vi,&b->bms);
  111460. /* compressed audio packets start after the headers
  111461. with sequence number 3 */
  111462. v->sequence=3;
  111463. return(0);
  111464. }
  111465. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111466. int i;
  111467. if(v){
  111468. vorbis_info *vi=v->vi;
  111469. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111470. private_state *b=(private_state*)v->backend_state;
  111471. if(b){
  111472. if(b->ve){
  111473. _ve_envelope_clear(b->ve);
  111474. _ogg_free(b->ve);
  111475. }
  111476. if(b->transform[0]){
  111477. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111478. _ogg_free(b->transform[0][0]);
  111479. _ogg_free(b->transform[0]);
  111480. }
  111481. if(b->transform[1]){
  111482. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111483. _ogg_free(b->transform[1][0]);
  111484. _ogg_free(b->transform[1]);
  111485. }
  111486. if(b->flr){
  111487. for(i=0;i<ci->floors;i++)
  111488. _floor_P[ci->floor_type[i]]->
  111489. free_look(b->flr[i]);
  111490. _ogg_free(b->flr);
  111491. }
  111492. if(b->residue){
  111493. for(i=0;i<ci->residues;i++)
  111494. _residue_P[ci->residue_type[i]]->
  111495. free_look(b->residue[i]);
  111496. _ogg_free(b->residue);
  111497. }
  111498. if(b->psy){
  111499. for(i=0;i<ci->psys;i++)
  111500. _vp_psy_clear(b->psy+i);
  111501. _ogg_free(b->psy);
  111502. }
  111503. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111504. vorbis_bitrate_clear(&b->bms);
  111505. drft_clear(&b->fft_look[0]);
  111506. drft_clear(&b->fft_look[1]);
  111507. }
  111508. if(v->pcm){
  111509. for(i=0;i<vi->channels;i++)
  111510. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111511. _ogg_free(v->pcm);
  111512. if(v->pcmret)_ogg_free(v->pcmret);
  111513. }
  111514. if(b){
  111515. /* free header, header1, header2 */
  111516. if(b->header)_ogg_free(b->header);
  111517. if(b->header1)_ogg_free(b->header1);
  111518. if(b->header2)_ogg_free(b->header2);
  111519. _ogg_free(b);
  111520. }
  111521. memset(v,0,sizeof(*v));
  111522. }
  111523. }
  111524. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111525. int i;
  111526. vorbis_info *vi=v->vi;
  111527. private_state *b=(private_state*)v->backend_state;
  111528. /* free header, header1, header2 */
  111529. if(b->header)_ogg_free(b->header);b->header=NULL;
  111530. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111531. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111532. /* Do we have enough storage space for the requested buffer? If not,
  111533. expand the PCM (and envelope) storage */
  111534. if(v->pcm_current+vals>=v->pcm_storage){
  111535. v->pcm_storage=v->pcm_current+vals*2;
  111536. for(i=0;i<vi->channels;i++){
  111537. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111538. }
  111539. }
  111540. for(i=0;i<vi->channels;i++)
  111541. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111542. return(v->pcmret);
  111543. }
  111544. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111545. int i;
  111546. int order=32;
  111547. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111548. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111549. long j;
  111550. v->preextrapolate=1;
  111551. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111552. for(i=0;i<v->vi->channels;i++){
  111553. /* need to run the extrapolation in reverse! */
  111554. for(j=0;j<v->pcm_current;j++)
  111555. work[j]=v->pcm[i][v->pcm_current-j-1];
  111556. /* prime as above */
  111557. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111558. /* run the predictor filter */
  111559. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111560. order,
  111561. work+v->pcm_current-v->centerW,
  111562. v->centerW);
  111563. for(j=0;j<v->pcm_current;j++)
  111564. v->pcm[i][v->pcm_current-j-1]=work[j];
  111565. }
  111566. }
  111567. }
  111568. /* call with val<=0 to set eof */
  111569. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111570. vorbis_info *vi=v->vi;
  111571. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111572. if(vals<=0){
  111573. int order=32;
  111574. int i;
  111575. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111576. /* if it wasn't done earlier (very short sample) */
  111577. if(!v->preextrapolate)
  111578. _preextrapolate_helper(v);
  111579. /* We're encoding the end of the stream. Just make sure we have
  111580. [at least] a few full blocks of zeroes at the end. */
  111581. /* actually, we don't want zeroes; that could drop a large
  111582. amplitude off a cliff, creating spread spectrum noise that will
  111583. suck to encode. Extrapolate for the sake of cleanliness. */
  111584. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111585. v->eofflag=v->pcm_current;
  111586. v->pcm_current+=ci->blocksizes[1]*3;
  111587. for(i=0;i<vi->channels;i++){
  111588. if(v->eofflag>order*2){
  111589. /* extrapolate with LPC to fill in */
  111590. long n;
  111591. /* make a predictor filter */
  111592. n=v->eofflag;
  111593. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111594. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111595. /* run the predictor filter */
  111596. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111597. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111598. }else{
  111599. /* not enough data to extrapolate (unlikely to happen due to
  111600. guarding the overlap, but bulletproof in case that
  111601. assumtion goes away). zeroes will do. */
  111602. memset(v->pcm[i]+v->eofflag,0,
  111603. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111604. }
  111605. }
  111606. }else{
  111607. if(v->pcm_current+vals>v->pcm_storage)
  111608. return(OV_EINVAL);
  111609. v->pcm_current+=vals;
  111610. /* we may want to reverse extrapolate the beginning of a stream
  111611. too... in case we're beginning on a cliff! */
  111612. /* clumsy, but simple. It only runs once, so simple is good. */
  111613. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111614. _preextrapolate_helper(v);
  111615. }
  111616. return(0);
  111617. }
  111618. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111619. the next block on which to continue analysis */
  111620. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111621. int i;
  111622. vorbis_info *vi=v->vi;
  111623. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111624. private_state *b=(private_state*)v->backend_state;
  111625. vorbis_look_psy_global *g=b->psy_g_look;
  111626. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111627. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111628. /* check to see if we're started... */
  111629. if(!v->preextrapolate)return(0);
  111630. /* check to see if we're done... */
  111631. if(v->eofflag==-1)return(0);
  111632. /* By our invariant, we have lW, W and centerW set. Search for
  111633. the next boundary so we can determine nW (the next window size)
  111634. which lets us compute the shape of the current block's window */
  111635. /* we do an envelope search even on a single blocksize; we may still
  111636. be throwing more bits at impulses, and envelope search handles
  111637. marking impulses too. */
  111638. {
  111639. long bp=_ve_envelope_search(v);
  111640. if(bp==-1){
  111641. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111642. full long block */
  111643. v->nW=0;
  111644. }else{
  111645. if(ci->blocksizes[0]==ci->blocksizes[1])
  111646. v->nW=0;
  111647. else
  111648. v->nW=bp;
  111649. }
  111650. }
  111651. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111652. {
  111653. /* center of next block + next block maximum right side. */
  111654. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111655. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111656. although this check is
  111657. less strict that the
  111658. _ve_envelope_search,
  111659. the search is not run
  111660. if we only use one
  111661. block size */
  111662. }
  111663. /* fill in the block. Note that for a short window, lW and nW are *short*
  111664. regardless of actual settings in the stream */
  111665. _vorbis_block_ripcord(vb);
  111666. vb->lW=v->lW;
  111667. vb->W=v->W;
  111668. vb->nW=v->nW;
  111669. if(v->W){
  111670. if(!v->lW || !v->nW){
  111671. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111672. /*fprintf(stderr,"-");*/
  111673. }else{
  111674. vbi->blocktype=BLOCKTYPE_LONG;
  111675. /*fprintf(stderr,"_");*/
  111676. }
  111677. }else{
  111678. if(_ve_envelope_mark(v)){
  111679. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111680. /*fprintf(stderr,"|");*/
  111681. }else{
  111682. vbi->blocktype=BLOCKTYPE_PADDING;
  111683. /*fprintf(stderr,".");*/
  111684. }
  111685. }
  111686. vb->vd=v;
  111687. vb->sequence=v->sequence++;
  111688. vb->granulepos=v->granulepos;
  111689. vb->pcmend=ci->blocksizes[v->W];
  111690. /* copy the vectors; this uses the local storage in vb */
  111691. /* this tracks 'strongest peak' for later psychoacoustics */
  111692. /* moved to the global psy state; clean this mess up */
  111693. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111694. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111695. vbi->ampmax=g->ampmax;
  111696. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111697. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111698. for(i=0;i<vi->channels;i++){
  111699. vbi->pcmdelay[i]=
  111700. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111701. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111702. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111703. /* before we added the delay
  111704. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111705. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111706. */
  111707. }
  111708. /* handle eof detection: eof==0 means that we've not yet received EOF
  111709. eof>0 marks the last 'real' sample in pcm[]
  111710. eof<0 'no more to do'; doesn't get here */
  111711. if(v->eofflag){
  111712. if(v->centerW>=v->eofflag){
  111713. v->eofflag=-1;
  111714. vb->eofflag=1;
  111715. return(1);
  111716. }
  111717. }
  111718. /* advance storage vectors and clean up */
  111719. {
  111720. int new_centerNext=ci->blocksizes[1]/2;
  111721. int movementW=centerNext-new_centerNext;
  111722. if(movementW>0){
  111723. _ve_envelope_shift(b->ve,movementW);
  111724. v->pcm_current-=movementW;
  111725. for(i=0;i<vi->channels;i++)
  111726. memmove(v->pcm[i],v->pcm[i]+movementW,
  111727. v->pcm_current*sizeof(*v->pcm[i]));
  111728. v->lW=v->W;
  111729. v->W=v->nW;
  111730. v->centerW=new_centerNext;
  111731. if(v->eofflag){
  111732. v->eofflag-=movementW;
  111733. if(v->eofflag<=0)v->eofflag=-1;
  111734. /* do not add padding to end of stream! */
  111735. if(v->centerW>=v->eofflag){
  111736. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111737. }else{
  111738. v->granulepos+=movementW;
  111739. }
  111740. }else{
  111741. v->granulepos+=movementW;
  111742. }
  111743. }
  111744. }
  111745. /* done */
  111746. return(1);
  111747. }
  111748. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111749. vorbis_info *vi=v->vi;
  111750. codec_setup_info *ci;
  111751. int hs;
  111752. if(!v->backend_state)return -1;
  111753. if(!vi)return -1;
  111754. ci=(codec_setup_info*) vi->codec_setup;
  111755. if(!ci)return -1;
  111756. hs=ci->halfrate_flag;
  111757. v->centerW=ci->blocksizes[1]>>(hs+1);
  111758. v->pcm_current=v->centerW>>hs;
  111759. v->pcm_returned=-1;
  111760. v->granulepos=-1;
  111761. v->sequence=-1;
  111762. v->eofflag=0;
  111763. ((private_state *)(v->backend_state))->sample_count=-1;
  111764. return(0);
  111765. }
  111766. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111767. if(_vds_shared_init(v,vi,0)) return 1;
  111768. vorbis_synthesis_restart(v);
  111769. return 0;
  111770. }
  111771. /* Unlike in analysis, the window is only partially applied for each
  111772. block. The time domain envelope is not yet handled at the point of
  111773. calling (as it relies on the previous block). */
  111774. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111775. vorbis_info *vi=v->vi;
  111776. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111777. private_state *b=(private_state*)v->backend_state;
  111778. int hs=ci->halfrate_flag;
  111779. int i,j;
  111780. if(!vb)return(OV_EINVAL);
  111781. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111782. v->lW=v->W;
  111783. v->W=vb->W;
  111784. v->nW=-1;
  111785. if((v->sequence==-1)||
  111786. (v->sequence+1 != vb->sequence)){
  111787. v->granulepos=-1; /* out of sequence; lose count */
  111788. b->sample_count=-1;
  111789. }
  111790. v->sequence=vb->sequence;
  111791. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111792. was called on block */
  111793. int n=ci->blocksizes[v->W]>>(hs+1);
  111794. int n0=ci->blocksizes[0]>>(hs+1);
  111795. int n1=ci->blocksizes[1]>>(hs+1);
  111796. int thisCenter;
  111797. int prevCenter;
  111798. v->glue_bits+=vb->glue_bits;
  111799. v->time_bits+=vb->time_bits;
  111800. v->floor_bits+=vb->floor_bits;
  111801. v->res_bits+=vb->res_bits;
  111802. if(v->centerW){
  111803. thisCenter=n1;
  111804. prevCenter=0;
  111805. }else{
  111806. thisCenter=0;
  111807. prevCenter=n1;
  111808. }
  111809. /* v->pcm is now used like a two-stage double buffer. We don't want
  111810. to have to constantly shift *or* adjust memory usage. Don't
  111811. accept a new block until the old is shifted out */
  111812. for(j=0;j<vi->channels;j++){
  111813. /* the overlap/add section */
  111814. if(v->lW){
  111815. if(v->W){
  111816. /* large/large */
  111817. float *w=_vorbis_window_get(b->window[1]-hs);
  111818. float *pcm=v->pcm[j]+prevCenter;
  111819. float *p=vb->pcm[j];
  111820. for(i=0;i<n1;i++)
  111821. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111822. }else{
  111823. /* large/small */
  111824. float *w=_vorbis_window_get(b->window[0]-hs);
  111825. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111826. float *p=vb->pcm[j];
  111827. for(i=0;i<n0;i++)
  111828. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111829. }
  111830. }else{
  111831. if(v->W){
  111832. /* small/large */
  111833. float *w=_vorbis_window_get(b->window[0]-hs);
  111834. float *pcm=v->pcm[j]+prevCenter;
  111835. float *p=vb->pcm[j]+n1/2-n0/2;
  111836. for(i=0;i<n0;i++)
  111837. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111838. for(;i<n1/2+n0/2;i++)
  111839. pcm[i]=p[i];
  111840. }else{
  111841. /* small/small */
  111842. float *w=_vorbis_window_get(b->window[0]-hs);
  111843. float *pcm=v->pcm[j]+prevCenter;
  111844. float *p=vb->pcm[j];
  111845. for(i=0;i<n0;i++)
  111846. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111847. }
  111848. }
  111849. /* the copy section */
  111850. {
  111851. float *pcm=v->pcm[j]+thisCenter;
  111852. float *p=vb->pcm[j]+n;
  111853. for(i=0;i<n;i++)
  111854. pcm[i]=p[i];
  111855. }
  111856. }
  111857. if(v->centerW)
  111858. v->centerW=0;
  111859. else
  111860. v->centerW=n1;
  111861. /* deal with initial packet state; we do this using the explicit
  111862. pcm_returned==-1 flag otherwise we're sensitive to first block
  111863. being short or long */
  111864. if(v->pcm_returned==-1){
  111865. v->pcm_returned=thisCenter;
  111866. v->pcm_current=thisCenter;
  111867. }else{
  111868. v->pcm_returned=prevCenter;
  111869. v->pcm_current=prevCenter+
  111870. ((ci->blocksizes[v->lW]/4+
  111871. ci->blocksizes[v->W]/4)>>hs);
  111872. }
  111873. }
  111874. /* track the frame number... This is for convenience, but also
  111875. making sure our last packet doesn't end with added padding. If
  111876. the last packet is partial, the number of samples we'll have to
  111877. return will be past the vb->granulepos.
  111878. This is not foolproof! It will be confused if we begin
  111879. decoding at the last page after a seek or hole. In that case,
  111880. we don't have a starting point to judge where the last frame
  111881. is. For this reason, vorbisfile will always try to make sure
  111882. it reads the last two marked pages in proper sequence */
  111883. if(b->sample_count==-1){
  111884. b->sample_count=0;
  111885. }else{
  111886. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111887. }
  111888. if(v->granulepos==-1){
  111889. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111890. v->granulepos=vb->granulepos;
  111891. /* is this a short page? */
  111892. if(b->sample_count>v->granulepos){
  111893. /* corner case; if this is both the first and last audio page,
  111894. then spec says the end is cut, not beginning */
  111895. if(vb->eofflag){
  111896. /* trim the end */
  111897. /* no preceeding granulepos; assume we started at zero (we'd
  111898. have to in a short single-page stream) */
  111899. /* granulepos could be -1 due to a seek, but that would result
  111900. in a long count, not short count */
  111901. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111902. }else{
  111903. /* trim the beginning */
  111904. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111905. if(v->pcm_returned>v->pcm_current)
  111906. v->pcm_returned=v->pcm_current;
  111907. }
  111908. }
  111909. }
  111910. }else{
  111911. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111912. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111913. if(v->granulepos>vb->granulepos){
  111914. long extra=v->granulepos-vb->granulepos;
  111915. if(extra)
  111916. if(vb->eofflag){
  111917. /* partial last frame. Strip the extra samples off */
  111918. v->pcm_current-=extra>>hs;
  111919. } /* else {Shouldn't happen *unless* the bitstream is out of
  111920. spec. Either way, believe the bitstream } */
  111921. } /* else {Shouldn't happen *unless* the bitstream is out of
  111922. spec. Either way, believe the bitstream } */
  111923. v->granulepos=vb->granulepos;
  111924. }
  111925. }
  111926. /* Update, cleanup */
  111927. if(vb->eofflag)v->eofflag=1;
  111928. return(0);
  111929. }
  111930. /* pcm==NULL indicates we just want the pending samples, no more */
  111931. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111932. vorbis_info *vi=v->vi;
  111933. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111934. if(pcm){
  111935. int i;
  111936. for(i=0;i<vi->channels;i++)
  111937. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111938. *pcm=v->pcmret;
  111939. }
  111940. return(v->pcm_current-v->pcm_returned);
  111941. }
  111942. return(0);
  111943. }
  111944. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111945. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111946. v->pcm_returned+=n;
  111947. return(0);
  111948. }
  111949. /* intended for use with a specific vorbisfile feature; we want access
  111950. to the [usually synthetic/postextrapolated] buffer and lapping at
  111951. the end of a decode cycle, specifically, a half-short-block worth.
  111952. This funtion works like pcmout above, except it will also expose
  111953. this implicit buffer data not normally decoded. */
  111954. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111955. vorbis_info *vi=v->vi;
  111956. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111957. int hs=ci->halfrate_flag;
  111958. int n=ci->blocksizes[v->W]>>(hs+1);
  111959. int n0=ci->blocksizes[0]>>(hs+1);
  111960. int n1=ci->blocksizes[1]>>(hs+1);
  111961. int i,j;
  111962. if(v->pcm_returned<0)return 0;
  111963. /* our returned data ends at pcm_returned; because the synthesis pcm
  111964. buffer is a two-fragment ring, that means our data block may be
  111965. fragmented by buffering, wrapping or a short block not filling
  111966. out a buffer. To simplify things, we unfragment if it's at all
  111967. possibly needed. Otherwise, we'd need to call lapout more than
  111968. once as well as hold additional dsp state. Opt for
  111969. simplicity. */
  111970. /* centerW was advanced by blockin; it would be the center of the
  111971. *next* block */
  111972. if(v->centerW==n1){
  111973. /* the data buffer wraps; swap the halves */
  111974. /* slow, sure, small */
  111975. for(j=0;j<vi->channels;j++){
  111976. float *p=v->pcm[j];
  111977. for(i=0;i<n1;i++){
  111978. float temp=p[i];
  111979. p[i]=p[i+n1];
  111980. p[i+n1]=temp;
  111981. }
  111982. }
  111983. v->pcm_current-=n1;
  111984. v->pcm_returned-=n1;
  111985. v->centerW=0;
  111986. }
  111987. /* solidify buffer into contiguous space */
  111988. if((v->lW^v->W)==1){
  111989. /* long/short or short/long */
  111990. for(j=0;j<vi->channels;j++){
  111991. float *s=v->pcm[j];
  111992. float *d=v->pcm[j]+(n1-n0)/2;
  111993. for(i=(n1+n0)/2-1;i>=0;--i)
  111994. d[i]=s[i];
  111995. }
  111996. v->pcm_returned+=(n1-n0)/2;
  111997. v->pcm_current+=(n1-n0)/2;
  111998. }else{
  111999. if(v->lW==0){
  112000. /* short/short */
  112001. for(j=0;j<vi->channels;j++){
  112002. float *s=v->pcm[j];
  112003. float *d=v->pcm[j]+n1-n0;
  112004. for(i=n0-1;i>=0;--i)
  112005. d[i]=s[i];
  112006. }
  112007. v->pcm_returned+=n1-n0;
  112008. v->pcm_current+=n1-n0;
  112009. }
  112010. }
  112011. if(pcm){
  112012. int i;
  112013. for(i=0;i<vi->channels;i++)
  112014. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  112015. *pcm=v->pcmret;
  112016. }
  112017. return(n1+n-v->pcm_returned);
  112018. }
  112019. float *vorbis_window(vorbis_dsp_state *v,int W){
  112020. vorbis_info *vi=v->vi;
  112021. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112022. int hs=ci->halfrate_flag;
  112023. private_state *b=(private_state*)v->backend_state;
  112024. if(b->window[W]-1<0)return NULL;
  112025. return _vorbis_window_get(b->window[W]-hs);
  112026. }
  112027. #endif
  112028. /*** End of inlined file: block.c ***/
  112029. /*** Start of inlined file: codebook.c ***/
  112030. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112031. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112032. // tasks..
  112033. #if JUCE_MSVC
  112034. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112035. #endif
  112036. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112037. #if JUCE_USE_OGGVORBIS
  112038. #include <stdlib.h>
  112039. #include <string.h>
  112040. #include <math.h>
  112041. /* packs the given codebook into the bitstream **************************/
  112042. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  112043. long i,j;
  112044. int ordered=0;
  112045. /* first the basic parameters */
  112046. oggpack_write(opb,0x564342,24);
  112047. oggpack_write(opb,c->dim,16);
  112048. oggpack_write(opb,c->entries,24);
  112049. /* pack the codewords. There are two packings; length ordered and
  112050. length random. Decide between the two now. */
  112051. for(i=1;i<c->entries;i++)
  112052. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  112053. if(i==c->entries)ordered=1;
  112054. if(ordered){
  112055. /* length ordered. We only need to say how many codewords of
  112056. each length. The actual codewords are generated
  112057. deterministically */
  112058. long count=0;
  112059. oggpack_write(opb,1,1); /* ordered */
  112060. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  112061. for(i=1;i<c->entries;i++){
  112062. long thisx=c->lengthlist[i];
  112063. long last=c->lengthlist[i-1];
  112064. if(thisx>last){
  112065. for(j=last;j<thisx;j++){
  112066. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112067. count=i;
  112068. }
  112069. }
  112070. }
  112071. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112072. }else{
  112073. /* length random. Again, we don't code the codeword itself, just
  112074. the length. This time, though, we have to encode each length */
  112075. oggpack_write(opb,0,1); /* unordered */
  112076. /* algortihmic mapping has use for 'unused entries', which we tag
  112077. here. The algorithmic mapping happens as usual, but the unused
  112078. entry has no codeword. */
  112079. for(i=0;i<c->entries;i++)
  112080. if(c->lengthlist[i]==0)break;
  112081. if(i==c->entries){
  112082. oggpack_write(opb,0,1); /* no unused entries */
  112083. for(i=0;i<c->entries;i++)
  112084. oggpack_write(opb,c->lengthlist[i]-1,5);
  112085. }else{
  112086. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112087. for(i=0;i<c->entries;i++){
  112088. if(c->lengthlist[i]==0){
  112089. oggpack_write(opb,0,1);
  112090. }else{
  112091. oggpack_write(opb,1,1);
  112092. oggpack_write(opb,c->lengthlist[i]-1,5);
  112093. }
  112094. }
  112095. }
  112096. }
  112097. /* is the entry number the desired return value, or do we have a
  112098. mapping? If we have a mapping, what type? */
  112099. oggpack_write(opb,c->maptype,4);
  112100. switch(c->maptype){
  112101. case 0:
  112102. /* no mapping */
  112103. break;
  112104. case 1:case 2:
  112105. /* implicitly populated value mapping */
  112106. /* explicitly populated value mapping */
  112107. if(!c->quantlist){
  112108. /* no quantlist? error */
  112109. return(-1);
  112110. }
  112111. /* values that define the dequantization */
  112112. oggpack_write(opb,c->q_min,32);
  112113. oggpack_write(opb,c->q_delta,32);
  112114. oggpack_write(opb,c->q_quant-1,4);
  112115. oggpack_write(opb,c->q_sequencep,1);
  112116. {
  112117. int quantvals;
  112118. switch(c->maptype){
  112119. case 1:
  112120. /* a single column of (c->entries/c->dim) quantized values for
  112121. building a full value list algorithmically (square lattice) */
  112122. quantvals=_book_maptype1_quantvals(c);
  112123. break;
  112124. case 2:
  112125. /* every value (c->entries*c->dim total) specified explicitly */
  112126. quantvals=c->entries*c->dim;
  112127. break;
  112128. default: /* NOT_REACHABLE */
  112129. quantvals=-1;
  112130. }
  112131. /* quantized values */
  112132. for(i=0;i<quantvals;i++)
  112133. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112134. }
  112135. break;
  112136. default:
  112137. /* error case; we don't have any other map types now */
  112138. return(-1);
  112139. }
  112140. return(0);
  112141. }
  112142. /* unpacks a codebook from the packet buffer into the codebook struct,
  112143. readies the codebook auxiliary structures for decode *************/
  112144. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112145. long i,j;
  112146. memset(s,0,sizeof(*s));
  112147. s->allocedp=1;
  112148. /* make sure alignment is correct */
  112149. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112150. /* first the basic parameters */
  112151. s->dim=oggpack_read(opb,16);
  112152. s->entries=oggpack_read(opb,24);
  112153. if(s->entries==-1)goto _eofout;
  112154. /* codeword ordering.... length ordered or unordered? */
  112155. switch((int)oggpack_read(opb,1)){
  112156. case 0:
  112157. /* unordered */
  112158. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112159. /* allocated but unused entries? */
  112160. if(oggpack_read(opb,1)){
  112161. /* yes, unused entries */
  112162. for(i=0;i<s->entries;i++){
  112163. if(oggpack_read(opb,1)){
  112164. long num=oggpack_read(opb,5);
  112165. if(num==-1)goto _eofout;
  112166. s->lengthlist[i]=num+1;
  112167. }else
  112168. s->lengthlist[i]=0;
  112169. }
  112170. }else{
  112171. /* all entries used; no tagging */
  112172. for(i=0;i<s->entries;i++){
  112173. long num=oggpack_read(opb,5);
  112174. if(num==-1)goto _eofout;
  112175. s->lengthlist[i]=num+1;
  112176. }
  112177. }
  112178. break;
  112179. case 1:
  112180. /* ordered */
  112181. {
  112182. long length=oggpack_read(opb,5)+1;
  112183. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112184. for(i=0;i<s->entries;){
  112185. long num=oggpack_read(opb,_ilog(s->entries-i));
  112186. if(num==-1)goto _eofout;
  112187. for(j=0;j<num && i<s->entries;j++,i++)
  112188. s->lengthlist[i]=length;
  112189. length++;
  112190. }
  112191. }
  112192. break;
  112193. default:
  112194. /* EOF */
  112195. return(-1);
  112196. }
  112197. /* Do we have a mapping to unpack? */
  112198. switch((s->maptype=oggpack_read(opb,4))){
  112199. case 0:
  112200. /* no mapping */
  112201. break;
  112202. case 1: case 2:
  112203. /* implicitly populated value mapping */
  112204. /* explicitly populated value mapping */
  112205. s->q_min=oggpack_read(opb,32);
  112206. s->q_delta=oggpack_read(opb,32);
  112207. s->q_quant=oggpack_read(opb,4)+1;
  112208. s->q_sequencep=oggpack_read(opb,1);
  112209. {
  112210. int quantvals=0;
  112211. switch(s->maptype){
  112212. case 1:
  112213. quantvals=_book_maptype1_quantvals(s);
  112214. break;
  112215. case 2:
  112216. quantvals=s->entries*s->dim;
  112217. break;
  112218. }
  112219. /* quantized values */
  112220. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112221. for(i=0;i<quantvals;i++)
  112222. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112223. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112224. }
  112225. break;
  112226. default:
  112227. goto _errout;
  112228. }
  112229. /* all set */
  112230. return(0);
  112231. _errout:
  112232. _eofout:
  112233. vorbis_staticbook_clear(s);
  112234. return(-1);
  112235. }
  112236. /* returns the number of bits ************************************************/
  112237. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112238. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112239. return(book->c->lengthlist[a]);
  112240. }
  112241. /* One the encode side, our vector writers are each designed for a
  112242. specific purpose, and the encoder is not flexible without modification:
  112243. The LSP vector coder uses a single stage nearest-match with no
  112244. interleave, so no step and no error return. This is specced by floor0
  112245. and doesn't change.
  112246. Residue0 encoding interleaves, uses multiple stages, and each stage
  112247. peels of a specific amount of resolution from a lattice (thus we want
  112248. to match by threshold, not nearest match). Residue doesn't *have* to
  112249. be encoded that way, but to change it, one will need to add more
  112250. infrastructure on the encode side (decode side is specced and simpler) */
  112251. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112252. /* returns entry number and *modifies a* to the quantization value *****/
  112253. int vorbis_book_errorv(codebook *book,float *a){
  112254. int dim=book->dim,k;
  112255. int best=_best(book,a,1);
  112256. for(k=0;k<dim;k++)
  112257. a[k]=(book->valuelist+best*dim)[k];
  112258. return(best);
  112259. }
  112260. /* returns the number of bits and *modifies a* to the quantization value *****/
  112261. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112262. int k,dim=book->dim;
  112263. for(k=0;k<dim;k++)
  112264. a[k]=(book->valuelist+best*dim)[k];
  112265. return(vorbis_book_encode(book,best,b));
  112266. }
  112267. /* the 'eliminate the decode tree' optimization actually requires the
  112268. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112269. (and one of the first places where carefully thought out design
  112270. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112271. to an MSb bitpacker), but not actually the huge hit it appears to
  112272. be. The first-stage decode table catches most words so that
  112273. bitreverse is not in the main execution path. */
  112274. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112275. int read=book->dec_maxlength;
  112276. long lo,hi;
  112277. long lok = oggpack_look(b,book->dec_firsttablen);
  112278. if (lok >= 0) {
  112279. long entry = book->dec_firsttable[lok];
  112280. if(entry&0x80000000UL){
  112281. lo=(entry>>15)&0x7fff;
  112282. hi=book->used_entries-(entry&0x7fff);
  112283. }else{
  112284. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112285. return(entry-1);
  112286. }
  112287. }else{
  112288. lo=0;
  112289. hi=book->used_entries;
  112290. }
  112291. lok = oggpack_look(b, read);
  112292. while(lok<0 && read>1)
  112293. lok = oggpack_look(b, --read);
  112294. if(lok<0)return -1;
  112295. /* bisect search for the codeword in the ordered list */
  112296. {
  112297. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112298. while(hi-lo>1){
  112299. long p=(hi-lo)>>1;
  112300. long test=book->codelist[lo+p]>testword;
  112301. lo+=p&(test-1);
  112302. hi-=p&(-test);
  112303. }
  112304. if(book->dec_codelengths[lo]<=read){
  112305. oggpack_adv(b, book->dec_codelengths[lo]);
  112306. return(lo);
  112307. }
  112308. }
  112309. oggpack_adv(b, read);
  112310. return(-1);
  112311. }
  112312. /* Decode side is specced and easier, because we don't need to find
  112313. matches using different criteria; we simply read and map. There are
  112314. two things we need to do 'depending':
  112315. We may need to support interleave. We don't really, but it's
  112316. convenient to do it here rather than rebuild the vector later.
  112317. Cascades may be additive or multiplicitive; this is not inherent in
  112318. the codebook, but set in the code using the codebook. Like
  112319. interleaving, it's easiest to do it here.
  112320. addmul==0 -> declarative (set the value)
  112321. addmul==1 -> additive
  112322. addmul==2 -> multiplicitive */
  112323. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112324. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112325. long packed_entry=decode_packed_entry_number(book,b);
  112326. if(packed_entry>=0)
  112327. return(book->dec_index[packed_entry]);
  112328. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112329. return(packed_entry);
  112330. }
  112331. /* returns 0 on OK or -1 on eof *************************************/
  112332. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112333. int step=n/book->dim;
  112334. long *entry = (long*)alloca(sizeof(*entry)*step);
  112335. float **t = (float**)alloca(sizeof(*t)*step);
  112336. int i,j,o;
  112337. for (i = 0; i < step; i++) {
  112338. entry[i]=decode_packed_entry_number(book,b);
  112339. if(entry[i]==-1)return(-1);
  112340. t[i] = book->valuelist+entry[i]*book->dim;
  112341. }
  112342. for(i=0,o=0;i<book->dim;i++,o+=step)
  112343. for (j=0;j<step;j++)
  112344. a[o+j]+=t[j][i];
  112345. return(0);
  112346. }
  112347. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112348. int i,j,entry;
  112349. float *t;
  112350. if(book->dim>8){
  112351. for(i=0;i<n;){
  112352. entry = decode_packed_entry_number(book,b);
  112353. if(entry==-1)return(-1);
  112354. t = book->valuelist+entry*book->dim;
  112355. for (j=0;j<book->dim;)
  112356. a[i++]+=t[j++];
  112357. }
  112358. }else{
  112359. for(i=0;i<n;){
  112360. entry = decode_packed_entry_number(book,b);
  112361. if(entry==-1)return(-1);
  112362. t = book->valuelist+entry*book->dim;
  112363. j=0;
  112364. switch((int)book->dim){
  112365. case 8:
  112366. a[i++]+=t[j++];
  112367. case 7:
  112368. a[i++]+=t[j++];
  112369. case 6:
  112370. a[i++]+=t[j++];
  112371. case 5:
  112372. a[i++]+=t[j++];
  112373. case 4:
  112374. a[i++]+=t[j++];
  112375. case 3:
  112376. a[i++]+=t[j++];
  112377. case 2:
  112378. a[i++]+=t[j++];
  112379. case 1:
  112380. a[i++]+=t[j++];
  112381. case 0:
  112382. break;
  112383. }
  112384. }
  112385. }
  112386. return(0);
  112387. }
  112388. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112389. int i,j,entry;
  112390. float *t;
  112391. for(i=0;i<n;){
  112392. entry = decode_packed_entry_number(book,b);
  112393. if(entry==-1)return(-1);
  112394. t = book->valuelist+entry*book->dim;
  112395. for (j=0;j<book->dim;)
  112396. a[i++]=t[j++];
  112397. }
  112398. return(0);
  112399. }
  112400. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112401. oggpack_buffer *b,int n){
  112402. long i,j,entry;
  112403. int chptr=0;
  112404. for(i=offset/ch;i<(offset+n)/ch;){
  112405. entry = decode_packed_entry_number(book,b);
  112406. if(entry==-1)return(-1);
  112407. {
  112408. const float *t = book->valuelist+entry*book->dim;
  112409. for (j=0;j<book->dim;j++){
  112410. a[chptr++][i]+=t[j];
  112411. if(chptr==ch){
  112412. chptr=0;
  112413. i++;
  112414. }
  112415. }
  112416. }
  112417. }
  112418. return(0);
  112419. }
  112420. #ifdef _V_SELFTEST
  112421. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112422. number of vectors through (keeping track of the quantized values),
  112423. and decode using the unpacked book. quantized version of in should
  112424. exactly equal out */
  112425. #include <stdio.h>
  112426. #include "vorbis/book/lsp20_0.vqh"
  112427. #include "vorbis/book/res0a_13.vqh"
  112428. #define TESTSIZE 40
  112429. float test1[TESTSIZE]={
  112430. 0.105939f,
  112431. 0.215373f,
  112432. 0.429117f,
  112433. 0.587974f,
  112434. 0.181173f,
  112435. 0.296583f,
  112436. 0.515707f,
  112437. 0.715261f,
  112438. 0.162327f,
  112439. 0.263834f,
  112440. 0.342876f,
  112441. 0.406025f,
  112442. 0.103571f,
  112443. 0.223561f,
  112444. 0.368513f,
  112445. 0.540313f,
  112446. 0.136672f,
  112447. 0.395882f,
  112448. 0.587183f,
  112449. 0.652476f,
  112450. 0.114338f,
  112451. 0.417300f,
  112452. 0.525486f,
  112453. 0.698679f,
  112454. 0.147492f,
  112455. 0.324481f,
  112456. 0.643089f,
  112457. 0.757582f,
  112458. 0.139556f,
  112459. 0.215795f,
  112460. 0.324559f,
  112461. 0.399387f,
  112462. 0.120236f,
  112463. 0.267420f,
  112464. 0.446940f,
  112465. 0.608760f,
  112466. 0.115587f,
  112467. 0.287234f,
  112468. 0.571081f,
  112469. 0.708603f,
  112470. };
  112471. float test3[TESTSIZE]={
  112472. 0,1,-2,3,4,-5,6,7,8,9,
  112473. 8,-2,7,-1,4,6,8,3,1,-9,
  112474. 10,11,12,13,14,15,26,17,18,19,
  112475. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112476. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112477. &_vq_book_res0a_13,NULL};
  112478. float *testvec[]={test1,test3};
  112479. int main(){
  112480. oggpack_buffer write;
  112481. oggpack_buffer read;
  112482. long ptr=0,i;
  112483. oggpack_writeinit(&write);
  112484. fprintf(stderr,"Testing codebook abstraction...:\n");
  112485. while(testlist[ptr]){
  112486. codebook c;
  112487. static_codebook s;
  112488. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112489. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112490. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112491. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112492. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112493. /* pack the codebook, write the testvector */
  112494. oggpack_reset(&write);
  112495. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112496. we can write */
  112497. vorbis_staticbook_pack(testlist[ptr],&write);
  112498. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112499. for(i=0;i<TESTSIZE;i+=c.dim){
  112500. int best=_best(&c,qv+i,1);
  112501. vorbis_book_encodev(&c,best,qv+i,&write);
  112502. }
  112503. vorbis_book_clear(&c);
  112504. fprintf(stderr,"OK.\n");
  112505. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112506. /* transfer the write data to a read buffer and unpack/read */
  112507. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112508. if(vorbis_staticbook_unpack(&read,&s)){
  112509. fprintf(stderr,"Error unpacking codebook.\n");
  112510. exit(1);
  112511. }
  112512. if(vorbis_book_init_decode(&c,&s)){
  112513. fprintf(stderr,"Error initializing codebook.\n");
  112514. exit(1);
  112515. }
  112516. for(i=0;i<TESTSIZE;i+=c.dim)
  112517. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112518. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112519. exit(1);
  112520. }
  112521. for(i=0;i<TESTSIZE;i++)
  112522. if(fabs(qv[i]-iv[i])>.000001){
  112523. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112524. iv[i],qv[i],i);
  112525. exit(1);
  112526. }
  112527. fprintf(stderr,"OK\n");
  112528. ptr++;
  112529. }
  112530. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112531. exit(0);
  112532. }
  112533. #endif
  112534. #endif
  112535. /*** End of inlined file: codebook.c ***/
  112536. /*** Start of inlined file: envelope.c ***/
  112537. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112538. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112539. // tasks..
  112540. #if JUCE_MSVC
  112541. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112542. #endif
  112543. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112544. #if JUCE_USE_OGGVORBIS
  112545. #include <stdlib.h>
  112546. #include <string.h>
  112547. #include <stdio.h>
  112548. #include <math.h>
  112549. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112550. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112551. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112552. int ch=vi->channels;
  112553. int i,j;
  112554. int n=e->winlength=128;
  112555. e->searchstep=64; /* not random */
  112556. e->minenergy=gi->preecho_minenergy;
  112557. e->ch=ch;
  112558. e->storage=128;
  112559. e->cursor=ci->blocksizes[1]/2;
  112560. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112561. mdct_init(&e->mdct,n);
  112562. for(i=0;i<n;i++){
  112563. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112564. e->mdct_win[i]*=e->mdct_win[i];
  112565. }
  112566. /* magic follows */
  112567. e->band[0].begin=2; e->band[0].end=4;
  112568. e->band[1].begin=4; e->band[1].end=5;
  112569. e->band[2].begin=6; e->band[2].end=6;
  112570. e->band[3].begin=9; e->band[3].end=8;
  112571. e->band[4].begin=13; e->band[4].end=8;
  112572. e->band[5].begin=17; e->band[5].end=8;
  112573. e->band[6].begin=22; e->band[6].end=8;
  112574. for(j=0;j<VE_BANDS;j++){
  112575. n=e->band[j].end;
  112576. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112577. for(i=0;i<n;i++){
  112578. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112579. e->band[j].total+=e->band[j].window[i];
  112580. }
  112581. e->band[j].total=1./e->band[j].total;
  112582. }
  112583. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112584. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112585. }
  112586. void _ve_envelope_clear(envelope_lookup *e){
  112587. int i;
  112588. mdct_clear(&e->mdct);
  112589. for(i=0;i<VE_BANDS;i++)
  112590. _ogg_free(e->band[i].window);
  112591. _ogg_free(e->mdct_win);
  112592. _ogg_free(e->filter);
  112593. _ogg_free(e->mark);
  112594. memset(e,0,sizeof(*e));
  112595. }
  112596. /* fairly straight threshhold-by-band based until we find something
  112597. that works better and isn't patented. */
  112598. static int _ve_amp(envelope_lookup *ve,
  112599. vorbis_info_psy_global *gi,
  112600. float *data,
  112601. envelope_band *bands,
  112602. envelope_filter_state *filters,
  112603. long pos){
  112604. long n=ve->winlength;
  112605. int ret=0;
  112606. long i,j;
  112607. float decay;
  112608. /* we want to have a 'minimum bar' for energy, else we're just
  112609. basing blocks on quantization noise that outweighs the signal
  112610. itself (for low power signals) */
  112611. float minV=ve->minenergy;
  112612. float *vec=(float*) alloca(n*sizeof(*vec));
  112613. /* stretch is used to gradually lengthen the number of windows
  112614. considered prevoius-to-potential-trigger */
  112615. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112616. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112617. if(penalty<0.f)penalty=0.f;
  112618. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112619. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112620. totalshift+pos*ve->searchstep);*/
  112621. /* window and transform */
  112622. for(i=0;i<n;i++)
  112623. vec[i]=data[i]*ve->mdct_win[i];
  112624. mdct_forward(&ve->mdct,vec,vec);
  112625. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112626. /* near-DC spreading function; this has nothing to do with
  112627. psychoacoustics, just sidelobe leakage and window size */
  112628. {
  112629. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112630. int ptr=filters->nearptr;
  112631. /* the accumulation is regularly refreshed from scratch to avoid
  112632. floating point creep */
  112633. if(ptr==0){
  112634. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112635. filters->nearDC_partialacc=temp;
  112636. }else{
  112637. decay=filters->nearDC_acc+=temp;
  112638. filters->nearDC_partialacc+=temp;
  112639. }
  112640. filters->nearDC_acc-=filters->nearDC[ptr];
  112641. filters->nearDC[ptr]=temp;
  112642. decay*=(1./(VE_NEARDC+1));
  112643. filters->nearptr++;
  112644. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112645. decay=todB(&decay)*.5-15.f;
  112646. }
  112647. /* perform spreading and limiting, also smooth the spectrum. yes,
  112648. the MDCT results in all real coefficients, but it still *behaves*
  112649. like real/imaginary pairs */
  112650. for(i=0;i<n/2;i+=2){
  112651. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112652. val=todB(&val)*.5f;
  112653. if(val<decay)val=decay;
  112654. if(val<minV)val=minV;
  112655. vec[i>>1]=val;
  112656. decay-=8.;
  112657. }
  112658. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112659. /* perform preecho/postecho triggering by band */
  112660. for(j=0;j<VE_BANDS;j++){
  112661. float acc=0.;
  112662. float valmax,valmin;
  112663. /* accumulate amplitude */
  112664. for(i=0;i<bands[j].end;i++)
  112665. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112666. acc*=bands[j].total;
  112667. /* convert amplitude to delta */
  112668. {
  112669. int p,thisx=filters[j].ampptr;
  112670. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112671. p=thisx;
  112672. p--;
  112673. if(p<0)p+=VE_AMP;
  112674. postmax=max(acc,filters[j].ampbuf[p]);
  112675. postmin=min(acc,filters[j].ampbuf[p]);
  112676. for(i=0;i<stretch;i++){
  112677. p--;
  112678. if(p<0)p+=VE_AMP;
  112679. premax=max(premax,filters[j].ampbuf[p]);
  112680. premin=min(premin,filters[j].ampbuf[p]);
  112681. }
  112682. valmin=postmin-premin;
  112683. valmax=postmax-premax;
  112684. /*filters[j].markers[pos]=valmax;*/
  112685. filters[j].ampbuf[thisx]=acc;
  112686. filters[j].ampptr++;
  112687. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112688. }
  112689. /* look at min/max, decide trigger */
  112690. if(valmax>gi->preecho_thresh[j]+penalty){
  112691. ret|=1;
  112692. ret|=4;
  112693. }
  112694. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112695. }
  112696. return(ret);
  112697. }
  112698. #if 0
  112699. static int seq=0;
  112700. static ogg_int64_t totalshift=-1024;
  112701. #endif
  112702. long _ve_envelope_search(vorbis_dsp_state *v){
  112703. vorbis_info *vi=v->vi;
  112704. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112705. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112706. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112707. long i,j;
  112708. int first=ve->current/ve->searchstep;
  112709. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112710. if(first<0)first=0;
  112711. /* make sure we have enough storage to match the PCM */
  112712. if(last+VE_WIN+VE_POST>ve->storage){
  112713. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112714. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112715. }
  112716. for(j=first;j<last;j++){
  112717. int ret=0;
  112718. ve->stretch++;
  112719. if(ve->stretch>VE_MAXSTRETCH*2)
  112720. ve->stretch=VE_MAXSTRETCH*2;
  112721. for(i=0;i<ve->ch;i++){
  112722. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112723. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112724. }
  112725. ve->mark[j+VE_POST]=0;
  112726. if(ret&1){
  112727. ve->mark[j]=1;
  112728. ve->mark[j+1]=1;
  112729. }
  112730. if(ret&2){
  112731. ve->mark[j]=1;
  112732. if(j>0)ve->mark[j-1]=1;
  112733. }
  112734. if(ret&4)ve->stretch=-1;
  112735. }
  112736. ve->current=last*ve->searchstep;
  112737. {
  112738. long centerW=v->centerW;
  112739. long testW=
  112740. centerW+
  112741. ci->blocksizes[v->W]/4+
  112742. ci->blocksizes[1]/2+
  112743. ci->blocksizes[0]/4;
  112744. j=ve->cursor;
  112745. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112746. working back one window */
  112747. if(j>=testW)return(1);
  112748. ve->cursor=j;
  112749. if(ve->mark[j/ve->searchstep]){
  112750. if(j>centerW){
  112751. #if 0
  112752. if(j>ve->curmark){
  112753. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112754. int l,m;
  112755. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112756. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112757. seq,
  112758. (totalshift+ve->cursor)/44100.,
  112759. (totalshift+j)/44100.);
  112760. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112761. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112762. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112763. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112764. for(m=0;m<VE_BANDS;m++){
  112765. char buf[80];
  112766. sprintf(buf,"delL%d",m);
  112767. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112768. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112769. }
  112770. for(m=0;m<VE_BANDS;m++){
  112771. char buf[80];
  112772. sprintf(buf,"delR%d",m);
  112773. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112774. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112775. }
  112776. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112777. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112778. seq++;
  112779. }
  112780. #endif
  112781. ve->curmark=j;
  112782. if(j>=testW)return(1);
  112783. return(0);
  112784. }
  112785. }
  112786. j+=ve->searchstep;
  112787. }
  112788. }
  112789. return(-1);
  112790. }
  112791. int _ve_envelope_mark(vorbis_dsp_state *v){
  112792. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112793. vorbis_info *vi=v->vi;
  112794. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112795. long centerW=v->centerW;
  112796. long beginW=centerW-ci->blocksizes[v->W]/4;
  112797. long endW=centerW+ci->blocksizes[v->W]/4;
  112798. if(v->W){
  112799. beginW-=ci->blocksizes[v->lW]/4;
  112800. endW+=ci->blocksizes[v->nW]/4;
  112801. }else{
  112802. beginW-=ci->blocksizes[0]/4;
  112803. endW+=ci->blocksizes[0]/4;
  112804. }
  112805. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112806. {
  112807. long first=beginW/ve->searchstep;
  112808. long last=endW/ve->searchstep;
  112809. long i;
  112810. for(i=first;i<last;i++)
  112811. if(ve->mark[i])return(1);
  112812. }
  112813. return(0);
  112814. }
  112815. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112816. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112817. ahead of ve->current */
  112818. int smallshift=shift/e->searchstep;
  112819. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112820. #if 0
  112821. for(i=0;i<VE_BANDS*e->ch;i++)
  112822. memmove(e->filter[i].markers,
  112823. e->filter[i].markers+smallshift,
  112824. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112825. totalshift+=shift;
  112826. #endif
  112827. e->current-=shift;
  112828. if(e->curmark>=0)
  112829. e->curmark-=shift;
  112830. e->cursor-=shift;
  112831. }
  112832. #endif
  112833. /*** End of inlined file: envelope.c ***/
  112834. /*** Start of inlined file: floor0.c ***/
  112835. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112836. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112837. // tasks..
  112838. #if JUCE_MSVC
  112839. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112840. #endif
  112841. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112842. #if JUCE_USE_OGGVORBIS
  112843. #include <stdlib.h>
  112844. #include <string.h>
  112845. #include <math.h>
  112846. /*** Start of inlined file: lsp.h ***/
  112847. #ifndef _V_LSP_H_
  112848. #define _V_LSP_H_
  112849. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112850. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112851. float *lsp,int m,
  112852. float amp,float ampoffset);
  112853. #endif
  112854. /*** End of inlined file: lsp.h ***/
  112855. #include <stdio.h>
  112856. typedef struct {
  112857. int ln;
  112858. int m;
  112859. int **linearmap;
  112860. int n[2];
  112861. vorbis_info_floor0 *vi;
  112862. long bits;
  112863. long frames;
  112864. } vorbis_look_floor0;
  112865. /***********************************************/
  112866. static void floor0_free_info(vorbis_info_floor *i){
  112867. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112868. if(info){
  112869. memset(info,0,sizeof(*info));
  112870. _ogg_free(info);
  112871. }
  112872. }
  112873. static void floor0_free_look(vorbis_look_floor *i){
  112874. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112875. if(look){
  112876. if(look->linearmap){
  112877. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112878. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112879. _ogg_free(look->linearmap);
  112880. }
  112881. memset(look,0,sizeof(*look));
  112882. _ogg_free(look);
  112883. }
  112884. }
  112885. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112886. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112887. int j;
  112888. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112889. info->order=oggpack_read(opb,8);
  112890. info->rate=oggpack_read(opb,16);
  112891. info->barkmap=oggpack_read(opb,16);
  112892. info->ampbits=oggpack_read(opb,6);
  112893. info->ampdB=oggpack_read(opb,8);
  112894. info->numbooks=oggpack_read(opb,4)+1;
  112895. if(info->order<1)goto err_out;
  112896. if(info->rate<1)goto err_out;
  112897. if(info->barkmap<1)goto err_out;
  112898. if(info->numbooks<1)goto err_out;
  112899. for(j=0;j<info->numbooks;j++){
  112900. info->books[j]=oggpack_read(opb,8);
  112901. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112902. }
  112903. return(info);
  112904. err_out:
  112905. floor0_free_info(info);
  112906. return(NULL);
  112907. }
  112908. /* initialize Bark scale and normalization lookups. We could do this
  112909. with static tables, but Vorbis allows a number of possible
  112910. combinations, so it's best to do it computationally.
  112911. The below is authoritative in terms of defining scale mapping.
  112912. Note that the scale depends on the sampling rate as well as the
  112913. linear block and mapping sizes */
  112914. static void floor0_map_lazy_init(vorbis_block *vb,
  112915. vorbis_info_floor *infoX,
  112916. vorbis_look_floor0 *look){
  112917. if(!look->linearmap[vb->W]){
  112918. vorbis_dsp_state *vd=vb->vd;
  112919. vorbis_info *vi=vd->vi;
  112920. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112921. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112922. int W=vb->W;
  112923. int n=ci->blocksizes[W]/2,j;
  112924. /* we choose a scaling constant so that:
  112925. floor(bark(rate/2-1)*C)=mapped-1
  112926. floor(bark(rate/2)*C)=mapped */
  112927. float scale=look->ln/toBARK(info->rate/2.f);
  112928. /* the mapping from a linear scale to a smaller bark scale is
  112929. straightforward. We do *not* make sure that the linear mapping
  112930. does not skip bark-scale bins; the decoder simply skips them and
  112931. the encoder may do what it wishes in filling them. They're
  112932. necessary in some mapping combinations to keep the scale spacing
  112933. accurate */
  112934. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112935. for(j=0;j<n;j++){
  112936. int val=floor( toBARK((info->rate/2.f)/n*j)
  112937. *scale); /* bark numbers represent band edges */
  112938. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112939. look->linearmap[W][j]=val;
  112940. }
  112941. look->linearmap[W][j]=-1;
  112942. look->n[W]=n;
  112943. }
  112944. }
  112945. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112946. vorbis_info_floor *i){
  112947. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112948. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112949. look->m=info->order;
  112950. look->ln=info->barkmap;
  112951. look->vi=info;
  112952. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112953. return look;
  112954. }
  112955. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112956. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112957. vorbis_info_floor0 *info=look->vi;
  112958. int j,k;
  112959. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112960. if(ampraw>0){ /* also handles the -1 out of data case */
  112961. long maxval=(1<<info->ampbits)-1;
  112962. float amp=(float)ampraw/maxval*info->ampdB;
  112963. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112964. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112965. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112966. codebook *b=ci->fullbooks+info->books[booknum];
  112967. float last=0.f;
  112968. /* the additional b->dim is a guard against any possible stack
  112969. smash; b->dim is provably more than we can overflow the
  112970. vector */
  112971. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112972. for(j=0;j<look->m;j+=b->dim)
  112973. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112974. for(j=0;j<look->m;){
  112975. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112976. last=lsp[j-1];
  112977. }
  112978. lsp[look->m]=amp;
  112979. return(lsp);
  112980. }
  112981. }
  112982. eop:
  112983. return(NULL);
  112984. }
  112985. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112986. void *memo,float *out){
  112987. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112988. vorbis_info_floor0 *info=look->vi;
  112989. floor0_map_lazy_init(vb,info,look);
  112990. if(memo){
  112991. float *lsp=(float *)memo;
  112992. float amp=lsp[look->m];
  112993. /* take the coefficients back to a spectral envelope curve */
  112994. vorbis_lsp_to_curve(out,
  112995. look->linearmap[vb->W],
  112996. look->n[vb->W],
  112997. look->ln,
  112998. lsp,look->m,amp,(float)info->ampdB);
  112999. return(1);
  113000. }
  113001. memset(out,0,sizeof(*out)*look->n[vb->W]);
  113002. return(0);
  113003. }
  113004. /* export hooks */
  113005. vorbis_func_floor floor0_exportbundle={
  113006. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  113007. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  113008. };
  113009. #endif
  113010. /*** End of inlined file: floor0.c ***/
  113011. /*** Start of inlined file: floor1.c ***/
  113012. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113013. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113014. // tasks..
  113015. #if JUCE_MSVC
  113016. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113017. #endif
  113018. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113019. #if JUCE_USE_OGGVORBIS
  113020. #include <stdlib.h>
  113021. #include <string.h>
  113022. #include <math.h>
  113023. #include <stdio.h>
  113024. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  113025. typedef struct {
  113026. int sorted_index[VIF_POSIT+2];
  113027. int forward_index[VIF_POSIT+2];
  113028. int reverse_index[VIF_POSIT+2];
  113029. int hineighbor[VIF_POSIT];
  113030. int loneighbor[VIF_POSIT];
  113031. int posts;
  113032. int n;
  113033. int quant_q;
  113034. vorbis_info_floor1 *vi;
  113035. long phrasebits;
  113036. long postbits;
  113037. long frames;
  113038. } vorbis_look_floor1;
  113039. typedef struct lsfit_acc{
  113040. long x0;
  113041. long x1;
  113042. long xa;
  113043. long ya;
  113044. long x2a;
  113045. long y2a;
  113046. long xya;
  113047. long an;
  113048. } lsfit_acc;
  113049. /***********************************************/
  113050. static void floor1_free_info(vorbis_info_floor *i){
  113051. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113052. if(info){
  113053. memset(info,0,sizeof(*info));
  113054. _ogg_free(info);
  113055. }
  113056. }
  113057. static void floor1_free_look(vorbis_look_floor *i){
  113058. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  113059. if(look){
  113060. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  113061. (float)look->phrasebits/look->frames,
  113062. (float)look->postbits/look->frames,
  113063. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113064. memset(look,0,sizeof(*look));
  113065. _ogg_free(look);
  113066. }
  113067. }
  113068. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113069. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113070. int j,k;
  113071. int count=0;
  113072. int rangebits;
  113073. int maxposit=info->postlist[1];
  113074. int maxclass=-1;
  113075. /* save out partitions */
  113076. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113077. for(j=0;j<info->partitions;j++){
  113078. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113079. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113080. }
  113081. /* save out partition classes */
  113082. for(j=0;j<maxclass+1;j++){
  113083. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113084. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113085. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113086. for(k=0;k<(1<<info->class_subs[j]);k++)
  113087. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113088. }
  113089. /* save out the post list */
  113090. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113091. oggpack_write(opb,ilog2(maxposit),4);
  113092. rangebits=ilog2(maxposit);
  113093. for(j=0,k=0;j<info->partitions;j++){
  113094. count+=info->class_dim[info->partitionclass[j]];
  113095. for(;k<count;k++)
  113096. oggpack_write(opb,info->postlist[k+2],rangebits);
  113097. }
  113098. }
  113099. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113100. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113101. int j,k,count=0,maxclass=-1,rangebits;
  113102. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113103. /* read partitions */
  113104. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113105. for(j=0;j<info->partitions;j++){
  113106. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113107. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113108. }
  113109. /* read partition classes */
  113110. for(j=0;j<maxclass+1;j++){
  113111. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113112. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113113. if(info->class_subs[j]<0)
  113114. goto err_out;
  113115. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113116. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113117. goto err_out;
  113118. for(k=0;k<(1<<info->class_subs[j]);k++){
  113119. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113120. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113121. goto err_out;
  113122. }
  113123. }
  113124. /* read the post list */
  113125. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113126. rangebits=oggpack_read(opb,4);
  113127. for(j=0,k=0;j<info->partitions;j++){
  113128. count+=info->class_dim[info->partitionclass[j]];
  113129. for(;k<count;k++){
  113130. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113131. if(t<0 || t>=(1<<rangebits))
  113132. goto err_out;
  113133. }
  113134. }
  113135. info->postlist[0]=0;
  113136. info->postlist[1]=1<<rangebits;
  113137. return(info);
  113138. err_out:
  113139. floor1_free_info(info);
  113140. return(NULL);
  113141. }
  113142. static int JUCE_CDECL icomp(const void *a,const void *b){
  113143. return(**(int **)a-**(int **)b);
  113144. }
  113145. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113146. vorbis_info_floor *in){
  113147. int *sortpointer[VIF_POSIT+2];
  113148. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113149. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113150. int i,j,n=0;
  113151. look->vi=info;
  113152. look->n=info->postlist[1];
  113153. /* we drop each position value in-between already decoded values,
  113154. and use linear interpolation to predict each new value past the
  113155. edges. The positions are read in the order of the position
  113156. list... we precompute the bounding positions in the lookup. Of
  113157. course, the neighbors can change (if a position is declined), but
  113158. this is an initial mapping */
  113159. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113160. n+=2;
  113161. look->posts=n;
  113162. /* also store a sorted position index */
  113163. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113164. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113165. /* points from sort order back to range number */
  113166. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113167. /* points from range order to sorted position */
  113168. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113169. /* we actually need the post values too */
  113170. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113171. /* quantize values to multiplier spec */
  113172. switch(info->mult){
  113173. case 1: /* 1024 -> 256 */
  113174. look->quant_q=256;
  113175. break;
  113176. case 2: /* 1024 -> 128 */
  113177. look->quant_q=128;
  113178. break;
  113179. case 3: /* 1024 -> 86 */
  113180. look->quant_q=86;
  113181. break;
  113182. case 4: /* 1024 -> 64 */
  113183. look->quant_q=64;
  113184. break;
  113185. }
  113186. /* discover our neighbors for decode where we don't use fit flags
  113187. (that would push the neighbors outward) */
  113188. for(i=0;i<n-2;i++){
  113189. int lo=0;
  113190. int hi=1;
  113191. int lx=0;
  113192. int hx=look->n;
  113193. int currentx=info->postlist[i+2];
  113194. for(j=0;j<i+2;j++){
  113195. int x=info->postlist[j];
  113196. if(x>lx && x<currentx){
  113197. lo=j;
  113198. lx=x;
  113199. }
  113200. if(x<hx && x>currentx){
  113201. hi=j;
  113202. hx=x;
  113203. }
  113204. }
  113205. look->loneighbor[i]=lo;
  113206. look->hineighbor[i]=hi;
  113207. }
  113208. return(look);
  113209. }
  113210. static int render_point(int x0,int x1,int y0,int y1,int x){
  113211. y0&=0x7fff; /* mask off flag */
  113212. y1&=0x7fff;
  113213. {
  113214. int dy=y1-y0;
  113215. int adx=x1-x0;
  113216. int ady=abs(dy);
  113217. int err=ady*(x-x0);
  113218. int off=err/adx;
  113219. if(dy<0)return(y0-off);
  113220. return(y0+off);
  113221. }
  113222. }
  113223. static int vorbis_dBquant(const float *x){
  113224. int i= *x*7.3142857f+1023.5f;
  113225. if(i>1023)return(1023);
  113226. if(i<0)return(0);
  113227. return i;
  113228. }
  113229. static float FLOOR1_fromdB_LOOKUP[256]={
  113230. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113231. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113232. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113233. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113234. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113235. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113236. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113237. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113238. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113239. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113240. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113241. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113242. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113243. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113244. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113245. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113246. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113247. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113248. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113249. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113250. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113251. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113252. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113253. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113254. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113255. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113256. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113257. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113258. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113259. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113260. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113261. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113262. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113263. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113264. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113265. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113266. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113267. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113268. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113269. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113270. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113271. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113272. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113273. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113274. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113275. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113276. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113277. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113278. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113279. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113280. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113281. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113282. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113283. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113284. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113285. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113286. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113287. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113288. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113289. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113290. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113291. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113292. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113293. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113294. };
  113295. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113296. int dy=y1-y0;
  113297. int adx=x1-x0;
  113298. int ady=abs(dy);
  113299. int base=dy/adx;
  113300. int sy=(dy<0?base-1:base+1);
  113301. int x=x0;
  113302. int y=y0;
  113303. int err=0;
  113304. ady-=abs(base*adx);
  113305. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113306. while(++x<x1){
  113307. err=err+ady;
  113308. if(err>=adx){
  113309. err-=adx;
  113310. y+=sy;
  113311. }else{
  113312. y+=base;
  113313. }
  113314. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113315. }
  113316. }
  113317. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113318. int dy=y1-y0;
  113319. int adx=x1-x0;
  113320. int ady=abs(dy);
  113321. int base=dy/adx;
  113322. int sy=(dy<0?base-1:base+1);
  113323. int x=x0;
  113324. int y=y0;
  113325. int err=0;
  113326. ady-=abs(base*adx);
  113327. d[x]=y;
  113328. while(++x<x1){
  113329. err=err+ady;
  113330. if(err>=adx){
  113331. err-=adx;
  113332. y+=sy;
  113333. }else{
  113334. y+=base;
  113335. }
  113336. d[x]=y;
  113337. }
  113338. }
  113339. /* the floor has already been filtered to only include relevant sections */
  113340. static int accumulate_fit(const float *flr,const float *mdct,
  113341. int x0, int x1,lsfit_acc *a,
  113342. int n,vorbis_info_floor1 *info){
  113343. long i;
  113344. 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;
  113345. memset(a,0,sizeof(*a));
  113346. a->x0=x0;
  113347. a->x1=x1;
  113348. if(x1>=n)x1=n-1;
  113349. for(i=x0;i<=x1;i++){
  113350. int quantized=vorbis_dBquant(flr+i);
  113351. if(quantized){
  113352. if(mdct[i]+info->twofitatten>=flr[i]){
  113353. xa += i;
  113354. ya += quantized;
  113355. x2a += i*i;
  113356. y2a += quantized*quantized;
  113357. xya += i*quantized;
  113358. na++;
  113359. }else{
  113360. xb += i;
  113361. yb += quantized;
  113362. x2b += i*i;
  113363. y2b += quantized*quantized;
  113364. xyb += i*quantized;
  113365. nb++;
  113366. }
  113367. }
  113368. }
  113369. xb+=xa;
  113370. yb+=ya;
  113371. x2b+=x2a;
  113372. y2b+=y2a;
  113373. xyb+=xya;
  113374. nb+=na;
  113375. /* weight toward the actually used frequencies if we meet the threshhold */
  113376. {
  113377. int weight=nb*info->twofitweight/(na+1);
  113378. a->xa=xa*weight+xb;
  113379. a->ya=ya*weight+yb;
  113380. a->x2a=x2a*weight+x2b;
  113381. a->y2a=y2a*weight+y2b;
  113382. a->xya=xya*weight+xyb;
  113383. a->an=na*weight+nb;
  113384. }
  113385. return(na);
  113386. }
  113387. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113388. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113389. long x0=a[0].x0;
  113390. long x1=a[fits-1].x1;
  113391. for(i=0;i<fits;i++){
  113392. x+=a[i].xa;
  113393. y+=a[i].ya;
  113394. x2+=a[i].x2a;
  113395. y2+=a[i].y2a;
  113396. xy+=a[i].xya;
  113397. an+=a[i].an;
  113398. }
  113399. if(*y0>=0){
  113400. x+= x0;
  113401. y+= *y0;
  113402. x2+= x0 * x0;
  113403. y2+= *y0 * *y0;
  113404. xy+= *y0 * x0;
  113405. an++;
  113406. }
  113407. if(*y1>=0){
  113408. x+= x1;
  113409. y+= *y1;
  113410. x2+= x1 * x1;
  113411. y2+= *y1 * *y1;
  113412. xy+= *y1 * x1;
  113413. an++;
  113414. }
  113415. if(an){
  113416. /* need 64 bit multiplies, which C doesn't give portably as int */
  113417. double fx=x;
  113418. double fy=y;
  113419. double fx2=x2;
  113420. double fxy=xy;
  113421. double denom=1./(an*fx2-fx*fx);
  113422. double a=(fy*fx2-fxy*fx)*denom;
  113423. double b=(an*fxy-fx*fy)*denom;
  113424. *y0=rint(a+b*x0);
  113425. *y1=rint(a+b*x1);
  113426. /* limit to our range! */
  113427. if(*y0>1023)*y0=1023;
  113428. if(*y1>1023)*y1=1023;
  113429. if(*y0<0)*y0=0;
  113430. if(*y1<0)*y1=0;
  113431. }else{
  113432. *y0=0;
  113433. *y1=0;
  113434. }
  113435. }
  113436. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113437. long y=0;
  113438. int i;
  113439. for(i=0;i<fits && y==0;i++)
  113440. y+=a[i].ya;
  113441. *y0=*y1=y;
  113442. }*/
  113443. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113444. const float *mdct,
  113445. vorbis_info_floor1 *info){
  113446. int dy=y1-y0;
  113447. int adx=x1-x0;
  113448. int ady=abs(dy);
  113449. int base=dy/adx;
  113450. int sy=(dy<0?base-1:base+1);
  113451. int x=x0;
  113452. int y=y0;
  113453. int err=0;
  113454. int val=vorbis_dBquant(mask+x);
  113455. int mse=0;
  113456. int n=0;
  113457. ady-=abs(base*adx);
  113458. mse=(y-val);
  113459. mse*=mse;
  113460. n++;
  113461. if(mdct[x]+info->twofitatten>=mask[x]){
  113462. if(y+info->maxover<val)return(1);
  113463. if(y-info->maxunder>val)return(1);
  113464. }
  113465. while(++x<x1){
  113466. err=err+ady;
  113467. if(err>=adx){
  113468. err-=adx;
  113469. y+=sy;
  113470. }else{
  113471. y+=base;
  113472. }
  113473. val=vorbis_dBquant(mask+x);
  113474. mse+=((y-val)*(y-val));
  113475. n++;
  113476. if(mdct[x]+info->twofitatten>=mask[x]){
  113477. if(val){
  113478. if(y+info->maxover<val)return(1);
  113479. if(y-info->maxunder>val)return(1);
  113480. }
  113481. }
  113482. }
  113483. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113484. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113485. if(mse/n>info->maxerr)return(1);
  113486. return(0);
  113487. }
  113488. static int post_Y(int *A,int *B,int pos){
  113489. if(A[pos]<0)
  113490. return B[pos];
  113491. if(B[pos]<0)
  113492. return A[pos];
  113493. return (A[pos]+B[pos])>>1;
  113494. }
  113495. int *floor1_fit(vorbis_block *vb,void *look_,
  113496. const float *logmdct, /* in */
  113497. const float *logmask){
  113498. long i,j;
  113499. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113500. vorbis_info_floor1 *info=look->vi;
  113501. long n=look->n;
  113502. long posts=look->posts;
  113503. long nonzero=0;
  113504. lsfit_acc fits[VIF_POSIT+1];
  113505. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113506. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113507. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113508. int hineighbor[VIF_POSIT+2];
  113509. int *output=NULL;
  113510. int memo[VIF_POSIT+2];
  113511. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113512. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113513. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113514. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113515. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113516. /* quantize the relevant floor points and collect them into line fit
  113517. structures (one per minimal division) at the same time */
  113518. if(posts==0){
  113519. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113520. }else{
  113521. for(i=0;i<posts-1;i++)
  113522. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113523. look->sorted_index[i+1],fits+i,
  113524. n,info);
  113525. }
  113526. if(nonzero){
  113527. /* start by fitting the implicit base case.... */
  113528. int y0=-200;
  113529. int y1=-200;
  113530. fit_line(fits,posts-1,&y0,&y1);
  113531. fit_valueA[0]=y0;
  113532. fit_valueB[0]=y0;
  113533. fit_valueB[1]=y1;
  113534. fit_valueA[1]=y1;
  113535. /* Non degenerate case */
  113536. /* start progressive splitting. This is a greedy, non-optimal
  113537. algorithm, but simple and close enough to the best
  113538. answer. */
  113539. for(i=2;i<posts;i++){
  113540. int sortpos=look->reverse_index[i];
  113541. int ln=loneighbor[sortpos];
  113542. int hn=hineighbor[sortpos];
  113543. /* eliminate repeat searches of a particular range with a memo */
  113544. if(memo[ln]!=hn){
  113545. /* haven't performed this error search yet */
  113546. int lsortpos=look->reverse_index[ln];
  113547. int hsortpos=look->reverse_index[hn];
  113548. memo[ln]=hn;
  113549. {
  113550. /* A note: we want to bound/minimize *local*, not global, error */
  113551. int lx=info->postlist[ln];
  113552. int hx=info->postlist[hn];
  113553. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113554. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113555. if(ly==-1 || hy==-1){
  113556. exit(1);
  113557. }
  113558. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113559. /* outside error bounds/begin search area. Split it. */
  113560. int ly0=-200;
  113561. int ly1=-200;
  113562. int hy0=-200;
  113563. int hy1=-200;
  113564. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113565. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113566. /* store new edge values */
  113567. fit_valueB[ln]=ly0;
  113568. if(ln==0)fit_valueA[ln]=ly0;
  113569. fit_valueA[i]=ly1;
  113570. fit_valueB[i]=hy0;
  113571. fit_valueA[hn]=hy1;
  113572. if(hn==1)fit_valueB[hn]=hy1;
  113573. if(ly1>=0 || hy0>=0){
  113574. /* store new neighbor values */
  113575. for(j=sortpos-1;j>=0;j--)
  113576. if(hineighbor[j]==hn)
  113577. hineighbor[j]=i;
  113578. else
  113579. break;
  113580. for(j=sortpos+1;j<posts;j++)
  113581. if(loneighbor[j]==ln)
  113582. loneighbor[j]=i;
  113583. else
  113584. break;
  113585. }
  113586. }else{
  113587. fit_valueA[i]=-200;
  113588. fit_valueB[i]=-200;
  113589. }
  113590. }
  113591. }
  113592. }
  113593. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113594. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113595. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113596. /* fill in posts marked as not using a fit; we will zero
  113597. back out to 'unused' when encoding them so long as curve
  113598. interpolation doesn't force them into use */
  113599. for(i=2;i<posts;i++){
  113600. int ln=look->loneighbor[i-2];
  113601. int hn=look->hineighbor[i-2];
  113602. int x0=info->postlist[ln];
  113603. int x1=info->postlist[hn];
  113604. int y0=output[ln];
  113605. int y1=output[hn];
  113606. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113607. int vx=post_Y(fit_valueA,fit_valueB,i);
  113608. if(vx>=0 && predicted!=vx){
  113609. output[i]=vx;
  113610. }else{
  113611. output[i]= predicted|0x8000;
  113612. }
  113613. }
  113614. }
  113615. return(output);
  113616. }
  113617. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113618. int *A,int *B,
  113619. int del){
  113620. long i;
  113621. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113622. long posts=look->posts;
  113623. int *output=NULL;
  113624. if(A && B){
  113625. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113626. for(i=0;i<posts;i++){
  113627. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113628. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113629. }
  113630. }
  113631. return(output);
  113632. }
  113633. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113634. void*look_,
  113635. int *post,int *ilogmask){
  113636. long i,j;
  113637. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113638. vorbis_info_floor1 *info=look->vi;
  113639. long posts=look->posts;
  113640. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113641. int out[VIF_POSIT+2];
  113642. static_codebook **sbooks=ci->book_param;
  113643. codebook *books=ci->fullbooks;
  113644. static long seq=0;
  113645. /* quantize values to multiplier spec */
  113646. if(post){
  113647. for(i=0;i<posts;i++){
  113648. int val=post[i]&0x7fff;
  113649. switch(info->mult){
  113650. case 1: /* 1024 -> 256 */
  113651. val>>=2;
  113652. break;
  113653. case 2: /* 1024 -> 128 */
  113654. val>>=3;
  113655. break;
  113656. case 3: /* 1024 -> 86 */
  113657. val/=12;
  113658. break;
  113659. case 4: /* 1024 -> 64 */
  113660. val>>=4;
  113661. break;
  113662. }
  113663. post[i]=val | (post[i]&0x8000);
  113664. }
  113665. out[0]=post[0];
  113666. out[1]=post[1];
  113667. /* find prediction values for each post and subtract them */
  113668. for(i=2;i<posts;i++){
  113669. int ln=look->loneighbor[i-2];
  113670. int hn=look->hineighbor[i-2];
  113671. int x0=info->postlist[ln];
  113672. int x1=info->postlist[hn];
  113673. int y0=post[ln];
  113674. int y1=post[hn];
  113675. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113676. if((post[i]&0x8000) || (predicted==post[i])){
  113677. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113678. in interpolation */
  113679. out[i]=0;
  113680. }else{
  113681. int headroom=(look->quant_q-predicted<predicted?
  113682. look->quant_q-predicted:predicted);
  113683. int val=post[i]-predicted;
  113684. /* at this point the 'deviation' value is in the range +/- max
  113685. range, but the real, unique range can always be mapped to
  113686. only [0-maxrange). So we want to wrap the deviation into
  113687. this limited range, but do it in the way that least screws
  113688. an essentially gaussian probability distribution. */
  113689. if(val<0)
  113690. if(val<-headroom)
  113691. val=headroom-val-1;
  113692. else
  113693. val=-1-(val<<1);
  113694. else
  113695. if(val>=headroom)
  113696. val= val+headroom;
  113697. else
  113698. val<<=1;
  113699. out[i]=val;
  113700. post[ln]&=0x7fff;
  113701. post[hn]&=0x7fff;
  113702. }
  113703. }
  113704. /* we have everything we need. pack it out */
  113705. /* mark nontrivial floor */
  113706. oggpack_write(opb,1,1);
  113707. /* beginning/end post */
  113708. look->frames++;
  113709. look->postbits+=ilog(look->quant_q-1)*2;
  113710. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113711. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113712. /* partition by partition */
  113713. for(i=0,j=2;i<info->partitions;i++){
  113714. int classx=info->partitionclass[i];
  113715. int cdim=info->class_dim[classx];
  113716. int csubbits=info->class_subs[classx];
  113717. int csub=1<<csubbits;
  113718. int bookas[8]={0,0,0,0,0,0,0,0};
  113719. int cval=0;
  113720. int cshift=0;
  113721. int k,l;
  113722. /* generate the partition's first stage cascade value */
  113723. if(csubbits){
  113724. int maxval[8];
  113725. for(k=0;k<csub;k++){
  113726. int booknum=info->class_subbook[classx][k];
  113727. if(booknum<0){
  113728. maxval[k]=1;
  113729. }else{
  113730. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113731. }
  113732. }
  113733. for(k=0;k<cdim;k++){
  113734. for(l=0;l<csub;l++){
  113735. int val=out[j+k];
  113736. if(val<maxval[l]){
  113737. bookas[k]=l;
  113738. break;
  113739. }
  113740. }
  113741. cval|= bookas[k]<<cshift;
  113742. cshift+=csubbits;
  113743. }
  113744. /* write it */
  113745. look->phrasebits+=
  113746. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113747. #ifdef TRAIN_FLOOR1
  113748. {
  113749. FILE *of;
  113750. char buffer[80];
  113751. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113752. vb->pcmend/2,posts-2,class);
  113753. of=fopen(buffer,"a");
  113754. fprintf(of,"%d\n",cval);
  113755. fclose(of);
  113756. }
  113757. #endif
  113758. }
  113759. /* write post values */
  113760. for(k=0;k<cdim;k++){
  113761. int book=info->class_subbook[classx][bookas[k]];
  113762. if(book>=0){
  113763. /* hack to allow training with 'bad' books */
  113764. if(out[j+k]<(books+book)->entries)
  113765. look->postbits+=vorbis_book_encode(books+book,
  113766. out[j+k],opb);
  113767. /*else
  113768. fprintf(stderr,"+!");*/
  113769. #ifdef TRAIN_FLOOR1
  113770. {
  113771. FILE *of;
  113772. char buffer[80];
  113773. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113774. vb->pcmend/2,posts-2,class,bookas[k]);
  113775. of=fopen(buffer,"a");
  113776. fprintf(of,"%d\n",out[j+k]);
  113777. fclose(of);
  113778. }
  113779. #endif
  113780. }
  113781. }
  113782. j+=cdim;
  113783. }
  113784. {
  113785. /* generate quantized floor equivalent to what we'd unpack in decode */
  113786. /* render the lines */
  113787. int hx=0;
  113788. int lx=0;
  113789. int ly=post[0]*info->mult;
  113790. for(j=1;j<look->posts;j++){
  113791. int current=look->forward_index[j];
  113792. int hy=post[current]&0x7fff;
  113793. if(hy==post[current]){
  113794. hy*=info->mult;
  113795. hx=info->postlist[current];
  113796. render_line0(lx,hx,ly,hy,ilogmask);
  113797. lx=hx;
  113798. ly=hy;
  113799. }
  113800. }
  113801. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113802. seq++;
  113803. return(1);
  113804. }
  113805. }else{
  113806. oggpack_write(opb,0,1);
  113807. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113808. seq++;
  113809. return(0);
  113810. }
  113811. }
  113812. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113813. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113814. vorbis_info_floor1 *info=look->vi;
  113815. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113816. int i,j,k;
  113817. codebook *books=ci->fullbooks;
  113818. /* unpack wrapped/predicted values from stream */
  113819. if(oggpack_read(&vb->opb,1)==1){
  113820. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113821. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113822. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113823. /* partition by partition */
  113824. for(i=0,j=2;i<info->partitions;i++){
  113825. int classx=info->partitionclass[i];
  113826. int cdim=info->class_dim[classx];
  113827. int csubbits=info->class_subs[classx];
  113828. int csub=1<<csubbits;
  113829. int cval=0;
  113830. /* decode the partition's first stage cascade value */
  113831. if(csubbits){
  113832. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113833. if(cval==-1)goto eop;
  113834. }
  113835. for(k=0;k<cdim;k++){
  113836. int book=info->class_subbook[classx][cval&(csub-1)];
  113837. cval>>=csubbits;
  113838. if(book>=0){
  113839. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113840. goto eop;
  113841. }else{
  113842. fit_value[j+k]=0;
  113843. }
  113844. }
  113845. j+=cdim;
  113846. }
  113847. /* unwrap positive values and reconsitute via linear interpolation */
  113848. for(i=2;i<look->posts;i++){
  113849. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113850. info->postlist[look->hineighbor[i-2]],
  113851. fit_value[look->loneighbor[i-2]],
  113852. fit_value[look->hineighbor[i-2]],
  113853. info->postlist[i]);
  113854. int hiroom=look->quant_q-predicted;
  113855. int loroom=predicted;
  113856. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113857. int val=fit_value[i];
  113858. if(val){
  113859. if(val>=room){
  113860. if(hiroom>loroom){
  113861. val = val-loroom;
  113862. }else{
  113863. val = -1-(val-hiroom);
  113864. }
  113865. }else{
  113866. if(val&1){
  113867. val= -((val+1)>>1);
  113868. }else{
  113869. val>>=1;
  113870. }
  113871. }
  113872. fit_value[i]=val+predicted;
  113873. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113874. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113875. }else{
  113876. fit_value[i]=predicted|0x8000;
  113877. }
  113878. }
  113879. return(fit_value);
  113880. }
  113881. eop:
  113882. return(NULL);
  113883. }
  113884. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113885. float *out){
  113886. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113887. vorbis_info_floor1 *info=look->vi;
  113888. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113889. int n=ci->blocksizes[vb->W]/2;
  113890. int j;
  113891. if(memo){
  113892. /* render the lines */
  113893. int *fit_value=(int *)memo;
  113894. int hx=0;
  113895. int lx=0;
  113896. int ly=fit_value[0]*info->mult;
  113897. for(j=1;j<look->posts;j++){
  113898. int current=look->forward_index[j];
  113899. int hy=fit_value[current]&0x7fff;
  113900. if(hy==fit_value[current]){
  113901. hy*=info->mult;
  113902. hx=info->postlist[current];
  113903. render_line(lx,hx,ly,hy,out);
  113904. lx=hx;
  113905. ly=hy;
  113906. }
  113907. }
  113908. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113909. return(1);
  113910. }
  113911. memset(out,0,sizeof(*out)*n);
  113912. return(0);
  113913. }
  113914. /* export hooks */
  113915. vorbis_func_floor floor1_exportbundle={
  113916. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113917. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113918. };
  113919. #endif
  113920. /*** End of inlined file: floor1.c ***/
  113921. /*** Start of inlined file: info.c ***/
  113922. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113923. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113924. // tasks..
  113925. #if JUCE_MSVC
  113926. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113927. #endif
  113928. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113929. #if JUCE_USE_OGGVORBIS
  113930. /* general handling of the header and the vorbis_info structure (and
  113931. substructures) */
  113932. #include <stdlib.h>
  113933. #include <string.h>
  113934. #include <ctype.h>
  113935. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113936. while(bytes--){
  113937. oggpack_write(o,*s++,8);
  113938. }
  113939. }
  113940. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113941. while(bytes--){
  113942. *buf++=oggpack_read(o,8);
  113943. }
  113944. }
  113945. void vorbis_comment_init(vorbis_comment *vc){
  113946. memset(vc,0,sizeof(*vc));
  113947. }
  113948. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113949. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113950. (vc->comments+2)*sizeof(*vc->user_comments));
  113951. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113952. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113953. vc->comment_lengths[vc->comments]=strlen(comment);
  113954. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113955. strcpy(vc->user_comments[vc->comments], comment);
  113956. vc->comments++;
  113957. vc->user_comments[vc->comments]=NULL;
  113958. }
  113959. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113960. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113961. strcpy(comment, tag);
  113962. strcat(comment, "=");
  113963. strcat(comment, contents);
  113964. vorbis_comment_add(vc, comment);
  113965. }
  113966. /* This is more or less the same as strncasecmp - but that doesn't exist
  113967. * everywhere, and this is a fairly trivial function, so we include it */
  113968. static int tagcompare(const char *s1, const char *s2, int n){
  113969. int c=0;
  113970. while(c < n){
  113971. if(toupper(s1[c]) != toupper(s2[c]))
  113972. return !0;
  113973. c++;
  113974. }
  113975. return 0;
  113976. }
  113977. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113978. long i;
  113979. int found = 0;
  113980. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113981. char *fulltag = (char*)alloca(taglen+ 1);
  113982. strcpy(fulltag, tag);
  113983. strcat(fulltag, "=");
  113984. for(i=0;i<vc->comments;i++){
  113985. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113986. if(count == found)
  113987. /* We return a pointer to the data, not a copy */
  113988. return vc->user_comments[i] + taglen;
  113989. else
  113990. found++;
  113991. }
  113992. }
  113993. return NULL; /* didn't find anything */
  113994. }
  113995. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113996. int i,count=0;
  113997. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113998. char *fulltag = (char*)alloca(taglen+1);
  113999. strcpy(fulltag,tag);
  114000. strcat(fulltag, "=");
  114001. for(i=0;i<vc->comments;i++){
  114002. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  114003. count++;
  114004. }
  114005. return count;
  114006. }
  114007. void vorbis_comment_clear(vorbis_comment *vc){
  114008. if(vc){
  114009. long i;
  114010. for(i=0;i<vc->comments;i++)
  114011. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  114012. if(vc->user_comments)_ogg_free(vc->user_comments);
  114013. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  114014. if(vc->vendor)_ogg_free(vc->vendor);
  114015. }
  114016. memset(vc,0,sizeof(*vc));
  114017. }
  114018. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  114019. They may be equal, but short will never ge greater than long */
  114020. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  114021. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  114022. return ci ? ci->blocksizes[zo] : -1;
  114023. }
  114024. /* used by synthesis, which has a full, alloced vi */
  114025. void vorbis_info_init(vorbis_info *vi){
  114026. memset(vi,0,sizeof(*vi));
  114027. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  114028. }
  114029. void vorbis_info_clear(vorbis_info *vi){
  114030. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114031. int i;
  114032. if(ci){
  114033. for(i=0;i<ci->modes;i++)
  114034. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  114035. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  114036. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  114037. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  114038. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  114039. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  114040. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  114041. for(i=0;i<ci->books;i++){
  114042. if(ci->book_param[i]){
  114043. /* knows if the book was not alloced */
  114044. vorbis_staticbook_destroy(ci->book_param[i]);
  114045. }
  114046. if(ci->fullbooks)
  114047. vorbis_book_clear(ci->fullbooks+i);
  114048. }
  114049. if(ci->fullbooks)
  114050. _ogg_free(ci->fullbooks);
  114051. for(i=0;i<ci->psys;i++)
  114052. _vi_psy_free(ci->psy_param[i]);
  114053. _ogg_free(ci);
  114054. }
  114055. memset(vi,0,sizeof(*vi));
  114056. }
  114057. /* Header packing/unpacking ********************************************/
  114058. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  114059. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114060. if(!ci)return(OV_EFAULT);
  114061. vi->version=oggpack_read(opb,32);
  114062. if(vi->version!=0)return(OV_EVERSION);
  114063. vi->channels=oggpack_read(opb,8);
  114064. vi->rate=oggpack_read(opb,32);
  114065. vi->bitrate_upper=oggpack_read(opb,32);
  114066. vi->bitrate_nominal=oggpack_read(opb,32);
  114067. vi->bitrate_lower=oggpack_read(opb,32);
  114068. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114069. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114070. if(vi->rate<1)goto err_out;
  114071. if(vi->channels<1)goto err_out;
  114072. if(ci->blocksizes[0]<8)goto err_out;
  114073. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114074. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114075. return(0);
  114076. err_out:
  114077. vorbis_info_clear(vi);
  114078. return(OV_EBADHEADER);
  114079. }
  114080. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114081. int i;
  114082. int vendorlen=oggpack_read(opb,32);
  114083. if(vendorlen<0)goto err_out;
  114084. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114085. _v_readstring(opb,vc->vendor,vendorlen);
  114086. vc->comments=oggpack_read(opb,32);
  114087. if(vc->comments<0)goto err_out;
  114088. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114089. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114090. for(i=0;i<vc->comments;i++){
  114091. int len=oggpack_read(opb,32);
  114092. if(len<0)goto err_out;
  114093. vc->comment_lengths[i]=len;
  114094. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114095. _v_readstring(opb,vc->user_comments[i],len);
  114096. }
  114097. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114098. return(0);
  114099. err_out:
  114100. vorbis_comment_clear(vc);
  114101. return(OV_EBADHEADER);
  114102. }
  114103. /* all of the real encoding details are here. The modes, books,
  114104. everything */
  114105. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114106. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114107. int i;
  114108. if(!ci)return(OV_EFAULT);
  114109. /* codebooks */
  114110. ci->books=oggpack_read(opb,8)+1;
  114111. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114112. for(i=0;i<ci->books;i++){
  114113. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114114. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114115. }
  114116. /* time backend settings; hooks are unused */
  114117. {
  114118. int times=oggpack_read(opb,6)+1;
  114119. for(i=0;i<times;i++){
  114120. int test=oggpack_read(opb,16);
  114121. if(test<0 || test>=VI_TIMEB)goto err_out;
  114122. }
  114123. }
  114124. /* floor backend settings */
  114125. ci->floors=oggpack_read(opb,6)+1;
  114126. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114127. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114128. for(i=0;i<ci->floors;i++){
  114129. ci->floor_type[i]=oggpack_read(opb,16);
  114130. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114131. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114132. if(!ci->floor_param[i])goto err_out;
  114133. }
  114134. /* residue backend settings */
  114135. ci->residues=oggpack_read(opb,6)+1;
  114136. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114137. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114138. for(i=0;i<ci->residues;i++){
  114139. ci->residue_type[i]=oggpack_read(opb,16);
  114140. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114141. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114142. if(!ci->residue_param[i])goto err_out;
  114143. }
  114144. /* map backend settings */
  114145. ci->maps=oggpack_read(opb,6)+1;
  114146. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114147. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114148. for(i=0;i<ci->maps;i++){
  114149. ci->map_type[i]=oggpack_read(opb,16);
  114150. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114151. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114152. if(!ci->map_param[i])goto err_out;
  114153. }
  114154. /* mode settings */
  114155. ci->modes=oggpack_read(opb,6)+1;
  114156. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114157. for(i=0;i<ci->modes;i++){
  114158. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114159. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114160. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114161. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114162. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114163. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114164. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114165. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114166. }
  114167. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114168. return(0);
  114169. err_out:
  114170. vorbis_info_clear(vi);
  114171. return(OV_EBADHEADER);
  114172. }
  114173. /* The Vorbis header is in three packets; the initial small packet in
  114174. the first page that identifies basic parameters, a second packet
  114175. with bitstream comments and a third packet that holds the
  114176. codebook. */
  114177. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114178. oggpack_buffer opb;
  114179. if(op){
  114180. oggpack_readinit(&opb,op->packet,op->bytes);
  114181. /* Which of the three types of header is this? */
  114182. /* Also verify header-ness, vorbis */
  114183. {
  114184. char buffer[6];
  114185. int packtype=oggpack_read(&opb,8);
  114186. memset(buffer,0,6);
  114187. _v_readstring(&opb,buffer,6);
  114188. if(memcmp(buffer,"vorbis",6)){
  114189. /* not a vorbis header */
  114190. return(OV_ENOTVORBIS);
  114191. }
  114192. switch(packtype){
  114193. case 0x01: /* least significant *bit* is read first */
  114194. if(!op->b_o_s){
  114195. /* Not the initial packet */
  114196. return(OV_EBADHEADER);
  114197. }
  114198. if(vi->rate!=0){
  114199. /* previously initialized info header */
  114200. return(OV_EBADHEADER);
  114201. }
  114202. return(_vorbis_unpack_info(vi,&opb));
  114203. case 0x03: /* least significant *bit* is read first */
  114204. if(vi->rate==0){
  114205. /* um... we didn't get the initial header */
  114206. return(OV_EBADHEADER);
  114207. }
  114208. return(_vorbis_unpack_comment(vc,&opb));
  114209. case 0x05: /* least significant *bit* is read first */
  114210. if(vi->rate==0 || vc->vendor==NULL){
  114211. /* um... we didn;t get the initial header or comments yet */
  114212. return(OV_EBADHEADER);
  114213. }
  114214. return(_vorbis_unpack_books(vi,&opb));
  114215. default:
  114216. /* Not a valid vorbis header type */
  114217. return(OV_EBADHEADER);
  114218. break;
  114219. }
  114220. }
  114221. }
  114222. return(OV_EBADHEADER);
  114223. }
  114224. /* pack side **********************************************************/
  114225. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114226. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114227. if(!ci)return(OV_EFAULT);
  114228. /* preamble */
  114229. oggpack_write(opb,0x01,8);
  114230. _v_writestring(opb,"vorbis", 6);
  114231. /* basic information about the stream */
  114232. oggpack_write(opb,0x00,32);
  114233. oggpack_write(opb,vi->channels,8);
  114234. oggpack_write(opb,vi->rate,32);
  114235. oggpack_write(opb,vi->bitrate_upper,32);
  114236. oggpack_write(opb,vi->bitrate_nominal,32);
  114237. oggpack_write(opb,vi->bitrate_lower,32);
  114238. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114239. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114240. oggpack_write(opb,1,1);
  114241. return(0);
  114242. }
  114243. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114244. char temp[]="Xiph.Org libVorbis I 20050304";
  114245. int bytes = strlen(temp);
  114246. /* preamble */
  114247. oggpack_write(opb,0x03,8);
  114248. _v_writestring(opb,"vorbis", 6);
  114249. /* vendor */
  114250. oggpack_write(opb,bytes,32);
  114251. _v_writestring(opb,temp, bytes);
  114252. /* comments */
  114253. oggpack_write(opb,vc->comments,32);
  114254. if(vc->comments){
  114255. int i;
  114256. for(i=0;i<vc->comments;i++){
  114257. if(vc->user_comments[i]){
  114258. oggpack_write(opb,vc->comment_lengths[i],32);
  114259. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114260. }else{
  114261. oggpack_write(opb,0,32);
  114262. }
  114263. }
  114264. }
  114265. oggpack_write(opb,1,1);
  114266. return(0);
  114267. }
  114268. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114269. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114270. int i;
  114271. if(!ci)return(OV_EFAULT);
  114272. oggpack_write(opb,0x05,8);
  114273. _v_writestring(opb,"vorbis", 6);
  114274. /* books */
  114275. oggpack_write(opb,ci->books-1,8);
  114276. for(i=0;i<ci->books;i++)
  114277. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114278. /* times; hook placeholders */
  114279. oggpack_write(opb,0,6);
  114280. oggpack_write(opb,0,16);
  114281. /* floors */
  114282. oggpack_write(opb,ci->floors-1,6);
  114283. for(i=0;i<ci->floors;i++){
  114284. oggpack_write(opb,ci->floor_type[i],16);
  114285. if(_floor_P[ci->floor_type[i]]->pack)
  114286. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114287. else
  114288. goto err_out;
  114289. }
  114290. /* residues */
  114291. oggpack_write(opb,ci->residues-1,6);
  114292. for(i=0;i<ci->residues;i++){
  114293. oggpack_write(opb,ci->residue_type[i],16);
  114294. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114295. }
  114296. /* maps */
  114297. oggpack_write(opb,ci->maps-1,6);
  114298. for(i=0;i<ci->maps;i++){
  114299. oggpack_write(opb,ci->map_type[i],16);
  114300. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114301. }
  114302. /* modes */
  114303. oggpack_write(opb,ci->modes-1,6);
  114304. for(i=0;i<ci->modes;i++){
  114305. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114306. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114307. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114308. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114309. }
  114310. oggpack_write(opb,1,1);
  114311. return(0);
  114312. err_out:
  114313. return(-1);
  114314. }
  114315. int vorbis_commentheader_out(vorbis_comment *vc,
  114316. ogg_packet *op){
  114317. oggpack_buffer opb;
  114318. oggpack_writeinit(&opb);
  114319. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114320. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114321. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114322. op->bytes=oggpack_bytes(&opb);
  114323. op->b_o_s=0;
  114324. op->e_o_s=0;
  114325. op->granulepos=0;
  114326. op->packetno=1;
  114327. return 0;
  114328. }
  114329. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114330. vorbis_comment *vc,
  114331. ogg_packet *op,
  114332. ogg_packet *op_comm,
  114333. ogg_packet *op_code){
  114334. int ret=OV_EIMPL;
  114335. vorbis_info *vi=v->vi;
  114336. oggpack_buffer opb;
  114337. private_state *b=(private_state*)v->backend_state;
  114338. if(!b){
  114339. ret=OV_EFAULT;
  114340. goto err_out;
  114341. }
  114342. /* first header packet **********************************************/
  114343. oggpack_writeinit(&opb);
  114344. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114345. /* build the packet */
  114346. if(b->header)_ogg_free(b->header);
  114347. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114348. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114349. op->packet=b->header;
  114350. op->bytes=oggpack_bytes(&opb);
  114351. op->b_o_s=1;
  114352. op->e_o_s=0;
  114353. op->granulepos=0;
  114354. op->packetno=0;
  114355. /* second header packet (comments) **********************************/
  114356. oggpack_reset(&opb);
  114357. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114358. if(b->header1)_ogg_free(b->header1);
  114359. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114360. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114361. op_comm->packet=b->header1;
  114362. op_comm->bytes=oggpack_bytes(&opb);
  114363. op_comm->b_o_s=0;
  114364. op_comm->e_o_s=0;
  114365. op_comm->granulepos=0;
  114366. op_comm->packetno=1;
  114367. /* third header packet (modes/codebooks) ****************************/
  114368. oggpack_reset(&opb);
  114369. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114370. if(b->header2)_ogg_free(b->header2);
  114371. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114372. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114373. op_code->packet=b->header2;
  114374. op_code->bytes=oggpack_bytes(&opb);
  114375. op_code->b_o_s=0;
  114376. op_code->e_o_s=0;
  114377. op_code->granulepos=0;
  114378. op_code->packetno=2;
  114379. oggpack_writeclear(&opb);
  114380. return(0);
  114381. err_out:
  114382. oggpack_writeclear(&opb);
  114383. memset(op,0,sizeof(*op));
  114384. memset(op_comm,0,sizeof(*op_comm));
  114385. memset(op_code,0,sizeof(*op_code));
  114386. if(b->header)_ogg_free(b->header);
  114387. if(b->header1)_ogg_free(b->header1);
  114388. if(b->header2)_ogg_free(b->header2);
  114389. b->header=NULL;
  114390. b->header1=NULL;
  114391. b->header2=NULL;
  114392. return(ret);
  114393. }
  114394. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114395. if(granulepos>=0)
  114396. return((double)granulepos/v->vi->rate);
  114397. return(-1);
  114398. }
  114399. #endif
  114400. /*** End of inlined file: info.c ***/
  114401. /*** Start of inlined file: lpc.c ***/
  114402. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114403. are derived from code written by Jutta Degener and Carsten Bormann;
  114404. thus we include their copyright below. The entirety of this file
  114405. is freely redistributable on the condition that both of these
  114406. copyright notices are preserved without modification. */
  114407. /* Preserved Copyright: *********************************************/
  114408. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114409. Technische Universita"t Berlin
  114410. Any use of this software is permitted provided that this notice is not
  114411. removed and that neither the authors nor the Technische Universita"t
  114412. Berlin are deemed to have made any representations as to the
  114413. suitability of this software for any purpose nor are held responsible
  114414. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114415. THIS SOFTWARE.
  114416. As a matter of courtesy, the authors request to be informed about uses
  114417. this software has found, about bugs in this software, and about any
  114418. improvements that may be of general interest.
  114419. Berlin, 28.11.1994
  114420. Jutta Degener
  114421. Carsten Bormann
  114422. *********************************************************************/
  114423. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114424. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114425. // tasks..
  114426. #if JUCE_MSVC
  114427. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114428. #endif
  114429. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114430. #if JUCE_USE_OGGVORBIS
  114431. #include <stdlib.h>
  114432. #include <string.h>
  114433. #include <math.h>
  114434. /* Autocorrelation LPC coeff generation algorithm invented by
  114435. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114436. /* Input : n elements of time doamin data
  114437. Output: m lpc coefficients, excitation energy */
  114438. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114439. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114440. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114441. double error;
  114442. int i,j;
  114443. /* autocorrelation, p+1 lag coefficients */
  114444. j=m+1;
  114445. while(j--){
  114446. double d=0; /* double needed for accumulator depth */
  114447. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114448. aut[j]=d;
  114449. }
  114450. /* Generate lpc coefficients from autocorr values */
  114451. error=aut[0];
  114452. for(i=0;i<m;i++){
  114453. double r= -aut[i+1];
  114454. if(error==0){
  114455. memset(lpci,0,m*sizeof(*lpci));
  114456. return 0;
  114457. }
  114458. /* Sum up this iteration's reflection coefficient; note that in
  114459. Vorbis we don't save it. If anyone wants to recycle this code
  114460. and needs reflection coefficients, save the results of 'r' from
  114461. each iteration. */
  114462. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114463. r/=error;
  114464. /* Update LPC coefficients and total error */
  114465. lpc[i]=r;
  114466. for(j=0;j<i/2;j++){
  114467. double tmp=lpc[j];
  114468. lpc[j]+=r*lpc[i-1-j];
  114469. lpc[i-1-j]+=r*tmp;
  114470. }
  114471. if(i%2)lpc[j]+=lpc[j]*r;
  114472. error*=1.f-r*r;
  114473. }
  114474. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114475. /* we need the error value to know how big an impulse to hit the
  114476. filter with later */
  114477. return error;
  114478. }
  114479. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114480. float *data,long n){
  114481. /* in: coeff[0...m-1] LPC coefficients
  114482. prime[0...m-1] initial values (allocated size of n+m-1)
  114483. out: data[0...n-1] data samples */
  114484. long i,j,o,p;
  114485. float y;
  114486. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114487. if(!prime)
  114488. for(i=0;i<m;i++)
  114489. work[i]=0.f;
  114490. else
  114491. for(i=0;i<m;i++)
  114492. work[i]=prime[i];
  114493. for(i=0;i<n;i++){
  114494. y=0;
  114495. o=i;
  114496. p=m;
  114497. for(j=0;j<m;j++)
  114498. y-=work[o++]*coeff[--p];
  114499. data[i]=work[o]=y;
  114500. }
  114501. }
  114502. #endif
  114503. /*** End of inlined file: lpc.c ***/
  114504. /*** Start of inlined file: lsp.c ***/
  114505. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114506. an iterative root polisher (CACM algorithm 283). It *is* possible
  114507. to confuse this algorithm into not converging; that should only
  114508. happen with absurdly closely spaced roots (very sharp peaks in the
  114509. LPC f response) which in turn should be impossible in our use of
  114510. the code. If this *does* happen anyway, it's a bug in the floor
  114511. finder; find the cause of the confusion (probably a single bin
  114512. spike or accidental near-float-limit resolution problems) and
  114513. correct it. */
  114514. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114515. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114516. // tasks..
  114517. #if JUCE_MSVC
  114518. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114519. #endif
  114520. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114521. #if JUCE_USE_OGGVORBIS
  114522. #include <math.h>
  114523. #include <string.h>
  114524. #include <stdlib.h>
  114525. /*** Start of inlined file: lookup.h ***/
  114526. #ifndef _V_LOOKUP_H_
  114527. #ifdef FLOAT_LOOKUP
  114528. extern float vorbis_coslook(float a);
  114529. extern float vorbis_invsqlook(float a);
  114530. extern float vorbis_invsq2explook(int a);
  114531. extern float vorbis_fromdBlook(float a);
  114532. #endif
  114533. #ifdef INT_LOOKUP
  114534. extern long vorbis_invsqlook_i(long a,long e);
  114535. extern long vorbis_coslook_i(long a);
  114536. extern float vorbis_fromdBlook_i(long a);
  114537. #endif
  114538. #endif
  114539. /*** End of inlined file: lookup.h ***/
  114540. /* three possible LSP to f curve functions; the exact computation
  114541. (float), a lookup based float implementation, and an integer
  114542. implementation. The float lookup is likely the optimal choice on
  114543. any machine with an FPU. The integer implementation is *not* fixed
  114544. point (due to the need for a large dynamic range and thus a
  114545. seperately tracked exponent) and thus much more complex than the
  114546. relatively simple float implementations. It's mostly for future
  114547. work on a fully fixed point implementation for processors like the
  114548. ARM family. */
  114549. /* undefine both for the 'old' but more precise implementation */
  114550. #define FLOAT_LOOKUP
  114551. #undef INT_LOOKUP
  114552. #ifdef FLOAT_LOOKUP
  114553. /*** Start of inlined file: lookup.c ***/
  114554. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114555. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114556. // tasks..
  114557. #if JUCE_MSVC
  114558. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114559. #endif
  114560. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114561. #if JUCE_USE_OGGVORBIS
  114562. #include <math.h>
  114563. /*** Start of inlined file: lookup.h ***/
  114564. #ifndef _V_LOOKUP_H_
  114565. #ifdef FLOAT_LOOKUP
  114566. extern float vorbis_coslook(float a);
  114567. extern float vorbis_invsqlook(float a);
  114568. extern float vorbis_invsq2explook(int a);
  114569. extern float vorbis_fromdBlook(float a);
  114570. #endif
  114571. #ifdef INT_LOOKUP
  114572. extern long vorbis_invsqlook_i(long a,long e);
  114573. extern long vorbis_coslook_i(long a);
  114574. extern float vorbis_fromdBlook_i(long a);
  114575. #endif
  114576. #endif
  114577. /*** End of inlined file: lookup.h ***/
  114578. /*** Start of inlined file: lookup_data.h ***/
  114579. #ifndef _V_LOOKUP_DATA_H_
  114580. #ifdef FLOAT_LOOKUP
  114581. #define COS_LOOKUP_SZ 128
  114582. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114583. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114584. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114585. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114586. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114587. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114588. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114589. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114590. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114591. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114592. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114593. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114594. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114595. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114596. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114597. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114598. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114599. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114600. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114601. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114602. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114603. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114604. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114605. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114606. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114607. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114608. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114609. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114610. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114611. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114612. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114613. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114614. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114615. -1.0000000000000f,
  114616. };
  114617. #define INVSQ_LOOKUP_SZ 32
  114618. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114619. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114620. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114621. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114622. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114623. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114624. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114625. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114626. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114627. 1.000000000000f,
  114628. };
  114629. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114630. #define INVSQ2EXP_LOOKUP_MAX 32
  114631. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114632. INVSQ2EXP_LOOKUP_MIN+1]={
  114633. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114634. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114635. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114636. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114637. 256.f, 181.019336f, 128.f, 90.50966799f,
  114638. 64.f, 45.254834f, 32.f, 22.627417f,
  114639. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114640. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114641. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114642. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114643. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114644. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114645. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114646. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114647. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114648. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114649. 1.525878906e-05f,
  114650. };
  114651. #endif
  114652. #define FROMdB_LOOKUP_SZ 35
  114653. #define FROMdB2_LOOKUP_SZ 32
  114654. #define FROMdB_SHIFT 5
  114655. #define FROMdB2_SHIFT 3
  114656. #define FROMdB2_MASK 31
  114657. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114658. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114659. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114660. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114661. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114662. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114663. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114664. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114665. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114666. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114667. };
  114668. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114669. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114670. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114671. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114672. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114673. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114674. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114675. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114676. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114677. };
  114678. #ifdef INT_LOOKUP
  114679. #define INVSQ_LOOKUP_I_SHIFT 10
  114680. #define INVSQ_LOOKUP_I_MASK 1023
  114681. static long INVSQ_LOOKUP_I[64+1]={
  114682. 92682l, 91966l, 91267l, 90583l,
  114683. 89915l, 89261l, 88621l, 87995l,
  114684. 87381l, 86781l, 86192l, 85616l,
  114685. 85051l, 84497l, 83953l, 83420l,
  114686. 82897l, 82384l, 81880l, 81385l,
  114687. 80899l, 80422l, 79953l, 79492l,
  114688. 79039l, 78594l, 78156l, 77726l,
  114689. 77302l, 76885l, 76475l, 76072l,
  114690. 75674l, 75283l, 74898l, 74519l,
  114691. 74146l, 73778l, 73415l, 73058l,
  114692. 72706l, 72359l, 72016l, 71679l,
  114693. 71347l, 71019l, 70695l, 70376l,
  114694. 70061l, 69750l, 69444l, 69141l,
  114695. 68842l, 68548l, 68256l, 67969l,
  114696. 67685l, 67405l, 67128l, 66855l,
  114697. 66585l, 66318l, 66054l, 65794l,
  114698. 65536l,
  114699. };
  114700. #define COS_LOOKUP_I_SHIFT 9
  114701. #define COS_LOOKUP_I_MASK 511
  114702. #define COS_LOOKUP_I_SZ 128
  114703. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114704. 16384l, 16379l, 16364l, 16340l,
  114705. 16305l, 16261l, 16207l, 16143l,
  114706. 16069l, 15986l, 15893l, 15791l,
  114707. 15679l, 15557l, 15426l, 15286l,
  114708. 15137l, 14978l, 14811l, 14635l,
  114709. 14449l, 14256l, 14053l, 13842l,
  114710. 13623l, 13395l, 13160l, 12916l,
  114711. 12665l, 12406l, 12140l, 11866l,
  114712. 11585l, 11297l, 11003l, 10702l,
  114713. 10394l, 10080l, 9760l, 9434l,
  114714. 9102l, 8765l, 8423l, 8076l,
  114715. 7723l, 7366l, 7005l, 6639l,
  114716. 6270l, 5897l, 5520l, 5139l,
  114717. 4756l, 4370l, 3981l, 3590l,
  114718. 3196l, 2801l, 2404l, 2006l,
  114719. 1606l, 1205l, 804l, 402l,
  114720. 0l, -401l, -803l, -1204l,
  114721. -1605l, -2005l, -2403l, -2800l,
  114722. -3195l, -3589l, -3980l, -4369l,
  114723. -4755l, -5138l, -5519l, -5896l,
  114724. -6269l, -6638l, -7004l, -7365l,
  114725. -7722l, -8075l, -8422l, -8764l,
  114726. -9101l, -9433l, -9759l, -10079l,
  114727. -10393l, -10701l, -11002l, -11296l,
  114728. -11584l, -11865l, -12139l, -12405l,
  114729. -12664l, -12915l, -13159l, -13394l,
  114730. -13622l, -13841l, -14052l, -14255l,
  114731. -14448l, -14634l, -14810l, -14977l,
  114732. -15136l, -15285l, -15425l, -15556l,
  114733. -15678l, -15790l, -15892l, -15985l,
  114734. -16068l, -16142l, -16206l, -16260l,
  114735. -16304l, -16339l, -16363l, -16378l,
  114736. -16383l,
  114737. };
  114738. #endif
  114739. #endif
  114740. /*** End of inlined file: lookup_data.h ***/
  114741. #ifdef FLOAT_LOOKUP
  114742. /* interpolated lookup based cos function, domain 0 to PI only */
  114743. float vorbis_coslook(float a){
  114744. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114745. int i=vorbis_ftoi(d-.5);
  114746. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114747. }
  114748. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114749. float vorbis_invsqlook(float a){
  114750. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114751. int i=vorbis_ftoi(d-.5f);
  114752. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114753. }
  114754. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114755. float vorbis_invsq2explook(int a){
  114756. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114757. }
  114758. #include <stdio.h>
  114759. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114760. float vorbis_fromdBlook(float a){
  114761. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114762. return (i<0)?1.f:
  114763. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114764. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114765. }
  114766. #endif
  114767. #ifdef INT_LOOKUP
  114768. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114769. 16.16 format
  114770. returns in m.8 format */
  114771. long vorbis_invsqlook_i(long a,long e){
  114772. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114773. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114774. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114775. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114776. d)>>16); /* result 1.16 */
  114777. e+=32;
  114778. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114779. e=(e>>1)-8;
  114780. return(val>>e);
  114781. }
  114782. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114783. /* a is in n.12 format */
  114784. float vorbis_fromdBlook_i(long a){
  114785. int i=(-a)>>(12-FROMdB2_SHIFT);
  114786. return (i<0)?1.f:
  114787. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114788. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114789. }
  114790. /* interpolated lookup based cos function, domain 0 to PI only */
  114791. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114792. long vorbis_coslook_i(long a){
  114793. int i=a>>COS_LOOKUP_I_SHIFT;
  114794. int d=a&COS_LOOKUP_I_MASK;
  114795. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114796. COS_LOOKUP_I_SHIFT);
  114797. }
  114798. #endif
  114799. #endif
  114800. /*** End of inlined file: lookup.c ***/
  114801. /* catch this in the build system; we #include for
  114802. compilers (like gcc) that can't inline across
  114803. modules */
  114804. /* side effect: changes *lsp to cosines of lsp */
  114805. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114806. float amp,float ampoffset){
  114807. int i;
  114808. float wdel=M_PI/ln;
  114809. vorbis_fpu_control fpu;
  114810. (void) fpu; // to avoid an unused variable warning
  114811. vorbis_fpu_setround(&fpu);
  114812. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114813. i=0;
  114814. while(i<n){
  114815. int k=map[i];
  114816. int qexp;
  114817. float p=.7071067812f;
  114818. float q=.7071067812f;
  114819. float w=vorbis_coslook(wdel*k);
  114820. float *ftmp=lsp;
  114821. int c=m>>1;
  114822. do{
  114823. q*=ftmp[0]-w;
  114824. p*=ftmp[1]-w;
  114825. ftmp+=2;
  114826. }while(--c);
  114827. if(m&1){
  114828. /* odd order filter; slightly assymetric */
  114829. /* the last coefficient */
  114830. q*=ftmp[0]-w;
  114831. q*=q;
  114832. p*=p*(1.f-w*w);
  114833. }else{
  114834. /* even order filter; still symmetric */
  114835. q*=q*(1.f+w);
  114836. p*=p*(1.f-w);
  114837. }
  114838. q=frexp(p+q,&qexp);
  114839. q=vorbis_fromdBlook(amp*
  114840. vorbis_invsqlook(q)*
  114841. vorbis_invsq2explook(qexp+m)-
  114842. ampoffset);
  114843. do{
  114844. curve[i++]*=q;
  114845. }while(map[i]==k);
  114846. }
  114847. vorbis_fpu_restore(fpu);
  114848. }
  114849. #else
  114850. #ifdef INT_LOOKUP
  114851. /*** Start of inlined file: lookup.c ***/
  114852. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114853. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114854. // tasks..
  114855. #if JUCE_MSVC
  114856. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114857. #endif
  114858. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114859. #if JUCE_USE_OGGVORBIS
  114860. #include <math.h>
  114861. /*** Start of inlined file: lookup.h ***/
  114862. #ifndef _V_LOOKUP_H_
  114863. #ifdef FLOAT_LOOKUP
  114864. extern float vorbis_coslook(float a);
  114865. extern float vorbis_invsqlook(float a);
  114866. extern float vorbis_invsq2explook(int a);
  114867. extern float vorbis_fromdBlook(float a);
  114868. #endif
  114869. #ifdef INT_LOOKUP
  114870. extern long vorbis_invsqlook_i(long a,long e);
  114871. extern long vorbis_coslook_i(long a);
  114872. extern float vorbis_fromdBlook_i(long a);
  114873. #endif
  114874. #endif
  114875. /*** End of inlined file: lookup.h ***/
  114876. /*** Start of inlined file: lookup_data.h ***/
  114877. #ifndef _V_LOOKUP_DATA_H_
  114878. #ifdef FLOAT_LOOKUP
  114879. #define COS_LOOKUP_SZ 128
  114880. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114881. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114882. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114883. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114884. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114885. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114886. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114887. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114888. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114889. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114890. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114891. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114892. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114893. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114894. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114895. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114896. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114897. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114898. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114899. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114900. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114901. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114902. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114903. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114904. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114905. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114906. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114907. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114908. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114909. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114910. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114911. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114912. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114913. -1.0000000000000f,
  114914. };
  114915. #define INVSQ_LOOKUP_SZ 32
  114916. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114917. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114918. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114919. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114920. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114921. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114922. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114923. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114924. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114925. 1.000000000000f,
  114926. };
  114927. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114928. #define INVSQ2EXP_LOOKUP_MAX 32
  114929. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114930. INVSQ2EXP_LOOKUP_MIN+1]={
  114931. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114932. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114933. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114934. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114935. 256.f, 181.019336f, 128.f, 90.50966799f,
  114936. 64.f, 45.254834f, 32.f, 22.627417f,
  114937. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114938. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114939. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114940. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114941. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114942. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114943. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114944. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114945. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114946. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114947. 1.525878906e-05f,
  114948. };
  114949. #endif
  114950. #define FROMdB_LOOKUP_SZ 35
  114951. #define FROMdB2_LOOKUP_SZ 32
  114952. #define FROMdB_SHIFT 5
  114953. #define FROMdB2_SHIFT 3
  114954. #define FROMdB2_MASK 31
  114955. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114956. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114957. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114958. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114959. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114960. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114961. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114962. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114963. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114964. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114965. };
  114966. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114967. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114968. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114969. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114970. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114971. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114972. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114973. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114974. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114975. };
  114976. #ifdef INT_LOOKUP
  114977. #define INVSQ_LOOKUP_I_SHIFT 10
  114978. #define INVSQ_LOOKUP_I_MASK 1023
  114979. static long INVSQ_LOOKUP_I[64+1]={
  114980. 92682l, 91966l, 91267l, 90583l,
  114981. 89915l, 89261l, 88621l, 87995l,
  114982. 87381l, 86781l, 86192l, 85616l,
  114983. 85051l, 84497l, 83953l, 83420l,
  114984. 82897l, 82384l, 81880l, 81385l,
  114985. 80899l, 80422l, 79953l, 79492l,
  114986. 79039l, 78594l, 78156l, 77726l,
  114987. 77302l, 76885l, 76475l, 76072l,
  114988. 75674l, 75283l, 74898l, 74519l,
  114989. 74146l, 73778l, 73415l, 73058l,
  114990. 72706l, 72359l, 72016l, 71679l,
  114991. 71347l, 71019l, 70695l, 70376l,
  114992. 70061l, 69750l, 69444l, 69141l,
  114993. 68842l, 68548l, 68256l, 67969l,
  114994. 67685l, 67405l, 67128l, 66855l,
  114995. 66585l, 66318l, 66054l, 65794l,
  114996. 65536l,
  114997. };
  114998. #define COS_LOOKUP_I_SHIFT 9
  114999. #define COS_LOOKUP_I_MASK 511
  115000. #define COS_LOOKUP_I_SZ 128
  115001. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  115002. 16384l, 16379l, 16364l, 16340l,
  115003. 16305l, 16261l, 16207l, 16143l,
  115004. 16069l, 15986l, 15893l, 15791l,
  115005. 15679l, 15557l, 15426l, 15286l,
  115006. 15137l, 14978l, 14811l, 14635l,
  115007. 14449l, 14256l, 14053l, 13842l,
  115008. 13623l, 13395l, 13160l, 12916l,
  115009. 12665l, 12406l, 12140l, 11866l,
  115010. 11585l, 11297l, 11003l, 10702l,
  115011. 10394l, 10080l, 9760l, 9434l,
  115012. 9102l, 8765l, 8423l, 8076l,
  115013. 7723l, 7366l, 7005l, 6639l,
  115014. 6270l, 5897l, 5520l, 5139l,
  115015. 4756l, 4370l, 3981l, 3590l,
  115016. 3196l, 2801l, 2404l, 2006l,
  115017. 1606l, 1205l, 804l, 402l,
  115018. 0l, -401l, -803l, -1204l,
  115019. -1605l, -2005l, -2403l, -2800l,
  115020. -3195l, -3589l, -3980l, -4369l,
  115021. -4755l, -5138l, -5519l, -5896l,
  115022. -6269l, -6638l, -7004l, -7365l,
  115023. -7722l, -8075l, -8422l, -8764l,
  115024. -9101l, -9433l, -9759l, -10079l,
  115025. -10393l, -10701l, -11002l, -11296l,
  115026. -11584l, -11865l, -12139l, -12405l,
  115027. -12664l, -12915l, -13159l, -13394l,
  115028. -13622l, -13841l, -14052l, -14255l,
  115029. -14448l, -14634l, -14810l, -14977l,
  115030. -15136l, -15285l, -15425l, -15556l,
  115031. -15678l, -15790l, -15892l, -15985l,
  115032. -16068l, -16142l, -16206l, -16260l,
  115033. -16304l, -16339l, -16363l, -16378l,
  115034. -16383l,
  115035. };
  115036. #endif
  115037. #endif
  115038. /*** End of inlined file: lookup_data.h ***/
  115039. #ifdef FLOAT_LOOKUP
  115040. /* interpolated lookup based cos function, domain 0 to PI only */
  115041. float vorbis_coslook(float a){
  115042. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  115043. int i=vorbis_ftoi(d-.5);
  115044. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  115045. }
  115046. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115047. float vorbis_invsqlook(float a){
  115048. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  115049. int i=vorbis_ftoi(d-.5f);
  115050. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  115051. }
  115052. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115053. float vorbis_invsq2explook(int a){
  115054. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  115055. }
  115056. #include <stdio.h>
  115057. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115058. float vorbis_fromdBlook(float a){
  115059. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  115060. return (i<0)?1.f:
  115061. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115062. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115063. }
  115064. #endif
  115065. #ifdef INT_LOOKUP
  115066. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115067. 16.16 format
  115068. returns in m.8 format */
  115069. long vorbis_invsqlook_i(long a,long e){
  115070. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115071. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115072. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115073. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115074. d)>>16); /* result 1.16 */
  115075. e+=32;
  115076. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115077. e=(e>>1)-8;
  115078. return(val>>e);
  115079. }
  115080. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115081. /* a is in n.12 format */
  115082. float vorbis_fromdBlook_i(long a){
  115083. int i=(-a)>>(12-FROMdB2_SHIFT);
  115084. return (i<0)?1.f:
  115085. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115086. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115087. }
  115088. /* interpolated lookup based cos function, domain 0 to PI only */
  115089. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115090. long vorbis_coslook_i(long a){
  115091. int i=a>>COS_LOOKUP_I_SHIFT;
  115092. int d=a&COS_LOOKUP_I_MASK;
  115093. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115094. COS_LOOKUP_I_SHIFT);
  115095. }
  115096. #endif
  115097. #endif
  115098. /*** End of inlined file: lookup.c ***/
  115099. /* catch this in the build system; we #include for
  115100. compilers (like gcc) that can't inline across
  115101. modules */
  115102. static int MLOOP_1[64]={
  115103. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115104. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115105. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115106. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115107. };
  115108. static int MLOOP_2[64]={
  115109. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115110. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115111. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115112. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115113. };
  115114. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115115. /* side effect: changes *lsp to cosines of lsp */
  115116. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115117. float amp,float ampoffset){
  115118. /* 0 <= m < 256 */
  115119. /* set up for using all int later */
  115120. int i;
  115121. int ampoffseti=rint(ampoffset*4096.f);
  115122. int ampi=rint(amp*16.f);
  115123. long *ilsp=alloca(m*sizeof(*ilsp));
  115124. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115125. i=0;
  115126. while(i<n){
  115127. int j,k=map[i];
  115128. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115129. unsigned long qi=46341;
  115130. int qexp=0,shift;
  115131. long wi=vorbis_coslook_i(k*65536/ln);
  115132. qi*=labs(ilsp[0]-wi);
  115133. pi*=labs(ilsp[1]-wi);
  115134. for(j=3;j<m;j+=2){
  115135. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115136. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115137. shift=MLOOP_3[(pi|qi)>>16];
  115138. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115139. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115140. qexp+=shift;
  115141. }
  115142. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115143. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115144. shift=MLOOP_3[(pi|qi)>>16];
  115145. /* pi,qi normalized collectively, both tracked using qexp */
  115146. if(m&1){
  115147. /* odd order filter; slightly assymetric */
  115148. /* the last coefficient */
  115149. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115150. pi=(pi>>shift)<<14;
  115151. qexp+=shift;
  115152. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115153. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115154. shift=MLOOP_3[(pi|qi)>>16];
  115155. pi>>=shift;
  115156. qi>>=shift;
  115157. qexp+=shift-14*((m+1)>>1);
  115158. pi=((pi*pi)>>16);
  115159. qi=((qi*qi)>>16);
  115160. qexp=qexp*2+m;
  115161. pi*=(1<<14)-((wi*wi)>>14);
  115162. qi+=pi>>14;
  115163. }else{
  115164. /* even order filter; still symmetric */
  115165. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115166. worth tracking step by step */
  115167. pi>>=shift;
  115168. qi>>=shift;
  115169. qexp+=shift-7*m;
  115170. pi=((pi*pi)>>16);
  115171. qi=((qi*qi)>>16);
  115172. qexp=qexp*2+m;
  115173. pi*=(1<<14)-wi;
  115174. qi*=(1<<14)+wi;
  115175. qi=(qi+pi)>>14;
  115176. }
  115177. /* we've let the normalization drift because it wasn't important;
  115178. however, for the lookup, things must be normalized again. We
  115179. need at most one right shift or a number of left shifts */
  115180. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115181. qi>>=1; qexp++;
  115182. }else
  115183. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115184. qi<<=1; qexp--;
  115185. }
  115186. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115187. vorbis_invsqlook_i(qi,qexp)-
  115188. /* m.8, m+n<=8 */
  115189. ampoffseti); /* 8.12[0] */
  115190. curve[i]*=amp;
  115191. while(map[++i]==k)curve[i]*=amp;
  115192. }
  115193. }
  115194. #else
  115195. /* old, nonoptimized but simple version for any poor sap who needs to
  115196. figure out what the hell this code does, or wants the other
  115197. fraction of a dB precision */
  115198. /* side effect: changes *lsp to cosines of lsp */
  115199. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115200. float amp,float ampoffset){
  115201. int i;
  115202. float wdel=M_PI/ln;
  115203. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115204. i=0;
  115205. while(i<n){
  115206. int j,k=map[i];
  115207. float p=.5f;
  115208. float q=.5f;
  115209. float w=2.f*cos(wdel*k);
  115210. for(j=1;j<m;j+=2){
  115211. q *= w-lsp[j-1];
  115212. p *= w-lsp[j];
  115213. }
  115214. if(j==m){
  115215. /* odd order filter; slightly assymetric */
  115216. /* the last coefficient */
  115217. q*=w-lsp[j-1];
  115218. p*=p*(4.f-w*w);
  115219. q*=q;
  115220. }else{
  115221. /* even order filter; still symmetric */
  115222. p*=p*(2.f-w);
  115223. q*=q*(2.f+w);
  115224. }
  115225. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115226. curve[i]*=q;
  115227. while(map[++i]==k)curve[i]*=q;
  115228. }
  115229. }
  115230. #endif
  115231. #endif
  115232. static void cheby(float *g, int ord) {
  115233. int i, j;
  115234. g[0] *= .5f;
  115235. for(i=2; i<= ord; i++) {
  115236. for(j=ord; j >= i; j--) {
  115237. g[j-2] -= g[j];
  115238. g[j] += g[j];
  115239. }
  115240. }
  115241. }
  115242. static int JUCE_CDECL comp(const void *a,const void *b){
  115243. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115244. }
  115245. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115246. but there are root sets for which it gets into limit cycles
  115247. (exacerbated by zero suppression) and fails. We can't afford to
  115248. fail, even if the failure is 1 in 100,000,000, so we now use
  115249. Laguerre and later polish with Newton-Raphson (which can then
  115250. afford to fail) */
  115251. #define EPSILON 10e-7
  115252. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115253. int i,m;
  115254. double lastdelta=0.f;
  115255. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115256. for(i=0;i<=ord;i++)defl[i]=a[i];
  115257. for(m=ord;m>0;m--){
  115258. double newx=0.f,delta;
  115259. /* iterate a root */
  115260. while(1){
  115261. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115262. /* eval the polynomial and its first two derivatives */
  115263. for(i=m;i>0;i--){
  115264. ppp = newx*ppp + pp;
  115265. pp = newx*pp + p;
  115266. p = newx*p + defl[i-1];
  115267. }
  115268. /* Laguerre's method */
  115269. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115270. if(denom<0)
  115271. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115272. if(pp>0){
  115273. denom = pp + sqrt(denom);
  115274. if(denom<EPSILON)denom=EPSILON;
  115275. }else{
  115276. denom = pp - sqrt(denom);
  115277. if(denom>-(EPSILON))denom=-(EPSILON);
  115278. }
  115279. delta = m*p/denom;
  115280. newx -= delta;
  115281. if(delta<0.f)delta*=-1;
  115282. if(fabs(delta/newx)<10e-12)break;
  115283. lastdelta=delta;
  115284. }
  115285. r[m-1]=newx;
  115286. /* forward deflation */
  115287. for(i=m;i>0;i--)
  115288. defl[i-1]+=newx*defl[i];
  115289. defl++;
  115290. }
  115291. return(0);
  115292. }
  115293. /* for spit-and-polish only */
  115294. static int Newton_Raphson(float *a,int ord,float *r){
  115295. int i, k, count=0;
  115296. double error=1.f;
  115297. double *root=(double*)alloca(ord*sizeof(*root));
  115298. for(i=0; i<ord;i++) root[i] = r[i];
  115299. while(error>1e-20){
  115300. error=0;
  115301. for(i=0; i<ord; i++) { /* Update each point. */
  115302. double pp=0.,delta;
  115303. double rooti=root[i];
  115304. double p=a[ord];
  115305. for(k=ord-1; k>= 0; k--) {
  115306. pp= pp* rooti + p;
  115307. p = p * rooti + a[k];
  115308. }
  115309. delta = p/pp;
  115310. root[i] -= delta;
  115311. error+= delta*delta;
  115312. }
  115313. if(count>40)return(-1);
  115314. count++;
  115315. }
  115316. /* Replaced the original bubble sort with a real sort. With your
  115317. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115318. for(i=0; i<ord;i++) r[i] = root[i];
  115319. return(0);
  115320. }
  115321. /* Convert lpc coefficients to lsp coefficients */
  115322. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115323. int order2=(m+1)>>1;
  115324. int g1_order,g2_order;
  115325. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115326. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115327. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115328. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115329. int i;
  115330. /* even and odd are slightly different base cases */
  115331. g1_order=(m+1)>>1;
  115332. g2_order=(m) >>1;
  115333. /* Compute the lengths of the x polynomials. */
  115334. /* Compute the first half of K & R F1 & F2 polynomials. */
  115335. /* Compute half of the symmetric and antisymmetric polynomials. */
  115336. /* Remove the roots at +1 and -1. */
  115337. g1[g1_order] = 1.f;
  115338. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115339. g2[g2_order] = 1.f;
  115340. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115341. if(g1_order>g2_order){
  115342. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115343. }else{
  115344. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115345. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115346. }
  115347. /* Convert into polynomials in cos(alpha) */
  115348. cheby(g1,g1_order);
  115349. cheby(g2,g2_order);
  115350. /* Find the roots of the 2 even polynomials.*/
  115351. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115352. Laguerre_With_Deflation(g2,g2_order,g2r))
  115353. return(-1);
  115354. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115355. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115356. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115357. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115358. for(i=0;i<g1_order;i++)
  115359. lsp[i*2] = acos(g1r[i]);
  115360. for(i=0;i<g2_order;i++)
  115361. lsp[i*2+1] = acos(g2r[i]);
  115362. return(0);
  115363. }
  115364. #endif
  115365. /*** End of inlined file: lsp.c ***/
  115366. /*** Start of inlined file: mapping0.c ***/
  115367. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115368. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115369. // tasks..
  115370. #if JUCE_MSVC
  115371. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115372. #endif
  115373. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115374. #if JUCE_USE_OGGVORBIS
  115375. #include <stdlib.h>
  115376. #include <stdio.h>
  115377. #include <string.h>
  115378. #include <math.h>
  115379. /* simplistic, wasteful way of doing this (unique lookup for each
  115380. mode/submapping); there should be a central repository for
  115381. identical lookups. That will require minor work, so I'm putting it
  115382. off as low priority.
  115383. Why a lookup for each backend in a given mode? Because the
  115384. blocksize is set by the mode, and low backend lookups may require
  115385. parameters from other areas of the mode/mapping */
  115386. static void mapping0_free_info(vorbis_info_mapping *i){
  115387. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115388. if(info){
  115389. memset(info,0,sizeof(*info));
  115390. _ogg_free(info);
  115391. }
  115392. }
  115393. static int ilog3(unsigned int v){
  115394. int ret=0;
  115395. if(v)--v;
  115396. while(v){
  115397. ret++;
  115398. v>>=1;
  115399. }
  115400. return(ret);
  115401. }
  115402. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115403. oggpack_buffer *opb){
  115404. int i;
  115405. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115406. /* another 'we meant to do it this way' hack... up to beta 4, we
  115407. packed 4 binary zeros here to signify one submapping in use. We
  115408. now redefine that to mean four bitflags that indicate use of
  115409. deeper features; bit0:submappings, bit1:coupling,
  115410. bit2,3:reserved. This is backward compatable with all actual uses
  115411. of the beta code. */
  115412. if(info->submaps>1){
  115413. oggpack_write(opb,1,1);
  115414. oggpack_write(opb,info->submaps-1,4);
  115415. }else
  115416. oggpack_write(opb,0,1);
  115417. if(info->coupling_steps>0){
  115418. oggpack_write(opb,1,1);
  115419. oggpack_write(opb,info->coupling_steps-1,8);
  115420. for(i=0;i<info->coupling_steps;i++){
  115421. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115422. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115423. }
  115424. }else
  115425. oggpack_write(opb,0,1);
  115426. oggpack_write(opb,0,2); /* 2,3:reserved */
  115427. /* we don't write the channel submappings if we only have one... */
  115428. if(info->submaps>1){
  115429. for(i=0;i<vi->channels;i++)
  115430. oggpack_write(opb,info->chmuxlist[i],4);
  115431. }
  115432. for(i=0;i<info->submaps;i++){
  115433. oggpack_write(opb,0,8); /* time submap unused */
  115434. oggpack_write(opb,info->floorsubmap[i],8);
  115435. oggpack_write(opb,info->residuesubmap[i],8);
  115436. }
  115437. }
  115438. /* also responsible for range checking */
  115439. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115440. int i;
  115441. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115442. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115443. memset(info,0,sizeof(*info));
  115444. if(oggpack_read(opb,1))
  115445. info->submaps=oggpack_read(opb,4)+1;
  115446. else
  115447. info->submaps=1;
  115448. if(oggpack_read(opb,1)){
  115449. info->coupling_steps=oggpack_read(opb,8)+1;
  115450. for(i=0;i<info->coupling_steps;i++){
  115451. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115452. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115453. if(testM<0 ||
  115454. testA<0 ||
  115455. testM==testA ||
  115456. testM>=vi->channels ||
  115457. testA>=vi->channels) goto err_out;
  115458. }
  115459. }
  115460. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115461. if(info->submaps>1){
  115462. for(i=0;i<vi->channels;i++){
  115463. info->chmuxlist[i]=oggpack_read(opb,4);
  115464. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115465. }
  115466. }
  115467. for(i=0;i<info->submaps;i++){
  115468. oggpack_read(opb,8); /* time submap unused */
  115469. info->floorsubmap[i]=oggpack_read(opb,8);
  115470. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115471. info->residuesubmap[i]=oggpack_read(opb,8);
  115472. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115473. }
  115474. return info;
  115475. err_out:
  115476. mapping0_free_info(info);
  115477. return(NULL);
  115478. }
  115479. #if 0
  115480. static long seq=0;
  115481. static ogg_int64_t total=0;
  115482. static float FLOOR1_fromdB_LOOKUP[256]={
  115483. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115484. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115485. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115486. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115487. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115488. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115489. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115490. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115491. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115492. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115493. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115494. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115495. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115496. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115497. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115498. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115499. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115500. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115501. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115502. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115503. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115504. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115505. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115506. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115507. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115508. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115509. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115510. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115511. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115512. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115513. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115514. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115515. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115516. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115517. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115518. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115519. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115520. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115521. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115522. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115523. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115524. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115525. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115526. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115527. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115528. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115529. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115530. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115531. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115532. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115533. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115534. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115535. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115536. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115537. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115538. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115539. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115540. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115541. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115542. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115543. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115544. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115545. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115546. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115547. };
  115548. #endif
  115549. extern int *floor1_fit(vorbis_block *vb,void *look,
  115550. const float *logmdct, /* in */
  115551. const float *logmask);
  115552. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115553. int *A,int *B,
  115554. int del);
  115555. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115556. void*look,
  115557. int *post,int *ilogmask);
  115558. static int mapping0_forward(vorbis_block *vb){
  115559. vorbis_dsp_state *vd=vb->vd;
  115560. vorbis_info *vi=vd->vi;
  115561. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115562. private_state *b=(private_state*)vb->vd->backend_state;
  115563. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115564. int n=vb->pcmend;
  115565. int i,j,k;
  115566. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115567. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115568. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115569. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115570. float global_ampmax=vbi->ampmax;
  115571. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115572. int blocktype=vbi->blocktype;
  115573. int modenumber=vb->W;
  115574. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115575. vorbis_look_psy *psy_look=
  115576. b->psy+blocktype+(vb->W?2:0);
  115577. vb->mode=modenumber;
  115578. for(i=0;i<vi->channels;i++){
  115579. float scale=4.f/n;
  115580. float scale_dB;
  115581. float *pcm =vb->pcm[i];
  115582. float *logfft =pcm;
  115583. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115584. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115585. todB estimation used on IEEE 754
  115586. compliant machines had a bug that
  115587. returned dB values about a third
  115588. of a decibel too high. The bug
  115589. was harmless because tunings
  115590. implicitly took that into
  115591. account. However, fixing the bug
  115592. in the estimator requires
  115593. changing all the tunings as well.
  115594. For now, it's easier to sync
  115595. things back up here, and
  115596. recalibrate the tunings in the
  115597. next major model upgrade. */
  115598. #if 0
  115599. if(vi->channels==2)
  115600. if(i==0)
  115601. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115602. else
  115603. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115604. #endif
  115605. /* window the PCM data */
  115606. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115607. #if 0
  115608. if(vi->channels==2)
  115609. if(i==0)
  115610. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115611. else
  115612. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115613. #endif
  115614. /* transform the PCM data */
  115615. /* only MDCT right now.... */
  115616. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115617. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115618. drft_forward(&b->fft_look[vb->W],pcm);
  115619. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115620. original todB estimation used on
  115621. IEEE 754 compliant machines had a
  115622. bug that returned dB values about
  115623. a third of a decibel too high.
  115624. The bug was harmless because
  115625. tunings implicitly took that into
  115626. account. However, fixing the bug
  115627. in the estimator requires
  115628. changing all the tunings as well.
  115629. For now, it's easier to sync
  115630. things back up here, and
  115631. recalibrate the tunings in the
  115632. next major model upgrade. */
  115633. local_ampmax[i]=logfft[0];
  115634. for(j=1;j<n-1;j+=2){
  115635. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115636. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115637. .345 is a hack; the original todB
  115638. estimation used on IEEE 754
  115639. compliant machines had a bug that
  115640. returned dB values about a third
  115641. of a decibel too high. The bug
  115642. was harmless because tunings
  115643. implicitly took that into
  115644. account. However, fixing the bug
  115645. in the estimator requires
  115646. changing all the tunings as well.
  115647. For now, it's easier to sync
  115648. things back up here, and
  115649. recalibrate the tunings in the
  115650. next major model upgrade. */
  115651. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115652. }
  115653. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115654. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115655. #if 0
  115656. if(vi->channels==2){
  115657. if(i==0){
  115658. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115659. }else{
  115660. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115661. }
  115662. }
  115663. #endif
  115664. }
  115665. {
  115666. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115667. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115668. for(i=0;i<vi->channels;i++){
  115669. /* the encoder setup assumes that all the modes used by any
  115670. specific bitrate tweaking use the same floor */
  115671. int submap=info->chmuxlist[i];
  115672. /* the following makes things clearer to *me* anyway */
  115673. float *mdct =gmdct[i];
  115674. float *logfft =vb->pcm[i];
  115675. float *logmdct =logfft+n/2;
  115676. float *logmask =logfft;
  115677. vb->mode=modenumber;
  115678. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115679. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115680. for(j=0;j<n/2;j++)
  115681. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115682. todB estimation used on IEEE 754
  115683. compliant machines had a bug that
  115684. returned dB values about a third
  115685. of a decibel too high. The bug
  115686. was harmless because tunings
  115687. implicitly took that into
  115688. account. However, fixing the bug
  115689. in the estimator requires
  115690. changing all the tunings as well.
  115691. For now, it's easier to sync
  115692. things back up here, and
  115693. recalibrate the tunings in the
  115694. next major model upgrade. */
  115695. #if 0
  115696. if(vi->channels==2){
  115697. if(i==0)
  115698. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115699. else
  115700. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115701. }else{
  115702. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115703. }
  115704. #endif
  115705. /* first step; noise masking. Not only does 'noise masking'
  115706. give us curves from which we can decide how much resolution
  115707. to give noise parts of the spectrum, it also implicitly hands
  115708. us a tonality estimate (the larger the value in the
  115709. 'noise_depth' vector, the more tonal that area is) */
  115710. _vp_noisemask(psy_look,
  115711. logmdct,
  115712. noise); /* noise does not have by-frequency offset
  115713. bias applied yet */
  115714. #if 0
  115715. if(vi->channels==2){
  115716. if(i==0)
  115717. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115718. else
  115719. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115720. }
  115721. #endif
  115722. /* second step: 'all the other crap'; all the stuff that isn't
  115723. computed/fit for bitrate management goes in the second psy
  115724. vector. This includes tone masking, peak limiting and ATH */
  115725. _vp_tonemask(psy_look,
  115726. logfft,
  115727. tone,
  115728. global_ampmax,
  115729. local_ampmax[i]);
  115730. #if 0
  115731. if(vi->channels==2){
  115732. if(i==0)
  115733. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115734. else
  115735. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115736. }
  115737. #endif
  115738. /* third step; we offset the noise vectors, overlay tone
  115739. masking. We then do a floor1-specific line fit. If we're
  115740. performing bitrate management, the line fit is performed
  115741. multiple times for up/down tweakage on demand. */
  115742. #if 0
  115743. {
  115744. float aotuv[psy_look->n];
  115745. #endif
  115746. _vp_offset_and_mix(psy_look,
  115747. noise,
  115748. tone,
  115749. 1,
  115750. logmask,
  115751. mdct,
  115752. logmdct);
  115753. #if 0
  115754. if(vi->channels==2){
  115755. if(i==0)
  115756. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115757. else
  115758. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115759. }
  115760. }
  115761. #endif
  115762. #if 0
  115763. if(vi->channels==2){
  115764. if(i==0)
  115765. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115766. else
  115767. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115768. }
  115769. #endif
  115770. /* this algorithm is hardwired to floor 1 for now; abort out if
  115771. we're *not* floor1. This won't happen unless someone has
  115772. broken the encode setup lib. Guard it anyway. */
  115773. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115774. floor_posts[i][PACKETBLOBS/2]=
  115775. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115776. logmdct,
  115777. logmask);
  115778. /* are we managing bitrate? If so, perform two more fits for
  115779. later rate tweaking (fits represent hi/lo) */
  115780. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115781. /* higher rate by way of lower noise curve */
  115782. _vp_offset_and_mix(psy_look,
  115783. noise,
  115784. tone,
  115785. 2,
  115786. logmask,
  115787. mdct,
  115788. logmdct);
  115789. #if 0
  115790. if(vi->channels==2){
  115791. if(i==0)
  115792. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115793. else
  115794. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115795. }
  115796. #endif
  115797. floor_posts[i][PACKETBLOBS-1]=
  115798. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115799. logmdct,
  115800. logmask);
  115801. /* lower rate by way of higher noise curve */
  115802. _vp_offset_and_mix(psy_look,
  115803. noise,
  115804. tone,
  115805. 0,
  115806. logmask,
  115807. mdct,
  115808. logmdct);
  115809. #if 0
  115810. if(vi->channels==2)
  115811. if(i==0)
  115812. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115813. else
  115814. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115815. #endif
  115816. floor_posts[i][0]=
  115817. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115818. logmdct,
  115819. logmask);
  115820. /* we also interpolate a range of intermediate curves for
  115821. intermediate rates */
  115822. for(k=1;k<PACKETBLOBS/2;k++)
  115823. floor_posts[i][k]=
  115824. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115825. floor_posts[i][0],
  115826. floor_posts[i][PACKETBLOBS/2],
  115827. k*65536/(PACKETBLOBS/2));
  115828. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115829. floor_posts[i][k]=
  115830. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115831. floor_posts[i][PACKETBLOBS/2],
  115832. floor_posts[i][PACKETBLOBS-1],
  115833. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115834. }
  115835. }
  115836. }
  115837. vbi->ampmax=global_ampmax;
  115838. /*
  115839. the next phases are performed once for vbr-only and PACKETBLOB
  115840. times for bitrate managed modes.
  115841. 1) encode actual mode being used
  115842. 2) encode the floor for each channel, compute coded mask curve/res
  115843. 3) normalize and couple.
  115844. 4) encode residue
  115845. 5) save packet bytes to the packetblob vector
  115846. */
  115847. /* iterate over the many masking curve fits we've created */
  115848. {
  115849. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115850. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115851. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115852. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115853. float **mag_memo;
  115854. int **mag_sort;
  115855. if(info->coupling_steps){
  115856. mag_memo=_vp_quantize_couple_memo(vb,
  115857. &ci->psy_g_param,
  115858. psy_look,
  115859. info,
  115860. gmdct);
  115861. mag_sort=_vp_quantize_couple_sort(vb,
  115862. psy_look,
  115863. info,
  115864. mag_memo);
  115865. hf_reduction(&ci->psy_g_param,
  115866. psy_look,
  115867. info,
  115868. mag_memo);
  115869. }
  115870. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115871. if(psy_look->vi->normal_channel_p){
  115872. for(i=0;i<vi->channels;i++){
  115873. float *mdct =gmdct[i];
  115874. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115875. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115876. }
  115877. }
  115878. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115879. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115880. k++){
  115881. oggpack_buffer *opb=vbi->packetblob[k];
  115882. /* start out our new packet blob with packet type and mode */
  115883. /* Encode the packet type */
  115884. oggpack_write(opb,0,1);
  115885. /* Encode the modenumber */
  115886. /* Encode frame mode, pre,post windowsize, then dispatch */
  115887. oggpack_write(opb,modenumber,b->modebits);
  115888. if(vb->W){
  115889. oggpack_write(opb,vb->lW,1);
  115890. oggpack_write(opb,vb->nW,1);
  115891. }
  115892. /* encode floor, compute masking curve, sep out residue */
  115893. for(i=0;i<vi->channels;i++){
  115894. int submap=info->chmuxlist[i];
  115895. float *mdct =gmdct[i];
  115896. float *res =vb->pcm[i];
  115897. int *ilogmask=ilogmaskch[i]=
  115898. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115899. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115900. floor_posts[i][k],
  115901. ilogmask);
  115902. #if 0
  115903. {
  115904. char buf[80];
  115905. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115906. float work[n/2];
  115907. for(j=0;j<n/2;j++)
  115908. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115909. _analysis_output(buf,seq,work,n/2,1,1,0);
  115910. }
  115911. #endif
  115912. _vp_remove_floor(psy_look,
  115913. mdct,
  115914. ilogmask,
  115915. res,
  115916. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115917. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115918. #if 0
  115919. {
  115920. char buf[80];
  115921. float work[n/2];
  115922. for(j=0;j<n/2;j++)
  115923. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115924. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115925. _analysis_output(buf,seq,work,n/2,1,1,0);
  115926. }
  115927. #endif
  115928. }
  115929. /* our iteration is now based on masking curve, not prequant and
  115930. coupling. Only one prequant/coupling step */
  115931. /* quantize/couple */
  115932. /* incomplete implementation that assumes the tree is all depth
  115933. one, or no tree at all */
  115934. if(info->coupling_steps){
  115935. _vp_couple(k,
  115936. &ci->psy_g_param,
  115937. psy_look,
  115938. info,
  115939. vb->pcm,
  115940. mag_memo,
  115941. mag_sort,
  115942. ilogmaskch,
  115943. nonzero,
  115944. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115945. }
  115946. /* classify and encode by submap */
  115947. for(i=0;i<info->submaps;i++){
  115948. int ch_in_bundle=0;
  115949. long **classifications;
  115950. int resnum=info->residuesubmap[i];
  115951. for(j=0;j<vi->channels;j++){
  115952. if(info->chmuxlist[j]==i){
  115953. zerobundle[ch_in_bundle]=0;
  115954. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115955. res_bundle[ch_in_bundle]=vb->pcm[j];
  115956. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115957. }
  115958. }
  115959. classifications=_residue_P[ci->residue_type[resnum]]->
  115960. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115961. _residue_P[ci->residue_type[resnum]]->
  115962. forward(opb,vb,b->residue[resnum],
  115963. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115964. }
  115965. /* ok, done encoding. Next protopacket. */
  115966. }
  115967. }
  115968. #if 0
  115969. seq++;
  115970. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115971. #endif
  115972. return(0);
  115973. }
  115974. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115975. vorbis_dsp_state *vd=vb->vd;
  115976. vorbis_info *vi=vd->vi;
  115977. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115978. private_state *b=(private_state*)vd->backend_state;
  115979. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115980. int i,j;
  115981. long n=vb->pcmend=ci->blocksizes[vb->W];
  115982. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115983. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115984. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115985. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115986. /* recover the spectral envelope; store it in the PCM vector for now */
  115987. for(i=0;i<vi->channels;i++){
  115988. int submap=info->chmuxlist[i];
  115989. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115990. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115991. if(floormemo[i])
  115992. nonzero[i]=1;
  115993. else
  115994. nonzero[i]=0;
  115995. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115996. }
  115997. /* channel coupling can 'dirty' the nonzero listing */
  115998. for(i=0;i<info->coupling_steps;i++){
  115999. if(nonzero[info->coupling_mag[i]] ||
  116000. nonzero[info->coupling_ang[i]]){
  116001. nonzero[info->coupling_mag[i]]=1;
  116002. nonzero[info->coupling_ang[i]]=1;
  116003. }
  116004. }
  116005. /* recover the residue into our working vectors */
  116006. for(i=0;i<info->submaps;i++){
  116007. int ch_in_bundle=0;
  116008. for(j=0;j<vi->channels;j++){
  116009. if(info->chmuxlist[j]==i){
  116010. if(nonzero[j])
  116011. zerobundle[ch_in_bundle]=1;
  116012. else
  116013. zerobundle[ch_in_bundle]=0;
  116014. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  116015. }
  116016. }
  116017. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  116018. inverse(vb,b->residue[info->residuesubmap[i]],
  116019. pcmbundle,zerobundle,ch_in_bundle);
  116020. }
  116021. /* channel coupling */
  116022. for(i=info->coupling_steps-1;i>=0;i--){
  116023. float *pcmM=vb->pcm[info->coupling_mag[i]];
  116024. float *pcmA=vb->pcm[info->coupling_ang[i]];
  116025. for(j=0;j<n/2;j++){
  116026. float mag=pcmM[j];
  116027. float ang=pcmA[j];
  116028. if(mag>0)
  116029. if(ang>0){
  116030. pcmM[j]=mag;
  116031. pcmA[j]=mag-ang;
  116032. }else{
  116033. pcmA[j]=mag;
  116034. pcmM[j]=mag+ang;
  116035. }
  116036. else
  116037. if(ang>0){
  116038. pcmM[j]=mag;
  116039. pcmA[j]=mag+ang;
  116040. }else{
  116041. pcmA[j]=mag;
  116042. pcmM[j]=mag-ang;
  116043. }
  116044. }
  116045. }
  116046. /* compute and apply spectral envelope */
  116047. for(i=0;i<vi->channels;i++){
  116048. float *pcm=vb->pcm[i];
  116049. int submap=info->chmuxlist[i];
  116050. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116051. inverse2(vb,b->flr[info->floorsubmap[submap]],
  116052. floormemo[i],pcm);
  116053. }
  116054. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  116055. /* only MDCT right now.... */
  116056. for(i=0;i<vi->channels;i++){
  116057. float *pcm=vb->pcm[i];
  116058. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  116059. }
  116060. /* all done! */
  116061. return(0);
  116062. }
  116063. /* export hooks */
  116064. vorbis_func_mapping mapping0_exportbundle={
  116065. &mapping0_pack,
  116066. &mapping0_unpack,
  116067. &mapping0_free_info,
  116068. &mapping0_forward,
  116069. &mapping0_inverse
  116070. };
  116071. #endif
  116072. /*** End of inlined file: mapping0.c ***/
  116073. /*** Start of inlined file: mdct.c ***/
  116074. /* this can also be run as an integer transform by uncommenting a
  116075. define in mdct.h; the integerization is a first pass and although
  116076. it's likely stable for Vorbis, the dynamic range is constrained and
  116077. roundoff isn't done (so it's noisy). Consider it functional, but
  116078. only a starting point. There's no point on a machine with an FPU */
  116079. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116080. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116081. // tasks..
  116082. #if JUCE_MSVC
  116083. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116084. #endif
  116085. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116086. #if JUCE_USE_OGGVORBIS
  116087. #include <stdio.h>
  116088. #include <stdlib.h>
  116089. #include <string.h>
  116090. #include <math.h>
  116091. /* build lookups for trig functions; also pre-figure scaling and
  116092. some window function algebra. */
  116093. void mdct_init(mdct_lookup *lookup,int n){
  116094. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116095. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116096. int i;
  116097. int n2=n>>1;
  116098. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116099. lookup->n=n;
  116100. lookup->trig=T;
  116101. lookup->bitrev=bitrev;
  116102. /* trig lookups... */
  116103. for(i=0;i<n/4;i++){
  116104. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116105. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116106. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116107. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116108. }
  116109. for(i=0;i<n/8;i++){
  116110. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116111. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116112. }
  116113. /* bitreverse lookup... */
  116114. {
  116115. int mask=(1<<(log2n-1))-1,i,j;
  116116. int msb=1<<(log2n-2);
  116117. for(i=0;i<n/8;i++){
  116118. int acc=0;
  116119. for(j=0;msb>>j;j++)
  116120. if((msb>>j)&i)acc|=1<<j;
  116121. bitrev[i*2]=((~acc)&mask)-1;
  116122. bitrev[i*2+1]=acc;
  116123. }
  116124. }
  116125. lookup->scale=FLOAT_CONV(4.f/n);
  116126. }
  116127. /* 8 point butterfly (in place, 4 register) */
  116128. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116129. REG_TYPE r0 = x[6] + x[2];
  116130. REG_TYPE r1 = x[6] - x[2];
  116131. REG_TYPE r2 = x[4] + x[0];
  116132. REG_TYPE r3 = x[4] - x[0];
  116133. x[6] = r0 + r2;
  116134. x[4] = r0 - r2;
  116135. r0 = x[5] - x[1];
  116136. r2 = x[7] - x[3];
  116137. x[0] = r1 + r0;
  116138. x[2] = r1 - r0;
  116139. r0 = x[5] + x[1];
  116140. r1 = x[7] + x[3];
  116141. x[3] = r2 + r3;
  116142. x[1] = r2 - r3;
  116143. x[7] = r1 + r0;
  116144. x[5] = r1 - r0;
  116145. }
  116146. /* 16 point butterfly (in place, 4 register) */
  116147. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116148. REG_TYPE r0 = x[1] - x[9];
  116149. REG_TYPE r1 = x[0] - x[8];
  116150. x[8] += x[0];
  116151. x[9] += x[1];
  116152. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116153. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116154. r0 = x[3] - x[11];
  116155. r1 = x[10] - x[2];
  116156. x[10] += x[2];
  116157. x[11] += x[3];
  116158. x[2] = r0;
  116159. x[3] = r1;
  116160. r0 = x[12] - x[4];
  116161. r1 = x[13] - x[5];
  116162. x[12] += x[4];
  116163. x[13] += x[5];
  116164. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116165. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116166. r0 = x[14] - x[6];
  116167. r1 = x[15] - x[7];
  116168. x[14] += x[6];
  116169. x[15] += x[7];
  116170. x[6] = r0;
  116171. x[7] = r1;
  116172. mdct_butterfly_8(x);
  116173. mdct_butterfly_8(x+8);
  116174. }
  116175. /* 32 point butterfly (in place, 4 register) */
  116176. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116177. REG_TYPE r0 = x[30] - x[14];
  116178. REG_TYPE r1 = x[31] - x[15];
  116179. x[30] += x[14];
  116180. x[31] += x[15];
  116181. x[14] = r0;
  116182. x[15] = r1;
  116183. r0 = x[28] - x[12];
  116184. r1 = x[29] - x[13];
  116185. x[28] += x[12];
  116186. x[29] += x[13];
  116187. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116188. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116189. r0 = x[26] - x[10];
  116190. r1 = x[27] - x[11];
  116191. x[26] += x[10];
  116192. x[27] += x[11];
  116193. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116194. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116195. r0 = x[24] - x[8];
  116196. r1 = x[25] - x[9];
  116197. x[24] += x[8];
  116198. x[25] += x[9];
  116199. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116200. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116201. r0 = x[22] - x[6];
  116202. r1 = x[7] - x[23];
  116203. x[22] += x[6];
  116204. x[23] += x[7];
  116205. x[6] = r1;
  116206. x[7] = r0;
  116207. r0 = x[4] - x[20];
  116208. r1 = x[5] - x[21];
  116209. x[20] += x[4];
  116210. x[21] += x[5];
  116211. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116212. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116213. r0 = x[2] - x[18];
  116214. r1 = x[3] - x[19];
  116215. x[18] += x[2];
  116216. x[19] += x[3];
  116217. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116218. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116219. r0 = x[0] - x[16];
  116220. r1 = x[1] - x[17];
  116221. x[16] += x[0];
  116222. x[17] += x[1];
  116223. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116224. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116225. mdct_butterfly_16(x);
  116226. mdct_butterfly_16(x+16);
  116227. }
  116228. /* N point first stage butterfly (in place, 2 register) */
  116229. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116230. DATA_TYPE *x,
  116231. int points){
  116232. DATA_TYPE *x1 = x + points - 8;
  116233. DATA_TYPE *x2 = x + (points>>1) - 8;
  116234. REG_TYPE r0;
  116235. REG_TYPE r1;
  116236. do{
  116237. r0 = x1[6] - x2[6];
  116238. r1 = x1[7] - x2[7];
  116239. x1[6] += x2[6];
  116240. x1[7] += x2[7];
  116241. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116242. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116243. r0 = x1[4] - x2[4];
  116244. r1 = x1[5] - x2[5];
  116245. x1[4] += x2[4];
  116246. x1[5] += x2[5];
  116247. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116248. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116249. r0 = x1[2] - x2[2];
  116250. r1 = x1[3] - x2[3];
  116251. x1[2] += x2[2];
  116252. x1[3] += x2[3];
  116253. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116254. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116255. r0 = x1[0] - x2[0];
  116256. r1 = x1[1] - x2[1];
  116257. x1[0] += x2[0];
  116258. x1[1] += x2[1];
  116259. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116260. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116261. x1-=8;
  116262. x2-=8;
  116263. T+=16;
  116264. }while(x2>=x);
  116265. }
  116266. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116267. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116268. DATA_TYPE *x,
  116269. int points,
  116270. int trigint){
  116271. DATA_TYPE *x1 = x + points - 8;
  116272. DATA_TYPE *x2 = x + (points>>1) - 8;
  116273. REG_TYPE r0;
  116274. REG_TYPE r1;
  116275. do{
  116276. r0 = x1[6] - x2[6];
  116277. r1 = x1[7] - x2[7];
  116278. x1[6] += x2[6];
  116279. x1[7] += x2[7];
  116280. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116281. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116282. T+=trigint;
  116283. r0 = x1[4] - x2[4];
  116284. r1 = x1[5] - x2[5];
  116285. x1[4] += x2[4];
  116286. x1[5] += x2[5];
  116287. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116288. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116289. T+=trigint;
  116290. r0 = x1[2] - x2[2];
  116291. r1 = x1[3] - x2[3];
  116292. x1[2] += x2[2];
  116293. x1[3] += x2[3];
  116294. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116295. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116296. T+=trigint;
  116297. r0 = x1[0] - x2[0];
  116298. r1 = x1[1] - x2[1];
  116299. x1[0] += x2[0];
  116300. x1[1] += x2[1];
  116301. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116302. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116303. T+=trigint;
  116304. x1-=8;
  116305. x2-=8;
  116306. }while(x2>=x);
  116307. }
  116308. STIN void mdct_butterflies(mdct_lookup *init,
  116309. DATA_TYPE *x,
  116310. int points){
  116311. DATA_TYPE *T=init->trig;
  116312. int stages=init->log2n-5;
  116313. int i,j;
  116314. if(--stages>0){
  116315. mdct_butterfly_first(T,x,points);
  116316. }
  116317. for(i=1;--stages>0;i++){
  116318. for(j=0;j<(1<<i);j++)
  116319. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116320. }
  116321. for(j=0;j<points;j+=32)
  116322. mdct_butterfly_32(x+j);
  116323. }
  116324. void mdct_clear(mdct_lookup *l){
  116325. if(l){
  116326. if(l->trig)_ogg_free(l->trig);
  116327. if(l->bitrev)_ogg_free(l->bitrev);
  116328. memset(l,0,sizeof(*l));
  116329. }
  116330. }
  116331. STIN void mdct_bitreverse(mdct_lookup *init,
  116332. DATA_TYPE *x){
  116333. int n = init->n;
  116334. int *bit = init->bitrev;
  116335. DATA_TYPE *w0 = x;
  116336. DATA_TYPE *w1 = x = w0+(n>>1);
  116337. DATA_TYPE *T = init->trig+n;
  116338. do{
  116339. DATA_TYPE *x0 = x+bit[0];
  116340. DATA_TYPE *x1 = x+bit[1];
  116341. REG_TYPE r0 = x0[1] - x1[1];
  116342. REG_TYPE r1 = x0[0] + x1[0];
  116343. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116344. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116345. w1 -= 4;
  116346. r0 = HALVE(x0[1] + x1[1]);
  116347. r1 = HALVE(x0[0] - x1[0]);
  116348. w0[0] = r0 + r2;
  116349. w1[2] = r0 - r2;
  116350. w0[1] = r1 + r3;
  116351. w1[3] = r3 - r1;
  116352. x0 = x+bit[2];
  116353. x1 = x+bit[3];
  116354. r0 = x0[1] - x1[1];
  116355. r1 = x0[0] + x1[0];
  116356. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116357. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116358. r0 = HALVE(x0[1] + x1[1]);
  116359. r1 = HALVE(x0[0] - x1[0]);
  116360. w0[2] = r0 + r2;
  116361. w1[0] = r0 - r2;
  116362. w0[3] = r1 + r3;
  116363. w1[1] = r3 - r1;
  116364. T += 4;
  116365. bit += 4;
  116366. w0 += 4;
  116367. }while(w0<w1);
  116368. }
  116369. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116370. int n=init->n;
  116371. int n2=n>>1;
  116372. int n4=n>>2;
  116373. /* rotate */
  116374. DATA_TYPE *iX = in+n2-7;
  116375. DATA_TYPE *oX = out+n2+n4;
  116376. DATA_TYPE *T = init->trig+n4;
  116377. do{
  116378. oX -= 4;
  116379. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116380. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116381. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116382. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116383. iX -= 8;
  116384. T += 4;
  116385. }while(iX>=in);
  116386. iX = in+n2-8;
  116387. oX = out+n2+n4;
  116388. T = init->trig+n4;
  116389. do{
  116390. T -= 4;
  116391. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116392. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116393. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116394. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116395. iX -= 8;
  116396. oX += 4;
  116397. }while(iX>=in);
  116398. mdct_butterflies(init,out+n2,n2);
  116399. mdct_bitreverse(init,out);
  116400. /* roatate + window */
  116401. {
  116402. DATA_TYPE *oX1=out+n2+n4;
  116403. DATA_TYPE *oX2=out+n2+n4;
  116404. DATA_TYPE *iX =out;
  116405. T =init->trig+n2;
  116406. do{
  116407. oX1-=4;
  116408. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116409. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116410. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116411. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116412. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116413. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116414. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116415. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116416. oX2+=4;
  116417. iX += 8;
  116418. T += 8;
  116419. }while(iX<oX1);
  116420. iX=out+n2+n4;
  116421. oX1=out+n4;
  116422. oX2=oX1;
  116423. do{
  116424. oX1-=4;
  116425. iX-=4;
  116426. oX2[0] = -(oX1[3] = iX[3]);
  116427. oX2[1] = -(oX1[2] = iX[2]);
  116428. oX2[2] = -(oX1[1] = iX[1]);
  116429. oX2[3] = -(oX1[0] = iX[0]);
  116430. oX2+=4;
  116431. }while(oX2<iX);
  116432. iX=out+n2+n4;
  116433. oX1=out+n2+n4;
  116434. oX2=out+n2;
  116435. do{
  116436. oX1-=4;
  116437. oX1[0]= iX[3];
  116438. oX1[1]= iX[2];
  116439. oX1[2]= iX[1];
  116440. oX1[3]= iX[0];
  116441. iX+=4;
  116442. }while(oX1>oX2);
  116443. }
  116444. }
  116445. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116446. int n=init->n;
  116447. int n2=n>>1;
  116448. int n4=n>>2;
  116449. int n8=n>>3;
  116450. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116451. DATA_TYPE *w2=w+n2;
  116452. /* rotate */
  116453. /* window + rotate + step 1 */
  116454. REG_TYPE r0;
  116455. REG_TYPE r1;
  116456. DATA_TYPE *x0=in+n2+n4;
  116457. DATA_TYPE *x1=x0+1;
  116458. DATA_TYPE *T=init->trig+n2;
  116459. int i=0;
  116460. for(i=0;i<n8;i+=2){
  116461. x0 -=4;
  116462. T-=2;
  116463. r0= x0[2] + x1[0];
  116464. r1= x0[0] + x1[2];
  116465. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116466. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116467. x1 +=4;
  116468. }
  116469. x1=in+1;
  116470. for(;i<n2-n8;i+=2){
  116471. T-=2;
  116472. x0 -=4;
  116473. r0= x0[2] - x1[0];
  116474. r1= x0[0] - x1[2];
  116475. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116476. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116477. x1 +=4;
  116478. }
  116479. x0=in+n;
  116480. for(;i<n2;i+=2){
  116481. T-=2;
  116482. x0 -=4;
  116483. r0= -x0[2] - x1[0];
  116484. r1= -x0[0] - x1[2];
  116485. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116486. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116487. x1 +=4;
  116488. }
  116489. mdct_butterflies(init,w+n2,n2);
  116490. mdct_bitreverse(init,w);
  116491. /* roatate + window */
  116492. T=init->trig+n2;
  116493. x0=out+n2;
  116494. for(i=0;i<n4;i++){
  116495. x0--;
  116496. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116497. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116498. w+=2;
  116499. T+=2;
  116500. }
  116501. }
  116502. #endif
  116503. /*** End of inlined file: mdct.c ***/
  116504. /*** Start of inlined file: psy.c ***/
  116505. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116506. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116507. // tasks..
  116508. #if JUCE_MSVC
  116509. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116510. #endif
  116511. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116512. #if JUCE_USE_OGGVORBIS
  116513. #include <stdlib.h>
  116514. #include <math.h>
  116515. #include <string.h>
  116516. /*** Start of inlined file: masking.h ***/
  116517. #ifndef _V_MASKING_H_
  116518. #define _V_MASKING_H_
  116519. /* more detailed ATH; the bass if flat to save stressing the floor
  116520. overly for only a bin or two of savings. */
  116521. #define MAX_ATH 88
  116522. static float ATH[]={
  116523. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116524. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116525. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116526. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116527. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116528. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116529. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116530. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116531. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116532. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116533. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116534. };
  116535. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116536. replaced by an empirically collected data set. The previously
  116537. published values were, far too often, simply on crack. */
  116538. #define EHMER_OFFSET 16
  116539. #define EHMER_MAX 56
  116540. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116541. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116542. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116543. for collection of these curves) */
  116544. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116545. /* 62.5 Hz */
  116546. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116547. -60, -60, -60, -60, -62, -62, -65, -73,
  116548. -69, -68, -68, -67, -70, -70, -72, -74,
  116549. -75, -79, -79, -80, -83, -88, -93, -100,
  116550. -110, -999, -999, -999, -999, -999, -999, -999,
  116551. -999, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -999, -999, -999, -999, -999},
  116553. { -48, -48, -48, -48, -48, -48, -48, -48,
  116554. -48, -48, -48, -48, -48, -53, -61, -66,
  116555. -66, -68, -67, -70, -76, -76, -72, -73,
  116556. -75, -76, -78, -79, -83, -88, -93, -100,
  116557. -110, -999, -999, -999, -999, -999, -999, -999,
  116558. -999, -999, -999, -999, -999, -999, -999, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999},
  116560. { -37, -37, -37, -37, -37, -37, -37, -37,
  116561. -38, -40, -42, -46, -48, -53, -55, -62,
  116562. -65, -58, -56, -56, -61, -60, -65, -67,
  116563. -69, -71, -77, -77, -78, -80, -82, -84,
  116564. -88, -93, -98, -106, -112, -999, -999, -999,
  116565. -999, -999, -999, -999, -999, -999, -999, -999,
  116566. -999, -999, -999, -999, -999, -999, -999, -999},
  116567. { -25, -25, -25, -25, -25, -25, -25, -25,
  116568. -25, -26, -27, -29, -32, -38, -48, -52,
  116569. -52, -50, -48, -48, -51, -52, -54, -60,
  116570. -67, -67, -66, -68, -69, -73, -73, -76,
  116571. -80, -81, -81, -85, -85, -86, -88, -93,
  116572. -100, -110, -999, -999, -999, -999, -999, -999,
  116573. -999, -999, -999, -999, -999, -999, -999, -999},
  116574. { -16, -16, -16, -16, -16, -16, -16, -16,
  116575. -17, -19, -20, -22, -26, -28, -31, -40,
  116576. -47, -39, -39, -40, -42, -43, -47, -51,
  116577. -57, -52, -55, -55, -60, -58, -62, -63,
  116578. -70, -67, -69, -72, -73, -77, -80, -82,
  116579. -83, -87, -90, -94, -98, -104, -115, -999,
  116580. -999, -999, -999, -999, -999, -999, -999, -999},
  116581. { -8, -8, -8, -8, -8, -8, -8, -8,
  116582. -8, -8, -10, -11, -15, -19, -25, -30,
  116583. -34, -31, -30, -31, -29, -32, -35, -42,
  116584. -48, -42, -44, -46, -50, -50, -51, -52,
  116585. -59, -54, -55, -55, -58, -62, -63, -66,
  116586. -72, -73, -76, -75, -78, -80, -80, -81,
  116587. -84, -88, -90, -94, -98, -101, -106, -110}},
  116588. /* 88Hz */
  116589. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116590. -66, -66, -66, -66, -66, -67, -67, -67,
  116591. -76, -72, -71, -74, -76, -76, -75, -78,
  116592. -79, -79, -81, -83, -86, -89, -93, -97,
  116593. -100, -105, -110, -999, -999, -999, -999, -999,
  116594. -999, -999, -999, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -999, -999, -999, -999},
  116596. { -47, -47, -47, -47, -47, -47, -47, -47,
  116597. -47, -47, -47, -48, -51, -55, -59, -66,
  116598. -66, -66, -67, -66, -68, -69, -70, -74,
  116599. -79, -77, -77, -78, -80, -81, -82, -84,
  116600. -86, -88, -91, -95, -100, -108, -116, -999,
  116601. -999, -999, -999, -999, -999, -999, -999, -999,
  116602. -999, -999, -999, -999, -999, -999, -999, -999},
  116603. { -36, -36, -36, -36, -36, -36, -36, -36,
  116604. -36, -37, -37, -41, -44, -48, -51, -58,
  116605. -62, -60, -57, -59, -59, -60, -63, -65,
  116606. -72, -71, -70, -72, -74, -77, -76, -78,
  116607. -81, -81, -80, -83, -86, -91, -96, -100,
  116608. -105, -110, -999, -999, -999, -999, -999, -999,
  116609. -999, -999, -999, -999, -999, -999, -999, -999},
  116610. { -28, -28, -28, -28, -28, -28, -28, -28,
  116611. -28, -30, -32, -32, -33, -35, -41, -49,
  116612. -50, -49, -47, -48, -48, -52, -51, -57,
  116613. -65, -61, -59, -61, -64, -69, -70, -74,
  116614. -77, -77, -78, -81, -84, -85, -87, -90,
  116615. -92, -96, -100, -107, -112, -999, -999, -999,
  116616. -999, -999, -999, -999, -999, -999, -999, -999},
  116617. { -19, -19, -19, -19, -19, -19, -19, -19,
  116618. -20, -21, -23, -27, -30, -35, -36, -41,
  116619. -46, -44, -42, -40, -41, -41, -43, -48,
  116620. -55, -53, -52, -53, -56, -59, -58, -60,
  116621. -67, -66, -69, -71, -72, -75, -79, -81,
  116622. -84, -87, -90, -93, -97, -101, -107, -114,
  116623. -999, -999, -999, -999, -999, -999, -999, -999},
  116624. { -9, -9, -9, -9, -9, -9, -9, -9,
  116625. -11, -12, -12, -15, -16, -20, -23, -30,
  116626. -37, -34, -33, -34, -31, -32, -32, -38,
  116627. -47, -44, -41, -40, -47, -49, -46, -46,
  116628. -58, -50, -50, -54, -58, -62, -64, -67,
  116629. -67, -70, -72, -76, -79, -83, -87, -91,
  116630. -96, -100, -104, -110, -999, -999, -999, -999}},
  116631. /* 125 Hz */
  116632. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116633. -62, -62, -63, -64, -66, -67, -66, -68,
  116634. -75, -72, -76, -75, -76, -78, -79, -82,
  116635. -84, -85, -90, -94, -101, -110, -999, -999,
  116636. -999, -999, -999, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -999, -999, -999, -999, -999, -999},
  116639. { -59, -59, -59, -59, -59, -59, -59, -59,
  116640. -59, -59, -59, -60, -60, -61, -63, -66,
  116641. -71, -68, -70, -70, -71, -72, -72, -75,
  116642. -81, -78, -79, -82, -83, -86, -90, -97,
  116643. -103, -113, -999, -999, -999, -999, -999, -999,
  116644. -999, -999, -999, -999, -999, -999, -999, -999,
  116645. -999, -999, -999, -999, -999, -999, -999, -999},
  116646. { -53, -53, -53, -53, -53, -53, -53, -53,
  116647. -53, -54, -55, -57, -56, -57, -55, -61,
  116648. -65, -60, -60, -62, -63, -63, -66, -68,
  116649. -74, -73, -75, -75, -78, -80, -80, -82,
  116650. -85, -90, -96, -101, -108, -999, -999, -999,
  116651. -999, -999, -999, -999, -999, -999, -999, -999,
  116652. -999, -999, -999, -999, -999, -999, -999, -999},
  116653. { -46, -46, -46, -46, -46, -46, -46, -46,
  116654. -46, -46, -47, -47, -47, -47, -48, -51,
  116655. -57, -51, -49, -50, -51, -53, -54, -59,
  116656. -66, -60, -62, -67, -67, -70, -72, -75,
  116657. -76, -78, -81, -85, -88, -94, -97, -104,
  116658. -112, -999, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -999, -999, -999, -999, -999},
  116660. { -36, -36, -36, -36, -36, -36, -36, -36,
  116661. -39, -41, -42, -42, -39, -38, -41, -43,
  116662. -52, -44, -40, -39, -37, -37, -40, -47,
  116663. -54, -50, -48, -50, -55, -61, -59, -62,
  116664. -66, -66, -66, -69, -69, -73, -74, -74,
  116665. -75, -77, -79, -82, -87, -91, -95, -100,
  116666. -108, -115, -999, -999, -999, -999, -999, -999},
  116667. { -28, -26, -24, -22, -20, -20, -23, -29,
  116668. -30, -31, -28, -27, -28, -28, -28, -35,
  116669. -40, -33, -32, -29, -30, -30, -30, -37,
  116670. -45, -41, -37, -38, -45, -47, -47, -48,
  116671. -53, -49, -48, -50, -49, -49, -51, -52,
  116672. -58, -56, -57, -56, -60, -61, -62, -70,
  116673. -72, -74, -78, -83, -88, -93, -100, -106}},
  116674. /* 177 Hz */
  116675. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116676. -999, -110, -105, -100, -95, -91, -87, -83,
  116677. -80, -78, -76, -78, -78, -81, -83, -85,
  116678. -86, -85, -86, -87, -90, -97, -107, -999,
  116679. -999, -999, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999},
  116682. {-999, -999, -999, -110, -105, -100, -95, -90,
  116683. -85, -81, -77, -73, -70, -67, -67, -68,
  116684. -75, -73, -70, -69, -70, -72, -75, -79,
  116685. -84, -83, -84, -86, -88, -89, -89, -93,
  116686. -98, -105, -112, -999, -999, -999, -999, -999,
  116687. -999, -999, -999, -999, -999, -999, -999, -999,
  116688. -999, -999, -999, -999, -999, -999, -999, -999},
  116689. {-105, -100, -95, -90, -85, -80, -76, -71,
  116690. -68, -68, -65, -63, -63, -62, -62, -64,
  116691. -65, -64, -61, -62, -63, -64, -66, -68,
  116692. -73, -73, -74, -75, -76, -81, -83, -85,
  116693. -88, -89, -92, -95, -100, -108, -999, -999,
  116694. -999, -999, -999, -999, -999, -999, -999, -999,
  116695. -999, -999, -999, -999, -999, -999, -999, -999},
  116696. { -80, -75, -71, -68, -65, -63, -62, -61,
  116697. -61, -61, -61, -59, -56, -57, -53, -50,
  116698. -58, -52, -50, -50, -52, -53, -54, -58,
  116699. -67, -63, -67, -68, -72, -75, -78, -80,
  116700. -81, -81, -82, -85, -89, -90, -93, -97,
  116701. -101, -107, -114, -999, -999, -999, -999, -999,
  116702. -999, -999, -999, -999, -999, -999, -999, -999},
  116703. { -65, -61, -59, -57, -56, -55, -55, -56,
  116704. -56, -57, -55, -53, -52, -47, -44, -44,
  116705. -50, -44, -41, -39, -39, -42, -40, -46,
  116706. -51, -49, -50, -53, -54, -63, -60, -61,
  116707. -62, -66, -66, -66, -70, -73, -74, -75,
  116708. -76, -75, -79, -85, -89, -91, -96, -102,
  116709. -110, -999, -999, -999, -999, -999, -999, -999},
  116710. { -52, -50, -49, -49, -48, -48, -48, -49,
  116711. -50, -50, -49, -46, -43, -39, -35, -33,
  116712. -38, -36, -32, -29, -32, -32, -32, -35,
  116713. -44, -39, -38, -38, -46, -50, -45, -46,
  116714. -53, -50, -50, -50, -54, -54, -53, -53,
  116715. -56, -57, -59, -66, -70, -72, -74, -79,
  116716. -83, -85, -90, -97, -114, -999, -999, -999}},
  116717. /* 250 Hz */
  116718. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116719. -100, -95, -90, -86, -80, -75, -75, -79,
  116720. -80, -79, -80, -81, -82, -88, -95, -103,
  116721. -110, -999, -999, -999, -999, -999, -999, -999,
  116722. -999, -999, -999, -999, -999, -999, -999, -999,
  116723. -999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999},
  116725. {-999, -999, -999, -999, -108, -103, -98, -93,
  116726. -88, -83, -79, -78, -75, -71, -67, -68,
  116727. -73, -73, -72, -73, -75, -77, -80, -82,
  116728. -88, -93, -100, -107, -114, -999, -999, -999,
  116729. -999, -999, -999, -999, -999, -999, -999, -999,
  116730. -999, -999, -999, -999, -999, -999, -999, -999,
  116731. -999, -999, -999, -999, -999, -999, -999, -999},
  116732. {-999, -999, -999, -110, -105, -101, -96, -90,
  116733. -86, -81, -77, -73, -69, -66, -61, -62,
  116734. -66, -64, -62, -65, -66, -70, -72, -76,
  116735. -81, -80, -84, -90, -95, -102, -110, -999,
  116736. -999, -999, -999, -999, -999, -999, -999, -999,
  116737. -999, -999, -999, -999, -999, -999, -999, -999,
  116738. -999, -999, -999, -999, -999, -999, -999, -999},
  116739. {-999, -999, -999, -107, -103, -97, -92, -88,
  116740. -83, -79, -74, -70, -66, -59, -53, -58,
  116741. -62, -55, -54, -54, -54, -58, -61, -62,
  116742. -72, -70, -72, -75, -78, -80, -81, -80,
  116743. -83, -83, -88, -93, -100, -107, -115, -999,
  116744. -999, -999, -999, -999, -999, -999, -999, -999,
  116745. -999, -999, -999, -999, -999, -999, -999, -999},
  116746. {-999, -999, -999, -105, -100, -95, -90, -85,
  116747. -80, -75, -70, -66, -62, -56, -48, -44,
  116748. -48, -46, -46, -43, -46, -48, -48, -51,
  116749. -58, -58, -59, -60, -62, -62, -61, -61,
  116750. -65, -64, -65, -68, -70, -74, -75, -78,
  116751. -81, -86, -95, -110, -999, -999, -999, -999,
  116752. -999, -999, -999, -999, -999, -999, -999, -999},
  116753. {-999, -999, -105, -100, -95, -90, -85, -80,
  116754. -75, -70, -65, -61, -55, -49, -39, -33,
  116755. -40, -35, -32, -38, -40, -33, -35, -37,
  116756. -46, -41, -45, -44, -46, -42, -45, -46,
  116757. -52, -50, -50, -50, -54, -54, -55, -57,
  116758. -62, -64, -66, -68, -70, -76, -81, -90,
  116759. -100, -110, -999, -999, -999, -999, -999, -999}},
  116760. /* 354 hz */
  116761. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116762. -105, -98, -90, -85, -82, -83, -80, -78,
  116763. -84, -79, -80, -83, -87, -89, -91, -93,
  116764. -99, -106, -117, -999, -999, -999, -999, -999,
  116765. -999, -999, -999, -999, -999, -999, -999, -999,
  116766. -999, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999},
  116768. {-999, -999, -999, -999, -999, -999, -999, -999,
  116769. -105, -98, -90, -85, -80, -75, -70, -68,
  116770. -74, -72, -74, -77, -80, -82, -85, -87,
  116771. -92, -89, -91, -95, -100, -106, -112, -999,
  116772. -999, -999, -999, -999, -999, -999, -999, -999,
  116773. -999, -999, -999, -999, -999, -999, -999, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999},
  116775. {-999, -999, -999, -999, -999, -999, -999, -999,
  116776. -105, -98, -90, -83, -75, -71, -63, -64,
  116777. -67, -62, -64, -67, -70, -73, -77, -81,
  116778. -84, -83, -85, -89, -90, -93, -98, -104,
  116779. -109, -114, -999, -999, -999, -999, -999, -999,
  116780. -999, -999, -999, -999, -999, -999, -999, -999,
  116781. -999, -999, -999, -999, -999, -999, -999, -999},
  116782. {-999, -999, -999, -999, -999, -999, -999, -999,
  116783. -103, -96, -88, -81, -75, -68, -58, -54,
  116784. -56, -54, -56, -56, -58, -60, -63, -66,
  116785. -74, -69, -72, -72, -75, -74, -77, -81,
  116786. -81, -82, -84, -87, -93, -96, -99, -104,
  116787. -110, -999, -999, -999, -999, -999, -999, -999,
  116788. -999, -999, -999, -999, -999, -999, -999, -999},
  116789. {-999, -999, -999, -999, -999, -108, -102, -96,
  116790. -91, -85, -80, -74, -68, -60, -51, -46,
  116791. -48, -46, -43, -45, -47, -47, -49, -48,
  116792. -56, -53, -55, -58, -57, -63, -58, -60,
  116793. -66, -64, -67, -70, -70, -74, -77, -84,
  116794. -86, -89, -91, -93, -94, -101, -109, -118,
  116795. -999, -999, -999, -999, -999, -999, -999, -999},
  116796. {-999, -999, -999, -108, -103, -98, -93, -88,
  116797. -83, -78, -73, -68, -60, -53, -44, -35,
  116798. -38, -38, -34, -34, -36, -40, -41, -44,
  116799. -51, -45, -46, -47, -46, -54, -50, -49,
  116800. -50, -50, -50, -51, -54, -57, -58, -60,
  116801. -66, -66, -66, -64, -65, -68, -77, -82,
  116802. -87, -95, -110, -999, -999, -999, -999, -999}},
  116803. /* 500 Hz */
  116804. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116805. -107, -102, -97, -92, -87, -83, -78, -75,
  116806. -82, -79, -83, -85, -89, -92, -95, -98,
  116807. -101, -105, -109, -113, -999, -999, -999, -999,
  116808. -999, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -999, -999, -999, -999, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999},
  116811. {-999, -999, -999, -999, -999, -999, -999, -106,
  116812. -100, -95, -90, -86, -81, -78, -74, -69,
  116813. -74, -74, -76, -79, -83, -84, -86, -89,
  116814. -92, -97, -93, -100, -103, -107, -110, -999,
  116815. -999, -999, -999, -999, -999, -999, -999, -999,
  116816. -999, -999, -999, -999, -999, -999, -999, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999},
  116818. {-999, -999, -999, -999, -999, -999, -106, -100,
  116819. -95, -90, -87, -83, -80, -75, -69, -60,
  116820. -66, -66, -68, -70, -74, -78, -79, -81,
  116821. -81, -83, -84, -87, -93, -96, -99, -103,
  116822. -107, -110, -999, -999, -999, -999, -999, -999,
  116823. -999, -999, -999, -999, -999, -999, -999, -999,
  116824. -999, -999, -999, -999, -999, -999, -999, -999},
  116825. {-999, -999, -999, -999, -999, -108, -103, -98,
  116826. -93, -89, -85, -82, -78, -71, -62, -55,
  116827. -58, -58, -54, -54, -55, -59, -61, -62,
  116828. -70, -66, -66, -67, -70, -72, -75, -78,
  116829. -84, -84, -84, -88, -91, -90, -95, -98,
  116830. -102, -103, -106, -110, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999},
  116832. {-999, -999, -999, -999, -108, -103, -98, -94,
  116833. -90, -87, -82, -79, -73, -67, -58, -47,
  116834. -50, -45, -41, -45, -48, -44, -44, -49,
  116835. -54, -51, -48, -47, -49, -50, -51, -57,
  116836. -58, -60, -63, -69, -70, -69, -71, -74,
  116837. -78, -82, -90, -95, -101, -105, -110, -999,
  116838. -999, -999, -999, -999, -999, -999, -999, -999},
  116839. {-999, -999, -999, -105, -101, -97, -93, -90,
  116840. -85, -80, -77, -72, -65, -56, -48, -37,
  116841. -40, -36, -34, -40, -50, -47, -38, -41,
  116842. -47, -38, -35, -39, -38, -43, -40, -45,
  116843. -50, -45, -44, -47, -50, -55, -48, -48,
  116844. -52, -66, -70, -76, -82, -90, -97, -105,
  116845. -110, -999, -999, -999, -999, -999, -999, -999}},
  116846. /* 707 Hz */
  116847. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -108, -103, -98, -93, -86, -79, -76,
  116849. -83, -81, -85, -87, -89, -93, -98, -102,
  116850. -107, -112, -999, -999, -999, -999, -999, -999,
  116851. -999, -999, -999, -999, -999, -999, -999, -999,
  116852. -999, -999, -999, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999},
  116854. {-999, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -108, -103, -98, -93, -86, -79, -71,
  116856. -77, -74, -77, -79, -81, -84, -85, -90,
  116857. -92, -93, -92, -98, -101, -108, -112, -999,
  116858. -999, -999, -999, -999, -999, -999, -999, -999,
  116859. -999, -999, -999, -999, -999, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999},
  116861. {-999, -999, -999, -999, -999, -999, -999, -999,
  116862. -108, -103, -98, -93, -87, -78, -68, -65,
  116863. -66, -62, -65, -67, -70, -73, -75, -78,
  116864. -82, -82, -83, -84, -91, -93, -98, -102,
  116865. -106, -110, -999, -999, -999, -999, -999, -999,
  116866. -999, -999, -999, -999, -999, -999, -999, -999,
  116867. -999, -999, -999, -999, -999, -999, -999, -999},
  116868. {-999, -999, -999, -999, -999, -999, -999, -999,
  116869. -105, -100, -95, -90, -82, -74, -62, -57,
  116870. -58, -56, -51, -52, -52, -54, -54, -58,
  116871. -66, -59, -60, -63, -66, -69, -73, -79,
  116872. -83, -84, -80, -81, -81, -82, -88, -92,
  116873. -98, -105, -113, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999},
  116875. {-999, -999, -999, -999, -999, -999, -999, -107,
  116876. -102, -97, -92, -84, -79, -69, -57, -47,
  116877. -52, -47, -44, -45, -50, -52, -42, -42,
  116878. -53, -43, -43, -48, -51, -56, -55, -52,
  116879. -57, -59, -61, -62, -67, -71, -78, -83,
  116880. -86, -94, -98, -103, -110, -999, -999, -999,
  116881. -999, -999, -999, -999, -999, -999, -999, -999},
  116882. {-999, -999, -999, -999, -999, -999, -105, -100,
  116883. -95, -90, -84, -78, -70, -61, -51, -41,
  116884. -40, -38, -40, -46, -52, -51, -41, -40,
  116885. -46, -40, -38, -38, -41, -46, -41, -46,
  116886. -47, -43, -43, -45, -41, -45, -56, -67,
  116887. -68, -83, -87, -90, -95, -102, -107, -113,
  116888. -999, -999, -999, -999, -999, -999, -999, -999}},
  116889. /* 1000 Hz */
  116890. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -109, -105, -101, -96, -91, -84, -77,
  116892. -82, -82, -85, -89, -94, -100, -106, -110,
  116893. -999, -999, -999, -999, -999, -999, -999, -999,
  116894. -999, -999, -999, -999, -999, -999, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999},
  116897. {-999, -999, -999, -999, -999, -999, -999, -999,
  116898. -999, -106, -103, -98, -92, -85, -80, -71,
  116899. -75, -72, -76, -80, -84, -86, -89, -93,
  116900. -100, -107, -113, -999, -999, -999, -999, -999,
  116901. -999, -999, -999, -999, -999, -999, -999, -999,
  116902. -999, -999, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999},
  116904. {-999, -999, -999, -999, -999, -999, -999, -107,
  116905. -104, -101, -97, -92, -88, -84, -80, -64,
  116906. -66, -63, -64, -66, -69, -73, -77, -83,
  116907. -83, -86, -91, -98, -104, -111, -999, -999,
  116908. -999, -999, -999, -999, -999, -999, -999, -999,
  116909. -999, -999, -999, -999, -999, -999, -999, -999,
  116910. -999, -999, -999, -999, -999, -999, -999, -999},
  116911. {-999, -999, -999, -999, -999, -999, -999, -107,
  116912. -104, -101, -97, -92, -90, -84, -74, -57,
  116913. -58, -52, -55, -54, -50, -52, -50, -52,
  116914. -63, -62, -69, -76, -77, -78, -78, -79,
  116915. -82, -88, -94, -100, -106, -111, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999},
  116918. {-999, -999, -999, -999, -999, -999, -106, -102,
  116919. -98, -95, -90, -85, -83, -78, -70, -50,
  116920. -50, -41, -44, -49, -47, -50, -50, -44,
  116921. -55, -46, -47, -48, -48, -54, -49, -49,
  116922. -58, -62, -71, -81, -87, -92, -97, -102,
  116923. -108, -114, -999, -999, -999, -999, -999, -999,
  116924. -999, -999, -999, -999, -999, -999, -999, -999},
  116925. {-999, -999, -999, -999, -999, -999, -106, -102,
  116926. -98, -95, -90, -85, -83, -78, -70, -45,
  116927. -43, -41, -47, -50, -51, -50, -49, -45,
  116928. -47, -41, -44, -41, -39, -43, -38, -37,
  116929. -40, -41, -44, -50, -58, -65, -73, -79,
  116930. -85, -92, -97, -101, -105, -109, -113, -999,
  116931. -999, -999, -999, -999, -999, -999, -999, -999}},
  116932. /* 1414 Hz */
  116933. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -107, -100, -95, -87, -81,
  116935. -85, -83, -88, -93, -100, -107, -114, -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, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999},
  116940. {-999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -107, -101, -95, -88, -83, -76,
  116942. -73, -72, -79, -84, -90, -95, -100, -105,
  116943. -110, -115, -999, -999, -999, -999, -999, -999,
  116944. -999, -999, -999, -999, -999, -999, -999, -999,
  116945. -999, -999, -999, -999, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999},
  116947. {-999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -104, -98, -92, -87, -81, -70,
  116949. -65, -62, -67, -71, -74, -80, -85, -91,
  116950. -95, -99, -103, -108, -111, -114, -999, -999,
  116951. -999, -999, -999, -999, -999, -999, -999, -999,
  116952. -999, -999, -999, -999, -999, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999},
  116954. {-999, -999, -999, -999, -999, -999, -999, -999,
  116955. -999, -999, -103, -97, -90, -85, -76, -60,
  116956. -56, -54, -60, -62, -61, -56, -63, -65,
  116957. -73, -74, -77, -75, -78, -81, -86, -87,
  116958. -88, -91, -94, -98, -103, -110, -999, -999,
  116959. -999, -999, -999, -999, -999, -999, -999, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999},
  116961. {-999, -999, -999, -999, -999, -999, -999, -105,
  116962. -100, -97, -92, -86, -81, -79, -70, -57,
  116963. -51, -47, -51, -58, -60, -56, -53, -50,
  116964. -58, -52, -50, -50, -53, -55, -64, -69,
  116965. -71, -85, -82, -78, -81, -85, -95, -102,
  116966. -112, -999, -999, -999, -999, -999, -999, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999},
  116968. {-999, -999, -999, -999, -999, -999, -999, -105,
  116969. -100, -97, -92, -85, -83, -79, -72, -49,
  116970. -40, -43, -43, -54, -56, -51, -50, -40,
  116971. -43, -38, -36, -35, -37, -38, -37, -44,
  116972. -54, -60, -57, -60, -70, -75, -84, -92,
  116973. -103, -112, -999, -999, -999, -999, -999, -999,
  116974. -999, -999, -999, -999, -999, -999, -999, -999}},
  116975. /* 2000 Hz */
  116976. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116977. -999, -999, -999, -110, -102, -95, -89, -82,
  116978. -83, -84, -90, -92, -99, -107, -113, -999,
  116979. -999, -999, -999, -999, -999, -999, -999, -999,
  116980. -999, -999, -999, -999, -999, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999},
  116983. {-999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -107, -101, -95, -89, -83, -72,
  116985. -74, -78, -85, -88, -88, -90, -92, -98,
  116986. -105, -111, -999, -999, -999, -999, -999, -999,
  116987. -999, -999, -999, -999, -999, -999, -999, -999,
  116988. -999, -999, -999, -999, -999, -999, -999, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999},
  116990. {-999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -109, -103, -97, -93, -87, -81, -70,
  116992. -70, -67, -75, -73, -76, -79, -81, -83,
  116993. -88, -89, -97, -103, -110, -999, -999, -999,
  116994. -999, -999, -999, -999, -999, -999, -999, -999,
  116995. -999, -999, -999, -999, -999, -999, -999, -999,
  116996. -999, -999, -999, -999, -999, -999, -999, -999},
  116997. {-999, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -107, -100, -94, -88, -83, -75, -63,
  116999. -59, -59, -63, -66, -60, -62, -67, -67,
  117000. -77, -76, -81, -88, -86, -92, -96, -102,
  117001. -109, -116, -999, -999, -999, -999, -999, -999,
  117002. -999, -999, -999, -999, -999, -999, -999, -999,
  117003. -999, -999, -999, -999, -999, -999, -999, -999},
  117004. {-999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -105, -98, -92, -86, -81, -73, -56,
  117006. -52, -47, -55, -60, -58, -52, -51, -45,
  117007. -49, -50, -53, -54, -61, -71, -70, -69,
  117008. -78, -79, -87, -90, -96, -104, -112, -999,
  117009. -999, -999, -999, -999, -999, -999, -999, -999,
  117010. -999, -999, -999, -999, -999, -999, -999, -999},
  117011. {-999, -999, -999, -999, -999, -999, -999, -999,
  117012. -999, -103, -96, -90, -86, -78, -70, -51,
  117013. -42, -47, -48, -55, -54, -54, -53, -42,
  117014. -35, -28, -33, -38, -37, -44, -47, -49,
  117015. -54, -63, -68, -78, -82, -89, -94, -99,
  117016. -104, -109, -114, -999, -999, -999, -999, -999,
  117017. -999, -999, -999, -999, -999, -999, -999, -999}},
  117018. /* 2828 Hz */
  117019. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -999, -110, -100, -90, -79,
  117021. -85, -81, -82, -82, -89, -94, -99, -103,
  117022. -109, -115, -999, -999, -999, -999, -999, -999,
  117023. -999, -999, -999, -999, -999, -999, -999, -999,
  117024. -999, -999, -999, -999, -999, -999, -999, -999,
  117025. -999, -999, -999, -999, -999, -999, -999, -999},
  117026. {-999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -105, -97, -85, -72,
  117028. -74, -70, -70, -70, -76, -85, -91, -93,
  117029. -97, -103, -109, -115, -999, -999, -999, -999,
  117030. -999, -999, -999, -999, -999, -999, -999, -999,
  117031. -999, -999, -999, -999, -999, -999, -999, -999,
  117032. -999, -999, -999, -999, -999, -999, -999, -999},
  117033. {-999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -112, -93, -81, -68,
  117035. -62, -60, -60, -57, -63, -70, -77, -82,
  117036. -90, -93, -98, -104, -109, -113, -999, -999,
  117037. -999, -999, -999, -999, -999, -999, -999, -999,
  117038. -999, -999, -999, -999, -999, -999, -999, -999,
  117039. -999, -999, -999, -999, -999, -999, -999, -999},
  117040. {-999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -113, -100, -93, -84, -63,
  117042. -58, -48, -53, -54, -52, -52, -57, -64,
  117043. -66, -76, -83, -81, -85, -85, -90, -95,
  117044. -98, -101, -103, -106, -108, -111, -999, -999,
  117045. -999, -999, -999, -999, -999, -999, -999, -999,
  117046. -999, -999, -999, -999, -999, -999, -999, -999},
  117047. {-999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -105, -95, -86, -74, -53,
  117049. -50, -38, -43, -49, -43, -42, -39, -39,
  117050. -46, -52, -57, -56, -72, -69, -74, -81,
  117051. -87, -92, -94, -97, -99, -102, -105, -108,
  117052. -999, -999, -999, -999, -999, -999, -999, -999,
  117053. -999, -999, -999, -999, -999, -999, -999, -999},
  117054. {-999, -999, -999, -999, -999, -999, -999, -999,
  117055. -999, -999, -108, -99, -90, -76, -66, -45,
  117056. -43, -41, -44, -47, -43, -47, -40, -30,
  117057. -31, -31, -39, -33, -40, -41, -43, -53,
  117058. -59, -70, -73, -77, -79, -82, -84, -87,
  117059. -999, -999, -999, -999, -999, -999, -999, -999,
  117060. -999, -999, -999, -999, -999, -999, -999, -999}},
  117061. /* 4000 Hz */
  117062. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -999, -999, -110, -91, -76,
  117064. -75, -85, -93, -98, -104, -110, -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, -999, -999, -999,
  117068. -999, -999, -999, -999, -999, -999, -999, -999},
  117069. {-999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -999, -110, -91, -70,
  117071. -70, -75, -86, -89, -94, -98, -101, -106,
  117072. -110, -999, -999, -999, -999, -999, -999, -999,
  117073. -999, -999, -999, -999, -999, -999, -999, -999,
  117074. -999, -999, -999, -999, -999, -999, -999, -999,
  117075. -999, -999, -999, -999, -999, -999, -999, -999},
  117076. {-999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -999, -110, -95, -80, -60,
  117078. -65, -64, -74, -83, -88, -91, -95, -99,
  117079. -103, -107, -110, -999, -999, -999, -999, -999,
  117080. -999, -999, -999, -999, -999, -999, -999, -999,
  117081. -999, -999, -999, -999, -999, -999, -999, -999,
  117082. -999, -999, -999, -999, -999, -999, -999, -999},
  117083. {-999, -999, -999, -999, -999, -999, -999, -999,
  117084. -999, -999, -999, -999, -110, -95, -80, -58,
  117085. -55, -49, -66, -68, -71, -78, -78, -80,
  117086. -88, -85, -89, -97, -100, -105, -110, -999,
  117087. -999, -999, -999, -999, -999, -999, -999, -999,
  117088. -999, -999, -999, -999, -999, -999, -999, -999,
  117089. -999, -999, -999, -999, -999, -999, -999, -999},
  117090. {-999, -999, -999, -999, -999, -999, -999, -999,
  117091. -999, -999, -999, -999, -110, -95, -80, -53,
  117092. -52, -41, -59, -59, -49, -58, -56, -63,
  117093. -86, -79, -90, -93, -98, -103, -107, -112,
  117094. -999, -999, -999, -999, -999, -999, -999, -999,
  117095. -999, -999, -999, -999, -999, -999, -999, -999,
  117096. -999, -999, -999, -999, -999, -999, -999, -999},
  117097. {-999, -999, -999, -999, -999, -999, -999, -999,
  117098. -999, -999, -999, -110, -97, -91, -73, -45,
  117099. -40, -33, -53, -61, -49, -54, -50, -50,
  117100. -60, -52, -67, -74, -81, -92, -96, -100,
  117101. -105, -110, -999, -999, -999, -999, -999, -999,
  117102. -999, -999, -999, -999, -999, -999, -999, -999,
  117103. -999, -999, -999, -999, -999, -999, -999, -999}},
  117104. /* 5657 Hz */
  117105. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -999, -113, -106, -99, -92, -77,
  117107. -80, -88, -97, -106, -115, -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, -999, -999, -999, -999, -999,
  117111. -999, -999, -999, -999, -999, -999, -999, -999},
  117112. {-999, -999, -999, -999, -999, -999, -999, -999,
  117113. -999, -999, -116, -109, -102, -95, -89, -74,
  117114. -72, -88, -87, -95, -102, -109, -116, -999,
  117115. -999, -999, -999, -999, -999, -999, -999, -999,
  117116. -999, -999, -999, -999, -999, -999, -999, -999,
  117117. -999, -999, -999, -999, -999, -999, -999, -999,
  117118. -999, -999, -999, -999, -999, -999, -999, -999},
  117119. {-999, -999, -999, -999, -999, -999, -999, -999,
  117120. -999, -999, -116, -109, -102, -95, -89, -75,
  117121. -66, -74, -77, -78, -86, -87, -90, -96,
  117122. -105, -115, -999, -999, -999, -999, -999, -999,
  117123. -999, -999, -999, -999, -999, -999, -999, -999,
  117124. -999, -999, -999, -999, -999, -999, -999, -999,
  117125. -999, -999, -999, -999, -999, -999, -999, -999},
  117126. {-999, -999, -999, -999, -999, -999, -999, -999,
  117127. -999, -999, -115, -108, -101, -94, -88, -66,
  117128. -56, -61, -70, -65, -78, -72, -83, -84,
  117129. -93, -98, -105, -110, -999, -999, -999, -999,
  117130. -999, -999, -999, -999, -999, -999, -999, -999,
  117131. -999, -999, -999, -999, -999, -999, -999, -999,
  117132. -999, -999, -999, -999, -999, -999, -999, -999},
  117133. {-999, -999, -999, -999, -999, -999, -999, -999,
  117134. -999, -999, -110, -105, -95, -89, -82, -57,
  117135. -52, -52, -59, -56, -59, -58, -69, -67,
  117136. -88, -82, -82, -89, -94, -100, -108, -999,
  117137. -999, -999, -999, -999, -999, -999, -999, -999,
  117138. -999, -999, -999, -999, -999, -999, -999, -999,
  117139. -999, -999, -999, -999, -999, -999, -999, -999},
  117140. {-999, -999, -999, -999, -999, -999, -999, -999,
  117141. -999, -110, -101, -96, -90, -83, -77, -54,
  117142. -43, -38, -50, -48, -52, -48, -42, -42,
  117143. -51, -52, -53, -59, -65, -71, -78, -85,
  117144. -95, -999, -999, -999, -999, -999, -999, -999,
  117145. -999, -999, -999, -999, -999, -999, -999, -999,
  117146. -999, -999, -999, -999, -999, -999, -999, -999}},
  117147. /* 8000 Hz */
  117148. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117149. -999, -999, -999, -999, -120, -105, -86, -68,
  117150. -78, -79, -90, -100, -110, -999, -999, -999,
  117151. -999, -999, -999, -999, -999, -999, -999, -999,
  117152. -999, -999, -999, -999, -999, -999, -999, -999,
  117153. -999, -999, -999, -999, -999, -999, -999, -999,
  117154. -999, -999, -999, -999, -999, -999, -999, -999},
  117155. {-999, -999, -999, -999, -999, -999, -999, -999,
  117156. -999, -999, -999, -999, -120, -105, -86, -66,
  117157. -73, -77, -88, -96, -105, -115, -999, -999,
  117158. -999, -999, -999, -999, -999, -999, -999, -999,
  117159. -999, -999, -999, -999, -999, -999, -999, -999,
  117160. -999, -999, -999, -999, -999, -999, -999, -999,
  117161. -999, -999, -999, -999, -999, -999, -999, -999},
  117162. {-999, -999, -999, -999, -999, -999, -999, -999,
  117163. -999, -999, -999, -120, -105, -92, -80, -61,
  117164. -64, -68, -80, -87, -92, -100, -110, -999,
  117165. -999, -999, -999, -999, -999, -999, -999, -999,
  117166. -999, -999, -999, -999, -999, -999, -999, -999,
  117167. -999, -999, -999, -999, -999, -999, -999, -999,
  117168. -999, -999, -999, -999, -999, -999, -999, -999},
  117169. {-999, -999, -999, -999, -999, -999, -999, -999,
  117170. -999, -999, -999, -120, -104, -91, -79, -52,
  117171. -60, -54, -64, -69, -77, -80, -82, -84,
  117172. -85, -87, -88, -90, -999, -999, -999, -999,
  117173. -999, -999, -999, -999, -999, -999, -999, -999,
  117174. -999, -999, -999, -999, -999, -999, -999, -999,
  117175. -999, -999, -999, -999, -999, -999, -999, -999},
  117176. {-999, -999, -999, -999, -999, -999, -999, -999,
  117177. -999, -999, -999, -118, -100, -87, -77, -49,
  117178. -50, -44, -58, -61, -61, -67, -65, -62,
  117179. -62, -62, -65, -68, -999, -999, -999, -999,
  117180. -999, -999, -999, -999, -999, -999, -999, -999,
  117181. -999, -999, -999, -999, -999, -999, -999, -999,
  117182. -999, -999, -999, -999, -999, -999, -999, -999},
  117183. {-999, -999, -999, -999, -999, -999, -999, -999,
  117184. -999, -999, -999, -115, -98, -84, -62, -49,
  117185. -44, -38, -46, -49, -49, -46, -39, -37,
  117186. -39, -40, -42, -43, -999, -999, -999, -999,
  117187. -999, -999, -999, -999, -999, -999, -999, -999,
  117188. -999, -999, -999, -999, -999, -999, -999, -999,
  117189. -999, -999, -999, -999, -999, -999, -999, -999}},
  117190. /* 11314 Hz */
  117191. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117192. -999, -999, -999, -999, -999, -110, -88, -74,
  117193. -77, -82, -82, -85, -90, -94, -99, -104,
  117194. -999, -999, -999, -999, -999, -999, -999, -999,
  117195. -999, -999, -999, -999, -999, -999, -999, -999,
  117196. -999, -999, -999, -999, -999, -999, -999, -999,
  117197. -999, -999, -999, -999, -999, -999, -999, -999},
  117198. {-999, -999, -999, -999, -999, -999, -999, -999,
  117199. -999, -999, -999, -999, -999, -110, -88, -66,
  117200. -70, -81, -80, -81, -84, -88, -91, -93,
  117201. -999, -999, -999, -999, -999, -999, -999, -999,
  117202. -999, -999, -999, -999, -999, -999, -999, -999,
  117203. -999, -999, -999, -999, -999, -999, -999, -999,
  117204. -999, -999, -999, -999, -999, -999, -999, -999},
  117205. {-999, -999, -999, -999, -999, -999, -999, -999,
  117206. -999, -999, -999, -999, -999, -110, -88, -61,
  117207. -63, -70, -71, -74, -77, -80, -83, -85,
  117208. -999, -999, -999, -999, -999, -999, -999, -999,
  117209. -999, -999, -999, -999, -999, -999, -999, -999,
  117210. -999, -999, -999, -999, -999, -999, -999, -999,
  117211. -999, -999, -999, -999, -999, -999, -999, -999},
  117212. {-999, -999, -999, -999, -999, -999, -999, -999,
  117213. -999, -999, -999, -999, -999, -110, -86, -62,
  117214. -63, -62, -62, -58, -52, -50, -50, -52,
  117215. -54, -999, -999, -999, -999, -999, -999, -999,
  117216. -999, -999, -999, -999, -999, -999, -999, -999,
  117217. -999, -999, -999, -999, -999, -999, -999, -999,
  117218. -999, -999, -999, -999, -999, -999, -999, -999},
  117219. {-999, -999, -999, -999, -999, -999, -999, -999,
  117220. -999, -999, -999, -999, -118, -108, -84, -53,
  117221. -50, -50, -50, -55, -47, -45, -40, -40,
  117222. -40, -999, -999, -999, -999, -999, -999, -999,
  117223. -999, -999, -999, -999, -999, -999, -999, -999,
  117224. -999, -999, -999, -999, -999, -999, -999, -999,
  117225. -999, -999, -999, -999, -999, -999, -999, -999},
  117226. {-999, -999, -999, -999, -999, -999, -999, -999,
  117227. -999, -999, -999, -999, -118, -100, -73, -43,
  117228. -37, -42, -43, -53, -38, -37, -35, -35,
  117229. -38, -999, -999, -999, -999, -999, -999, -999,
  117230. -999, -999, -999, -999, -999, -999, -999, -999,
  117231. -999, -999, -999, -999, -999, -999, -999, -999,
  117232. -999, -999, -999, -999, -999, -999, -999, -999}},
  117233. /* 16000 Hz */
  117234. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117235. -999, -999, -999, -110, -100, -91, -84, -74,
  117236. -80, -80, -80, -80, -80, -999, -999, -999,
  117237. -999, -999, -999, -999, -999, -999, -999, -999,
  117238. -999, -999, -999, -999, -999, -999, -999, -999,
  117239. -999, -999, -999, -999, -999, -999, -999, -999,
  117240. -999, -999, -999, -999, -999, -999, -999, -999},
  117241. {-999, -999, -999, -999, -999, -999, -999, -999,
  117242. -999, -999, -999, -110, -100, -91, -84, -74,
  117243. -68, -68, -68, -68, -68, -999, -999, -999,
  117244. -999, -999, -999, -999, -999, -999, -999, -999,
  117245. -999, -999, -999, -999, -999, -999, -999, -999,
  117246. -999, -999, -999, -999, -999, -999, -999, -999,
  117247. -999, -999, -999, -999, -999, -999, -999, -999},
  117248. {-999, -999, -999, -999, -999, -999, -999, -999,
  117249. -999, -999, -999, -110, -100, -86, -78, -70,
  117250. -60, -45, -30, -21, -999, -999, -999, -999,
  117251. -999, -999, -999, -999, -999, -999, -999, -999,
  117252. -999, -999, -999, -999, -999, -999, -999, -999,
  117253. -999, -999, -999, -999, -999, -999, -999, -999,
  117254. -999, -999, -999, -999, -999, -999, -999, -999},
  117255. {-999, -999, -999, -999, -999, -999, -999, -999,
  117256. -999, -999, -999, -110, -100, -87, -78, -67,
  117257. -48, -38, -29, -21, -999, -999, -999, -999,
  117258. -999, -999, -999, -999, -999, -999, -999, -999,
  117259. -999, -999, -999, -999, -999, -999, -999, -999,
  117260. -999, -999, -999, -999, -999, -999, -999, -999,
  117261. -999, -999, -999, -999, -999, -999, -999, -999},
  117262. {-999, -999, -999, -999, -999, -999, -999, -999,
  117263. -999, -999, -999, -110, -100, -86, -69, -56,
  117264. -45, -35, -33, -29, -999, -999, -999, -999,
  117265. -999, -999, -999, -999, -999, -999, -999, -999,
  117266. -999, -999, -999, -999, -999, -999, -999, -999,
  117267. -999, -999, -999, -999, -999, -999, -999, -999,
  117268. -999, -999, -999, -999, -999, -999, -999, -999},
  117269. {-999, -999, -999, -999, -999, -999, -999, -999,
  117270. -999, -999, -999, -110, -100, -83, -71, -48,
  117271. -27, -38, -37, -34, -999, -999, -999, -999,
  117272. -999, -999, -999, -999, -999, -999, -999, -999,
  117273. -999, -999, -999, -999, -999, -999, -999, -999,
  117274. -999, -999, -999, -999, -999, -999, -999, -999,
  117275. -999, -999, -999, -999, -999, -999, -999, -999}}
  117276. };
  117277. #endif
  117278. /*** End of inlined file: masking.h ***/
  117279. #define NEGINF -9999.f
  117280. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117281. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117282. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117283. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117284. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117285. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117286. look->channels=vi->channels;
  117287. look->ampmax=-9999.;
  117288. look->gi=gi;
  117289. return(look);
  117290. }
  117291. void _vp_global_free(vorbis_look_psy_global *look){
  117292. if(look){
  117293. memset(look,0,sizeof(*look));
  117294. _ogg_free(look);
  117295. }
  117296. }
  117297. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117298. if(i){
  117299. memset(i,0,sizeof(*i));
  117300. _ogg_free(i);
  117301. }
  117302. }
  117303. void _vi_psy_free(vorbis_info_psy *i){
  117304. if(i){
  117305. memset(i,0,sizeof(*i));
  117306. _ogg_free(i);
  117307. }
  117308. }
  117309. static void min_curve(float *c,
  117310. float *c2){
  117311. int i;
  117312. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117313. }
  117314. static void max_curve(float *c,
  117315. float *c2){
  117316. int i;
  117317. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117318. }
  117319. static void attenuate_curve(float *c,float att){
  117320. int i;
  117321. for(i=0;i<EHMER_MAX;i++)
  117322. c[i]+=att;
  117323. }
  117324. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117325. float center_boost, float center_decay_rate){
  117326. int i,j,k,m;
  117327. float ath[EHMER_MAX];
  117328. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117329. float athc[P_LEVELS][EHMER_MAX];
  117330. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117331. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117332. memset(workc,0,sizeof(workc));
  117333. for(i=0;i<P_BANDS;i++){
  117334. /* we add back in the ATH to avoid low level curves falling off to
  117335. -infinity and unnecessarily cutting off high level curves in the
  117336. curve limiting (last step). */
  117337. /* A half-band's settings must be valid over the whole band, and
  117338. it's better to mask too little than too much */
  117339. int ath_offset=i*4;
  117340. for(j=0;j<EHMER_MAX;j++){
  117341. float min=999.;
  117342. for(k=0;k<4;k++)
  117343. if(j+k+ath_offset<MAX_ATH){
  117344. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117345. }else{
  117346. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117347. }
  117348. ath[j]=min;
  117349. }
  117350. /* copy curves into working space, replicate the 50dB curve to 30
  117351. and 40, replicate the 100dB curve to 110 */
  117352. for(j=0;j<6;j++)
  117353. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117354. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117355. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117356. /* apply centered curve boost/decay */
  117357. for(j=0;j<P_LEVELS;j++){
  117358. for(k=0;k<EHMER_MAX;k++){
  117359. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117360. if(adj<0. && center_boost>0)adj=0.;
  117361. if(adj>0. && center_boost<0)adj=0.;
  117362. workc[i][j][k]+=adj;
  117363. }
  117364. }
  117365. /* normalize curves so the driving amplitude is 0dB */
  117366. /* make temp curves with the ATH overlayed */
  117367. for(j=0;j<P_LEVELS;j++){
  117368. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117369. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117370. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117371. max_curve(athc[j],workc[i][j]);
  117372. }
  117373. /* Now limit the louder curves.
  117374. the idea is this: We don't know what the playback attenuation
  117375. will be; 0dB SL moves every time the user twiddles the volume
  117376. knob. So that means we have to use a single 'most pessimal' curve
  117377. for all masking amplitudes, right? Wrong. The *loudest* sound
  117378. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117379. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117380. etc... */
  117381. for(j=1;j<P_LEVELS;j++){
  117382. min_curve(athc[j],athc[j-1]);
  117383. min_curve(workc[i][j],athc[j]);
  117384. }
  117385. }
  117386. for(i=0;i<P_BANDS;i++){
  117387. int hi_curve,lo_curve,bin;
  117388. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117389. /* low frequency curves are measured with greater resolution than
  117390. the MDCT/FFT will actually give us; we want the curve applied
  117391. to the tone data to be pessimistic and thus apply the minimum
  117392. masking possible for a given bin. That means that a single bin
  117393. could span more than one octave and that the curve will be a
  117394. composite of multiple octaves. It also may mean that a single
  117395. bin may span > an eighth of an octave and that the eighth
  117396. octave values may also be composited. */
  117397. /* which octave curves will we be compositing? */
  117398. bin=floor(fromOC(i*.5)/binHz);
  117399. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117400. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117401. if(lo_curve>i)lo_curve=i;
  117402. if(lo_curve<0)lo_curve=0;
  117403. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117404. for(m=0;m<P_LEVELS;m++){
  117405. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117406. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117407. /* render the curve into bins, then pull values back into curve.
  117408. The point is that any inherent subsampling aliasing results in
  117409. a safe minimum */
  117410. for(k=lo_curve;k<=hi_curve;k++){
  117411. int l=0;
  117412. for(j=0;j<EHMER_MAX;j++){
  117413. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117414. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117415. if(lo_bin<0)lo_bin=0;
  117416. if(lo_bin>n)lo_bin=n;
  117417. if(lo_bin<l)l=lo_bin;
  117418. if(hi_bin<0)hi_bin=0;
  117419. if(hi_bin>n)hi_bin=n;
  117420. for(;l<hi_bin && l<n;l++)
  117421. if(brute_buffer[l]>workc[k][m][j])
  117422. brute_buffer[l]=workc[k][m][j];
  117423. }
  117424. for(;l<n;l++)
  117425. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117426. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117427. }
  117428. /* be equally paranoid about being valid up to next half ocatve */
  117429. if(i+1<P_BANDS){
  117430. int l=0;
  117431. k=i+1;
  117432. for(j=0;j<EHMER_MAX;j++){
  117433. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117434. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117435. if(lo_bin<0)lo_bin=0;
  117436. if(lo_bin>n)lo_bin=n;
  117437. if(lo_bin<l)l=lo_bin;
  117438. if(hi_bin<0)hi_bin=0;
  117439. if(hi_bin>n)hi_bin=n;
  117440. for(;l<hi_bin && l<n;l++)
  117441. if(brute_buffer[l]>workc[k][m][j])
  117442. brute_buffer[l]=workc[k][m][j];
  117443. }
  117444. for(;l<n;l++)
  117445. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117446. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117447. }
  117448. for(j=0;j<EHMER_MAX;j++){
  117449. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117450. if(bin<0){
  117451. ret[i][m][j+2]=-999.;
  117452. }else{
  117453. if(bin>=n){
  117454. ret[i][m][j+2]=-999.;
  117455. }else{
  117456. ret[i][m][j+2]=brute_buffer[bin];
  117457. }
  117458. }
  117459. }
  117460. /* add fenceposts */
  117461. for(j=0;j<EHMER_OFFSET;j++)
  117462. if(ret[i][m][j+2]>-200.f)break;
  117463. ret[i][m][0]=j;
  117464. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117465. if(ret[i][m][j+2]>-200.f)
  117466. break;
  117467. ret[i][m][1]=j;
  117468. }
  117469. }
  117470. return(ret);
  117471. }
  117472. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117473. vorbis_info_psy_global *gi,int n,long rate){
  117474. long i,j,lo=-99,hi=1;
  117475. long maxoc;
  117476. memset(p,0,sizeof(*p));
  117477. p->eighth_octave_lines=gi->eighth_octave_lines;
  117478. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117479. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117480. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117481. p->total_octave_lines=maxoc-p->firstoc+1;
  117482. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117483. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117484. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117485. p->vi=vi;
  117486. p->n=n;
  117487. p->rate=rate;
  117488. /* AoTuV HF weighting */
  117489. p->m_val = 1.;
  117490. if(rate < 26000) p->m_val = 0;
  117491. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117492. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117493. /* set up the lookups for a given blocksize and sample rate */
  117494. for(i=0,j=0;i<MAX_ATH-1;i++){
  117495. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117496. float base=ATH[i];
  117497. if(j<endpos){
  117498. float delta=(ATH[i+1]-base)/(endpos-j);
  117499. for(;j<endpos && j<n;j++){
  117500. p->ath[j]=base+100.;
  117501. base+=delta;
  117502. }
  117503. }
  117504. }
  117505. for(i=0;i<n;i++){
  117506. float bark=toBARK(rate/(2*n)*i);
  117507. for(;lo+vi->noisewindowlomin<i &&
  117508. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117509. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117510. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117511. p->bark[i]=((lo-1)<<16)+(hi-1);
  117512. }
  117513. for(i=0;i<n;i++)
  117514. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117515. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117516. vi->tone_centerboost,vi->tone_decay);
  117517. /* set up rolling noise median */
  117518. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117519. for(i=0;i<P_NOISECURVES;i++)
  117520. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117521. for(i=0;i<n;i++){
  117522. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117523. int inthalfoc;
  117524. float del;
  117525. if(halfoc<0)halfoc=0;
  117526. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117527. inthalfoc=(int)halfoc;
  117528. del=halfoc-inthalfoc;
  117529. for(j=0;j<P_NOISECURVES;j++)
  117530. p->noiseoffset[j][i]=
  117531. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117532. p->vi->noiseoff[j][inthalfoc+1]*del;
  117533. }
  117534. #if 0
  117535. {
  117536. static int ls=0;
  117537. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117538. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117539. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117540. }
  117541. #endif
  117542. }
  117543. void _vp_psy_clear(vorbis_look_psy *p){
  117544. int i,j;
  117545. if(p){
  117546. if(p->ath)_ogg_free(p->ath);
  117547. if(p->octave)_ogg_free(p->octave);
  117548. if(p->bark)_ogg_free(p->bark);
  117549. if(p->tonecurves){
  117550. for(i=0;i<P_BANDS;i++){
  117551. for(j=0;j<P_LEVELS;j++){
  117552. _ogg_free(p->tonecurves[i][j]);
  117553. }
  117554. _ogg_free(p->tonecurves[i]);
  117555. }
  117556. _ogg_free(p->tonecurves);
  117557. }
  117558. if(p->noiseoffset){
  117559. for(i=0;i<P_NOISECURVES;i++){
  117560. _ogg_free(p->noiseoffset[i]);
  117561. }
  117562. _ogg_free(p->noiseoffset);
  117563. }
  117564. memset(p,0,sizeof(*p));
  117565. }
  117566. }
  117567. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117568. static void seed_curve(float *seed,
  117569. const float **curves,
  117570. float amp,
  117571. int oc, int n,
  117572. int linesper,float dBoffset){
  117573. int i,post1;
  117574. int seedptr;
  117575. const float *posts,*curve;
  117576. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117577. choice=max(choice,0);
  117578. choice=min(choice,P_LEVELS-1);
  117579. posts=curves[choice];
  117580. curve=posts+2;
  117581. post1=(int)posts[1];
  117582. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117583. for(i=posts[0];i<post1;i++){
  117584. if(seedptr>0){
  117585. float lin=amp+curve[i];
  117586. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117587. }
  117588. seedptr+=linesper;
  117589. if(seedptr>=n)break;
  117590. }
  117591. }
  117592. static void seed_loop(vorbis_look_psy *p,
  117593. const float ***curves,
  117594. const float *f,
  117595. const float *flr,
  117596. float *seed,
  117597. float specmax){
  117598. vorbis_info_psy *vi=p->vi;
  117599. long n=p->n,i;
  117600. float dBoffset=vi->max_curve_dB-specmax;
  117601. /* prime the working vector with peak values */
  117602. for(i=0;i<n;i++){
  117603. float max=f[i];
  117604. long oc=p->octave[i];
  117605. while(i+1<n && p->octave[i+1]==oc){
  117606. i++;
  117607. if(f[i]>max)max=f[i];
  117608. }
  117609. if(max+6.f>flr[i]){
  117610. oc=oc>>p->shiftoc;
  117611. if(oc>=P_BANDS)oc=P_BANDS-1;
  117612. if(oc<0)oc=0;
  117613. seed_curve(seed,
  117614. curves[oc],
  117615. max,
  117616. p->octave[i]-p->firstoc,
  117617. p->total_octave_lines,
  117618. p->eighth_octave_lines,
  117619. dBoffset);
  117620. }
  117621. }
  117622. }
  117623. static void seed_chase(float *seeds, int linesper, long n){
  117624. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117625. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117626. long stack=0;
  117627. long pos=0;
  117628. long i;
  117629. for(i=0;i<n;i++){
  117630. if(stack<2){
  117631. posstack[stack]=i;
  117632. ampstack[stack++]=seeds[i];
  117633. }else{
  117634. while(1){
  117635. if(seeds[i]<ampstack[stack-1]){
  117636. posstack[stack]=i;
  117637. ampstack[stack++]=seeds[i];
  117638. break;
  117639. }else{
  117640. if(i<posstack[stack-1]+linesper){
  117641. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117642. i<posstack[stack-2]+linesper){
  117643. /* we completely overlap, making stack-1 irrelevant. pop it */
  117644. stack--;
  117645. continue;
  117646. }
  117647. }
  117648. posstack[stack]=i;
  117649. ampstack[stack++]=seeds[i];
  117650. break;
  117651. }
  117652. }
  117653. }
  117654. }
  117655. /* the stack now contains only the positions that are relevant. Scan
  117656. 'em straight through */
  117657. for(i=0;i<stack;i++){
  117658. long endpos;
  117659. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117660. endpos=posstack[i+1];
  117661. }else{
  117662. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117663. discarded in short frames */
  117664. }
  117665. if(endpos>n)endpos=n;
  117666. for(;pos<endpos;pos++)
  117667. seeds[pos]=ampstack[i];
  117668. }
  117669. /* there. Linear time. I now remember this was on a problem set I
  117670. had in Grad Skool... I didn't solve it at the time ;-) */
  117671. }
  117672. /* bleaugh, this is more complicated than it needs to be */
  117673. #include<stdio.h>
  117674. static void max_seeds(vorbis_look_psy *p,
  117675. float *seed,
  117676. float *flr){
  117677. long n=p->total_octave_lines;
  117678. int linesper=p->eighth_octave_lines;
  117679. long linpos=0;
  117680. long pos;
  117681. seed_chase(seed,linesper,n); /* for masking */
  117682. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117683. while(linpos+1<p->n){
  117684. float minV=seed[pos];
  117685. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117686. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117687. while(pos+1<=end){
  117688. pos++;
  117689. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117690. minV=seed[pos];
  117691. }
  117692. end=pos+p->firstoc;
  117693. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117694. if(flr[linpos]<minV)flr[linpos]=minV;
  117695. }
  117696. {
  117697. float minV=seed[p->total_octave_lines-1];
  117698. for(;linpos<p->n;linpos++)
  117699. if(flr[linpos]<minV)flr[linpos]=minV;
  117700. }
  117701. }
  117702. static void bark_noise_hybridmp(int n,const long *b,
  117703. const float *f,
  117704. float *noise,
  117705. const float offset,
  117706. const int fixed){
  117707. float *N=(float*) alloca(n*sizeof(*N));
  117708. float *X=(float*) alloca(n*sizeof(*N));
  117709. float *XX=(float*) alloca(n*sizeof(*N));
  117710. float *Y=(float*) alloca(n*sizeof(*N));
  117711. float *XY=(float*) alloca(n*sizeof(*N));
  117712. float tN, tX, tXX, tY, tXY;
  117713. int i;
  117714. int lo, hi;
  117715. float R, A, B, D;
  117716. float w, x, y;
  117717. tN = tX = tXX = tY = tXY = 0.f;
  117718. y = f[0] + offset;
  117719. if (y < 1.f) y = 1.f;
  117720. w = y * y * .5;
  117721. tN += w;
  117722. tX += w;
  117723. tY += w * y;
  117724. N[0] = tN;
  117725. X[0] = tX;
  117726. XX[0] = tXX;
  117727. Y[0] = tY;
  117728. XY[0] = tXY;
  117729. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117730. y = f[i] + offset;
  117731. if (y < 1.f) y = 1.f;
  117732. w = y * y;
  117733. tN += w;
  117734. tX += w * x;
  117735. tXX += w * x * x;
  117736. tY += w * y;
  117737. tXY += w * x * y;
  117738. N[i] = tN;
  117739. X[i] = tX;
  117740. XX[i] = tXX;
  117741. Y[i] = tY;
  117742. XY[i] = tXY;
  117743. }
  117744. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117745. lo = b[i] >> 16;
  117746. if( lo>=0 ) break;
  117747. hi = b[i] & 0xffff;
  117748. tN = N[hi] + N[-lo];
  117749. tX = X[hi] - X[-lo];
  117750. tXX = XX[hi] + XX[-lo];
  117751. tY = Y[hi] + Y[-lo];
  117752. tXY = XY[hi] - XY[-lo];
  117753. A = tY * tXX - tX * tXY;
  117754. B = tN * tXY - tX * tY;
  117755. D = tN * tXX - tX * tX;
  117756. R = (A + x * B) / D;
  117757. if (R < 0.f)
  117758. R = 0.f;
  117759. noise[i] = R - offset;
  117760. }
  117761. for ( ;; i++, x += 1.f) {
  117762. lo = b[i] >> 16;
  117763. hi = b[i] & 0xffff;
  117764. if(hi>=n)break;
  117765. tN = N[hi] - N[lo];
  117766. tX = X[hi] - X[lo];
  117767. tXX = XX[hi] - XX[lo];
  117768. tY = Y[hi] - Y[lo];
  117769. tXY = XY[hi] - XY[lo];
  117770. A = tY * tXX - tX * tXY;
  117771. B = tN * tXY - tX * tY;
  117772. D = tN * tXX - tX * tX;
  117773. R = (A + x * B) / D;
  117774. if (R < 0.f) R = 0.f;
  117775. noise[i] = R - offset;
  117776. }
  117777. for ( ; i < n; i++, x += 1.f) {
  117778. R = (A + x * B) / D;
  117779. if (R < 0.f) R = 0.f;
  117780. noise[i] = R - offset;
  117781. }
  117782. if (fixed <= 0) return;
  117783. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117784. hi = i + fixed / 2;
  117785. lo = hi - fixed;
  117786. if(lo>=0)break;
  117787. tN = N[hi] + N[-lo];
  117788. tX = X[hi] - X[-lo];
  117789. tXX = XX[hi] + XX[-lo];
  117790. tY = Y[hi] + Y[-lo];
  117791. tXY = XY[hi] - XY[-lo];
  117792. A = tY * tXX - tX * tXY;
  117793. B = tN * tXY - tX * tY;
  117794. D = tN * tXX - tX * tX;
  117795. R = (A + x * B) / D;
  117796. if (R - offset < noise[i]) noise[i] = R - offset;
  117797. }
  117798. for ( ;; i++, x += 1.f) {
  117799. hi = i + fixed / 2;
  117800. lo = hi - fixed;
  117801. if(hi>=n)break;
  117802. tN = N[hi] - N[lo];
  117803. tX = X[hi] - X[lo];
  117804. tXX = XX[hi] - XX[lo];
  117805. tY = Y[hi] - Y[lo];
  117806. tXY = XY[hi] - XY[lo];
  117807. A = tY * tXX - tX * tXY;
  117808. B = tN * tXY - tX * tY;
  117809. D = tN * tXX - tX * tX;
  117810. R = (A + x * B) / D;
  117811. if (R - offset < noise[i]) noise[i] = R - offset;
  117812. }
  117813. for ( ; i < n; i++, x += 1.f) {
  117814. R = (A + x * B) / D;
  117815. if (R - offset < noise[i]) noise[i] = R - offset;
  117816. }
  117817. }
  117818. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117819. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117820. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117821. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117822. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117823. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117824. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117825. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117826. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117827. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117828. 973377.F, 913981.F, 858210.F, 805842.F,
  117829. 756669.F, 710497.F, 667142.F, 626433.F,
  117830. 588208.F, 552316.F, 518613.F, 486967.F,
  117831. 457252.F, 429351.F, 403152.F, 378551.F,
  117832. 355452.F, 333762.F, 313396.F, 294273.F,
  117833. 276316.F, 259455.F, 243623.F, 228757.F,
  117834. 214798.F, 201691.F, 189384.F, 177828.F,
  117835. 166977.F, 156788.F, 147221.F, 138237.F,
  117836. 129802.F, 121881.F, 114444.F, 107461.F,
  117837. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117838. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117839. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117840. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117841. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117842. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117843. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117844. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117845. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117846. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117847. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117848. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117849. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117850. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117851. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117852. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117853. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117854. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117855. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117856. 842.910F, 791.475F, 743.179F, 697.830F,
  117857. 655.249F, 615.265F, 577.722F, 542.469F,
  117858. 509.367F, 478.286F, 449.101F, 421.696F,
  117859. 395.964F, 371.803F, 349.115F, 327.812F,
  117860. 307.809F, 289.026F, 271.390F, 254.830F,
  117861. 239.280F, 224.679F, 210.969F, 198.096F,
  117862. 186.008F, 174.658F, 164.000F, 153.993F,
  117863. 144.596F, 135.773F, 127.488F, 119.708F,
  117864. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117865. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117866. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117867. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117868. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117869. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117870. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117871. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117872. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117873. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117874. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117875. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117876. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117877. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117878. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117879. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117880. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117881. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117882. 1.20790F, 1.13419F, 1.06499F, 1.F
  117883. };
  117884. void _vp_remove_floor(vorbis_look_psy *p,
  117885. float *mdct,
  117886. int *codedflr,
  117887. float *residue,
  117888. int sliding_lowpass){
  117889. int i,n=p->n;
  117890. if(sliding_lowpass>n)sliding_lowpass=n;
  117891. for(i=0;i<sliding_lowpass;i++){
  117892. residue[i]=
  117893. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117894. }
  117895. for(;i<n;i++)
  117896. residue[i]=0.;
  117897. }
  117898. void _vp_noisemask(vorbis_look_psy *p,
  117899. float *logmdct,
  117900. float *logmask){
  117901. int i,n=p->n;
  117902. float *work=(float*) alloca(n*sizeof(*work));
  117903. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117904. 140.,-1);
  117905. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117906. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117907. p->vi->noisewindowfixed);
  117908. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117909. #if 0
  117910. {
  117911. static int seq=0;
  117912. float work2[n];
  117913. for(i=0;i<n;i++){
  117914. work2[i]=logmask[i]+work[i];
  117915. }
  117916. if(seq&1)
  117917. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117918. else
  117919. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117920. if(seq&1)
  117921. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117922. else
  117923. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117924. seq++;
  117925. }
  117926. #endif
  117927. for(i=0;i<n;i++){
  117928. int dB=logmask[i]+.5;
  117929. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117930. if(dB<0)dB=0;
  117931. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117932. }
  117933. }
  117934. void _vp_tonemask(vorbis_look_psy *p,
  117935. float *logfft,
  117936. float *logmask,
  117937. float global_specmax,
  117938. float local_specmax){
  117939. int i,n=p->n;
  117940. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117941. float att=local_specmax+p->vi->ath_adjatt;
  117942. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117943. /* set the ATH (floating below localmax, not global max by a
  117944. specified att) */
  117945. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117946. for(i=0;i<n;i++)
  117947. logmask[i]=p->ath[i]+att;
  117948. /* tone masking */
  117949. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117950. max_seeds(p,seed,logmask);
  117951. }
  117952. void _vp_offset_and_mix(vorbis_look_psy *p,
  117953. float *noise,
  117954. float *tone,
  117955. int offset_select,
  117956. float *logmask,
  117957. float *mdct,
  117958. float *logmdct){
  117959. int i,n=p->n;
  117960. float de, coeffi, cx;/* AoTuV */
  117961. float toneatt=p->vi->tone_masteratt[offset_select];
  117962. cx = p->m_val;
  117963. for(i=0;i<n;i++){
  117964. float val= noise[i]+p->noiseoffset[offset_select][i];
  117965. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117966. logmask[i]=max(val,tone[i]+toneatt);
  117967. /* AoTuV */
  117968. /** @ M1 **
  117969. The following codes improve a noise problem.
  117970. A fundamental idea uses the value of masking and carries out
  117971. the relative compensation of the MDCT.
  117972. However, this code is not perfect and all noise problems cannot be solved.
  117973. by Aoyumi @ 2004/04/18
  117974. */
  117975. if(offset_select == 1) {
  117976. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117977. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117978. if(val > coeffi){
  117979. /* mdct value is > -17.2 dB below floor */
  117980. de = 1.0-((val-coeffi)*0.005*cx);
  117981. /* pro-rated attenuation:
  117982. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117983. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117984. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117985. etc... */
  117986. if(de < 0) de = 0.0001;
  117987. }else
  117988. /* mdct value is <= -17.2 dB below floor */
  117989. de = 1.0-((val-coeffi)*0.0003*cx);
  117990. /* pro-rated attenuation:
  117991. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117992. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117993. etc... */
  117994. mdct[i] *= de;
  117995. }
  117996. }
  117997. }
  117998. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117999. vorbis_info *vi=vd->vi;
  118000. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  118001. vorbis_info_psy_global *gi=&ci->psy_g_param;
  118002. int n=ci->blocksizes[vd->W]/2;
  118003. float secs=(float)n/vi->rate;
  118004. amp+=secs*gi->ampmax_att_per_sec;
  118005. if(amp<-9999)amp=-9999;
  118006. return(amp);
  118007. }
  118008. static void couple_lossless(float A, float B,
  118009. float *qA, float *qB){
  118010. int test1=fabs(*qA)>fabs(*qB);
  118011. test1-= fabs(*qA)<fabs(*qB);
  118012. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  118013. if(test1==1){
  118014. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  118015. }else{
  118016. float temp=*qB;
  118017. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  118018. *qA=temp;
  118019. }
  118020. if(*qB>fabs(*qA)*1.9999f){
  118021. *qB= -fabs(*qA)*2.f;
  118022. *qA= -*qA;
  118023. }
  118024. }
  118025. static float hypot_lookup[32]={
  118026. -0.009935, -0.011245, -0.012726, -0.014397,
  118027. -0.016282, -0.018407, -0.020800, -0.023494,
  118028. -0.026522, -0.029923, -0.033737, -0.038010,
  118029. -0.042787, -0.048121, -0.054064, -0.060671,
  118030. -0.068000, -0.076109, -0.085054, -0.094892,
  118031. -0.105675, -0.117451, -0.130260, -0.144134,
  118032. -0.159093, -0.175146, -0.192286, -0.210490,
  118033. -0.229718, -0.249913, -0.271001, -0.292893};
  118034. static void precomputed_couple_point(float premag,
  118035. int floorA,int floorB,
  118036. float *mag, float *ang){
  118037. int test=(floorA>floorB)-1;
  118038. int offset=31-abs(floorA-floorB);
  118039. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  118040. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  118041. *mag=premag*floormag;
  118042. *ang=0.f;
  118043. }
  118044. /* just like below, this is currently set up to only do
  118045. single-step-depth coupling. Otherwise, we'd have to do more
  118046. copying (which will be inevitable later) */
  118047. /* doing the real circular magnitude calculation is audibly superior
  118048. to (A+B)/sqrt(2) */
  118049. static float dipole_hypot(float a, float b){
  118050. if(a>0.){
  118051. if(b>0.)return sqrt(a*a+b*b);
  118052. if(a>-b)return sqrt(a*a-b*b);
  118053. return -sqrt(b*b-a*a);
  118054. }
  118055. if(b<0.)return -sqrt(a*a+b*b);
  118056. if(-a>b)return -sqrt(a*a-b*b);
  118057. return sqrt(b*b-a*a);
  118058. }
  118059. static float round_hypot(float a, float b){
  118060. if(a>0.){
  118061. if(b>0.)return sqrt(a*a+b*b);
  118062. if(a>-b)return sqrt(a*a+b*b);
  118063. return -sqrt(b*b+a*a);
  118064. }
  118065. if(b<0.)return -sqrt(a*a+b*b);
  118066. if(-a>b)return -sqrt(a*a+b*b);
  118067. return sqrt(b*b+a*a);
  118068. }
  118069. /* revert to round hypot for now */
  118070. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118071. vorbis_info_psy_global *g,
  118072. vorbis_look_psy *p,
  118073. vorbis_info_mapping0 *vi,
  118074. float **mdct){
  118075. int i,j,n=p->n;
  118076. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118077. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118078. for(i=0;i<vi->coupling_steps;i++){
  118079. float *mdctM=mdct[vi->coupling_mag[i]];
  118080. float *mdctA=mdct[vi->coupling_ang[i]];
  118081. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118082. for(j=0;j<limit;j++)
  118083. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118084. for(;j<n;j++)
  118085. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118086. }
  118087. return(ret);
  118088. }
  118089. /* this is for per-channel noise normalization */
  118090. static int JUCE_CDECL apsort(const void *a, const void *b){
  118091. float f1=fabs(**(float**)a);
  118092. float f2=fabs(**(float**)b);
  118093. return (f1<f2)-(f1>f2);
  118094. }
  118095. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118096. vorbis_look_psy *p,
  118097. vorbis_info_mapping0 *vi,
  118098. float **mags){
  118099. if(p->vi->normal_point_p){
  118100. int i,j,k,n=p->n;
  118101. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118102. int partition=p->vi->normal_partition;
  118103. float **work=(float**) alloca(sizeof(*work)*partition);
  118104. for(i=0;i<vi->coupling_steps;i++){
  118105. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118106. for(j=0;j<n;j+=partition){
  118107. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118108. qsort(work,partition,sizeof(*work),apsort);
  118109. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118110. }
  118111. }
  118112. return(ret);
  118113. }
  118114. return(NULL);
  118115. }
  118116. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118117. float *magnitudes,int *sortedindex){
  118118. int i,j,n=p->n;
  118119. vorbis_info_psy *vi=p->vi;
  118120. int partition=vi->normal_partition;
  118121. float **work=(float**) alloca(sizeof(*work)*partition);
  118122. int start=vi->normal_start;
  118123. for(j=start;j<n;j+=partition){
  118124. if(j+partition>n)partition=n-j;
  118125. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118126. qsort(work,partition,sizeof(*work),apsort);
  118127. for(i=0;i<partition;i++){
  118128. sortedindex[i+j-start]=work[i]-magnitudes;
  118129. }
  118130. }
  118131. }
  118132. void _vp_noise_normalize(vorbis_look_psy *p,
  118133. float *in,float *out,int *sortedindex){
  118134. int flag=0,i,j=0,n=p->n;
  118135. vorbis_info_psy *vi=p->vi;
  118136. int partition=vi->normal_partition;
  118137. int start=vi->normal_start;
  118138. if(start>n)start=n;
  118139. if(vi->normal_channel_p){
  118140. for(;j<start;j++)
  118141. out[j]=rint(in[j]);
  118142. for(;j+partition<=n;j+=partition){
  118143. float acc=0.;
  118144. int k;
  118145. for(i=j;i<j+partition;i++)
  118146. acc+=in[i]*in[i];
  118147. for(i=0;i<partition;i++){
  118148. k=sortedindex[i+j-start];
  118149. if(in[k]*in[k]>=.25f){
  118150. out[k]=rint(in[k]);
  118151. acc-=in[k]*in[k];
  118152. flag=1;
  118153. }else{
  118154. if(acc<vi->normal_thresh)break;
  118155. out[k]=unitnorm(in[k]);
  118156. acc-=1.;
  118157. }
  118158. }
  118159. for(;i<partition;i++){
  118160. k=sortedindex[i+j-start];
  118161. out[k]=0.;
  118162. }
  118163. }
  118164. }
  118165. for(;j<n;j++)
  118166. out[j]=rint(in[j]);
  118167. }
  118168. void _vp_couple(int blobno,
  118169. vorbis_info_psy_global *g,
  118170. vorbis_look_psy *p,
  118171. vorbis_info_mapping0 *vi,
  118172. float **res,
  118173. float **mag_memo,
  118174. int **mag_sort,
  118175. int **ifloor,
  118176. int *nonzero,
  118177. int sliding_lowpass){
  118178. int i,j,k,n=p->n;
  118179. /* perform any requested channel coupling */
  118180. /* point stereo can only be used in a first stage (in this encoder)
  118181. because of the dependency on floor lookups */
  118182. for(i=0;i<vi->coupling_steps;i++){
  118183. /* once we're doing multistage coupling in which a channel goes
  118184. through more than one coupling step, the floor vector
  118185. magnitudes will also have to be recalculated an propogated
  118186. along with PCM. Right now, we're not (that will wait until 5.1
  118187. most likely), so the code isn't here yet. The memory management
  118188. here is all assuming single depth couplings anyway. */
  118189. /* make sure coupling a zero and a nonzero channel results in two
  118190. nonzero channels. */
  118191. if(nonzero[vi->coupling_mag[i]] ||
  118192. nonzero[vi->coupling_ang[i]]){
  118193. float *rM=res[vi->coupling_mag[i]];
  118194. float *rA=res[vi->coupling_ang[i]];
  118195. float *qM=rM+n;
  118196. float *qA=rA+n;
  118197. int *floorM=ifloor[vi->coupling_mag[i]];
  118198. int *floorA=ifloor[vi->coupling_ang[i]];
  118199. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118200. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118201. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118202. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118203. int pointlimit=limit;
  118204. nonzero[vi->coupling_mag[i]]=1;
  118205. nonzero[vi->coupling_ang[i]]=1;
  118206. /* The threshold of a stereo is changed with the size of n */
  118207. if(n > 1000)
  118208. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118209. for(j=0;j<p->n;j+=partition){
  118210. float acc=0.f;
  118211. for(k=0;k<partition;k++){
  118212. int l=k+j;
  118213. if(l<sliding_lowpass){
  118214. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118215. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118216. precomputed_couple_point(mag_memo[i][l],
  118217. floorM[l],floorA[l],
  118218. qM+l,qA+l);
  118219. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118220. }else{
  118221. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118222. }
  118223. }else{
  118224. qM[l]=0.;
  118225. qA[l]=0.;
  118226. }
  118227. }
  118228. if(p->vi->normal_point_p){
  118229. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118230. int l=mag_sort[i][j+k];
  118231. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118232. qM[l]=unitnorm(qM[l]);
  118233. acc-=1.f;
  118234. }
  118235. }
  118236. }
  118237. }
  118238. }
  118239. }
  118240. }
  118241. /* AoTuV */
  118242. /** @ M2 **
  118243. The boost problem by the combination of noise normalization and point stereo is eased.
  118244. However, this is a temporary patch.
  118245. by Aoyumi @ 2004/04/18
  118246. */
  118247. void hf_reduction(vorbis_info_psy_global *g,
  118248. vorbis_look_psy *p,
  118249. vorbis_info_mapping0 *vi,
  118250. float **mdct){
  118251. int i,j,n=p->n, de=0.3*p->m_val;
  118252. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118253. for(i=0; i<vi->coupling_steps; i++){
  118254. /* for(j=start; j<limit; j++){} // ???*/
  118255. for(j=limit; j<n; j++)
  118256. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118257. }
  118258. }
  118259. #endif
  118260. /*** End of inlined file: psy.c ***/
  118261. /*** Start of inlined file: registry.c ***/
  118262. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118263. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118264. // tasks..
  118265. #if JUCE_MSVC
  118266. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118267. #endif
  118268. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118269. #if JUCE_USE_OGGVORBIS
  118270. /* seems like major overkill now; the backend numbers will grow into
  118271. the infrastructure soon enough */
  118272. extern vorbis_func_floor floor0_exportbundle;
  118273. extern vorbis_func_floor floor1_exportbundle;
  118274. extern vorbis_func_residue residue0_exportbundle;
  118275. extern vorbis_func_residue residue1_exportbundle;
  118276. extern vorbis_func_residue residue2_exportbundle;
  118277. extern vorbis_func_mapping mapping0_exportbundle;
  118278. vorbis_func_floor *_floor_P[]={
  118279. &floor0_exportbundle,
  118280. &floor1_exportbundle,
  118281. };
  118282. vorbis_func_residue *_residue_P[]={
  118283. &residue0_exportbundle,
  118284. &residue1_exportbundle,
  118285. &residue2_exportbundle,
  118286. };
  118287. vorbis_func_mapping *_mapping_P[]={
  118288. &mapping0_exportbundle,
  118289. };
  118290. #endif
  118291. /*** End of inlined file: registry.c ***/
  118292. /*** Start of inlined file: res0.c ***/
  118293. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118294. encode/decode loops are coded for clarity and performance is not
  118295. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118296. it's slow. */
  118297. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118298. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118299. // tasks..
  118300. #if JUCE_MSVC
  118301. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118302. #endif
  118303. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118304. #if JUCE_USE_OGGVORBIS
  118305. #include <stdlib.h>
  118306. #include <string.h>
  118307. #include <math.h>
  118308. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118309. #include <stdio.h>
  118310. #endif
  118311. typedef struct {
  118312. vorbis_info_residue0 *info;
  118313. int parts;
  118314. int stages;
  118315. codebook *fullbooks;
  118316. codebook *phrasebook;
  118317. codebook ***partbooks;
  118318. int partvals;
  118319. int **decodemap;
  118320. long postbits;
  118321. long phrasebits;
  118322. long frames;
  118323. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118324. int train_seq;
  118325. long *training_data[8][64];
  118326. float training_max[8][64];
  118327. float training_min[8][64];
  118328. float tmin;
  118329. float tmax;
  118330. #endif
  118331. } vorbis_look_residue0;
  118332. void res0_free_info(vorbis_info_residue *i){
  118333. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118334. if(info){
  118335. memset(info,0,sizeof(*info));
  118336. _ogg_free(info);
  118337. }
  118338. }
  118339. void res0_free_look(vorbis_look_residue *i){
  118340. int j;
  118341. if(i){
  118342. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118343. #ifdef TRAIN_RES
  118344. {
  118345. int j,k,l;
  118346. for(j=0;j<look->parts;j++){
  118347. /*fprintf(stderr,"partition %d: ",j);*/
  118348. for(k=0;k<8;k++)
  118349. if(look->training_data[k][j]){
  118350. char buffer[80];
  118351. FILE *of;
  118352. codebook *statebook=look->partbooks[j][k];
  118353. /* long and short into the same bucket by current convention */
  118354. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118355. of=fopen(buffer,"a");
  118356. for(l=0;l<statebook->entries;l++)
  118357. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118358. fclose(of);
  118359. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118360. look->training_min[k][j],look->training_max[k][j]);*/
  118361. _ogg_free(look->training_data[k][j]);
  118362. look->training_data[k][j]=NULL;
  118363. }
  118364. /*fprintf(stderr,"\n");*/
  118365. }
  118366. }
  118367. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118368. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118369. (float)look->phrasebits/look->frames,
  118370. (float)look->postbits/look->frames,
  118371. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118372. #endif
  118373. /*vorbis_info_residue0 *info=look->info;
  118374. fprintf(stderr,
  118375. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118376. "(%g/frame) \n",look->frames,look->phrasebits,
  118377. look->resbitsflat,
  118378. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118379. for(j=0;j<look->parts;j++){
  118380. long acc=0;
  118381. fprintf(stderr,"\t[%d] == ",j);
  118382. for(k=0;k<look->stages;k++)
  118383. if((info->secondstages[j]>>k)&1){
  118384. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118385. acc+=look->resbits[j][k];
  118386. }
  118387. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118388. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118389. }
  118390. fprintf(stderr,"\n");*/
  118391. for(j=0;j<look->parts;j++)
  118392. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118393. _ogg_free(look->partbooks);
  118394. for(j=0;j<look->partvals;j++)
  118395. _ogg_free(look->decodemap[j]);
  118396. _ogg_free(look->decodemap);
  118397. memset(look,0,sizeof(*look));
  118398. _ogg_free(look);
  118399. }
  118400. }
  118401. static int icount(unsigned int v){
  118402. int ret=0;
  118403. while(v){
  118404. ret+=v&1;
  118405. v>>=1;
  118406. }
  118407. return(ret);
  118408. }
  118409. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118410. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118411. int j,acc=0;
  118412. oggpack_write(opb,info->begin,24);
  118413. oggpack_write(opb,info->end,24);
  118414. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118415. code with a partitioned book */
  118416. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118417. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118418. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118419. bitmask of one indicates this partition class has bits to write
  118420. this pass */
  118421. for(j=0;j<info->partitions;j++){
  118422. if(ilog(info->secondstages[j])>3){
  118423. /* yes, this is a minor hack due to not thinking ahead */
  118424. oggpack_write(opb,info->secondstages[j],3);
  118425. oggpack_write(opb,1,1);
  118426. oggpack_write(opb,info->secondstages[j]>>3,5);
  118427. }else
  118428. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118429. acc+=icount(info->secondstages[j]);
  118430. }
  118431. for(j=0;j<acc;j++)
  118432. oggpack_write(opb,info->booklist[j],8);
  118433. }
  118434. /* vorbis_info is for range checking */
  118435. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118436. int j,acc=0;
  118437. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118438. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118439. info->begin=oggpack_read(opb,24);
  118440. info->end=oggpack_read(opb,24);
  118441. info->grouping=oggpack_read(opb,24)+1;
  118442. info->partitions=oggpack_read(opb,6)+1;
  118443. info->groupbook=oggpack_read(opb,8);
  118444. for(j=0;j<info->partitions;j++){
  118445. int cascade=oggpack_read(opb,3);
  118446. if(oggpack_read(opb,1))
  118447. cascade|=(oggpack_read(opb,5)<<3);
  118448. info->secondstages[j]=cascade;
  118449. acc+=icount(cascade);
  118450. }
  118451. for(j=0;j<acc;j++)
  118452. info->booklist[j]=oggpack_read(opb,8);
  118453. if(info->groupbook>=ci->books)goto errout;
  118454. for(j=0;j<acc;j++)
  118455. if(info->booklist[j]>=ci->books)goto errout;
  118456. return(info);
  118457. errout:
  118458. res0_free_info(info);
  118459. return(NULL);
  118460. }
  118461. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118462. vorbis_info_residue *vr){
  118463. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118464. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118465. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118466. int j,k,acc=0;
  118467. int dim;
  118468. int maxstage=0;
  118469. look->info=info;
  118470. look->parts=info->partitions;
  118471. look->fullbooks=ci->fullbooks;
  118472. look->phrasebook=ci->fullbooks+info->groupbook;
  118473. dim=look->phrasebook->dim;
  118474. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118475. for(j=0;j<look->parts;j++){
  118476. int stages=ilog(info->secondstages[j]);
  118477. if(stages){
  118478. if(stages>maxstage)maxstage=stages;
  118479. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118480. for(k=0;k<stages;k++)
  118481. if(info->secondstages[j]&(1<<k)){
  118482. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118483. #ifdef TRAIN_RES
  118484. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118485. sizeof(***look->training_data));
  118486. #endif
  118487. }
  118488. }
  118489. }
  118490. look->partvals=rint(pow((float)look->parts,(float)dim));
  118491. look->stages=maxstage;
  118492. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118493. for(j=0;j<look->partvals;j++){
  118494. long val=j;
  118495. long mult=look->partvals/look->parts;
  118496. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118497. for(k=0;k<dim;k++){
  118498. long deco=val/mult;
  118499. val-=deco*mult;
  118500. mult/=look->parts;
  118501. look->decodemap[j][k]=deco;
  118502. }
  118503. }
  118504. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118505. {
  118506. static int train_seq=0;
  118507. look->train_seq=train_seq++;
  118508. }
  118509. #endif
  118510. return(look);
  118511. }
  118512. /* break an abstraction and copy some code for performance purposes */
  118513. static int local_book_besterror(codebook *book,float *a){
  118514. int dim=book->dim,i,k,o;
  118515. int best=0;
  118516. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118517. /* find the quant val of each scalar */
  118518. for(k=0,o=dim;k<dim;++k){
  118519. float val=a[--o];
  118520. i=tt->threshvals>>1;
  118521. if(val<tt->quantthresh[i]){
  118522. if(val<tt->quantthresh[i-1]){
  118523. for(--i;i>0;--i)
  118524. if(val>=tt->quantthresh[i-1])
  118525. break;
  118526. }
  118527. }else{
  118528. for(++i;i<tt->threshvals-1;++i)
  118529. if(val<tt->quantthresh[i])break;
  118530. }
  118531. best=(best*tt->quantvals)+tt->quantmap[i];
  118532. }
  118533. /* regular lattices are easy :-) */
  118534. if(book->c->lengthlist[best]<=0){
  118535. const static_codebook *c=book->c;
  118536. int i,j;
  118537. float bestf=0.f;
  118538. float *e=book->valuelist;
  118539. best=-1;
  118540. for(i=0;i<book->entries;i++){
  118541. if(c->lengthlist[i]>0){
  118542. float thisx=0.f;
  118543. for(j=0;j<dim;j++){
  118544. float val=(e[j]-a[j]);
  118545. thisx+=val*val;
  118546. }
  118547. if(best==-1 || thisx<bestf){
  118548. bestf=thisx;
  118549. best=i;
  118550. }
  118551. }
  118552. e+=dim;
  118553. }
  118554. }
  118555. {
  118556. float *ptr=book->valuelist+best*dim;
  118557. for(i=0;i<dim;i++)
  118558. *a++ -= *ptr++;
  118559. }
  118560. return(best);
  118561. }
  118562. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118563. codebook *book,long *acc){
  118564. int i,bits=0;
  118565. int dim=book->dim;
  118566. int step=n/dim;
  118567. for(i=0;i<step;i++){
  118568. int entry=local_book_besterror(book,vec+i*dim);
  118569. #ifdef TRAIN_RES
  118570. acc[entry]++;
  118571. #endif
  118572. bits+=vorbis_book_encode(book,entry,opb);
  118573. }
  118574. return(bits);
  118575. }
  118576. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118577. float **in,int ch){
  118578. long i,j,k;
  118579. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118580. vorbis_info_residue0 *info=look->info;
  118581. /* move all this setup out later */
  118582. int samples_per_partition=info->grouping;
  118583. int possible_partitions=info->partitions;
  118584. int n=info->end-info->begin;
  118585. int partvals=n/samples_per_partition;
  118586. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118587. float scale=100./samples_per_partition;
  118588. /* we find the partition type for each partition of each
  118589. channel. We'll go back and do the interleaved encoding in a
  118590. bit. For now, clarity */
  118591. for(i=0;i<ch;i++){
  118592. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118593. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118594. }
  118595. for(i=0;i<partvals;i++){
  118596. int offset=i*samples_per_partition+info->begin;
  118597. for(j=0;j<ch;j++){
  118598. float max=0.;
  118599. float ent=0.;
  118600. for(k=0;k<samples_per_partition;k++){
  118601. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118602. ent+=fabs(rint(in[j][offset+k]));
  118603. }
  118604. ent*=scale;
  118605. for(k=0;k<possible_partitions-1;k++)
  118606. if(max<=info->classmetric1[k] &&
  118607. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118608. break;
  118609. partword[j][i]=k;
  118610. }
  118611. }
  118612. #ifdef TRAIN_RESAUX
  118613. {
  118614. FILE *of;
  118615. char buffer[80];
  118616. for(i=0;i<ch;i++){
  118617. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118618. of=fopen(buffer,"a");
  118619. for(j=0;j<partvals;j++)
  118620. fprintf(of,"%ld, ",partword[i][j]);
  118621. fprintf(of,"\n");
  118622. fclose(of);
  118623. }
  118624. }
  118625. #endif
  118626. look->frames++;
  118627. return(partword);
  118628. }
  118629. /* designed for stereo or other modes where the partition size is an
  118630. integer multiple of the number of channels encoded in the current
  118631. submap */
  118632. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118633. int ch){
  118634. long i,j,k,l;
  118635. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118636. vorbis_info_residue0 *info=look->info;
  118637. /* move all this setup out later */
  118638. int samples_per_partition=info->grouping;
  118639. int possible_partitions=info->partitions;
  118640. int n=info->end-info->begin;
  118641. int partvals=n/samples_per_partition;
  118642. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118643. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118644. FILE *of;
  118645. char buffer[80];
  118646. #endif
  118647. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118648. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118649. for(i=0,l=info->begin/ch;i<partvals;i++){
  118650. float magmax=0.f;
  118651. float angmax=0.f;
  118652. for(j=0;j<samples_per_partition;j+=ch){
  118653. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118654. for(k=1;k<ch;k++)
  118655. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118656. l++;
  118657. }
  118658. for(j=0;j<possible_partitions-1;j++)
  118659. if(magmax<=info->classmetric1[j] &&
  118660. angmax<=info->classmetric2[j])
  118661. break;
  118662. partword[0][i]=j;
  118663. }
  118664. #ifdef TRAIN_RESAUX
  118665. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118666. of=fopen(buffer,"a");
  118667. for(i=0;i<partvals;i++)
  118668. fprintf(of,"%ld, ",partword[0][i]);
  118669. fprintf(of,"\n");
  118670. fclose(of);
  118671. #endif
  118672. look->frames++;
  118673. return(partword);
  118674. }
  118675. static int _01forward(oggpack_buffer *opb,
  118676. vorbis_block *vb,vorbis_look_residue *vl,
  118677. float **in,int ch,
  118678. long **partword,
  118679. int (*encode)(oggpack_buffer *,float *,int,
  118680. codebook *,long *)){
  118681. long i,j,k,s;
  118682. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118683. vorbis_info_residue0 *info=look->info;
  118684. /* move all this setup out later */
  118685. int samples_per_partition=info->grouping;
  118686. int possible_partitions=info->partitions;
  118687. int partitions_per_word=look->phrasebook->dim;
  118688. int n=info->end-info->begin;
  118689. int partvals=n/samples_per_partition;
  118690. long resbits[128];
  118691. long resvals[128];
  118692. #ifdef TRAIN_RES
  118693. for(i=0;i<ch;i++)
  118694. for(j=info->begin;j<info->end;j++){
  118695. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118696. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118697. }
  118698. #endif
  118699. memset(resbits,0,sizeof(resbits));
  118700. memset(resvals,0,sizeof(resvals));
  118701. /* we code the partition words for each channel, then the residual
  118702. words for a partition per channel until we've written all the
  118703. residual words for that partition word. Then write the next
  118704. partition channel words... */
  118705. for(s=0;s<look->stages;s++){
  118706. for(i=0;i<partvals;){
  118707. /* first we encode a partition codeword for each channel */
  118708. if(s==0){
  118709. for(j=0;j<ch;j++){
  118710. long val=partword[j][i];
  118711. for(k=1;k<partitions_per_word;k++){
  118712. val*=possible_partitions;
  118713. if(i+k<partvals)
  118714. val+=partword[j][i+k];
  118715. }
  118716. /* training hack */
  118717. if(val<look->phrasebook->entries)
  118718. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118719. #if 0 /*def TRAIN_RES*/
  118720. else
  118721. fprintf(stderr,"!");
  118722. #endif
  118723. }
  118724. }
  118725. /* now we encode interleaved residual values for the partitions */
  118726. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118727. long offset=i*samples_per_partition+info->begin;
  118728. for(j=0;j<ch;j++){
  118729. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118730. if(info->secondstages[partword[j][i]]&(1<<s)){
  118731. codebook *statebook=look->partbooks[partword[j][i]][s];
  118732. if(statebook){
  118733. int ret;
  118734. long *accumulator=NULL;
  118735. #ifdef TRAIN_RES
  118736. accumulator=look->training_data[s][partword[j][i]];
  118737. {
  118738. int l;
  118739. float *samples=in[j]+offset;
  118740. for(l=0;l<samples_per_partition;l++){
  118741. if(samples[l]<look->training_min[s][partword[j][i]])
  118742. look->training_min[s][partword[j][i]]=samples[l];
  118743. if(samples[l]>look->training_max[s][partword[j][i]])
  118744. look->training_max[s][partword[j][i]]=samples[l];
  118745. }
  118746. }
  118747. #endif
  118748. ret=encode(opb,in[j]+offset,samples_per_partition,
  118749. statebook,accumulator);
  118750. look->postbits+=ret;
  118751. resbits[partword[j][i]]+=ret;
  118752. }
  118753. }
  118754. }
  118755. }
  118756. }
  118757. }
  118758. /*{
  118759. long total=0;
  118760. long totalbits=0;
  118761. fprintf(stderr,"%d :: ",vb->mode);
  118762. for(k=0;k<possible_partitions;k++){
  118763. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118764. total+=resvals[k];
  118765. totalbits+=resbits[k];
  118766. }
  118767. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118768. }*/
  118769. return(0);
  118770. }
  118771. /* a truncated packet here just means 'stop working'; it's not an error */
  118772. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118773. float **in,int ch,
  118774. long (*decodepart)(codebook *, float *,
  118775. oggpack_buffer *,int)){
  118776. long i,j,k,l,s;
  118777. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118778. vorbis_info_residue0 *info=look->info;
  118779. /* move all this setup out later */
  118780. int samples_per_partition=info->grouping;
  118781. int partitions_per_word=look->phrasebook->dim;
  118782. int n=info->end-info->begin;
  118783. int partvals=n/samples_per_partition;
  118784. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118785. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118786. for(j=0;j<ch;j++)
  118787. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118788. for(s=0;s<look->stages;s++){
  118789. /* each loop decodes on partition codeword containing
  118790. partitions_pre_word partitions */
  118791. for(i=0,l=0;i<partvals;l++){
  118792. if(s==0){
  118793. /* fetch the partition word for each channel */
  118794. for(j=0;j<ch;j++){
  118795. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118796. if(temp==-1)goto eopbreak;
  118797. partword[j][l]=look->decodemap[temp];
  118798. if(partword[j][l]==NULL)goto errout;
  118799. }
  118800. }
  118801. /* now we decode residual values for the partitions */
  118802. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118803. for(j=0;j<ch;j++){
  118804. long offset=info->begin+i*samples_per_partition;
  118805. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118806. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118807. if(stagebook){
  118808. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118809. samples_per_partition)==-1)goto eopbreak;
  118810. }
  118811. }
  118812. }
  118813. }
  118814. }
  118815. errout:
  118816. eopbreak:
  118817. return(0);
  118818. }
  118819. #if 0
  118820. /* residue 0 and 1 are just slight variants of one another. 0 is
  118821. interleaved, 1 is not */
  118822. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118823. float **in,int *nonzero,int ch){
  118824. /* we encode only the nonzero parts of a bundle */
  118825. int i,used=0;
  118826. for(i=0;i<ch;i++)
  118827. if(nonzero[i])
  118828. in[used++]=in[i];
  118829. if(used)
  118830. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118831. return(_01class(vb,vl,in,used));
  118832. else
  118833. return(0);
  118834. }
  118835. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118836. float **in,float **out,int *nonzero,int ch,
  118837. long **partword){
  118838. /* we encode only the nonzero parts of a bundle */
  118839. int i,j,used=0,n=vb->pcmend/2;
  118840. for(i=0;i<ch;i++)
  118841. if(nonzero[i]){
  118842. if(out)
  118843. for(j=0;j<n;j++)
  118844. out[i][j]+=in[i][j];
  118845. in[used++]=in[i];
  118846. }
  118847. if(used){
  118848. int ret=_01forward(vb,vl,in,used,partword,
  118849. _interleaved_encodepart);
  118850. if(out){
  118851. used=0;
  118852. for(i=0;i<ch;i++)
  118853. if(nonzero[i]){
  118854. for(j=0;j<n;j++)
  118855. out[i][j]-=in[used][j];
  118856. used++;
  118857. }
  118858. }
  118859. return(ret);
  118860. }else{
  118861. return(0);
  118862. }
  118863. }
  118864. #endif
  118865. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118866. float **in,int *nonzero,int ch){
  118867. int i,used=0;
  118868. for(i=0;i<ch;i++)
  118869. if(nonzero[i])
  118870. in[used++]=in[i];
  118871. if(used)
  118872. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118873. else
  118874. return(0);
  118875. }
  118876. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118877. float **in,float **out,int *nonzero,int ch,
  118878. long **partword){
  118879. int i,j,used=0,n=vb->pcmend/2;
  118880. for(i=0;i<ch;i++)
  118881. if(nonzero[i]){
  118882. if(out)
  118883. for(j=0;j<n;j++)
  118884. out[i][j]+=in[i][j];
  118885. in[used++]=in[i];
  118886. }
  118887. if(used){
  118888. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118889. if(out){
  118890. used=0;
  118891. for(i=0;i<ch;i++)
  118892. if(nonzero[i]){
  118893. for(j=0;j<n;j++)
  118894. out[i][j]-=in[used][j];
  118895. used++;
  118896. }
  118897. }
  118898. return(ret);
  118899. }else{
  118900. return(0);
  118901. }
  118902. }
  118903. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118904. float **in,int *nonzero,int ch){
  118905. int i,used=0;
  118906. for(i=0;i<ch;i++)
  118907. if(nonzero[i])
  118908. in[used++]=in[i];
  118909. if(used)
  118910. return(_01class(vb,vl,in,used));
  118911. else
  118912. return(0);
  118913. }
  118914. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118915. float **in,int *nonzero,int ch){
  118916. int i,used=0;
  118917. for(i=0;i<ch;i++)
  118918. if(nonzero[i])
  118919. in[used++]=in[i];
  118920. if(used)
  118921. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118922. else
  118923. return(0);
  118924. }
  118925. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118926. float **in,int *nonzero,int ch){
  118927. int i,used=0;
  118928. for(i=0;i<ch;i++)
  118929. if(nonzero[i])used++;
  118930. if(used)
  118931. return(_2class(vb,vl,in,ch));
  118932. else
  118933. return(0);
  118934. }
  118935. /* res2 is slightly more different; all the channels are interleaved
  118936. into a single vector and encoded. */
  118937. int res2_forward(oggpack_buffer *opb,
  118938. vorbis_block *vb,vorbis_look_residue *vl,
  118939. float **in,float **out,int *nonzero,int ch,
  118940. long **partword){
  118941. long i,j,k,n=vb->pcmend/2,used=0;
  118942. /* don't duplicate the code; use a working vector hack for now and
  118943. reshape ourselves into a single channel res1 */
  118944. /* ugly; reallocs for each coupling pass :-( */
  118945. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118946. for(i=0;i<ch;i++){
  118947. float *pcm=in[i];
  118948. if(nonzero[i])used++;
  118949. for(j=0,k=i;j<n;j++,k+=ch)
  118950. work[k]=pcm[j];
  118951. }
  118952. if(used){
  118953. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118954. /* update the sofar vector */
  118955. if(out){
  118956. for(i=0;i<ch;i++){
  118957. float *pcm=in[i];
  118958. float *sofar=out[i];
  118959. for(j=0,k=i;j<n;j++,k+=ch)
  118960. sofar[j]+=pcm[j]-work[k];
  118961. }
  118962. }
  118963. return(ret);
  118964. }else{
  118965. return(0);
  118966. }
  118967. }
  118968. /* duplicate code here as speed is somewhat more important */
  118969. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118970. float **in,int *nonzero,int ch){
  118971. long i,k,l,s;
  118972. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118973. vorbis_info_residue0 *info=look->info;
  118974. /* move all this setup out later */
  118975. int samples_per_partition=info->grouping;
  118976. int partitions_per_word=look->phrasebook->dim;
  118977. int n=info->end-info->begin;
  118978. int partvals=n/samples_per_partition;
  118979. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118980. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118981. for(i=0;i<ch;i++)if(nonzero[i])break;
  118982. if(i==ch)return(0); /* no nonzero vectors */
  118983. for(s=0;s<look->stages;s++){
  118984. for(i=0,l=0;i<partvals;l++){
  118985. if(s==0){
  118986. /* fetch the partition word */
  118987. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118988. if(temp==-1)goto eopbreak;
  118989. partword[l]=look->decodemap[temp];
  118990. if(partword[l]==NULL)goto errout;
  118991. }
  118992. /* now we decode residual values for the partitions */
  118993. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118994. if(info->secondstages[partword[l][k]]&(1<<s)){
  118995. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118996. if(stagebook){
  118997. if(vorbis_book_decodevv_add(stagebook,in,
  118998. i*samples_per_partition+info->begin,ch,
  118999. &vb->opb,samples_per_partition)==-1)
  119000. goto eopbreak;
  119001. }
  119002. }
  119003. }
  119004. }
  119005. errout:
  119006. eopbreak:
  119007. return(0);
  119008. }
  119009. vorbis_func_residue residue0_exportbundle={
  119010. NULL,
  119011. &res0_unpack,
  119012. &res0_look,
  119013. &res0_free_info,
  119014. &res0_free_look,
  119015. NULL,
  119016. NULL,
  119017. &res0_inverse
  119018. };
  119019. vorbis_func_residue residue1_exportbundle={
  119020. &res0_pack,
  119021. &res0_unpack,
  119022. &res0_look,
  119023. &res0_free_info,
  119024. &res0_free_look,
  119025. &res1_class,
  119026. &res1_forward,
  119027. &res1_inverse
  119028. };
  119029. vorbis_func_residue residue2_exportbundle={
  119030. &res0_pack,
  119031. &res0_unpack,
  119032. &res0_look,
  119033. &res0_free_info,
  119034. &res0_free_look,
  119035. &res2_class,
  119036. &res2_forward,
  119037. &res2_inverse
  119038. };
  119039. #endif
  119040. /*** End of inlined file: res0.c ***/
  119041. /*** Start of inlined file: sharedbook.c ***/
  119042. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119043. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119044. // tasks..
  119045. #if JUCE_MSVC
  119046. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119047. #endif
  119048. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119049. #if JUCE_USE_OGGVORBIS
  119050. #include <stdlib.h>
  119051. #include <math.h>
  119052. #include <string.h>
  119053. /**** pack/unpack helpers ******************************************/
  119054. int _ilog(unsigned int v){
  119055. int ret=0;
  119056. while(v){
  119057. ret++;
  119058. v>>=1;
  119059. }
  119060. return(ret);
  119061. }
  119062. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119063. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119064. Why not IEEE? It's just not that important here. */
  119065. #define VQ_FEXP 10
  119066. #define VQ_FMAN 21
  119067. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119068. /* doesn't currently guard under/overflow */
  119069. long _float32_pack(float val){
  119070. int sign=0;
  119071. long exp;
  119072. long mant;
  119073. if(val<0){
  119074. sign=0x80000000;
  119075. val= -val;
  119076. }
  119077. exp= floor(log(val)/log(2.f));
  119078. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119079. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119080. return(sign|exp|mant);
  119081. }
  119082. float _float32_unpack(long val){
  119083. double mant=val&0x1fffff;
  119084. int sign=val&0x80000000;
  119085. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119086. if(sign)mant= -mant;
  119087. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119088. }
  119089. /* given a list of word lengths, generate a list of codewords. Works
  119090. for length ordered or unordered, always assigns the lowest valued
  119091. codewords first. Extended to handle unused entries (length 0) */
  119092. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119093. long i,j,count=0;
  119094. ogg_uint32_t marker[33];
  119095. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119096. memset(marker,0,sizeof(marker));
  119097. for(i=0;i<n;i++){
  119098. long length=l[i];
  119099. if(length>0){
  119100. ogg_uint32_t entry=marker[length];
  119101. /* when we claim a node for an entry, we also claim the nodes
  119102. below it (pruning off the imagined tree that may have dangled
  119103. from it) as well as blocking the use of any nodes directly
  119104. above for leaves */
  119105. /* update ourself */
  119106. if(length<32 && (entry>>length)){
  119107. /* error condition; the lengths must specify an overpopulated tree */
  119108. _ogg_free(r);
  119109. return(NULL);
  119110. }
  119111. r[count++]=entry;
  119112. /* Look to see if the next shorter marker points to the node
  119113. above. if so, update it and repeat. */
  119114. {
  119115. for(j=length;j>0;j--){
  119116. if(marker[j]&1){
  119117. /* have to jump branches */
  119118. if(j==1)
  119119. marker[1]++;
  119120. else
  119121. marker[j]=marker[j-1]<<1;
  119122. break; /* invariant says next upper marker would already
  119123. have been moved if it was on the same path */
  119124. }
  119125. marker[j]++;
  119126. }
  119127. }
  119128. /* prune the tree; the implicit invariant says all the longer
  119129. markers were dangling from our just-taken node. Dangle them
  119130. from our *new* node. */
  119131. for(j=length+1;j<33;j++)
  119132. if((marker[j]>>1) == entry){
  119133. entry=marker[j];
  119134. marker[j]=marker[j-1]<<1;
  119135. }else
  119136. break;
  119137. }else
  119138. if(sparsecount==0)count++;
  119139. }
  119140. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119141. endian */
  119142. for(i=0,count=0;i<n;i++){
  119143. ogg_uint32_t temp=0;
  119144. for(j=0;j<l[i];j++){
  119145. temp<<=1;
  119146. temp|=(r[count]>>j)&1;
  119147. }
  119148. if(sparsecount){
  119149. if(l[i])
  119150. r[count++]=temp;
  119151. }else
  119152. r[count++]=temp;
  119153. }
  119154. return(r);
  119155. }
  119156. /* there might be a straightforward one-line way to do the below
  119157. that's portable and totally safe against roundoff, but I haven't
  119158. thought of it. Therefore, we opt on the side of caution */
  119159. long _book_maptype1_quantvals(const static_codebook *b){
  119160. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119161. /* the above *should* be reliable, but we'll not assume that FP is
  119162. ever reliable when bitstream sync is at stake; verify via integer
  119163. means that vals really is the greatest value of dim for which
  119164. vals^b->bim <= b->entries */
  119165. /* treat the above as an initial guess */
  119166. while(1){
  119167. long acc=1;
  119168. long acc1=1;
  119169. int i;
  119170. for(i=0;i<b->dim;i++){
  119171. acc*=vals;
  119172. acc1*=vals+1;
  119173. }
  119174. if(acc<=b->entries && acc1>b->entries){
  119175. return(vals);
  119176. }else{
  119177. if(acc>b->entries){
  119178. vals--;
  119179. }else{
  119180. vals++;
  119181. }
  119182. }
  119183. }
  119184. }
  119185. /* unpack the quantized list of values for encode/decode ***********/
  119186. /* we need to deal with two map types: in map type 1, the values are
  119187. generated algorithmically (each column of the vector counts through
  119188. the values in the quant vector). in map type 2, all the values came
  119189. in in an explicit list. Both value lists must be unpacked */
  119190. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119191. long j,k,count=0;
  119192. if(b->maptype==1 || b->maptype==2){
  119193. int quantvals;
  119194. float mindel=_float32_unpack(b->q_min);
  119195. float delta=_float32_unpack(b->q_delta);
  119196. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119197. /* maptype 1 and 2 both use a quantized value vector, but
  119198. different sizes */
  119199. switch(b->maptype){
  119200. case 1:
  119201. /* most of the time, entries%dimensions == 0, but we need to be
  119202. well defined. We define that the possible vales at each
  119203. scalar is values == entries/dim. If entries%dim != 0, we'll
  119204. have 'too few' values (values*dim<entries), which means that
  119205. we'll have 'left over' entries; left over entries use zeroed
  119206. values (and are wasted). So don't generate codebooks like
  119207. that */
  119208. quantvals=_book_maptype1_quantvals(b);
  119209. for(j=0;j<b->entries;j++){
  119210. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119211. float last=0.f;
  119212. int indexdiv=1;
  119213. for(k=0;k<b->dim;k++){
  119214. int index= (j/indexdiv)%quantvals;
  119215. float val=b->quantlist[index];
  119216. val=fabs(val)*delta+mindel+last;
  119217. if(b->q_sequencep)last=val;
  119218. if(sparsemap)
  119219. r[sparsemap[count]*b->dim+k]=val;
  119220. else
  119221. r[count*b->dim+k]=val;
  119222. indexdiv*=quantvals;
  119223. }
  119224. count++;
  119225. }
  119226. }
  119227. break;
  119228. case 2:
  119229. for(j=0;j<b->entries;j++){
  119230. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119231. float last=0.f;
  119232. for(k=0;k<b->dim;k++){
  119233. float val=b->quantlist[j*b->dim+k];
  119234. val=fabs(val)*delta+mindel+last;
  119235. if(b->q_sequencep)last=val;
  119236. if(sparsemap)
  119237. r[sparsemap[count]*b->dim+k]=val;
  119238. else
  119239. r[count*b->dim+k]=val;
  119240. }
  119241. count++;
  119242. }
  119243. }
  119244. break;
  119245. }
  119246. return(r);
  119247. }
  119248. return(NULL);
  119249. }
  119250. void vorbis_staticbook_clear(static_codebook *b){
  119251. if(b->allocedp){
  119252. if(b->quantlist)_ogg_free(b->quantlist);
  119253. if(b->lengthlist)_ogg_free(b->lengthlist);
  119254. if(b->nearest_tree){
  119255. _ogg_free(b->nearest_tree->ptr0);
  119256. _ogg_free(b->nearest_tree->ptr1);
  119257. _ogg_free(b->nearest_tree->p);
  119258. _ogg_free(b->nearest_tree->q);
  119259. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119260. _ogg_free(b->nearest_tree);
  119261. }
  119262. if(b->thresh_tree){
  119263. _ogg_free(b->thresh_tree->quantthresh);
  119264. _ogg_free(b->thresh_tree->quantmap);
  119265. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119266. _ogg_free(b->thresh_tree);
  119267. }
  119268. memset(b,0,sizeof(*b));
  119269. }
  119270. }
  119271. void vorbis_staticbook_destroy(static_codebook *b){
  119272. if(b->allocedp){
  119273. vorbis_staticbook_clear(b);
  119274. _ogg_free(b);
  119275. }
  119276. }
  119277. void vorbis_book_clear(codebook *b){
  119278. /* static book is not cleared; we're likely called on the lookup and
  119279. the static codebook belongs to the info struct */
  119280. if(b->valuelist)_ogg_free(b->valuelist);
  119281. if(b->codelist)_ogg_free(b->codelist);
  119282. if(b->dec_index)_ogg_free(b->dec_index);
  119283. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119284. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119285. memset(b,0,sizeof(*b));
  119286. }
  119287. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119288. memset(c,0,sizeof(*c));
  119289. c->c=s;
  119290. c->entries=s->entries;
  119291. c->used_entries=s->entries;
  119292. c->dim=s->dim;
  119293. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119294. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119295. return(0);
  119296. }
  119297. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119298. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119299. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119300. }
  119301. /* decode codebook arrangement is more heavily optimized than encode */
  119302. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119303. int i,j,n=0,tabn;
  119304. int *sortindex;
  119305. memset(c,0,sizeof(*c));
  119306. /* count actually used entries */
  119307. for(i=0;i<s->entries;i++)
  119308. if(s->lengthlist[i]>0)
  119309. n++;
  119310. c->entries=s->entries;
  119311. c->used_entries=n;
  119312. c->dim=s->dim;
  119313. /* two different remappings go on here.
  119314. First, we collapse the likely sparse codebook down only to
  119315. actually represented values/words. This collapsing needs to be
  119316. indexed as map-valueless books are used to encode original entry
  119317. positions as integers.
  119318. Second, we reorder all vectors, including the entry index above,
  119319. by sorted bitreversed codeword to allow treeless decode. */
  119320. {
  119321. /* perform sort */
  119322. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119323. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119324. if(codes==NULL)goto err_out;
  119325. for(i=0;i<n;i++){
  119326. codes[i]=ogg_bitreverse(codes[i]);
  119327. codep[i]=codes+i;
  119328. }
  119329. qsort(codep,n,sizeof(*codep),sort32a);
  119330. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119331. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119332. /* the index is a reverse index */
  119333. for(i=0;i<n;i++){
  119334. int position=codep[i]-codes;
  119335. sortindex[position]=i;
  119336. }
  119337. for(i=0;i<n;i++)
  119338. c->codelist[sortindex[i]]=codes[i];
  119339. _ogg_free(codes);
  119340. }
  119341. c->valuelist=_book_unquantize(s,n,sortindex);
  119342. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119343. for(n=0,i=0;i<s->entries;i++)
  119344. if(s->lengthlist[i]>0)
  119345. c->dec_index[sortindex[n++]]=i;
  119346. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119347. for(n=0,i=0;i<s->entries;i++)
  119348. if(s->lengthlist[i]>0)
  119349. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119350. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119351. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119352. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119353. tabn=1<<c->dec_firsttablen;
  119354. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119355. c->dec_maxlength=0;
  119356. for(i=0;i<n;i++){
  119357. if(c->dec_maxlength<c->dec_codelengths[i])
  119358. c->dec_maxlength=c->dec_codelengths[i];
  119359. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119360. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119361. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119362. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119363. }
  119364. }
  119365. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119366. hints for the non-direct-hits */
  119367. {
  119368. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119369. long lo=0,hi=0;
  119370. for(i=0;i<tabn;i++){
  119371. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119372. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119373. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119374. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119375. /* we only actually have 15 bits per hint to play with here.
  119376. In order to overflow gracefully (nothing breaks, efficiency
  119377. just drops), encode as the difference from the extremes. */
  119378. {
  119379. unsigned long loval=lo;
  119380. unsigned long hival=n-hi;
  119381. if(loval>0x7fff)loval=0x7fff;
  119382. if(hival>0x7fff)hival=0x7fff;
  119383. c->dec_firsttable[ogg_bitreverse(word)]=
  119384. 0x80000000UL | (loval<<15) | hival;
  119385. }
  119386. }
  119387. }
  119388. }
  119389. return(0);
  119390. err_out:
  119391. vorbis_book_clear(c);
  119392. return(-1);
  119393. }
  119394. static float _dist(int el,float *ref, float *b,int step){
  119395. int i;
  119396. float acc=0.f;
  119397. for(i=0;i<el;i++){
  119398. float val=(ref[i]-b[i*step]);
  119399. acc+=val*val;
  119400. }
  119401. return(acc);
  119402. }
  119403. int _best(codebook *book, float *a, int step){
  119404. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119405. #if 0
  119406. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119407. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119408. #endif
  119409. int dim=book->dim;
  119410. int k,o;
  119411. /*int savebest=-1;
  119412. float saverr;*/
  119413. /* do we have a threshhold encode hint? */
  119414. if(tt){
  119415. int index=0,i;
  119416. /* find the quant val of each scalar */
  119417. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119418. i=tt->threshvals>>1;
  119419. if(a[o]<tt->quantthresh[i]){
  119420. for(;i>0;i--)
  119421. if(a[o]>=tt->quantthresh[i-1])
  119422. break;
  119423. }else{
  119424. for(i++;i<tt->threshvals-1;i++)
  119425. if(a[o]<tt->quantthresh[i])break;
  119426. }
  119427. index=(index*tt->quantvals)+tt->quantmap[i];
  119428. }
  119429. /* regular lattices are easy :-) */
  119430. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119431. use a decision tree after all
  119432. and fall through*/
  119433. return(index);
  119434. }
  119435. #if 0
  119436. /* do we have a pigeonhole encode hint? */
  119437. if(pt){
  119438. const static_codebook *c=book->c;
  119439. int i,besti=-1;
  119440. float best=0.f;
  119441. int entry=0;
  119442. /* dealing with sequentialness is a pain in the ass */
  119443. if(c->q_sequencep){
  119444. int pv;
  119445. long mul=1;
  119446. float qlast=0;
  119447. for(k=0,o=0;k<dim;k++,o+=step){
  119448. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119449. if(pv<0 || pv>=pt->mapentries)break;
  119450. entry+=pt->pigeonmap[pv]*mul;
  119451. mul*=pt->quantvals;
  119452. qlast+=pv*pt->del+pt->min;
  119453. }
  119454. }else{
  119455. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119456. int pv=(int)((a[o]-pt->min)/pt->del);
  119457. if(pv<0 || pv>=pt->mapentries)break;
  119458. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119459. }
  119460. }
  119461. /* must be within the pigeonholable range; if we quant outside (or
  119462. in an entry that we define no list for), brute force it */
  119463. if(k==dim && pt->fitlength[entry]){
  119464. /* search the abbreviated list */
  119465. long *list=pt->fitlist+pt->fitmap[entry];
  119466. for(i=0;i<pt->fitlength[entry];i++){
  119467. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119468. if(besti==-1 || this<best){
  119469. best=this;
  119470. besti=list[i];
  119471. }
  119472. }
  119473. return(besti);
  119474. }
  119475. }
  119476. if(nt){
  119477. /* optimized using the decision tree */
  119478. while(1){
  119479. float c=0.f;
  119480. float *p=book->valuelist+nt->p[ptr];
  119481. float *q=book->valuelist+nt->q[ptr];
  119482. for(k=0,o=0;k<dim;k++,o+=step)
  119483. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119484. if(c>0.f) /* in A */
  119485. ptr= -nt->ptr0[ptr];
  119486. else /* in B */
  119487. ptr= -nt->ptr1[ptr];
  119488. if(ptr<=0)break;
  119489. }
  119490. return(-ptr);
  119491. }
  119492. #endif
  119493. /* brute force it! */
  119494. {
  119495. const static_codebook *c=book->c;
  119496. int i,besti=-1;
  119497. float best=0.f;
  119498. float *e=book->valuelist;
  119499. for(i=0;i<book->entries;i++){
  119500. if(c->lengthlist[i]>0){
  119501. float thisx=_dist(dim,e,a,step);
  119502. if(besti==-1 || thisx<best){
  119503. best=thisx;
  119504. besti=i;
  119505. }
  119506. }
  119507. e+=dim;
  119508. }
  119509. /*if(savebest!=-1 && savebest!=besti){
  119510. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119511. "original:");
  119512. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119513. fprintf(stderr,"\n"
  119514. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119515. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119516. (book->valuelist+savebest*dim)[i]);
  119517. fprintf(stderr,"\n"
  119518. "bruteforce (entry %d, err %g):",besti,best);
  119519. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119520. (book->valuelist+besti*dim)[i]);
  119521. fprintf(stderr,"\n");
  119522. }*/
  119523. return(besti);
  119524. }
  119525. }
  119526. long vorbis_book_codeword(codebook *book,int entry){
  119527. if(book->c) /* only use with encode; decode optimizations are
  119528. allowed to break this */
  119529. return book->codelist[entry];
  119530. return -1;
  119531. }
  119532. long vorbis_book_codelen(codebook *book,int entry){
  119533. if(book->c) /* only use with encode; decode optimizations are
  119534. allowed to break this */
  119535. return book->c->lengthlist[entry];
  119536. return -1;
  119537. }
  119538. #ifdef _V_SELFTEST
  119539. /* Unit tests of the dequantizer; this stuff will be OK
  119540. cross-platform, I simply want to be sure that special mapping cases
  119541. actually work properly; a bug could go unnoticed for a while */
  119542. #include <stdio.h>
  119543. /* cases:
  119544. no mapping
  119545. full, explicit mapping
  119546. algorithmic mapping
  119547. nonsequential
  119548. sequential
  119549. */
  119550. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119551. static long partial_quantlist1[]={0,7,2};
  119552. /* no mapping */
  119553. static_codebook test1={
  119554. 4,16,
  119555. NULL,
  119556. 0,
  119557. 0,0,0,0,
  119558. NULL,
  119559. NULL,NULL
  119560. };
  119561. static float *test1_result=NULL;
  119562. /* linear, full mapping, nonsequential */
  119563. static_codebook test2={
  119564. 4,3,
  119565. NULL,
  119566. 2,
  119567. -533200896,1611661312,4,0,
  119568. full_quantlist1,
  119569. NULL,NULL
  119570. };
  119571. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119572. /* linear, full mapping, sequential */
  119573. static_codebook test3={
  119574. 4,3,
  119575. NULL,
  119576. 2,
  119577. -533200896,1611661312,4,1,
  119578. full_quantlist1,
  119579. NULL,NULL
  119580. };
  119581. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119582. /* linear, algorithmic mapping, nonsequential */
  119583. static_codebook test4={
  119584. 3,27,
  119585. NULL,
  119586. 1,
  119587. -533200896,1611661312,4,0,
  119588. partial_quantlist1,
  119589. NULL,NULL
  119590. };
  119591. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119592. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119593. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119594. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119595. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119596. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119597. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119598. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119599. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119600. /* linear, algorithmic mapping, sequential */
  119601. static_codebook test5={
  119602. 3,27,
  119603. NULL,
  119604. 1,
  119605. -533200896,1611661312,4,1,
  119606. partial_quantlist1,
  119607. NULL,NULL
  119608. };
  119609. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119610. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119611. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119612. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119613. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119614. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119615. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119616. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119617. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119618. void run_test(static_codebook *b,float *comp){
  119619. float *out=_book_unquantize(b,b->entries,NULL);
  119620. int i;
  119621. if(comp){
  119622. if(!out){
  119623. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119624. exit(1);
  119625. }
  119626. for(i=0;i<b->entries*b->dim;i++)
  119627. if(fabs(out[i]-comp[i])>.0001){
  119628. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119629. "position %d, %g != %g\n",i,out[i],comp[i]);
  119630. exit(1);
  119631. }
  119632. }else{
  119633. if(out){
  119634. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119635. " correct result should have been NULL\n");
  119636. exit(1);
  119637. }
  119638. }
  119639. }
  119640. int main(){
  119641. /* run the nine dequant tests, and compare to the hand-rolled results */
  119642. fprintf(stderr,"Dequant test 1... ");
  119643. run_test(&test1,test1_result);
  119644. fprintf(stderr,"OK\nDequant test 2... ");
  119645. run_test(&test2,test2_result);
  119646. fprintf(stderr,"OK\nDequant test 3... ");
  119647. run_test(&test3,test3_result);
  119648. fprintf(stderr,"OK\nDequant test 4... ");
  119649. run_test(&test4,test4_result);
  119650. fprintf(stderr,"OK\nDequant test 5... ");
  119651. run_test(&test5,test5_result);
  119652. fprintf(stderr,"OK\n\n");
  119653. return(0);
  119654. }
  119655. #endif
  119656. #endif
  119657. /*** End of inlined file: sharedbook.c ***/
  119658. /*** Start of inlined file: smallft.c ***/
  119659. /* FFT implementation from OggSquish, minus cosine transforms,
  119660. * minus all but radix 2/4 case. In Vorbis we only need this
  119661. * cut-down version.
  119662. *
  119663. * To do more than just power-of-two sized vectors, see the full
  119664. * version I wrote for NetLib.
  119665. *
  119666. * Note that the packing is a little strange; rather than the FFT r/i
  119667. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119668. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119669. * FORTRAN version
  119670. */
  119671. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119672. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119673. // tasks..
  119674. #if JUCE_MSVC
  119675. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119676. #endif
  119677. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119678. #if JUCE_USE_OGGVORBIS
  119679. #include <stdlib.h>
  119680. #include <string.h>
  119681. #include <math.h>
  119682. static void drfti1(int n, float *wa, int *ifac){
  119683. static int ntryh[4] = { 4,2,3,5 };
  119684. static float tpi = 6.28318530717958648f;
  119685. float arg,argh,argld,fi;
  119686. int ntry=0,i,j=-1;
  119687. int k1, l1, l2, ib;
  119688. int ld, ii, ip, is, nq, nr;
  119689. int ido, ipm, nfm1;
  119690. int nl=n;
  119691. int nf=0;
  119692. L101:
  119693. j++;
  119694. if (j < 4)
  119695. ntry=ntryh[j];
  119696. else
  119697. ntry+=2;
  119698. L104:
  119699. nq=nl/ntry;
  119700. nr=nl-ntry*nq;
  119701. if (nr!=0) goto L101;
  119702. nf++;
  119703. ifac[nf+1]=ntry;
  119704. nl=nq;
  119705. if(ntry!=2)goto L107;
  119706. if(nf==1)goto L107;
  119707. for (i=1;i<nf;i++){
  119708. ib=nf-i+1;
  119709. ifac[ib+1]=ifac[ib];
  119710. }
  119711. ifac[2] = 2;
  119712. L107:
  119713. if(nl!=1)goto L104;
  119714. ifac[0]=n;
  119715. ifac[1]=nf;
  119716. argh=tpi/n;
  119717. is=0;
  119718. nfm1=nf-1;
  119719. l1=1;
  119720. if(nfm1==0)return;
  119721. for (k1=0;k1<nfm1;k1++){
  119722. ip=ifac[k1+2];
  119723. ld=0;
  119724. l2=l1*ip;
  119725. ido=n/l2;
  119726. ipm=ip-1;
  119727. for (j=0;j<ipm;j++){
  119728. ld+=l1;
  119729. i=is;
  119730. argld=(float)ld*argh;
  119731. fi=0.f;
  119732. for (ii=2;ii<ido;ii+=2){
  119733. fi+=1.f;
  119734. arg=fi*argld;
  119735. wa[i++]=cos(arg);
  119736. wa[i++]=sin(arg);
  119737. }
  119738. is+=ido;
  119739. }
  119740. l1=l2;
  119741. }
  119742. }
  119743. static void fdrffti(int n, float *wsave, int *ifac){
  119744. if (n == 1) return;
  119745. drfti1(n, wsave+n, ifac);
  119746. }
  119747. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119748. int i,k;
  119749. float ti2,tr2;
  119750. int t0,t1,t2,t3,t4,t5,t6;
  119751. t1=0;
  119752. t0=(t2=l1*ido);
  119753. t3=ido<<1;
  119754. for(k=0;k<l1;k++){
  119755. ch[t1<<1]=cc[t1]+cc[t2];
  119756. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119757. t1+=ido;
  119758. t2+=ido;
  119759. }
  119760. if(ido<2)return;
  119761. if(ido==2)goto L105;
  119762. t1=0;
  119763. t2=t0;
  119764. for(k=0;k<l1;k++){
  119765. t3=t2;
  119766. t4=(t1<<1)+(ido<<1);
  119767. t5=t1;
  119768. t6=t1+t1;
  119769. for(i=2;i<ido;i+=2){
  119770. t3+=2;
  119771. t4-=2;
  119772. t5+=2;
  119773. t6+=2;
  119774. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119775. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119776. ch[t6]=cc[t5]+ti2;
  119777. ch[t4]=ti2-cc[t5];
  119778. ch[t6-1]=cc[t5-1]+tr2;
  119779. ch[t4-1]=cc[t5-1]-tr2;
  119780. }
  119781. t1+=ido;
  119782. t2+=ido;
  119783. }
  119784. if(ido%2==1)return;
  119785. L105:
  119786. t3=(t2=(t1=ido)-1);
  119787. t2+=t0;
  119788. for(k=0;k<l1;k++){
  119789. ch[t1]=-cc[t2];
  119790. ch[t1-1]=cc[t3];
  119791. t1+=ido<<1;
  119792. t2+=ido;
  119793. t3+=ido;
  119794. }
  119795. }
  119796. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119797. float *wa2,float *wa3){
  119798. static float hsqt2 = .70710678118654752f;
  119799. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119800. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119801. t0=l1*ido;
  119802. t1=t0;
  119803. t4=t1<<1;
  119804. t2=t1+(t1<<1);
  119805. t3=0;
  119806. for(k=0;k<l1;k++){
  119807. tr1=cc[t1]+cc[t2];
  119808. tr2=cc[t3]+cc[t4];
  119809. ch[t5=t3<<2]=tr1+tr2;
  119810. ch[(ido<<2)+t5-1]=tr2-tr1;
  119811. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119812. ch[t5]=cc[t2]-cc[t1];
  119813. t1+=ido;
  119814. t2+=ido;
  119815. t3+=ido;
  119816. t4+=ido;
  119817. }
  119818. if(ido<2)return;
  119819. if(ido==2)goto L105;
  119820. t1=0;
  119821. for(k=0;k<l1;k++){
  119822. t2=t1;
  119823. t4=t1<<2;
  119824. t5=(t6=ido<<1)+t4;
  119825. for(i=2;i<ido;i+=2){
  119826. t3=(t2+=2);
  119827. t4+=2;
  119828. t5-=2;
  119829. t3+=t0;
  119830. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119831. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119832. t3+=t0;
  119833. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119834. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119835. t3+=t0;
  119836. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119837. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119838. tr1=cr2+cr4;
  119839. tr4=cr4-cr2;
  119840. ti1=ci2+ci4;
  119841. ti4=ci2-ci4;
  119842. ti2=cc[t2]+ci3;
  119843. ti3=cc[t2]-ci3;
  119844. tr2=cc[t2-1]+cr3;
  119845. tr3=cc[t2-1]-cr3;
  119846. ch[t4-1]=tr1+tr2;
  119847. ch[t4]=ti1+ti2;
  119848. ch[t5-1]=tr3-ti4;
  119849. ch[t5]=tr4-ti3;
  119850. ch[t4+t6-1]=ti4+tr3;
  119851. ch[t4+t6]=tr4+ti3;
  119852. ch[t5+t6-1]=tr2-tr1;
  119853. ch[t5+t6]=ti1-ti2;
  119854. }
  119855. t1+=ido;
  119856. }
  119857. if(ido&1)return;
  119858. L105:
  119859. t2=(t1=t0+ido-1)+(t0<<1);
  119860. t3=ido<<2;
  119861. t4=ido;
  119862. t5=ido<<1;
  119863. t6=ido;
  119864. for(k=0;k<l1;k++){
  119865. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119866. tr1=hsqt2*(cc[t1]-cc[t2]);
  119867. ch[t4-1]=tr1+cc[t6-1];
  119868. ch[t4+t5-1]=cc[t6-1]-tr1;
  119869. ch[t4]=ti1-cc[t1+t0];
  119870. ch[t4+t5]=ti1+cc[t1+t0];
  119871. t1+=ido;
  119872. t2+=ido;
  119873. t4+=t3;
  119874. t6+=ido;
  119875. }
  119876. }
  119877. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119878. float *c2,float *ch,float *ch2,float *wa){
  119879. static float tpi=6.283185307179586f;
  119880. int idij,ipph,i,j,k,l,ic,ik,is;
  119881. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119882. float dc2,ai1,ai2,ar1,ar2,ds2;
  119883. int nbd;
  119884. float dcp,arg,dsp,ar1h,ar2h;
  119885. int idp2,ipp2;
  119886. arg=tpi/(float)ip;
  119887. dcp=cos(arg);
  119888. dsp=sin(arg);
  119889. ipph=(ip+1)>>1;
  119890. ipp2=ip;
  119891. idp2=ido;
  119892. nbd=(ido-1)>>1;
  119893. t0=l1*ido;
  119894. t10=ip*ido;
  119895. if(ido==1)goto L119;
  119896. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119897. t1=0;
  119898. for(j=1;j<ip;j++){
  119899. t1+=t0;
  119900. t2=t1;
  119901. for(k=0;k<l1;k++){
  119902. ch[t2]=c1[t2];
  119903. t2+=ido;
  119904. }
  119905. }
  119906. is=-ido;
  119907. t1=0;
  119908. if(nbd>l1){
  119909. for(j=1;j<ip;j++){
  119910. t1+=t0;
  119911. is+=ido;
  119912. t2= -ido+t1;
  119913. for(k=0;k<l1;k++){
  119914. idij=is-1;
  119915. t2+=ido;
  119916. t3=t2;
  119917. for(i=2;i<ido;i+=2){
  119918. idij+=2;
  119919. t3+=2;
  119920. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119921. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119922. }
  119923. }
  119924. }
  119925. }else{
  119926. for(j=1;j<ip;j++){
  119927. is+=ido;
  119928. idij=is-1;
  119929. t1+=t0;
  119930. t2=t1;
  119931. for(i=2;i<ido;i+=2){
  119932. idij+=2;
  119933. t2+=2;
  119934. t3=t2;
  119935. for(k=0;k<l1;k++){
  119936. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119937. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119938. t3+=ido;
  119939. }
  119940. }
  119941. }
  119942. }
  119943. t1=0;
  119944. t2=ipp2*t0;
  119945. if(nbd<l1){
  119946. for(j=1;j<ipph;j++){
  119947. t1+=t0;
  119948. t2-=t0;
  119949. t3=t1;
  119950. t4=t2;
  119951. for(i=2;i<ido;i+=2){
  119952. t3+=2;
  119953. t4+=2;
  119954. t5=t3-ido;
  119955. t6=t4-ido;
  119956. for(k=0;k<l1;k++){
  119957. t5+=ido;
  119958. t6+=ido;
  119959. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119960. c1[t6-1]=ch[t5]-ch[t6];
  119961. c1[t5]=ch[t5]+ch[t6];
  119962. c1[t6]=ch[t6-1]-ch[t5-1];
  119963. }
  119964. }
  119965. }
  119966. }else{
  119967. for(j=1;j<ipph;j++){
  119968. t1+=t0;
  119969. t2-=t0;
  119970. t3=t1;
  119971. t4=t2;
  119972. for(k=0;k<l1;k++){
  119973. t5=t3;
  119974. t6=t4;
  119975. for(i=2;i<ido;i+=2){
  119976. t5+=2;
  119977. t6+=2;
  119978. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119979. c1[t6-1]=ch[t5]-ch[t6];
  119980. c1[t5]=ch[t5]+ch[t6];
  119981. c1[t6]=ch[t6-1]-ch[t5-1];
  119982. }
  119983. t3+=ido;
  119984. t4+=ido;
  119985. }
  119986. }
  119987. }
  119988. L119:
  119989. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119990. t1=0;
  119991. t2=ipp2*idl1;
  119992. for(j=1;j<ipph;j++){
  119993. t1+=t0;
  119994. t2-=t0;
  119995. t3=t1-ido;
  119996. t4=t2-ido;
  119997. for(k=0;k<l1;k++){
  119998. t3+=ido;
  119999. t4+=ido;
  120000. c1[t3]=ch[t3]+ch[t4];
  120001. c1[t4]=ch[t4]-ch[t3];
  120002. }
  120003. }
  120004. ar1=1.f;
  120005. ai1=0.f;
  120006. t1=0;
  120007. t2=ipp2*idl1;
  120008. t3=(ip-1)*idl1;
  120009. for(l=1;l<ipph;l++){
  120010. t1+=idl1;
  120011. t2-=idl1;
  120012. ar1h=dcp*ar1-dsp*ai1;
  120013. ai1=dcp*ai1+dsp*ar1;
  120014. ar1=ar1h;
  120015. t4=t1;
  120016. t5=t2;
  120017. t6=t3;
  120018. t7=idl1;
  120019. for(ik=0;ik<idl1;ik++){
  120020. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  120021. ch2[t5++]=ai1*c2[t6++];
  120022. }
  120023. dc2=ar1;
  120024. ds2=ai1;
  120025. ar2=ar1;
  120026. ai2=ai1;
  120027. t4=idl1;
  120028. t5=(ipp2-1)*idl1;
  120029. for(j=2;j<ipph;j++){
  120030. t4+=idl1;
  120031. t5-=idl1;
  120032. ar2h=dc2*ar2-ds2*ai2;
  120033. ai2=dc2*ai2+ds2*ar2;
  120034. ar2=ar2h;
  120035. t6=t1;
  120036. t7=t2;
  120037. t8=t4;
  120038. t9=t5;
  120039. for(ik=0;ik<idl1;ik++){
  120040. ch2[t6++]+=ar2*c2[t8++];
  120041. ch2[t7++]+=ai2*c2[t9++];
  120042. }
  120043. }
  120044. }
  120045. t1=0;
  120046. for(j=1;j<ipph;j++){
  120047. t1+=idl1;
  120048. t2=t1;
  120049. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120050. }
  120051. if(ido<l1)goto L132;
  120052. t1=0;
  120053. t2=0;
  120054. for(k=0;k<l1;k++){
  120055. t3=t1;
  120056. t4=t2;
  120057. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120058. t1+=ido;
  120059. t2+=t10;
  120060. }
  120061. goto L135;
  120062. L132:
  120063. for(i=0;i<ido;i++){
  120064. t1=i;
  120065. t2=i;
  120066. for(k=0;k<l1;k++){
  120067. cc[t2]=ch[t1];
  120068. t1+=ido;
  120069. t2+=t10;
  120070. }
  120071. }
  120072. L135:
  120073. t1=0;
  120074. t2=ido<<1;
  120075. t3=0;
  120076. t4=ipp2*t0;
  120077. for(j=1;j<ipph;j++){
  120078. t1+=t2;
  120079. t3+=t0;
  120080. t4-=t0;
  120081. t5=t1;
  120082. t6=t3;
  120083. t7=t4;
  120084. for(k=0;k<l1;k++){
  120085. cc[t5-1]=ch[t6];
  120086. cc[t5]=ch[t7];
  120087. t5+=t10;
  120088. t6+=ido;
  120089. t7+=ido;
  120090. }
  120091. }
  120092. if(ido==1)return;
  120093. if(nbd<l1)goto L141;
  120094. t1=-ido;
  120095. t3=0;
  120096. t4=0;
  120097. t5=ipp2*t0;
  120098. for(j=1;j<ipph;j++){
  120099. t1+=t2;
  120100. t3+=t2;
  120101. t4+=t0;
  120102. t5-=t0;
  120103. t6=t1;
  120104. t7=t3;
  120105. t8=t4;
  120106. t9=t5;
  120107. for(k=0;k<l1;k++){
  120108. for(i=2;i<ido;i+=2){
  120109. ic=idp2-i;
  120110. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120111. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120112. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120113. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120114. }
  120115. t6+=t10;
  120116. t7+=t10;
  120117. t8+=ido;
  120118. t9+=ido;
  120119. }
  120120. }
  120121. return;
  120122. L141:
  120123. t1=-ido;
  120124. t3=0;
  120125. t4=0;
  120126. t5=ipp2*t0;
  120127. for(j=1;j<ipph;j++){
  120128. t1+=t2;
  120129. t3+=t2;
  120130. t4+=t0;
  120131. t5-=t0;
  120132. for(i=2;i<ido;i+=2){
  120133. t6=idp2+t1-i;
  120134. t7=i+t3;
  120135. t8=i+t4;
  120136. t9=i+t5;
  120137. for(k=0;k<l1;k++){
  120138. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120139. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120140. cc[t7]=ch[t8]+ch[t9];
  120141. cc[t6]=ch[t9]-ch[t8];
  120142. t6+=t10;
  120143. t7+=t10;
  120144. t8+=ido;
  120145. t9+=ido;
  120146. }
  120147. }
  120148. }
  120149. }
  120150. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120151. int i,k1,l1,l2;
  120152. int na,kh,nf;
  120153. int ip,iw,ido,idl1,ix2,ix3;
  120154. nf=ifac[1];
  120155. na=1;
  120156. l2=n;
  120157. iw=n;
  120158. for(k1=0;k1<nf;k1++){
  120159. kh=nf-k1;
  120160. ip=ifac[kh+1];
  120161. l1=l2/ip;
  120162. ido=n/l2;
  120163. idl1=ido*l1;
  120164. iw-=(ip-1)*ido;
  120165. na=1-na;
  120166. if(ip!=4)goto L102;
  120167. ix2=iw+ido;
  120168. ix3=ix2+ido;
  120169. if(na!=0)
  120170. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120171. else
  120172. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120173. goto L110;
  120174. L102:
  120175. if(ip!=2)goto L104;
  120176. if(na!=0)goto L103;
  120177. dradf2(ido,l1,c,ch,wa+iw-1);
  120178. goto L110;
  120179. L103:
  120180. dradf2(ido,l1,ch,c,wa+iw-1);
  120181. goto L110;
  120182. L104:
  120183. if(ido==1)na=1-na;
  120184. if(na!=0)goto L109;
  120185. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120186. na=1;
  120187. goto L110;
  120188. L109:
  120189. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120190. na=0;
  120191. L110:
  120192. l2=l1;
  120193. }
  120194. if(na==1)return;
  120195. for(i=0;i<n;i++)c[i]=ch[i];
  120196. }
  120197. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120198. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120199. float ti2,tr2;
  120200. t0=l1*ido;
  120201. t1=0;
  120202. t2=0;
  120203. t3=(ido<<1)-1;
  120204. for(k=0;k<l1;k++){
  120205. ch[t1]=cc[t2]+cc[t3+t2];
  120206. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120207. t2=(t1+=ido)<<1;
  120208. }
  120209. if(ido<2)return;
  120210. if(ido==2)goto L105;
  120211. t1=0;
  120212. t2=0;
  120213. for(k=0;k<l1;k++){
  120214. t3=t1;
  120215. t5=(t4=t2)+(ido<<1);
  120216. t6=t0+t1;
  120217. for(i=2;i<ido;i+=2){
  120218. t3+=2;
  120219. t4+=2;
  120220. t5-=2;
  120221. t6+=2;
  120222. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120223. tr2=cc[t4-1]-cc[t5-1];
  120224. ch[t3]=cc[t4]-cc[t5];
  120225. ti2=cc[t4]+cc[t5];
  120226. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120227. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120228. }
  120229. t2=(t1+=ido)<<1;
  120230. }
  120231. if(ido%2==1)return;
  120232. L105:
  120233. t1=ido-1;
  120234. t2=ido-1;
  120235. for(k=0;k<l1;k++){
  120236. ch[t1]=cc[t2]+cc[t2];
  120237. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120238. t1+=ido;
  120239. t2+=ido<<1;
  120240. }
  120241. }
  120242. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120243. float *wa2){
  120244. static float taur = -.5f;
  120245. static float taui = .8660254037844386f;
  120246. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120247. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120248. t0=l1*ido;
  120249. t1=0;
  120250. t2=t0<<1;
  120251. t3=ido<<1;
  120252. t4=ido+(ido<<1);
  120253. t5=0;
  120254. for(k=0;k<l1;k++){
  120255. tr2=cc[t3-1]+cc[t3-1];
  120256. cr2=cc[t5]+(taur*tr2);
  120257. ch[t1]=cc[t5]+tr2;
  120258. ci3=taui*(cc[t3]+cc[t3]);
  120259. ch[t1+t0]=cr2-ci3;
  120260. ch[t1+t2]=cr2+ci3;
  120261. t1+=ido;
  120262. t3+=t4;
  120263. t5+=t4;
  120264. }
  120265. if(ido==1)return;
  120266. t1=0;
  120267. t3=ido<<1;
  120268. for(k=0;k<l1;k++){
  120269. t7=t1+(t1<<1);
  120270. t6=(t5=t7+t3);
  120271. t8=t1;
  120272. t10=(t9=t1+t0)+t0;
  120273. for(i=2;i<ido;i+=2){
  120274. t5+=2;
  120275. t6-=2;
  120276. t7+=2;
  120277. t8+=2;
  120278. t9+=2;
  120279. t10+=2;
  120280. tr2=cc[t5-1]+cc[t6-1];
  120281. cr2=cc[t7-1]+(taur*tr2);
  120282. ch[t8-1]=cc[t7-1]+tr2;
  120283. ti2=cc[t5]-cc[t6];
  120284. ci2=cc[t7]+(taur*ti2);
  120285. ch[t8]=cc[t7]+ti2;
  120286. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120287. ci3=taui*(cc[t5]+cc[t6]);
  120288. dr2=cr2-ci3;
  120289. dr3=cr2+ci3;
  120290. di2=ci2+cr3;
  120291. di3=ci2-cr3;
  120292. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120293. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120294. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120295. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120296. }
  120297. t1+=ido;
  120298. }
  120299. }
  120300. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120301. float *wa2,float *wa3){
  120302. static float sqrt2=1.414213562373095f;
  120303. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120304. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120305. t0=l1*ido;
  120306. t1=0;
  120307. t2=ido<<2;
  120308. t3=0;
  120309. t6=ido<<1;
  120310. for(k=0;k<l1;k++){
  120311. t4=t3+t6;
  120312. t5=t1;
  120313. tr3=cc[t4-1]+cc[t4-1];
  120314. tr4=cc[t4]+cc[t4];
  120315. tr1=cc[t3]-cc[(t4+=t6)-1];
  120316. tr2=cc[t3]+cc[t4-1];
  120317. ch[t5]=tr2+tr3;
  120318. ch[t5+=t0]=tr1-tr4;
  120319. ch[t5+=t0]=tr2-tr3;
  120320. ch[t5+=t0]=tr1+tr4;
  120321. t1+=ido;
  120322. t3+=t2;
  120323. }
  120324. if(ido<2)return;
  120325. if(ido==2)goto L105;
  120326. t1=0;
  120327. for(k=0;k<l1;k++){
  120328. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120329. t7=t1;
  120330. for(i=2;i<ido;i+=2){
  120331. t2+=2;
  120332. t3+=2;
  120333. t4-=2;
  120334. t5-=2;
  120335. t7+=2;
  120336. ti1=cc[t2]+cc[t5];
  120337. ti2=cc[t2]-cc[t5];
  120338. ti3=cc[t3]-cc[t4];
  120339. tr4=cc[t3]+cc[t4];
  120340. tr1=cc[t2-1]-cc[t5-1];
  120341. tr2=cc[t2-1]+cc[t5-1];
  120342. ti4=cc[t3-1]-cc[t4-1];
  120343. tr3=cc[t3-1]+cc[t4-1];
  120344. ch[t7-1]=tr2+tr3;
  120345. cr3=tr2-tr3;
  120346. ch[t7]=ti2+ti3;
  120347. ci3=ti2-ti3;
  120348. cr2=tr1-tr4;
  120349. cr4=tr1+tr4;
  120350. ci2=ti1+ti4;
  120351. ci4=ti1-ti4;
  120352. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120353. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120354. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120355. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120356. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120357. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120358. }
  120359. t1+=ido;
  120360. }
  120361. if(ido%2 == 1)return;
  120362. L105:
  120363. t1=ido;
  120364. t2=ido<<2;
  120365. t3=ido-1;
  120366. t4=ido+(ido<<1);
  120367. for(k=0;k<l1;k++){
  120368. t5=t3;
  120369. ti1=cc[t1]+cc[t4];
  120370. ti2=cc[t4]-cc[t1];
  120371. tr1=cc[t1-1]-cc[t4-1];
  120372. tr2=cc[t1-1]+cc[t4-1];
  120373. ch[t5]=tr2+tr2;
  120374. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120375. ch[t5+=t0]=ti2+ti2;
  120376. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120377. t3+=ido;
  120378. t1+=t2;
  120379. t4+=t2;
  120380. }
  120381. }
  120382. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120383. float *c2,float *ch,float *ch2,float *wa){
  120384. static float tpi=6.283185307179586f;
  120385. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120386. t11,t12;
  120387. float dc2,ai1,ai2,ar1,ar2,ds2;
  120388. int nbd;
  120389. float dcp,arg,dsp,ar1h,ar2h;
  120390. int ipp2;
  120391. t10=ip*ido;
  120392. t0=l1*ido;
  120393. arg=tpi/(float)ip;
  120394. dcp=cos(arg);
  120395. dsp=sin(arg);
  120396. nbd=(ido-1)>>1;
  120397. ipp2=ip;
  120398. ipph=(ip+1)>>1;
  120399. if(ido<l1)goto L103;
  120400. t1=0;
  120401. t2=0;
  120402. for(k=0;k<l1;k++){
  120403. t3=t1;
  120404. t4=t2;
  120405. for(i=0;i<ido;i++){
  120406. ch[t3]=cc[t4];
  120407. t3++;
  120408. t4++;
  120409. }
  120410. t1+=ido;
  120411. t2+=t10;
  120412. }
  120413. goto L106;
  120414. L103:
  120415. t1=0;
  120416. for(i=0;i<ido;i++){
  120417. t2=t1;
  120418. t3=t1;
  120419. for(k=0;k<l1;k++){
  120420. ch[t2]=cc[t3];
  120421. t2+=ido;
  120422. t3+=t10;
  120423. }
  120424. t1++;
  120425. }
  120426. L106:
  120427. t1=0;
  120428. t2=ipp2*t0;
  120429. t7=(t5=ido<<1);
  120430. for(j=1;j<ipph;j++){
  120431. t1+=t0;
  120432. t2-=t0;
  120433. t3=t1;
  120434. t4=t2;
  120435. t6=t5;
  120436. for(k=0;k<l1;k++){
  120437. ch[t3]=cc[t6-1]+cc[t6-1];
  120438. ch[t4]=cc[t6]+cc[t6];
  120439. t3+=ido;
  120440. t4+=ido;
  120441. t6+=t10;
  120442. }
  120443. t5+=t7;
  120444. }
  120445. if (ido == 1)goto L116;
  120446. if(nbd<l1)goto L112;
  120447. t1=0;
  120448. t2=ipp2*t0;
  120449. t7=0;
  120450. for(j=1;j<ipph;j++){
  120451. t1+=t0;
  120452. t2-=t0;
  120453. t3=t1;
  120454. t4=t2;
  120455. t7+=(ido<<1);
  120456. t8=t7;
  120457. for(k=0;k<l1;k++){
  120458. t5=t3;
  120459. t6=t4;
  120460. t9=t8;
  120461. t11=t8;
  120462. for(i=2;i<ido;i+=2){
  120463. t5+=2;
  120464. t6+=2;
  120465. t9+=2;
  120466. t11-=2;
  120467. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120468. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120469. ch[t5]=cc[t9]-cc[t11];
  120470. ch[t6]=cc[t9]+cc[t11];
  120471. }
  120472. t3+=ido;
  120473. t4+=ido;
  120474. t8+=t10;
  120475. }
  120476. }
  120477. goto L116;
  120478. L112:
  120479. t1=0;
  120480. t2=ipp2*t0;
  120481. t7=0;
  120482. for(j=1;j<ipph;j++){
  120483. t1+=t0;
  120484. t2-=t0;
  120485. t3=t1;
  120486. t4=t2;
  120487. t7+=(ido<<1);
  120488. t8=t7;
  120489. t9=t7;
  120490. for(i=2;i<ido;i+=2){
  120491. t3+=2;
  120492. t4+=2;
  120493. t8+=2;
  120494. t9-=2;
  120495. t5=t3;
  120496. t6=t4;
  120497. t11=t8;
  120498. t12=t9;
  120499. for(k=0;k<l1;k++){
  120500. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120501. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120502. ch[t5]=cc[t11]-cc[t12];
  120503. ch[t6]=cc[t11]+cc[t12];
  120504. t5+=ido;
  120505. t6+=ido;
  120506. t11+=t10;
  120507. t12+=t10;
  120508. }
  120509. }
  120510. }
  120511. L116:
  120512. ar1=1.f;
  120513. ai1=0.f;
  120514. t1=0;
  120515. t9=(t2=ipp2*idl1);
  120516. t3=(ip-1)*idl1;
  120517. for(l=1;l<ipph;l++){
  120518. t1+=idl1;
  120519. t2-=idl1;
  120520. ar1h=dcp*ar1-dsp*ai1;
  120521. ai1=dcp*ai1+dsp*ar1;
  120522. ar1=ar1h;
  120523. t4=t1;
  120524. t5=t2;
  120525. t6=0;
  120526. t7=idl1;
  120527. t8=t3;
  120528. for(ik=0;ik<idl1;ik++){
  120529. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120530. c2[t5++]=ai1*ch2[t8++];
  120531. }
  120532. dc2=ar1;
  120533. ds2=ai1;
  120534. ar2=ar1;
  120535. ai2=ai1;
  120536. t6=idl1;
  120537. t7=t9-idl1;
  120538. for(j=2;j<ipph;j++){
  120539. t6+=idl1;
  120540. t7-=idl1;
  120541. ar2h=dc2*ar2-ds2*ai2;
  120542. ai2=dc2*ai2+ds2*ar2;
  120543. ar2=ar2h;
  120544. t4=t1;
  120545. t5=t2;
  120546. t11=t6;
  120547. t12=t7;
  120548. for(ik=0;ik<idl1;ik++){
  120549. c2[t4++]+=ar2*ch2[t11++];
  120550. c2[t5++]+=ai2*ch2[t12++];
  120551. }
  120552. }
  120553. }
  120554. t1=0;
  120555. for(j=1;j<ipph;j++){
  120556. t1+=idl1;
  120557. t2=t1;
  120558. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120559. }
  120560. t1=0;
  120561. t2=ipp2*t0;
  120562. for(j=1;j<ipph;j++){
  120563. t1+=t0;
  120564. t2-=t0;
  120565. t3=t1;
  120566. t4=t2;
  120567. for(k=0;k<l1;k++){
  120568. ch[t3]=c1[t3]-c1[t4];
  120569. ch[t4]=c1[t3]+c1[t4];
  120570. t3+=ido;
  120571. t4+=ido;
  120572. }
  120573. }
  120574. if(ido==1)goto L132;
  120575. if(nbd<l1)goto L128;
  120576. t1=0;
  120577. t2=ipp2*t0;
  120578. for(j=1;j<ipph;j++){
  120579. t1+=t0;
  120580. t2-=t0;
  120581. t3=t1;
  120582. t4=t2;
  120583. for(k=0;k<l1;k++){
  120584. t5=t3;
  120585. t6=t4;
  120586. for(i=2;i<ido;i+=2){
  120587. t5+=2;
  120588. t6+=2;
  120589. ch[t5-1]=c1[t5-1]-c1[t6];
  120590. ch[t6-1]=c1[t5-1]+c1[t6];
  120591. ch[t5]=c1[t5]+c1[t6-1];
  120592. ch[t6]=c1[t5]-c1[t6-1];
  120593. }
  120594. t3+=ido;
  120595. t4+=ido;
  120596. }
  120597. }
  120598. goto L132;
  120599. L128:
  120600. t1=0;
  120601. t2=ipp2*t0;
  120602. for(j=1;j<ipph;j++){
  120603. t1+=t0;
  120604. t2-=t0;
  120605. t3=t1;
  120606. t4=t2;
  120607. for(i=2;i<ido;i+=2){
  120608. t3+=2;
  120609. t4+=2;
  120610. t5=t3;
  120611. t6=t4;
  120612. for(k=0;k<l1;k++){
  120613. ch[t5-1]=c1[t5-1]-c1[t6];
  120614. ch[t6-1]=c1[t5-1]+c1[t6];
  120615. ch[t5]=c1[t5]+c1[t6-1];
  120616. ch[t6]=c1[t5]-c1[t6-1];
  120617. t5+=ido;
  120618. t6+=ido;
  120619. }
  120620. }
  120621. }
  120622. L132:
  120623. if(ido==1)return;
  120624. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120625. t1=0;
  120626. for(j=1;j<ip;j++){
  120627. t2=(t1+=t0);
  120628. for(k=0;k<l1;k++){
  120629. c1[t2]=ch[t2];
  120630. t2+=ido;
  120631. }
  120632. }
  120633. if(nbd>l1)goto L139;
  120634. is= -ido-1;
  120635. t1=0;
  120636. for(j=1;j<ip;j++){
  120637. is+=ido;
  120638. t1+=t0;
  120639. idij=is;
  120640. t2=t1;
  120641. for(i=2;i<ido;i+=2){
  120642. t2+=2;
  120643. idij+=2;
  120644. t3=t2;
  120645. for(k=0;k<l1;k++){
  120646. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120647. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120648. t3+=ido;
  120649. }
  120650. }
  120651. }
  120652. return;
  120653. L139:
  120654. is= -ido-1;
  120655. t1=0;
  120656. for(j=1;j<ip;j++){
  120657. is+=ido;
  120658. t1+=t0;
  120659. t2=t1;
  120660. for(k=0;k<l1;k++){
  120661. idij=is;
  120662. t3=t2;
  120663. for(i=2;i<ido;i+=2){
  120664. idij+=2;
  120665. t3+=2;
  120666. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120667. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120668. }
  120669. t2+=ido;
  120670. }
  120671. }
  120672. }
  120673. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120674. int i,k1,l1,l2;
  120675. int na;
  120676. int nf,ip,iw,ix2,ix3,ido,idl1;
  120677. nf=ifac[1];
  120678. na=0;
  120679. l1=1;
  120680. iw=1;
  120681. for(k1=0;k1<nf;k1++){
  120682. ip=ifac[k1 + 2];
  120683. l2=ip*l1;
  120684. ido=n/l2;
  120685. idl1=ido*l1;
  120686. if(ip!=4)goto L103;
  120687. ix2=iw+ido;
  120688. ix3=ix2+ido;
  120689. if(na!=0)
  120690. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120691. else
  120692. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120693. na=1-na;
  120694. goto L115;
  120695. L103:
  120696. if(ip!=2)goto L106;
  120697. if(na!=0)
  120698. dradb2(ido,l1,ch,c,wa+iw-1);
  120699. else
  120700. dradb2(ido,l1,c,ch,wa+iw-1);
  120701. na=1-na;
  120702. goto L115;
  120703. L106:
  120704. if(ip!=3)goto L109;
  120705. ix2=iw+ido;
  120706. if(na!=0)
  120707. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120708. else
  120709. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120710. na=1-na;
  120711. goto L115;
  120712. L109:
  120713. /* The radix five case can be translated later..... */
  120714. /* if(ip!=5)goto L112;
  120715. ix2=iw+ido;
  120716. ix3=ix2+ido;
  120717. ix4=ix3+ido;
  120718. if(na!=0)
  120719. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120720. else
  120721. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120722. na=1-na;
  120723. goto L115;
  120724. L112:*/
  120725. if(na!=0)
  120726. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120727. else
  120728. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120729. if(ido==1)na=1-na;
  120730. L115:
  120731. l1=l2;
  120732. iw+=(ip-1)*ido;
  120733. }
  120734. if(na==0)return;
  120735. for(i=0;i<n;i++)c[i]=ch[i];
  120736. }
  120737. void drft_forward(drft_lookup *l,float *data){
  120738. if(l->n==1)return;
  120739. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120740. }
  120741. void drft_backward(drft_lookup *l,float *data){
  120742. if (l->n==1)return;
  120743. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120744. }
  120745. void drft_init(drft_lookup *l,int n){
  120746. l->n=n;
  120747. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120748. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120749. fdrffti(n, l->trigcache, l->splitcache);
  120750. }
  120751. void drft_clear(drft_lookup *l){
  120752. if(l){
  120753. if(l->trigcache)_ogg_free(l->trigcache);
  120754. if(l->splitcache)_ogg_free(l->splitcache);
  120755. memset(l,0,sizeof(*l));
  120756. }
  120757. }
  120758. #endif
  120759. /*** End of inlined file: smallft.c ***/
  120760. /*** Start of inlined file: synthesis.c ***/
  120761. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120762. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120763. // tasks..
  120764. #if JUCE_MSVC
  120765. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120766. #endif
  120767. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120768. #if JUCE_USE_OGGVORBIS
  120769. #include <stdio.h>
  120770. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120771. vorbis_dsp_state *vd=vb->vd;
  120772. private_state *b=(private_state*)vd->backend_state;
  120773. vorbis_info *vi=vd->vi;
  120774. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120775. oggpack_buffer *opb=&vb->opb;
  120776. int type,mode,i;
  120777. /* first things first. Make sure decode is ready */
  120778. _vorbis_block_ripcord(vb);
  120779. oggpack_readinit(opb,op->packet,op->bytes);
  120780. /* Check the packet type */
  120781. if(oggpack_read(opb,1)!=0){
  120782. /* Oops. This is not an audio data packet */
  120783. return(OV_ENOTAUDIO);
  120784. }
  120785. /* read our mode and pre/post windowsize */
  120786. mode=oggpack_read(opb,b->modebits);
  120787. if(mode==-1)return(OV_EBADPACKET);
  120788. vb->mode=mode;
  120789. vb->W=ci->mode_param[mode]->blockflag;
  120790. if(vb->W){
  120791. /* this doesn;t get mapped through mode selection as it's used
  120792. only for window selection */
  120793. vb->lW=oggpack_read(opb,1);
  120794. vb->nW=oggpack_read(opb,1);
  120795. if(vb->nW==-1) return(OV_EBADPACKET);
  120796. }else{
  120797. vb->lW=0;
  120798. vb->nW=0;
  120799. }
  120800. /* more setup */
  120801. vb->granulepos=op->granulepos;
  120802. vb->sequence=op->packetno;
  120803. vb->eofflag=op->e_o_s;
  120804. /* alloc pcm passback storage */
  120805. vb->pcmend=ci->blocksizes[vb->W];
  120806. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120807. for(i=0;i<vi->channels;i++)
  120808. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120809. /* unpack_header enforces range checking */
  120810. type=ci->map_type[ci->mode_param[mode]->mapping];
  120811. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120812. mapping]));
  120813. }
  120814. /* used to track pcm position without actually performing decode.
  120815. Useful for sequential 'fast forward' */
  120816. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120817. vorbis_dsp_state *vd=vb->vd;
  120818. private_state *b=(private_state*)vd->backend_state;
  120819. vorbis_info *vi=vd->vi;
  120820. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120821. oggpack_buffer *opb=&vb->opb;
  120822. int mode;
  120823. /* first things first. Make sure decode is ready */
  120824. _vorbis_block_ripcord(vb);
  120825. oggpack_readinit(opb,op->packet,op->bytes);
  120826. /* Check the packet type */
  120827. if(oggpack_read(opb,1)!=0){
  120828. /* Oops. This is not an audio data packet */
  120829. return(OV_ENOTAUDIO);
  120830. }
  120831. /* read our mode and pre/post windowsize */
  120832. mode=oggpack_read(opb,b->modebits);
  120833. if(mode==-1)return(OV_EBADPACKET);
  120834. vb->mode=mode;
  120835. vb->W=ci->mode_param[mode]->blockflag;
  120836. if(vb->W){
  120837. vb->lW=oggpack_read(opb,1);
  120838. vb->nW=oggpack_read(opb,1);
  120839. if(vb->nW==-1) return(OV_EBADPACKET);
  120840. }else{
  120841. vb->lW=0;
  120842. vb->nW=0;
  120843. }
  120844. /* more setup */
  120845. vb->granulepos=op->granulepos;
  120846. vb->sequence=op->packetno;
  120847. vb->eofflag=op->e_o_s;
  120848. /* no pcm */
  120849. vb->pcmend=0;
  120850. vb->pcm=NULL;
  120851. return(0);
  120852. }
  120853. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120854. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120855. oggpack_buffer opb;
  120856. int mode;
  120857. oggpack_readinit(&opb,op->packet,op->bytes);
  120858. /* Check the packet type */
  120859. if(oggpack_read(&opb,1)!=0){
  120860. /* Oops. This is not an audio data packet */
  120861. return(OV_ENOTAUDIO);
  120862. }
  120863. {
  120864. int modebits=0;
  120865. int v=ci->modes;
  120866. while(v>1){
  120867. modebits++;
  120868. v>>=1;
  120869. }
  120870. /* read our mode and pre/post windowsize */
  120871. mode=oggpack_read(&opb,modebits);
  120872. }
  120873. if(mode==-1)return(OV_EBADPACKET);
  120874. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120875. }
  120876. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120877. /* set / clear half-sample-rate mode */
  120878. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120879. /* right now, our MDCT can't handle < 64 sample windows. */
  120880. if(ci->blocksizes[0]<=64 && flag)return -1;
  120881. ci->halfrate_flag=(flag?1:0);
  120882. return 0;
  120883. }
  120884. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120885. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120886. return ci->halfrate_flag;
  120887. }
  120888. #endif
  120889. /*** End of inlined file: synthesis.c ***/
  120890. /*** Start of inlined file: vorbisenc.c ***/
  120891. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120892. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120893. // tasks..
  120894. #if JUCE_MSVC
  120895. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120896. #endif
  120897. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120898. #if JUCE_USE_OGGVORBIS
  120899. #include <stdlib.h>
  120900. #include <string.h>
  120901. #include <math.h>
  120902. /* careful with this; it's using static array sizing to make managing
  120903. all the modes a little less annoying. If we use a residue backend
  120904. with > 12 partition types, or a different division of iteration,
  120905. this needs to be updated. */
  120906. typedef struct {
  120907. static_codebook *books[12][3];
  120908. } static_bookblock;
  120909. typedef struct {
  120910. int res_type;
  120911. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120912. vorbis_info_residue0 *res;
  120913. static_codebook *book_aux;
  120914. static_codebook *book_aux_managed;
  120915. static_bookblock *books_base;
  120916. static_bookblock *books_base_managed;
  120917. } vorbis_residue_template;
  120918. typedef struct {
  120919. vorbis_info_mapping0 *map;
  120920. vorbis_residue_template *res;
  120921. } vorbis_mapping_template;
  120922. typedef struct vp_adjblock{
  120923. int block[P_BANDS];
  120924. } vp_adjblock;
  120925. typedef struct {
  120926. int data[NOISE_COMPAND_LEVELS];
  120927. } compandblock;
  120928. /* high level configuration information for setting things up
  120929. step-by-step with the detailed vorbis_encode_ctl interface.
  120930. There's a fair amount of redundancy such that interactive setup
  120931. does not directly deal with any vorbis_info or codec_setup_info
  120932. initialization; it's all stored (until full init) in this highlevel
  120933. setup, then flushed out to the real codec setup structs later. */
  120934. typedef struct {
  120935. int att[P_NOISECURVES];
  120936. float boost;
  120937. float decay;
  120938. } att3;
  120939. typedef struct { int data[P_NOISECURVES]; } adj3;
  120940. typedef struct {
  120941. int pre[PACKETBLOBS];
  120942. int post[PACKETBLOBS];
  120943. float kHz[PACKETBLOBS];
  120944. float lowpasskHz[PACKETBLOBS];
  120945. } adj_stereo;
  120946. typedef struct {
  120947. int lo;
  120948. int hi;
  120949. int fixed;
  120950. } noiseguard;
  120951. typedef struct {
  120952. int data[P_NOISECURVES][17];
  120953. } noise3;
  120954. typedef struct {
  120955. int mappings;
  120956. double *rate_mapping;
  120957. double *quality_mapping;
  120958. int coupling_restriction;
  120959. long samplerate_min_restriction;
  120960. long samplerate_max_restriction;
  120961. int *blocksize_short;
  120962. int *blocksize_long;
  120963. att3 *psy_tone_masteratt;
  120964. int *psy_tone_0dB;
  120965. int *psy_tone_dBsuppress;
  120966. vp_adjblock *psy_tone_adj_impulse;
  120967. vp_adjblock *psy_tone_adj_long;
  120968. vp_adjblock *psy_tone_adj_other;
  120969. noiseguard *psy_noiseguards;
  120970. noise3 *psy_noise_bias_impulse;
  120971. noise3 *psy_noise_bias_padding;
  120972. noise3 *psy_noise_bias_trans;
  120973. noise3 *psy_noise_bias_long;
  120974. int *psy_noise_dBsuppress;
  120975. compandblock *psy_noise_compand;
  120976. double *psy_noise_compand_short_mapping;
  120977. double *psy_noise_compand_long_mapping;
  120978. int *psy_noise_normal_start[2];
  120979. int *psy_noise_normal_partition[2];
  120980. double *psy_noise_normal_thresh;
  120981. int *psy_ath_float;
  120982. int *psy_ath_abs;
  120983. double *psy_lowpass;
  120984. vorbis_info_psy_global *global_params;
  120985. double *global_mapping;
  120986. adj_stereo *stereo_modes;
  120987. static_codebook ***floor_books;
  120988. vorbis_info_floor1 *floor_params;
  120989. int *floor_short_mapping;
  120990. int *floor_long_mapping;
  120991. vorbis_mapping_template *maps;
  120992. } ve_setup_data_template;
  120993. /* a few static coder conventions */
  120994. static vorbis_info_mode _mode_template[2]={
  120995. {0,0,0,0},
  120996. {1,0,0,1}
  120997. };
  120998. static vorbis_info_mapping0 _map_nominal[2]={
  120999. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  121000. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  121001. };
  121002. /*** Start of inlined file: setup_44.h ***/
  121003. /*** Start of inlined file: floor_all.h ***/
  121004. /*** Start of inlined file: floor_books.h ***/
  121005. static long _huff_lengthlist_line_256x7_0sub1[] = {
  121006. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  121007. };
  121008. static static_codebook _huff_book_line_256x7_0sub1 = {
  121009. 1, 9,
  121010. _huff_lengthlist_line_256x7_0sub1,
  121011. 0, 0, 0, 0, 0,
  121012. NULL,
  121013. NULL,
  121014. NULL,
  121015. NULL,
  121016. 0
  121017. };
  121018. static long _huff_lengthlist_line_256x7_0sub2[] = {
  121019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  121020. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  121021. };
  121022. static static_codebook _huff_book_line_256x7_0sub2 = {
  121023. 1, 25,
  121024. _huff_lengthlist_line_256x7_0sub2,
  121025. 0, 0, 0, 0, 0,
  121026. NULL,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. 0
  121031. };
  121032. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121035. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121036. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121037. };
  121038. static static_codebook _huff_book_line_256x7_0sub3 = {
  121039. 1, 64,
  121040. _huff_lengthlist_line_256x7_0sub3,
  121041. 0, 0, 0, 0, 0,
  121042. NULL,
  121043. NULL,
  121044. NULL,
  121045. NULL,
  121046. 0
  121047. };
  121048. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121049. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121050. };
  121051. static static_codebook _huff_book_line_256x7_1sub1 = {
  121052. 1, 9,
  121053. _huff_lengthlist_line_256x7_1sub1,
  121054. 0, 0, 0, 0, 0,
  121055. NULL,
  121056. NULL,
  121057. NULL,
  121058. NULL,
  121059. 0
  121060. };
  121061. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121063. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121064. };
  121065. static static_codebook _huff_book_line_256x7_1sub2 = {
  121066. 1, 25,
  121067. _huff_lengthlist_line_256x7_1sub2,
  121068. 0, 0, 0, 0, 0,
  121069. NULL,
  121070. NULL,
  121071. NULL,
  121072. NULL,
  121073. 0
  121074. };
  121075. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121078. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121079. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121080. };
  121081. static static_codebook _huff_book_line_256x7_1sub3 = {
  121082. 1, 64,
  121083. _huff_lengthlist_line_256x7_1sub3,
  121084. 0, 0, 0, 0, 0,
  121085. NULL,
  121086. NULL,
  121087. NULL,
  121088. NULL,
  121089. 0
  121090. };
  121091. static long _huff_lengthlist_line_256x7_class0[] = {
  121092. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121093. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121094. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121095. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121096. };
  121097. static static_codebook _huff_book_line_256x7_class0 = {
  121098. 1, 64,
  121099. _huff_lengthlist_line_256x7_class0,
  121100. 0, 0, 0, 0, 0,
  121101. NULL,
  121102. NULL,
  121103. NULL,
  121104. NULL,
  121105. 0
  121106. };
  121107. static long _huff_lengthlist_line_256x7_class1[] = {
  121108. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121109. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121110. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121111. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121112. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121113. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121114. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121115. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121116. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121117. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121118. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121119. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121120. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121121. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121122. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121123. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121124. };
  121125. static static_codebook _huff_book_line_256x7_class1 = {
  121126. 1, 256,
  121127. _huff_lengthlist_line_256x7_class1,
  121128. 0, 0, 0, 0, 0,
  121129. NULL,
  121130. NULL,
  121131. NULL,
  121132. NULL,
  121133. 0
  121134. };
  121135. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121136. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121137. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121138. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121139. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121140. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121141. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121142. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121143. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121144. };
  121145. static static_codebook _huff_book_line_512x17_0sub0 = {
  121146. 1, 128,
  121147. _huff_lengthlist_line_512x17_0sub0,
  121148. 0, 0, 0, 0, 0,
  121149. NULL,
  121150. NULL,
  121151. NULL,
  121152. NULL,
  121153. 0
  121154. };
  121155. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121156. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121157. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121158. };
  121159. static static_codebook _huff_book_line_512x17_1sub0 = {
  121160. 1, 32,
  121161. _huff_lengthlist_line_512x17_1sub0,
  121162. 0, 0, 0, 0, 0,
  121163. NULL,
  121164. NULL,
  121165. NULL,
  121166. NULL,
  121167. 0
  121168. };
  121169. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121172. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121173. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121174. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121175. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121176. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121177. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121178. };
  121179. static static_codebook _huff_book_line_512x17_1sub1 = {
  121180. 1, 128,
  121181. _huff_lengthlist_line_512x17_1sub1,
  121182. 0, 0, 0, 0, 0,
  121183. NULL,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. 0
  121188. };
  121189. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121190. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121191. 5, 3,
  121192. };
  121193. static static_codebook _huff_book_line_512x17_2sub1 = {
  121194. 1, 18,
  121195. _huff_lengthlist_line_512x17_2sub1,
  121196. 0, 0, 0, 0, 0,
  121197. NULL,
  121198. NULL,
  121199. NULL,
  121200. NULL,
  121201. 0
  121202. };
  121203. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121205. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121206. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121207. 9, 8,
  121208. };
  121209. static static_codebook _huff_book_line_512x17_2sub2 = {
  121210. 1, 50,
  121211. _huff_lengthlist_line_512x17_2sub2,
  121212. 0, 0, 0, 0, 0,
  121213. NULL,
  121214. NULL,
  121215. NULL,
  121216. NULL,
  121217. 0
  121218. };
  121219. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121223. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121224. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121225. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121226. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121227. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121228. };
  121229. static static_codebook _huff_book_line_512x17_2sub3 = {
  121230. 1, 128,
  121231. _huff_lengthlist_line_512x17_2sub3,
  121232. 0, 0, 0, 0, 0,
  121233. NULL,
  121234. NULL,
  121235. NULL,
  121236. NULL,
  121237. 0
  121238. };
  121239. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121240. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121241. 5, 5,
  121242. };
  121243. static static_codebook _huff_book_line_512x17_3sub1 = {
  121244. 1, 18,
  121245. _huff_lengthlist_line_512x17_3sub1,
  121246. 0, 0, 0, 0, 0,
  121247. NULL,
  121248. NULL,
  121249. NULL,
  121250. NULL,
  121251. 0
  121252. };
  121253. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121255. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121256. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121257. 11,14,
  121258. };
  121259. static static_codebook _huff_book_line_512x17_3sub2 = {
  121260. 1, 50,
  121261. _huff_lengthlist_line_512x17_3sub2,
  121262. 0, 0, 0, 0, 0,
  121263. NULL,
  121264. NULL,
  121265. NULL,
  121266. NULL,
  121267. 0
  121268. };
  121269. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  121273. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121274. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121275. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121276. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121277. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121278. };
  121279. static static_codebook _huff_book_line_512x17_3sub3 = {
  121280. 1, 128,
  121281. _huff_lengthlist_line_512x17_3sub3,
  121282. 0, 0, 0, 0, 0,
  121283. NULL,
  121284. NULL,
  121285. NULL,
  121286. NULL,
  121287. 0
  121288. };
  121289. static long _huff_lengthlist_line_512x17_class1[] = {
  121290. 1, 2, 3, 6, 5, 4, 7, 7,
  121291. };
  121292. static static_codebook _huff_book_line_512x17_class1 = {
  121293. 1, 8,
  121294. _huff_lengthlist_line_512x17_class1,
  121295. 0, 0, 0, 0, 0,
  121296. NULL,
  121297. NULL,
  121298. NULL,
  121299. NULL,
  121300. 0
  121301. };
  121302. static long _huff_lengthlist_line_512x17_class2[] = {
  121303. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121304. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121305. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121306. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121307. };
  121308. static static_codebook _huff_book_line_512x17_class2 = {
  121309. 1, 64,
  121310. _huff_lengthlist_line_512x17_class2,
  121311. 0, 0, 0, 0, 0,
  121312. NULL,
  121313. NULL,
  121314. NULL,
  121315. NULL,
  121316. 0
  121317. };
  121318. static long _huff_lengthlist_line_512x17_class3[] = {
  121319. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121320. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121321. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121322. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121323. };
  121324. static static_codebook _huff_book_line_512x17_class3 = {
  121325. 1, 64,
  121326. _huff_lengthlist_line_512x17_class3,
  121327. 0, 0, 0, 0, 0,
  121328. NULL,
  121329. NULL,
  121330. NULL,
  121331. NULL,
  121332. 0
  121333. };
  121334. static long _huff_lengthlist_line_128x4_class0[] = {
  121335. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121336. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121337. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121338. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121339. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121340. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121341. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121342. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121343. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121344. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121345. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121346. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121347. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121348. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121349. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121350. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121351. };
  121352. static static_codebook _huff_book_line_128x4_class0 = {
  121353. 1, 256,
  121354. _huff_lengthlist_line_128x4_class0,
  121355. 0, 0, 0, 0, 0,
  121356. NULL,
  121357. NULL,
  121358. NULL,
  121359. NULL,
  121360. 0
  121361. };
  121362. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121363. 2, 2, 2, 2,
  121364. };
  121365. static static_codebook _huff_book_line_128x4_0sub0 = {
  121366. 1, 4,
  121367. _huff_lengthlist_line_128x4_0sub0,
  121368. 0, 0, 0, 0, 0,
  121369. NULL,
  121370. NULL,
  121371. NULL,
  121372. NULL,
  121373. 0
  121374. };
  121375. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121376. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121377. };
  121378. static static_codebook _huff_book_line_128x4_0sub1 = {
  121379. 1, 10,
  121380. _huff_lengthlist_line_128x4_0sub1,
  121381. 0, 0, 0, 0, 0,
  121382. NULL,
  121383. NULL,
  121384. NULL,
  121385. NULL,
  121386. 0
  121387. };
  121388. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121390. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121391. };
  121392. static static_codebook _huff_book_line_128x4_0sub2 = {
  121393. 1, 25,
  121394. _huff_lengthlist_line_128x4_0sub2,
  121395. 0, 0, 0, 0, 0,
  121396. NULL,
  121397. NULL,
  121398. NULL,
  121399. NULL,
  121400. 0
  121401. };
  121402. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121405. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121406. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121407. };
  121408. static static_codebook _huff_book_line_128x4_0sub3 = {
  121409. 1, 64,
  121410. _huff_lengthlist_line_128x4_0sub3,
  121411. 0, 0, 0, 0, 0,
  121412. NULL,
  121413. NULL,
  121414. NULL,
  121415. NULL,
  121416. 0
  121417. };
  121418. static long _huff_lengthlist_line_256x4_class0[] = {
  121419. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121420. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121421. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121422. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121423. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121424. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121425. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121426. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121427. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121428. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121429. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121430. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121431. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121432. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121433. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121434. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121435. };
  121436. static static_codebook _huff_book_line_256x4_class0 = {
  121437. 1, 256,
  121438. _huff_lengthlist_line_256x4_class0,
  121439. 0, 0, 0, 0, 0,
  121440. NULL,
  121441. NULL,
  121442. NULL,
  121443. NULL,
  121444. 0
  121445. };
  121446. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121447. 2, 2, 2, 2,
  121448. };
  121449. static static_codebook _huff_book_line_256x4_0sub0 = {
  121450. 1, 4,
  121451. _huff_lengthlist_line_256x4_0sub0,
  121452. 0, 0, 0, 0, 0,
  121453. NULL,
  121454. NULL,
  121455. NULL,
  121456. NULL,
  121457. 0
  121458. };
  121459. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121460. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121461. };
  121462. static static_codebook _huff_book_line_256x4_0sub1 = {
  121463. 1, 10,
  121464. _huff_lengthlist_line_256x4_0sub1,
  121465. 0, 0, 0, 0, 0,
  121466. NULL,
  121467. NULL,
  121468. NULL,
  121469. NULL,
  121470. 0
  121471. };
  121472. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121474. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121475. };
  121476. static static_codebook _huff_book_line_256x4_0sub2 = {
  121477. 1, 25,
  121478. _huff_lengthlist_line_256x4_0sub2,
  121479. 0, 0, 0, 0, 0,
  121480. NULL,
  121481. NULL,
  121482. NULL,
  121483. NULL,
  121484. 0
  121485. };
  121486. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121489. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121490. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121491. };
  121492. static static_codebook _huff_book_line_256x4_0sub3 = {
  121493. 1, 64,
  121494. _huff_lengthlist_line_256x4_0sub3,
  121495. 0, 0, 0, 0, 0,
  121496. NULL,
  121497. NULL,
  121498. NULL,
  121499. NULL,
  121500. 0
  121501. };
  121502. static long _huff_lengthlist_line_128x7_class0[] = {
  121503. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121504. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121505. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121506. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121507. };
  121508. static static_codebook _huff_book_line_128x7_class0 = {
  121509. 1, 64,
  121510. _huff_lengthlist_line_128x7_class0,
  121511. 0, 0, 0, 0, 0,
  121512. NULL,
  121513. NULL,
  121514. NULL,
  121515. NULL,
  121516. 0
  121517. };
  121518. static long _huff_lengthlist_line_128x7_class1[] = {
  121519. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121520. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121521. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121522. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121523. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121524. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121525. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121526. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121527. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121528. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121529. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121530. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121531. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121532. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121533. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121534. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121535. };
  121536. static static_codebook _huff_book_line_128x7_class1 = {
  121537. 1, 256,
  121538. _huff_lengthlist_line_128x7_class1,
  121539. 0, 0, 0, 0, 0,
  121540. NULL,
  121541. NULL,
  121542. NULL,
  121543. NULL,
  121544. 0
  121545. };
  121546. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121547. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121548. };
  121549. static static_codebook _huff_book_line_128x7_0sub1 = {
  121550. 1, 9,
  121551. _huff_lengthlist_line_128x7_0sub1,
  121552. 0, 0, 0, 0, 0,
  121553. NULL,
  121554. NULL,
  121555. NULL,
  121556. NULL,
  121557. 0
  121558. };
  121559. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121561. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121562. };
  121563. static static_codebook _huff_book_line_128x7_0sub2 = {
  121564. 1, 25,
  121565. _huff_lengthlist_line_128x7_0sub2,
  121566. 0, 0, 0, 0, 0,
  121567. NULL,
  121568. NULL,
  121569. NULL,
  121570. NULL,
  121571. 0
  121572. };
  121573. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121576. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121577. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121578. };
  121579. static static_codebook _huff_book_line_128x7_0sub3 = {
  121580. 1, 64,
  121581. _huff_lengthlist_line_128x7_0sub3,
  121582. 0, 0, 0, 0, 0,
  121583. NULL,
  121584. NULL,
  121585. NULL,
  121586. NULL,
  121587. 0
  121588. };
  121589. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121590. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121591. };
  121592. static static_codebook _huff_book_line_128x7_1sub1 = {
  121593. 1, 9,
  121594. _huff_lengthlist_line_128x7_1sub1,
  121595. 0, 0, 0, 0, 0,
  121596. NULL,
  121597. NULL,
  121598. NULL,
  121599. NULL,
  121600. 0
  121601. };
  121602. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121604. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121605. };
  121606. static static_codebook _huff_book_line_128x7_1sub2 = {
  121607. 1, 25,
  121608. _huff_lengthlist_line_128x7_1sub2,
  121609. 0, 0, 0, 0, 0,
  121610. NULL,
  121611. NULL,
  121612. NULL,
  121613. NULL,
  121614. 0
  121615. };
  121616. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121619. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121620. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121621. };
  121622. static static_codebook _huff_book_line_128x7_1sub3 = {
  121623. 1, 64,
  121624. _huff_lengthlist_line_128x7_1sub3,
  121625. 0, 0, 0, 0, 0,
  121626. NULL,
  121627. NULL,
  121628. NULL,
  121629. NULL,
  121630. 0
  121631. };
  121632. static long _huff_lengthlist_line_128x11_class1[] = {
  121633. 1, 6, 3, 7, 2, 4, 5, 7,
  121634. };
  121635. static static_codebook _huff_book_line_128x11_class1 = {
  121636. 1, 8,
  121637. _huff_lengthlist_line_128x11_class1,
  121638. 0, 0, 0, 0, 0,
  121639. NULL,
  121640. NULL,
  121641. NULL,
  121642. NULL,
  121643. 0
  121644. };
  121645. static long _huff_lengthlist_line_128x11_class2[] = {
  121646. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121647. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121648. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121649. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121650. };
  121651. static static_codebook _huff_book_line_128x11_class2 = {
  121652. 1, 64,
  121653. _huff_lengthlist_line_128x11_class2,
  121654. 0, 0, 0, 0, 0,
  121655. NULL,
  121656. NULL,
  121657. NULL,
  121658. NULL,
  121659. 0
  121660. };
  121661. static long _huff_lengthlist_line_128x11_class3[] = {
  121662. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121663. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121664. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121665. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121666. };
  121667. static static_codebook _huff_book_line_128x11_class3 = {
  121668. 1, 64,
  121669. _huff_lengthlist_line_128x11_class3,
  121670. 0, 0, 0, 0, 0,
  121671. NULL,
  121672. NULL,
  121673. NULL,
  121674. NULL,
  121675. 0
  121676. };
  121677. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121678. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121679. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121680. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121681. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121682. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121683. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121684. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121685. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121686. };
  121687. static static_codebook _huff_book_line_128x11_0sub0 = {
  121688. 1, 128,
  121689. _huff_lengthlist_line_128x11_0sub0,
  121690. 0, 0, 0, 0, 0,
  121691. NULL,
  121692. NULL,
  121693. NULL,
  121694. NULL,
  121695. 0
  121696. };
  121697. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121698. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121699. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121700. };
  121701. static static_codebook _huff_book_line_128x11_1sub0 = {
  121702. 1, 32,
  121703. _huff_lengthlist_line_128x11_1sub0,
  121704. 0, 0, 0, 0, 0,
  121705. NULL,
  121706. NULL,
  121707. NULL,
  121708. NULL,
  121709. 0
  121710. };
  121711. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121715. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121716. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121717. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121718. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121719. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121720. };
  121721. static static_codebook _huff_book_line_128x11_1sub1 = {
  121722. 1, 128,
  121723. _huff_lengthlist_line_128x11_1sub1,
  121724. 0, 0, 0, 0, 0,
  121725. NULL,
  121726. NULL,
  121727. NULL,
  121728. NULL,
  121729. 0
  121730. };
  121731. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121732. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121733. 5, 5,
  121734. };
  121735. static static_codebook _huff_book_line_128x11_2sub1 = {
  121736. 1, 18,
  121737. _huff_lengthlist_line_128x11_2sub1,
  121738. 0, 0, 0, 0, 0,
  121739. NULL,
  121740. NULL,
  121741. NULL,
  121742. NULL,
  121743. 0
  121744. };
  121745. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121748. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121749. 8,11,
  121750. };
  121751. static static_codebook _huff_book_line_128x11_2sub2 = {
  121752. 1, 50,
  121753. _huff_lengthlist_line_128x11_2sub2,
  121754. 0, 0, 0, 0, 0,
  121755. NULL,
  121756. NULL,
  121757. NULL,
  121758. NULL,
  121759. 0
  121760. };
  121761. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121766. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121767. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121768. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121769. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121770. };
  121771. static static_codebook _huff_book_line_128x11_2sub3 = {
  121772. 1, 128,
  121773. _huff_lengthlist_line_128x11_2sub3,
  121774. 0, 0, 0, 0, 0,
  121775. NULL,
  121776. NULL,
  121777. NULL,
  121778. NULL,
  121779. 0
  121780. };
  121781. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121782. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121783. 5, 4,
  121784. };
  121785. static static_codebook _huff_book_line_128x11_3sub1 = {
  121786. 1, 18,
  121787. _huff_lengthlist_line_128x11_3sub1,
  121788. 0, 0, 0, 0, 0,
  121789. NULL,
  121790. NULL,
  121791. NULL,
  121792. NULL,
  121793. 0
  121794. };
  121795. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121797. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121798. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121799. 12, 6,
  121800. };
  121801. static static_codebook _huff_book_line_128x11_3sub2 = {
  121802. 1, 50,
  121803. _huff_lengthlist_line_128x11_3sub2,
  121804. 0, 0, 0, 0, 0,
  121805. NULL,
  121806. NULL,
  121807. NULL,
  121808. NULL,
  121809. 0
  121810. };
  121811. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121815. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121816. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121817. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121819. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121820. };
  121821. static static_codebook _huff_book_line_128x11_3sub3 = {
  121822. 1, 128,
  121823. _huff_lengthlist_line_128x11_3sub3,
  121824. 0, 0, 0, 0, 0,
  121825. NULL,
  121826. NULL,
  121827. NULL,
  121828. NULL,
  121829. 0
  121830. };
  121831. static long _huff_lengthlist_line_128x17_class1[] = {
  121832. 1, 3, 4, 7, 2, 5, 6, 7,
  121833. };
  121834. static static_codebook _huff_book_line_128x17_class1 = {
  121835. 1, 8,
  121836. _huff_lengthlist_line_128x17_class1,
  121837. 0, 0, 0, 0, 0,
  121838. NULL,
  121839. NULL,
  121840. NULL,
  121841. NULL,
  121842. 0
  121843. };
  121844. static long _huff_lengthlist_line_128x17_class2[] = {
  121845. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121846. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121847. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121848. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121849. };
  121850. static static_codebook _huff_book_line_128x17_class2 = {
  121851. 1, 64,
  121852. _huff_lengthlist_line_128x17_class2,
  121853. 0, 0, 0, 0, 0,
  121854. NULL,
  121855. NULL,
  121856. NULL,
  121857. NULL,
  121858. 0
  121859. };
  121860. static long _huff_lengthlist_line_128x17_class3[] = {
  121861. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121862. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121863. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121864. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121865. };
  121866. static static_codebook _huff_book_line_128x17_class3 = {
  121867. 1, 64,
  121868. _huff_lengthlist_line_128x17_class3,
  121869. 0, 0, 0, 0, 0,
  121870. NULL,
  121871. NULL,
  121872. NULL,
  121873. NULL,
  121874. 0
  121875. };
  121876. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121877. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121878. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121879. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121880. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121881. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121882. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121883. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121884. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121885. };
  121886. static static_codebook _huff_book_line_128x17_0sub0 = {
  121887. 1, 128,
  121888. _huff_lengthlist_line_128x17_0sub0,
  121889. 0, 0, 0, 0, 0,
  121890. NULL,
  121891. NULL,
  121892. NULL,
  121893. NULL,
  121894. 0
  121895. };
  121896. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121897. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121898. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121899. };
  121900. static static_codebook _huff_book_line_128x17_1sub0 = {
  121901. 1, 32,
  121902. _huff_lengthlist_line_128x17_1sub0,
  121903. 0, 0, 0, 0, 0,
  121904. NULL,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. 0
  121909. };
  121910. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121914. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121915. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121916. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121917. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121918. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121919. };
  121920. static static_codebook _huff_book_line_128x17_1sub1 = {
  121921. 1, 128,
  121922. _huff_lengthlist_line_128x17_1sub1,
  121923. 0, 0, 0, 0, 0,
  121924. NULL,
  121925. NULL,
  121926. NULL,
  121927. NULL,
  121928. 0
  121929. };
  121930. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121931. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121932. 9, 4,
  121933. };
  121934. static static_codebook _huff_book_line_128x17_2sub1 = {
  121935. 1, 18,
  121936. _huff_lengthlist_line_128x17_2sub1,
  121937. 0, 0, 0, 0, 0,
  121938. NULL,
  121939. NULL,
  121940. NULL,
  121941. NULL,
  121942. 0
  121943. };
  121944. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121947. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121948. 13,13,
  121949. };
  121950. static static_codebook _huff_book_line_128x17_2sub2 = {
  121951. 1, 50,
  121952. _huff_lengthlist_line_128x17_2sub2,
  121953. 0, 0, 0, 0, 0,
  121954. NULL,
  121955. NULL,
  121956. NULL,
  121957. NULL,
  121958. 0
  121959. };
  121960. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121965. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121966. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121967. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121968. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121969. };
  121970. static static_codebook _huff_book_line_128x17_2sub3 = {
  121971. 1, 128,
  121972. _huff_lengthlist_line_128x17_2sub3,
  121973. 0, 0, 0, 0, 0,
  121974. NULL,
  121975. NULL,
  121976. NULL,
  121977. NULL,
  121978. 0
  121979. };
  121980. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121981. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121982. 6, 4,
  121983. };
  121984. static static_codebook _huff_book_line_128x17_3sub1 = {
  121985. 1, 18,
  121986. _huff_lengthlist_line_128x17_3sub1,
  121987. 0, 0, 0, 0, 0,
  121988. NULL,
  121989. NULL,
  121990. NULL,
  121991. NULL,
  121992. 0
  121993. };
  121994. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121996. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121997. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121998. 10, 8,
  121999. };
  122000. static static_codebook _huff_book_line_128x17_3sub2 = {
  122001. 1, 50,
  122002. _huff_lengthlist_line_128x17_3sub2,
  122003. 0, 0, 0, 0, 0,
  122004. NULL,
  122005. NULL,
  122006. NULL,
  122007. NULL,
  122008. 0
  122009. };
  122010. static long _huff_lengthlist_line_128x17_3sub3[] = {
  122011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122014. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  122015. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  122016. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122019. };
  122020. static static_codebook _huff_book_line_128x17_3sub3 = {
  122021. 1, 128,
  122022. _huff_lengthlist_line_128x17_3sub3,
  122023. 0, 0, 0, 0, 0,
  122024. NULL,
  122025. NULL,
  122026. NULL,
  122027. NULL,
  122028. 0
  122029. };
  122030. static long _huff_lengthlist_line_1024x27_class1[] = {
  122031. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122032. };
  122033. static static_codebook _huff_book_line_1024x27_class1 = {
  122034. 1, 16,
  122035. _huff_lengthlist_line_1024x27_class1,
  122036. 0, 0, 0, 0, 0,
  122037. NULL,
  122038. NULL,
  122039. NULL,
  122040. NULL,
  122041. 0
  122042. };
  122043. static long _huff_lengthlist_line_1024x27_class2[] = {
  122044. 1, 4, 2, 6, 3, 7, 5, 7,
  122045. };
  122046. static static_codebook _huff_book_line_1024x27_class2 = {
  122047. 1, 8,
  122048. _huff_lengthlist_line_1024x27_class2,
  122049. 0, 0, 0, 0, 0,
  122050. NULL,
  122051. NULL,
  122052. NULL,
  122053. NULL,
  122054. 0
  122055. };
  122056. static long _huff_lengthlist_line_1024x27_class3[] = {
  122057. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122058. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122059. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122060. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122061. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122062. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122063. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122064. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122065. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122066. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122067. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122068. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122069. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122070. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122071. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122072. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122073. };
  122074. static static_codebook _huff_book_line_1024x27_class3 = {
  122075. 1, 256,
  122076. _huff_lengthlist_line_1024x27_class3,
  122077. 0, 0, 0, 0, 0,
  122078. NULL,
  122079. NULL,
  122080. NULL,
  122081. NULL,
  122082. 0
  122083. };
  122084. static long _huff_lengthlist_line_1024x27_class4[] = {
  122085. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122086. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122087. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122088. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122089. };
  122090. static static_codebook _huff_book_line_1024x27_class4 = {
  122091. 1, 64,
  122092. _huff_lengthlist_line_1024x27_class4,
  122093. 0, 0, 0, 0, 0,
  122094. NULL,
  122095. NULL,
  122096. NULL,
  122097. NULL,
  122098. 0
  122099. };
  122100. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122101. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122102. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122103. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122104. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122105. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122106. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122107. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122108. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122109. };
  122110. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122111. 1, 128,
  122112. _huff_lengthlist_line_1024x27_0sub0,
  122113. 0, 0, 0, 0, 0,
  122114. NULL,
  122115. NULL,
  122116. NULL,
  122117. NULL,
  122118. 0
  122119. };
  122120. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122121. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122122. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122123. };
  122124. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122125. 1, 32,
  122126. _huff_lengthlist_line_1024x27_1sub0,
  122127. 0, 0, 0, 0, 0,
  122128. NULL,
  122129. NULL,
  122130. NULL,
  122131. NULL,
  122132. 0
  122133. };
  122134. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122138. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122139. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122140. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122141. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122142. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122143. };
  122144. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122145. 1, 128,
  122146. _huff_lengthlist_line_1024x27_1sub1,
  122147. 0, 0, 0, 0, 0,
  122148. NULL,
  122149. NULL,
  122150. NULL,
  122151. NULL,
  122152. 0
  122153. };
  122154. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122155. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122156. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122157. };
  122158. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122159. 1, 32,
  122160. _huff_lengthlist_line_1024x27_2sub0,
  122161. 0, 0, 0, 0, 0,
  122162. NULL,
  122163. NULL,
  122164. NULL,
  122165. NULL,
  122166. 0
  122167. };
  122168. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122171. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122172. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122173. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122174. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122175. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122176. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122177. };
  122178. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122179. 1, 128,
  122180. _huff_lengthlist_line_1024x27_2sub1,
  122181. 0, 0, 0, 0, 0,
  122182. NULL,
  122183. NULL,
  122184. NULL,
  122185. NULL,
  122186. 0
  122187. };
  122188. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122189. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122190. 5, 5,
  122191. };
  122192. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122193. 1, 18,
  122194. _huff_lengthlist_line_1024x27_3sub1,
  122195. 0, 0, 0, 0, 0,
  122196. NULL,
  122197. NULL,
  122198. NULL,
  122199. NULL,
  122200. 0
  122201. };
  122202. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122204. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122205. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122206. 9,11,
  122207. };
  122208. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122209. 1, 50,
  122210. _huff_lengthlist_line_1024x27_3sub2,
  122211. 0, 0, 0, 0, 0,
  122212. NULL,
  122213. NULL,
  122214. NULL,
  122215. NULL,
  122216. 0
  122217. };
  122218. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122222. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122223. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122224. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122225. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122226. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122227. };
  122228. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122229. 1, 128,
  122230. _huff_lengthlist_line_1024x27_3sub3,
  122231. 0, 0, 0, 0, 0,
  122232. NULL,
  122233. NULL,
  122234. NULL,
  122235. NULL,
  122236. 0
  122237. };
  122238. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122239. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122240. 5, 4,
  122241. };
  122242. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122243. 1, 18,
  122244. _huff_lengthlist_line_1024x27_4sub1,
  122245. 0, 0, 0, 0, 0,
  122246. NULL,
  122247. NULL,
  122248. NULL,
  122249. NULL,
  122250. 0
  122251. };
  122252. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122255. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122256. 9,12,
  122257. };
  122258. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122259. 1, 50,
  122260. _huff_lengthlist_line_1024x27_4sub2,
  122261. 0, 0, 0, 0, 0,
  122262. NULL,
  122263. NULL,
  122264. NULL,
  122265. NULL,
  122266. 0
  122267. };
  122268. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122272. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122273. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122276. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122277. };
  122278. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122279. 1, 128,
  122280. _huff_lengthlist_line_1024x27_4sub3,
  122281. 0, 0, 0, 0, 0,
  122282. NULL,
  122283. NULL,
  122284. NULL,
  122285. NULL,
  122286. 0
  122287. };
  122288. static long _huff_lengthlist_line_2048x27_class1[] = {
  122289. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122290. };
  122291. static static_codebook _huff_book_line_2048x27_class1 = {
  122292. 1, 16,
  122293. _huff_lengthlist_line_2048x27_class1,
  122294. 0, 0, 0, 0, 0,
  122295. NULL,
  122296. NULL,
  122297. NULL,
  122298. NULL,
  122299. 0
  122300. };
  122301. static long _huff_lengthlist_line_2048x27_class2[] = {
  122302. 1, 2, 3, 6, 4, 7, 5, 7,
  122303. };
  122304. static static_codebook _huff_book_line_2048x27_class2 = {
  122305. 1, 8,
  122306. _huff_lengthlist_line_2048x27_class2,
  122307. 0, 0, 0, 0, 0,
  122308. NULL,
  122309. NULL,
  122310. NULL,
  122311. NULL,
  122312. 0
  122313. };
  122314. static long _huff_lengthlist_line_2048x27_class3[] = {
  122315. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122316. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122317. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122318. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122319. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122320. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122321. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122322. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122323. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122324. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122325. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122326. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122327. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122328. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122329. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122330. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122331. };
  122332. static static_codebook _huff_book_line_2048x27_class3 = {
  122333. 1, 256,
  122334. _huff_lengthlist_line_2048x27_class3,
  122335. 0, 0, 0, 0, 0,
  122336. NULL,
  122337. NULL,
  122338. NULL,
  122339. NULL,
  122340. 0
  122341. };
  122342. static long _huff_lengthlist_line_2048x27_class4[] = {
  122343. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122344. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122345. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122346. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122347. };
  122348. static static_codebook _huff_book_line_2048x27_class4 = {
  122349. 1, 64,
  122350. _huff_lengthlist_line_2048x27_class4,
  122351. 0, 0, 0, 0, 0,
  122352. NULL,
  122353. NULL,
  122354. NULL,
  122355. NULL,
  122356. 0
  122357. };
  122358. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122359. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122360. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122361. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122362. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122363. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122364. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122365. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122366. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122367. };
  122368. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122369. 1, 128,
  122370. _huff_lengthlist_line_2048x27_0sub0,
  122371. 0, 0, 0, 0, 0,
  122372. NULL,
  122373. NULL,
  122374. NULL,
  122375. NULL,
  122376. 0
  122377. };
  122378. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122379. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122380. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122381. };
  122382. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122383. 1, 32,
  122384. _huff_lengthlist_line_2048x27_1sub0,
  122385. 0, 0, 0, 0, 0,
  122386. NULL,
  122387. NULL,
  122388. NULL,
  122389. NULL,
  122390. 0
  122391. };
  122392. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122396. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122397. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122398. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122399. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122400. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122401. };
  122402. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122403. 1, 128,
  122404. _huff_lengthlist_line_2048x27_1sub1,
  122405. 0, 0, 0, 0, 0,
  122406. NULL,
  122407. NULL,
  122408. NULL,
  122409. NULL,
  122410. 0
  122411. };
  122412. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122413. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122414. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122415. };
  122416. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122417. 1, 32,
  122418. _huff_lengthlist_line_2048x27_2sub0,
  122419. 0, 0, 0, 0, 0,
  122420. NULL,
  122421. NULL,
  122422. NULL,
  122423. NULL,
  122424. 0
  122425. };
  122426. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122430. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122431. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122432. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122433. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122434. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122435. };
  122436. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122437. 1, 128,
  122438. _huff_lengthlist_line_2048x27_2sub1,
  122439. 0, 0, 0, 0, 0,
  122440. NULL,
  122441. NULL,
  122442. NULL,
  122443. NULL,
  122444. 0
  122445. };
  122446. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122447. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122448. 5, 5,
  122449. };
  122450. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122451. 1, 18,
  122452. _huff_lengthlist_line_2048x27_3sub1,
  122453. 0, 0, 0, 0, 0,
  122454. NULL,
  122455. NULL,
  122456. NULL,
  122457. NULL,
  122458. 0
  122459. };
  122460. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122463. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122464. 10,12,
  122465. };
  122466. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122467. 1, 50,
  122468. _huff_lengthlist_line_2048x27_3sub2,
  122469. 0, 0, 0, 0, 0,
  122470. NULL,
  122471. NULL,
  122472. NULL,
  122473. NULL,
  122474. 0
  122475. };
  122476. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122481. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122482. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122483. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122484. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122485. };
  122486. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122487. 1, 128,
  122488. _huff_lengthlist_line_2048x27_3sub3,
  122489. 0, 0, 0, 0, 0,
  122490. NULL,
  122491. NULL,
  122492. NULL,
  122493. NULL,
  122494. 0
  122495. };
  122496. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122497. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122498. 4, 5,
  122499. };
  122500. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122501. 1, 18,
  122502. _huff_lengthlist_line_2048x27_4sub1,
  122503. 0, 0, 0, 0, 0,
  122504. NULL,
  122505. NULL,
  122506. NULL,
  122507. NULL,
  122508. 0
  122509. };
  122510. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122513. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122514. 10,10,
  122515. };
  122516. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122517. 1, 50,
  122518. _huff_lengthlist_line_2048x27_4sub2,
  122519. 0, 0, 0, 0, 0,
  122520. NULL,
  122521. NULL,
  122522. NULL,
  122523. NULL,
  122524. 0
  122525. };
  122526. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122531. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122532. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122533. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122534. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122535. };
  122536. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122537. 1, 128,
  122538. _huff_lengthlist_line_2048x27_4sub3,
  122539. 0, 0, 0, 0, 0,
  122540. NULL,
  122541. NULL,
  122542. NULL,
  122543. NULL,
  122544. 0
  122545. };
  122546. static long _huff_lengthlist_line_256x4low_class0[] = {
  122547. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122548. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122549. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122550. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122551. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122552. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122553. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122554. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122555. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122556. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122557. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122558. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122559. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122560. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122561. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122562. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122563. };
  122564. static static_codebook _huff_book_line_256x4low_class0 = {
  122565. 1, 256,
  122566. _huff_lengthlist_line_256x4low_class0,
  122567. 0, 0, 0, 0, 0,
  122568. NULL,
  122569. NULL,
  122570. NULL,
  122571. NULL,
  122572. 0
  122573. };
  122574. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122575. 1, 3, 2, 3,
  122576. };
  122577. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122578. 1, 4,
  122579. _huff_lengthlist_line_256x4low_0sub0,
  122580. 0, 0, 0, 0, 0,
  122581. NULL,
  122582. NULL,
  122583. NULL,
  122584. NULL,
  122585. 0
  122586. };
  122587. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122588. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122589. };
  122590. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122591. 1, 10,
  122592. _huff_lengthlist_line_256x4low_0sub1,
  122593. 0, 0, 0, 0, 0,
  122594. NULL,
  122595. NULL,
  122596. NULL,
  122597. NULL,
  122598. 0
  122599. };
  122600. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122602. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122603. };
  122604. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122605. 1, 25,
  122606. _huff_lengthlist_line_256x4low_0sub2,
  122607. 0, 0, 0, 0, 0,
  122608. NULL,
  122609. NULL,
  122610. NULL,
  122611. NULL,
  122612. 0
  122613. };
  122614. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122617. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122618. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122619. };
  122620. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122621. 1, 64,
  122622. _huff_lengthlist_line_256x4low_0sub3,
  122623. 0, 0, 0, 0, 0,
  122624. NULL,
  122625. NULL,
  122626. NULL,
  122627. NULL,
  122628. 0
  122629. };
  122630. /*** End of inlined file: floor_books.h ***/
  122631. static static_codebook *_floor_128x4_books[]={
  122632. &_huff_book_line_128x4_class0,
  122633. &_huff_book_line_128x4_0sub0,
  122634. &_huff_book_line_128x4_0sub1,
  122635. &_huff_book_line_128x4_0sub2,
  122636. &_huff_book_line_128x4_0sub3,
  122637. };
  122638. static static_codebook *_floor_256x4_books[]={
  122639. &_huff_book_line_256x4_class0,
  122640. &_huff_book_line_256x4_0sub0,
  122641. &_huff_book_line_256x4_0sub1,
  122642. &_huff_book_line_256x4_0sub2,
  122643. &_huff_book_line_256x4_0sub3,
  122644. };
  122645. static static_codebook *_floor_128x7_books[]={
  122646. &_huff_book_line_128x7_class0,
  122647. &_huff_book_line_128x7_class1,
  122648. &_huff_book_line_128x7_0sub1,
  122649. &_huff_book_line_128x7_0sub2,
  122650. &_huff_book_line_128x7_0sub3,
  122651. &_huff_book_line_128x7_1sub1,
  122652. &_huff_book_line_128x7_1sub2,
  122653. &_huff_book_line_128x7_1sub3,
  122654. };
  122655. static static_codebook *_floor_256x7_books[]={
  122656. &_huff_book_line_256x7_class0,
  122657. &_huff_book_line_256x7_class1,
  122658. &_huff_book_line_256x7_0sub1,
  122659. &_huff_book_line_256x7_0sub2,
  122660. &_huff_book_line_256x7_0sub3,
  122661. &_huff_book_line_256x7_1sub1,
  122662. &_huff_book_line_256x7_1sub2,
  122663. &_huff_book_line_256x7_1sub3,
  122664. };
  122665. static static_codebook *_floor_128x11_books[]={
  122666. &_huff_book_line_128x11_class1,
  122667. &_huff_book_line_128x11_class2,
  122668. &_huff_book_line_128x11_class3,
  122669. &_huff_book_line_128x11_0sub0,
  122670. &_huff_book_line_128x11_1sub0,
  122671. &_huff_book_line_128x11_1sub1,
  122672. &_huff_book_line_128x11_2sub1,
  122673. &_huff_book_line_128x11_2sub2,
  122674. &_huff_book_line_128x11_2sub3,
  122675. &_huff_book_line_128x11_3sub1,
  122676. &_huff_book_line_128x11_3sub2,
  122677. &_huff_book_line_128x11_3sub3,
  122678. };
  122679. static static_codebook *_floor_128x17_books[]={
  122680. &_huff_book_line_128x17_class1,
  122681. &_huff_book_line_128x17_class2,
  122682. &_huff_book_line_128x17_class3,
  122683. &_huff_book_line_128x17_0sub0,
  122684. &_huff_book_line_128x17_1sub0,
  122685. &_huff_book_line_128x17_1sub1,
  122686. &_huff_book_line_128x17_2sub1,
  122687. &_huff_book_line_128x17_2sub2,
  122688. &_huff_book_line_128x17_2sub3,
  122689. &_huff_book_line_128x17_3sub1,
  122690. &_huff_book_line_128x17_3sub2,
  122691. &_huff_book_line_128x17_3sub3,
  122692. };
  122693. static static_codebook *_floor_256x4low_books[]={
  122694. &_huff_book_line_256x4low_class0,
  122695. &_huff_book_line_256x4low_0sub0,
  122696. &_huff_book_line_256x4low_0sub1,
  122697. &_huff_book_line_256x4low_0sub2,
  122698. &_huff_book_line_256x4low_0sub3,
  122699. };
  122700. static static_codebook *_floor_1024x27_books[]={
  122701. &_huff_book_line_1024x27_class1,
  122702. &_huff_book_line_1024x27_class2,
  122703. &_huff_book_line_1024x27_class3,
  122704. &_huff_book_line_1024x27_class4,
  122705. &_huff_book_line_1024x27_0sub0,
  122706. &_huff_book_line_1024x27_1sub0,
  122707. &_huff_book_line_1024x27_1sub1,
  122708. &_huff_book_line_1024x27_2sub0,
  122709. &_huff_book_line_1024x27_2sub1,
  122710. &_huff_book_line_1024x27_3sub1,
  122711. &_huff_book_line_1024x27_3sub2,
  122712. &_huff_book_line_1024x27_3sub3,
  122713. &_huff_book_line_1024x27_4sub1,
  122714. &_huff_book_line_1024x27_4sub2,
  122715. &_huff_book_line_1024x27_4sub3,
  122716. };
  122717. static static_codebook *_floor_2048x27_books[]={
  122718. &_huff_book_line_2048x27_class1,
  122719. &_huff_book_line_2048x27_class2,
  122720. &_huff_book_line_2048x27_class3,
  122721. &_huff_book_line_2048x27_class4,
  122722. &_huff_book_line_2048x27_0sub0,
  122723. &_huff_book_line_2048x27_1sub0,
  122724. &_huff_book_line_2048x27_1sub1,
  122725. &_huff_book_line_2048x27_2sub0,
  122726. &_huff_book_line_2048x27_2sub1,
  122727. &_huff_book_line_2048x27_3sub1,
  122728. &_huff_book_line_2048x27_3sub2,
  122729. &_huff_book_line_2048x27_3sub3,
  122730. &_huff_book_line_2048x27_4sub1,
  122731. &_huff_book_line_2048x27_4sub2,
  122732. &_huff_book_line_2048x27_4sub3,
  122733. };
  122734. static static_codebook *_floor_512x17_books[]={
  122735. &_huff_book_line_512x17_class1,
  122736. &_huff_book_line_512x17_class2,
  122737. &_huff_book_line_512x17_class3,
  122738. &_huff_book_line_512x17_0sub0,
  122739. &_huff_book_line_512x17_1sub0,
  122740. &_huff_book_line_512x17_1sub1,
  122741. &_huff_book_line_512x17_2sub1,
  122742. &_huff_book_line_512x17_2sub2,
  122743. &_huff_book_line_512x17_2sub3,
  122744. &_huff_book_line_512x17_3sub1,
  122745. &_huff_book_line_512x17_3sub2,
  122746. &_huff_book_line_512x17_3sub3,
  122747. };
  122748. static static_codebook **_floor_books[10]={
  122749. _floor_128x4_books,
  122750. _floor_256x4_books,
  122751. _floor_128x7_books,
  122752. _floor_256x7_books,
  122753. _floor_128x11_books,
  122754. _floor_128x17_books,
  122755. _floor_256x4low_books,
  122756. _floor_1024x27_books,
  122757. _floor_2048x27_books,
  122758. _floor_512x17_books,
  122759. };
  122760. static vorbis_info_floor1 _floor[10]={
  122761. /* 128 x 4 */
  122762. {
  122763. 1,{0},{4},{2},{0},
  122764. {{1,2,3,4}},
  122765. 4,{0,128, 33,8,16,70},
  122766. 60,30,500, 1.,18., -1
  122767. },
  122768. /* 256 x 4 */
  122769. {
  122770. 1,{0},{4},{2},{0},
  122771. {{1,2,3,4}},
  122772. 4,{0,256, 66,16,32,140},
  122773. 60,30,500, 1.,18., -1
  122774. },
  122775. /* 128 x 7 */
  122776. {
  122777. 2,{0,1},{3,4},{2,2},{0,1},
  122778. {{-1,2,3,4},{-1,5,6,7}},
  122779. 4,{0,128, 14,4,58, 2,8,28,90},
  122780. 60,30,500, 1.,18., -1
  122781. },
  122782. /* 256 x 7 */
  122783. {
  122784. 2,{0,1},{3,4},{2,2},{0,1},
  122785. {{-1,2,3,4},{-1,5,6,7}},
  122786. 4,{0,256, 28,8,116, 4,16,56,180},
  122787. 60,30,500, 1.,18., -1
  122788. },
  122789. /* 128 x 11 */
  122790. {
  122791. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122792. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122793. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122794. 60,30,500, 1,18., -1
  122795. },
  122796. /* 128 x 17 */
  122797. {
  122798. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122799. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122800. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122801. 60,30,500, 1,18., -1
  122802. },
  122803. /* 256 x 4 (low bitrate version) */
  122804. {
  122805. 1,{0},{4},{2},{0},
  122806. {{1,2,3,4}},
  122807. 4,{0,256, 66,16,32,140},
  122808. 60,30,500, 1.,18., -1
  122809. },
  122810. /* 1024 x 27 */
  122811. {
  122812. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122813. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122814. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122815. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122816. 60,30,500, 3,18., -1 /* lowpass */
  122817. },
  122818. /* 2048 x 27 */
  122819. {
  122820. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122821. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122822. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122823. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122824. 60,30,500, 3,18., -1 /* lowpass */
  122825. },
  122826. /* 512 x 17 */
  122827. {
  122828. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122829. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122830. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122831. 7,23,39, 55,79,110, 156,232,360},
  122832. 60,30,500, 1,18., -1 /* lowpass! */
  122833. },
  122834. };
  122835. /*** End of inlined file: floor_all.h ***/
  122836. /*** Start of inlined file: residue_44.h ***/
  122837. /*** Start of inlined file: res_books_stereo.h ***/
  122838. static long _vq_quantlist__16c0_s_p1_0[] = {
  122839. 1,
  122840. 0,
  122841. 2,
  122842. };
  122843. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122844. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122845. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122850. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122855. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  122890. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122895. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122900. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122936. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122941. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122946. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  123255. };
  123256. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123257. -0.5, 0.5,
  123258. };
  123259. static long _vq_quantmap__16c0_s_p1_0[] = {
  123260. 1, 0, 2,
  123261. };
  123262. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123263. _vq_quantthresh__16c0_s_p1_0,
  123264. _vq_quantmap__16c0_s_p1_0,
  123265. 3,
  123266. 3
  123267. };
  123268. static static_codebook _16c0_s_p1_0 = {
  123269. 8, 6561,
  123270. _vq_lengthlist__16c0_s_p1_0,
  123271. 1, -535822336, 1611661312, 2, 0,
  123272. _vq_quantlist__16c0_s_p1_0,
  123273. NULL,
  123274. &_vq_auxt__16c0_s_p1_0,
  123275. NULL,
  123276. 0
  123277. };
  123278. static long _vq_quantlist__16c0_s_p2_0[] = {
  123279. 2,
  123280. 1,
  123281. 3,
  123282. 0,
  123283. 4,
  123284. };
  123285. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123325. 0,
  123326. };
  123327. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123328. -1.5, -0.5, 0.5, 1.5,
  123329. };
  123330. static long _vq_quantmap__16c0_s_p2_0[] = {
  123331. 3, 1, 0, 2, 4,
  123332. };
  123333. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123334. _vq_quantthresh__16c0_s_p2_0,
  123335. _vq_quantmap__16c0_s_p2_0,
  123336. 5,
  123337. 5
  123338. };
  123339. static static_codebook _16c0_s_p2_0 = {
  123340. 4, 625,
  123341. _vq_lengthlist__16c0_s_p2_0,
  123342. 1, -533725184, 1611661312, 3, 0,
  123343. _vq_quantlist__16c0_s_p2_0,
  123344. NULL,
  123345. &_vq_auxt__16c0_s_p2_0,
  123346. NULL,
  123347. 0
  123348. };
  123349. static long _vq_quantlist__16c0_s_p3_0[] = {
  123350. 2,
  123351. 1,
  123352. 3,
  123353. 0,
  123354. 4,
  123355. };
  123356. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123357. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123396. 0,
  123397. };
  123398. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123399. -1.5, -0.5, 0.5, 1.5,
  123400. };
  123401. static long _vq_quantmap__16c0_s_p3_0[] = {
  123402. 3, 1, 0, 2, 4,
  123403. };
  123404. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123405. _vq_quantthresh__16c0_s_p3_0,
  123406. _vq_quantmap__16c0_s_p3_0,
  123407. 5,
  123408. 5
  123409. };
  123410. static static_codebook _16c0_s_p3_0 = {
  123411. 4, 625,
  123412. _vq_lengthlist__16c0_s_p3_0,
  123413. 1, -533725184, 1611661312, 3, 0,
  123414. _vq_quantlist__16c0_s_p3_0,
  123415. NULL,
  123416. &_vq_auxt__16c0_s_p3_0,
  123417. NULL,
  123418. 0
  123419. };
  123420. static long _vq_quantlist__16c0_s_p4_0[] = {
  123421. 4,
  123422. 3,
  123423. 5,
  123424. 2,
  123425. 6,
  123426. 1,
  123427. 7,
  123428. 0,
  123429. 8,
  123430. };
  123431. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123432. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123433. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123434. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123435. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123436. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0,
  123438. };
  123439. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123440. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123441. };
  123442. static long _vq_quantmap__16c0_s_p4_0[] = {
  123443. 7, 5, 3, 1, 0, 2, 4, 6,
  123444. 8,
  123445. };
  123446. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123447. _vq_quantthresh__16c0_s_p4_0,
  123448. _vq_quantmap__16c0_s_p4_0,
  123449. 9,
  123450. 9
  123451. };
  123452. static static_codebook _16c0_s_p4_0 = {
  123453. 2, 81,
  123454. _vq_lengthlist__16c0_s_p4_0,
  123455. 1, -531628032, 1611661312, 4, 0,
  123456. _vq_quantlist__16c0_s_p4_0,
  123457. NULL,
  123458. &_vq_auxt__16c0_s_p4_0,
  123459. NULL,
  123460. 0
  123461. };
  123462. static long _vq_quantlist__16c0_s_p5_0[] = {
  123463. 4,
  123464. 3,
  123465. 5,
  123466. 2,
  123467. 6,
  123468. 1,
  123469. 7,
  123470. 0,
  123471. 8,
  123472. };
  123473. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123474. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123475. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123476. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123477. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123478. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123479. 10,
  123480. };
  123481. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123482. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123483. };
  123484. static long _vq_quantmap__16c0_s_p5_0[] = {
  123485. 7, 5, 3, 1, 0, 2, 4, 6,
  123486. 8,
  123487. };
  123488. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123489. _vq_quantthresh__16c0_s_p5_0,
  123490. _vq_quantmap__16c0_s_p5_0,
  123491. 9,
  123492. 9
  123493. };
  123494. static static_codebook _16c0_s_p5_0 = {
  123495. 2, 81,
  123496. _vq_lengthlist__16c0_s_p5_0,
  123497. 1, -531628032, 1611661312, 4, 0,
  123498. _vq_quantlist__16c0_s_p5_0,
  123499. NULL,
  123500. &_vq_auxt__16c0_s_p5_0,
  123501. NULL,
  123502. 0
  123503. };
  123504. static long _vq_quantlist__16c0_s_p6_0[] = {
  123505. 8,
  123506. 7,
  123507. 9,
  123508. 6,
  123509. 10,
  123510. 5,
  123511. 11,
  123512. 4,
  123513. 12,
  123514. 3,
  123515. 13,
  123516. 2,
  123517. 14,
  123518. 1,
  123519. 15,
  123520. 0,
  123521. 16,
  123522. };
  123523. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123524. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123525. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123526. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123527. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123528. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123529. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123530. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123531. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123532. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123533. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123534. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123535. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123536. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123537. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123538. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123539. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123540. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123542. 14,
  123543. };
  123544. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123545. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123546. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123547. };
  123548. static long _vq_quantmap__16c0_s_p6_0[] = {
  123549. 15, 13, 11, 9, 7, 5, 3, 1,
  123550. 0, 2, 4, 6, 8, 10, 12, 14,
  123551. 16,
  123552. };
  123553. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123554. _vq_quantthresh__16c0_s_p6_0,
  123555. _vq_quantmap__16c0_s_p6_0,
  123556. 17,
  123557. 17
  123558. };
  123559. static static_codebook _16c0_s_p6_0 = {
  123560. 2, 289,
  123561. _vq_lengthlist__16c0_s_p6_0,
  123562. 1, -529530880, 1611661312, 5, 0,
  123563. _vq_quantlist__16c0_s_p6_0,
  123564. NULL,
  123565. &_vq_auxt__16c0_s_p6_0,
  123566. NULL,
  123567. 0
  123568. };
  123569. static long _vq_quantlist__16c0_s_p7_0[] = {
  123570. 1,
  123571. 0,
  123572. 2,
  123573. };
  123574. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123575. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123576. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123577. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123578. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123579. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123580. 13,
  123581. };
  123582. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123583. -5.5, 5.5,
  123584. };
  123585. static long _vq_quantmap__16c0_s_p7_0[] = {
  123586. 1, 0, 2,
  123587. };
  123588. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123589. _vq_quantthresh__16c0_s_p7_0,
  123590. _vq_quantmap__16c0_s_p7_0,
  123591. 3,
  123592. 3
  123593. };
  123594. static static_codebook _16c0_s_p7_0 = {
  123595. 4, 81,
  123596. _vq_lengthlist__16c0_s_p7_0,
  123597. 1, -529137664, 1618345984, 2, 0,
  123598. _vq_quantlist__16c0_s_p7_0,
  123599. NULL,
  123600. &_vq_auxt__16c0_s_p7_0,
  123601. NULL,
  123602. 0
  123603. };
  123604. static long _vq_quantlist__16c0_s_p7_1[] = {
  123605. 5,
  123606. 4,
  123607. 6,
  123608. 3,
  123609. 7,
  123610. 2,
  123611. 8,
  123612. 1,
  123613. 9,
  123614. 0,
  123615. 10,
  123616. };
  123617. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123618. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123619. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123620. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123621. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123622. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123623. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123624. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123625. 11,11,11, 9, 9, 9, 9,10,10,
  123626. };
  123627. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123628. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123629. 3.5, 4.5,
  123630. };
  123631. static long _vq_quantmap__16c0_s_p7_1[] = {
  123632. 9, 7, 5, 3, 1, 0, 2, 4,
  123633. 6, 8, 10,
  123634. };
  123635. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123636. _vq_quantthresh__16c0_s_p7_1,
  123637. _vq_quantmap__16c0_s_p7_1,
  123638. 11,
  123639. 11
  123640. };
  123641. static static_codebook _16c0_s_p7_1 = {
  123642. 2, 121,
  123643. _vq_lengthlist__16c0_s_p7_1,
  123644. 1, -531365888, 1611661312, 4, 0,
  123645. _vq_quantlist__16c0_s_p7_1,
  123646. NULL,
  123647. &_vq_auxt__16c0_s_p7_1,
  123648. NULL,
  123649. 0
  123650. };
  123651. static long _vq_quantlist__16c0_s_p8_0[] = {
  123652. 6,
  123653. 5,
  123654. 7,
  123655. 4,
  123656. 8,
  123657. 3,
  123658. 9,
  123659. 2,
  123660. 10,
  123661. 1,
  123662. 11,
  123663. 0,
  123664. 12,
  123665. };
  123666. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123667. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123668. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123669. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123670. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123671. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123672. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123673. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123674. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123675. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123676. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123677. 0,12,13,13,12,13,14,14,14,
  123678. };
  123679. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123680. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123681. 12.5, 17.5, 22.5, 27.5,
  123682. };
  123683. static long _vq_quantmap__16c0_s_p8_0[] = {
  123684. 11, 9, 7, 5, 3, 1, 0, 2,
  123685. 4, 6, 8, 10, 12,
  123686. };
  123687. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123688. _vq_quantthresh__16c0_s_p8_0,
  123689. _vq_quantmap__16c0_s_p8_0,
  123690. 13,
  123691. 13
  123692. };
  123693. static static_codebook _16c0_s_p8_0 = {
  123694. 2, 169,
  123695. _vq_lengthlist__16c0_s_p8_0,
  123696. 1, -526516224, 1616117760, 4, 0,
  123697. _vq_quantlist__16c0_s_p8_0,
  123698. NULL,
  123699. &_vq_auxt__16c0_s_p8_0,
  123700. NULL,
  123701. 0
  123702. };
  123703. static long _vq_quantlist__16c0_s_p8_1[] = {
  123704. 2,
  123705. 1,
  123706. 3,
  123707. 0,
  123708. 4,
  123709. };
  123710. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123711. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123712. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123713. };
  123714. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123715. -1.5, -0.5, 0.5, 1.5,
  123716. };
  123717. static long _vq_quantmap__16c0_s_p8_1[] = {
  123718. 3, 1, 0, 2, 4,
  123719. };
  123720. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123721. _vq_quantthresh__16c0_s_p8_1,
  123722. _vq_quantmap__16c0_s_p8_1,
  123723. 5,
  123724. 5
  123725. };
  123726. static static_codebook _16c0_s_p8_1 = {
  123727. 2, 25,
  123728. _vq_lengthlist__16c0_s_p8_1,
  123729. 1, -533725184, 1611661312, 3, 0,
  123730. _vq_quantlist__16c0_s_p8_1,
  123731. NULL,
  123732. &_vq_auxt__16c0_s_p8_1,
  123733. NULL,
  123734. 0
  123735. };
  123736. static long _vq_quantlist__16c0_s_p9_0[] = {
  123737. 1,
  123738. 0,
  123739. 2,
  123740. };
  123741. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123742. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123743. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123744. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123745. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123746. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123747. 7,
  123748. };
  123749. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123750. -157.5, 157.5,
  123751. };
  123752. static long _vq_quantmap__16c0_s_p9_0[] = {
  123753. 1, 0, 2,
  123754. };
  123755. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123756. _vq_quantthresh__16c0_s_p9_0,
  123757. _vq_quantmap__16c0_s_p9_0,
  123758. 3,
  123759. 3
  123760. };
  123761. static static_codebook _16c0_s_p9_0 = {
  123762. 4, 81,
  123763. _vq_lengthlist__16c0_s_p9_0,
  123764. 1, -518803456, 1628680192, 2, 0,
  123765. _vq_quantlist__16c0_s_p9_0,
  123766. NULL,
  123767. &_vq_auxt__16c0_s_p9_0,
  123768. NULL,
  123769. 0
  123770. };
  123771. static long _vq_quantlist__16c0_s_p9_1[] = {
  123772. 7,
  123773. 6,
  123774. 8,
  123775. 5,
  123776. 9,
  123777. 4,
  123778. 10,
  123779. 3,
  123780. 11,
  123781. 2,
  123782. 12,
  123783. 1,
  123784. 13,
  123785. 0,
  123786. 14,
  123787. };
  123788. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123789. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123790. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123791. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123792. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123793. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123794. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123795. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123796. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123797. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123798. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123799. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123800. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123801. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123802. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123803. 10,
  123804. };
  123805. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123806. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123807. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123808. };
  123809. static long _vq_quantmap__16c0_s_p9_1[] = {
  123810. 13, 11, 9, 7, 5, 3, 1, 0,
  123811. 2, 4, 6, 8, 10, 12, 14,
  123812. };
  123813. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123814. _vq_quantthresh__16c0_s_p9_1,
  123815. _vq_quantmap__16c0_s_p9_1,
  123816. 15,
  123817. 15
  123818. };
  123819. static static_codebook _16c0_s_p9_1 = {
  123820. 2, 225,
  123821. _vq_lengthlist__16c0_s_p9_1,
  123822. 1, -520986624, 1620377600, 4, 0,
  123823. _vq_quantlist__16c0_s_p9_1,
  123824. NULL,
  123825. &_vq_auxt__16c0_s_p9_1,
  123826. NULL,
  123827. 0
  123828. };
  123829. static long _vq_quantlist__16c0_s_p9_2[] = {
  123830. 10,
  123831. 9,
  123832. 11,
  123833. 8,
  123834. 12,
  123835. 7,
  123836. 13,
  123837. 6,
  123838. 14,
  123839. 5,
  123840. 15,
  123841. 4,
  123842. 16,
  123843. 3,
  123844. 17,
  123845. 2,
  123846. 18,
  123847. 1,
  123848. 19,
  123849. 0,
  123850. 20,
  123851. };
  123852. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123853. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123854. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123855. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123856. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123857. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123858. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123859. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123860. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123861. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123862. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123863. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123864. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123865. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123866. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123867. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123868. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123869. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123870. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123871. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123872. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123873. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123874. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123875. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123876. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123877. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123878. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123879. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123880. 10,11,10,10,11, 9,10,10,10,
  123881. };
  123882. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123883. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123884. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123885. 6.5, 7.5, 8.5, 9.5,
  123886. };
  123887. static long _vq_quantmap__16c0_s_p9_2[] = {
  123888. 19, 17, 15, 13, 11, 9, 7, 5,
  123889. 3, 1, 0, 2, 4, 6, 8, 10,
  123890. 12, 14, 16, 18, 20,
  123891. };
  123892. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123893. _vq_quantthresh__16c0_s_p9_2,
  123894. _vq_quantmap__16c0_s_p9_2,
  123895. 21,
  123896. 21
  123897. };
  123898. static static_codebook _16c0_s_p9_2 = {
  123899. 2, 441,
  123900. _vq_lengthlist__16c0_s_p9_2,
  123901. 1, -529268736, 1611661312, 5, 0,
  123902. _vq_quantlist__16c0_s_p9_2,
  123903. NULL,
  123904. &_vq_auxt__16c0_s_p9_2,
  123905. NULL,
  123906. 0
  123907. };
  123908. static long _huff_lengthlist__16c0_s_single[] = {
  123909. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123910. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123911. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123912. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123913. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123914. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123915. 16,16,18,18,
  123916. };
  123917. static static_codebook _huff_book__16c0_s_single = {
  123918. 2, 100,
  123919. _huff_lengthlist__16c0_s_single,
  123920. 0, 0, 0, 0, 0,
  123921. NULL,
  123922. NULL,
  123923. NULL,
  123924. NULL,
  123925. 0
  123926. };
  123927. static long _huff_lengthlist__16c1_s_long[] = {
  123928. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123929. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123930. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123931. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123932. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123933. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123934. 12,11,11,13,
  123935. };
  123936. static static_codebook _huff_book__16c1_s_long = {
  123937. 2, 100,
  123938. _huff_lengthlist__16c1_s_long,
  123939. 0, 0, 0, 0, 0,
  123940. NULL,
  123941. NULL,
  123942. NULL,
  123943. NULL,
  123944. 0
  123945. };
  123946. static long _vq_quantlist__16c1_s_p1_0[] = {
  123947. 1,
  123948. 0,
  123949. 2,
  123950. };
  123951. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123952. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123953. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123958. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123963. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  123998. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  124003. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  124008. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124044. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124049. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124054. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  124363. };
  124364. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124365. -0.5, 0.5,
  124366. };
  124367. static long _vq_quantmap__16c1_s_p1_0[] = {
  124368. 1, 0, 2,
  124369. };
  124370. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124371. _vq_quantthresh__16c1_s_p1_0,
  124372. _vq_quantmap__16c1_s_p1_0,
  124373. 3,
  124374. 3
  124375. };
  124376. static static_codebook _16c1_s_p1_0 = {
  124377. 8, 6561,
  124378. _vq_lengthlist__16c1_s_p1_0,
  124379. 1, -535822336, 1611661312, 2, 0,
  124380. _vq_quantlist__16c1_s_p1_0,
  124381. NULL,
  124382. &_vq_auxt__16c1_s_p1_0,
  124383. NULL,
  124384. 0
  124385. };
  124386. static long _vq_quantlist__16c1_s_p2_0[] = {
  124387. 2,
  124388. 1,
  124389. 3,
  124390. 0,
  124391. 4,
  124392. };
  124393. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124433. 0,
  124434. };
  124435. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124436. -1.5, -0.5, 0.5, 1.5,
  124437. };
  124438. static long _vq_quantmap__16c1_s_p2_0[] = {
  124439. 3, 1, 0, 2, 4,
  124440. };
  124441. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124442. _vq_quantthresh__16c1_s_p2_0,
  124443. _vq_quantmap__16c1_s_p2_0,
  124444. 5,
  124445. 5
  124446. };
  124447. static static_codebook _16c1_s_p2_0 = {
  124448. 4, 625,
  124449. _vq_lengthlist__16c1_s_p2_0,
  124450. 1, -533725184, 1611661312, 3, 0,
  124451. _vq_quantlist__16c1_s_p2_0,
  124452. NULL,
  124453. &_vq_auxt__16c1_s_p2_0,
  124454. NULL,
  124455. 0
  124456. };
  124457. static long _vq_quantlist__16c1_s_p3_0[] = {
  124458. 2,
  124459. 1,
  124460. 3,
  124461. 0,
  124462. 4,
  124463. };
  124464. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124465. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124504. 0,
  124505. };
  124506. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124507. -1.5, -0.5, 0.5, 1.5,
  124508. };
  124509. static long _vq_quantmap__16c1_s_p3_0[] = {
  124510. 3, 1, 0, 2, 4,
  124511. };
  124512. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124513. _vq_quantthresh__16c1_s_p3_0,
  124514. _vq_quantmap__16c1_s_p3_0,
  124515. 5,
  124516. 5
  124517. };
  124518. static static_codebook _16c1_s_p3_0 = {
  124519. 4, 625,
  124520. _vq_lengthlist__16c1_s_p3_0,
  124521. 1, -533725184, 1611661312, 3, 0,
  124522. _vq_quantlist__16c1_s_p3_0,
  124523. NULL,
  124524. &_vq_auxt__16c1_s_p3_0,
  124525. NULL,
  124526. 0
  124527. };
  124528. static long _vq_quantlist__16c1_s_p4_0[] = {
  124529. 4,
  124530. 3,
  124531. 5,
  124532. 2,
  124533. 6,
  124534. 1,
  124535. 7,
  124536. 0,
  124537. 8,
  124538. };
  124539. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124540. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124541. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124542. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124543. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124544. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124545. 0,
  124546. };
  124547. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124548. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124549. };
  124550. static long _vq_quantmap__16c1_s_p4_0[] = {
  124551. 7, 5, 3, 1, 0, 2, 4, 6,
  124552. 8,
  124553. };
  124554. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124555. _vq_quantthresh__16c1_s_p4_0,
  124556. _vq_quantmap__16c1_s_p4_0,
  124557. 9,
  124558. 9
  124559. };
  124560. static static_codebook _16c1_s_p4_0 = {
  124561. 2, 81,
  124562. _vq_lengthlist__16c1_s_p4_0,
  124563. 1, -531628032, 1611661312, 4, 0,
  124564. _vq_quantlist__16c1_s_p4_0,
  124565. NULL,
  124566. &_vq_auxt__16c1_s_p4_0,
  124567. NULL,
  124568. 0
  124569. };
  124570. static long _vq_quantlist__16c1_s_p5_0[] = {
  124571. 4,
  124572. 3,
  124573. 5,
  124574. 2,
  124575. 6,
  124576. 1,
  124577. 7,
  124578. 0,
  124579. 8,
  124580. };
  124581. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124582. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124583. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124584. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124585. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124586. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124587. 10,
  124588. };
  124589. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124590. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124591. };
  124592. static long _vq_quantmap__16c1_s_p5_0[] = {
  124593. 7, 5, 3, 1, 0, 2, 4, 6,
  124594. 8,
  124595. };
  124596. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124597. _vq_quantthresh__16c1_s_p5_0,
  124598. _vq_quantmap__16c1_s_p5_0,
  124599. 9,
  124600. 9
  124601. };
  124602. static static_codebook _16c1_s_p5_0 = {
  124603. 2, 81,
  124604. _vq_lengthlist__16c1_s_p5_0,
  124605. 1, -531628032, 1611661312, 4, 0,
  124606. _vq_quantlist__16c1_s_p5_0,
  124607. NULL,
  124608. &_vq_auxt__16c1_s_p5_0,
  124609. NULL,
  124610. 0
  124611. };
  124612. static long _vq_quantlist__16c1_s_p6_0[] = {
  124613. 8,
  124614. 7,
  124615. 9,
  124616. 6,
  124617. 10,
  124618. 5,
  124619. 11,
  124620. 4,
  124621. 12,
  124622. 3,
  124623. 13,
  124624. 2,
  124625. 14,
  124626. 1,
  124627. 15,
  124628. 0,
  124629. 16,
  124630. };
  124631. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124632. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124633. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124634. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124635. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124636. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124637. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124638. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124639. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124640. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124641. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124642. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124643. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124644. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124645. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124646. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124647. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124648. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124649. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124650. 14,
  124651. };
  124652. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124653. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124654. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124655. };
  124656. static long _vq_quantmap__16c1_s_p6_0[] = {
  124657. 15, 13, 11, 9, 7, 5, 3, 1,
  124658. 0, 2, 4, 6, 8, 10, 12, 14,
  124659. 16,
  124660. };
  124661. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124662. _vq_quantthresh__16c1_s_p6_0,
  124663. _vq_quantmap__16c1_s_p6_0,
  124664. 17,
  124665. 17
  124666. };
  124667. static static_codebook _16c1_s_p6_0 = {
  124668. 2, 289,
  124669. _vq_lengthlist__16c1_s_p6_0,
  124670. 1, -529530880, 1611661312, 5, 0,
  124671. _vq_quantlist__16c1_s_p6_0,
  124672. NULL,
  124673. &_vq_auxt__16c1_s_p6_0,
  124674. NULL,
  124675. 0
  124676. };
  124677. static long _vq_quantlist__16c1_s_p7_0[] = {
  124678. 1,
  124679. 0,
  124680. 2,
  124681. };
  124682. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124683. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124684. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124685. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124686. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124687. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124688. 11,
  124689. };
  124690. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124691. -5.5, 5.5,
  124692. };
  124693. static long _vq_quantmap__16c1_s_p7_0[] = {
  124694. 1, 0, 2,
  124695. };
  124696. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124697. _vq_quantthresh__16c1_s_p7_0,
  124698. _vq_quantmap__16c1_s_p7_0,
  124699. 3,
  124700. 3
  124701. };
  124702. static static_codebook _16c1_s_p7_0 = {
  124703. 4, 81,
  124704. _vq_lengthlist__16c1_s_p7_0,
  124705. 1, -529137664, 1618345984, 2, 0,
  124706. _vq_quantlist__16c1_s_p7_0,
  124707. NULL,
  124708. &_vq_auxt__16c1_s_p7_0,
  124709. NULL,
  124710. 0
  124711. };
  124712. static long _vq_quantlist__16c1_s_p7_1[] = {
  124713. 5,
  124714. 4,
  124715. 6,
  124716. 3,
  124717. 7,
  124718. 2,
  124719. 8,
  124720. 1,
  124721. 9,
  124722. 0,
  124723. 10,
  124724. };
  124725. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124726. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124727. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124728. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124729. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124730. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124731. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124732. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124733. 10,10,10, 8, 8, 8, 8, 9, 9,
  124734. };
  124735. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124736. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124737. 3.5, 4.5,
  124738. };
  124739. static long _vq_quantmap__16c1_s_p7_1[] = {
  124740. 9, 7, 5, 3, 1, 0, 2, 4,
  124741. 6, 8, 10,
  124742. };
  124743. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124744. _vq_quantthresh__16c1_s_p7_1,
  124745. _vq_quantmap__16c1_s_p7_1,
  124746. 11,
  124747. 11
  124748. };
  124749. static static_codebook _16c1_s_p7_1 = {
  124750. 2, 121,
  124751. _vq_lengthlist__16c1_s_p7_1,
  124752. 1, -531365888, 1611661312, 4, 0,
  124753. _vq_quantlist__16c1_s_p7_1,
  124754. NULL,
  124755. &_vq_auxt__16c1_s_p7_1,
  124756. NULL,
  124757. 0
  124758. };
  124759. static long _vq_quantlist__16c1_s_p8_0[] = {
  124760. 6,
  124761. 5,
  124762. 7,
  124763. 4,
  124764. 8,
  124765. 3,
  124766. 9,
  124767. 2,
  124768. 10,
  124769. 1,
  124770. 11,
  124771. 0,
  124772. 12,
  124773. };
  124774. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124775. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124776. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124777. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124778. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124779. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124780. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124781. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124782. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124783. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124784. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124785. 0,12,12,12,12,13,13,14,15,
  124786. };
  124787. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124788. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124789. 12.5, 17.5, 22.5, 27.5,
  124790. };
  124791. static long _vq_quantmap__16c1_s_p8_0[] = {
  124792. 11, 9, 7, 5, 3, 1, 0, 2,
  124793. 4, 6, 8, 10, 12,
  124794. };
  124795. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124796. _vq_quantthresh__16c1_s_p8_0,
  124797. _vq_quantmap__16c1_s_p8_0,
  124798. 13,
  124799. 13
  124800. };
  124801. static static_codebook _16c1_s_p8_0 = {
  124802. 2, 169,
  124803. _vq_lengthlist__16c1_s_p8_0,
  124804. 1, -526516224, 1616117760, 4, 0,
  124805. _vq_quantlist__16c1_s_p8_0,
  124806. NULL,
  124807. &_vq_auxt__16c1_s_p8_0,
  124808. NULL,
  124809. 0
  124810. };
  124811. static long _vq_quantlist__16c1_s_p8_1[] = {
  124812. 2,
  124813. 1,
  124814. 3,
  124815. 0,
  124816. 4,
  124817. };
  124818. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124819. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124820. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124821. };
  124822. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124823. -1.5, -0.5, 0.5, 1.5,
  124824. };
  124825. static long _vq_quantmap__16c1_s_p8_1[] = {
  124826. 3, 1, 0, 2, 4,
  124827. };
  124828. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124829. _vq_quantthresh__16c1_s_p8_1,
  124830. _vq_quantmap__16c1_s_p8_1,
  124831. 5,
  124832. 5
  124833. };
  124834. static static_codebook _16c1_s_p8_1 = {
  124835. 2, 25,
  124836. _vq_lengthlist__16c1_s_p8_1,
  124837. 1, -533725184, 1611661312, 3, 0,
  124838. _vq_quantlist__16c1_s_p8_1,
  124839. NULL,
  124840. &_vq_auxt__16c1_s_p8_1,
  124841. NULL,
  124842. 0
  124843. };
  124844. static long _vq_quantlist__16c1_s_p9_0[] = {
  124845. 6,
  124846. 5,
  124847. 7,
  124848. 4,
  124849. 8,
  124850. 3,
  124851. 9,
  124852. 2,
  124853. 10,
  124854. 1,
  124855. 11,
  124856. 0,
  124857. 12,
  124858. };
  124859. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124860. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124861. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124862. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124863. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124864. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124865. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124866. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124867. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124868. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124869. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124870. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124871. };
  124872. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124873. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124874. 787.5, 1102.5, 1417.5, 1732.5,
  124875. };
  124876. static long _vq_quantmap__16c1_s_p9_0[] = {
  124877. 11, 9, 7, 5, 3, 1, 0, 2,
  124878. 4, 6, 8, 10, 12,
  124879. };
  124880. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124881. _vq_quantthresh__16c1_s_p9_0,
  124882. _vq_quantmap__16c1_s_p9_0,
  124883. 13,
  124884. 13
  124885. };
  124886. static static_codebook _16c1_s_p9_0 = {
  124887. 2, 169,
  124888. _vq_lengthlist__16c1_s_p9_0,
  124889. 1, -513964032, 1628680192, 4, 0,
  124890. _vq_quantlist__16c1_s_p9_0,
  124891. NULL,
  124892. &_vq_auxt__16c1_s_p9_0,
  124893. NULL,
  124894. 0
  124895. };
  124896. static long _vq_quantlist__16c1_s_p9_1[] = {
  124897. 7,
  124898. 6,
  124899. 8,
  124900. 5,
  124901. 9,
  124902. 4,
  124903. 10,
  124904. 3,
  124905. 11,
  124906. 2,
  124907. 12,
  124908. 1,
  124909. 13,
  124910. 0,
  124911. 14,
  124912. };
  124913. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124914. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124915. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124916. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124917. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124918. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124919. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124920. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124921. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124922. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124923. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124924. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124925. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124926. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124927. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124928. 13,
  124929. };
  124930. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124931. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124932. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124933. };
  124934. static long _vq_quantmap__16c1_s_p9_1[] = {
  124935. 13, 11, 9, 7, 5, 3, 1, 0,
  124936. 2, 4, 6, 8, 10, 12, 14,
  124937. };
  124938. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124939. _vq_quantthresh__16c1_s_p9_1,
  124940. _vq_quantmap__16c1_s_p9_1,
  124941. 15,
  124942. 15
  124943. };
  124944. static static_codebook _16c1_s_p9_1 = {
  124945. 2, 225,
  124946. _vq_lengthlist__16c1_s_p9_1,
  124947. 1, -520986624, 1620377600, 4, 0,
  124948. _vq_quantlist__16c1_s_p9_1,
  124949. NULL,
  124950. &_vq_auxt__16c1_s_p9_1,
  124951. NULL,
  124952. 0
  124953. };
  124954. static long _vq_quantlist__16c1_s_p9_2[] = {
  124955. 10,
  124956. 9,
  124957. 11,
  124958. 8,
  124959. 12,
  124960. 7,
  124961. 13,
  124962. 6,
  124963. 14,
  124964. 5,
  124965. 15,
  124966. 4,
  124967. 16,
  124968. 3,
  124969. 17,
  124970. 2,
  124971. 18,
  124972. 1,
  124973. 19,
  124974. 0,
  124975. 20,
  124976. };
  124977. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124978. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124979. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124980. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124981. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124982. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124983. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124984. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124985. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124986. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124987. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124988. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124989. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124990. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124991. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124992. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124993. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124994. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124995. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124996. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124997. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124998. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124999. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  125000. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  125001. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  125002. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  125003. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  125004. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  125005. 11,11,11,11,12,11,11,12,11,
  125006. };
  125007. static float _vq_quantthresh__16c1_s_p9_2[] = {
  125008. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125009. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125010. 6.5, 7.5, 8.5, 9.5,
  125011. };
  125012. static long _vq_quantmap__16c1_s_p9_2[] = {
  125013. 19, 17, 15, 13, 11, 9, 7, 5,
  125014. 3, 1, 0, 2, 4, 6, 8, 10,
  125015. 12, 14, 16, 18, 20,
  125016. };
  125017. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  125018. _vq_quantthresh__16c1_s_p9_2,
  125019. _vq_quantmap__16c1_s_p9_2,
  125020. 21,
  125021. 21
  125022. };
  125023. static static_codebook _16c1_s_p9_2 = {
  125024. 2, 441,
  125025. _vq_lengthlist__16c1_s_p9_2,
  125026. 1, -529268736, 1611661312, 5, 0,
  125027. _vq_quantlist__16c1_s_p9_2,
  125028. NULL,
  125029. &_vq_auxt__16c1_s_p9_2,
  125030. NULL,
  125031. 0
  125032. };
  125033. static long _huff_lengthlist__16c1_s_short[] = {
  125034. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125035. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125036. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125037. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125038. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125039. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125040. 9, 9,10,13,
  125041. };
  125042. static static_codebook _huff_book__16c1_s_short = {
  125043. 2, 100,
  125044. _huff_lengthlist__16c1_s_short,
  125045. 0, 0, 0, 0, 0,
  125046. NULL,
  125047. NULL,
  125048. NULL,
  125049. NULL,
  125050. 0
  125051. };
  125052. static long _huff_lengthlist__16c2_s_long[] = {
  125053. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125054. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125055. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125056. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125057. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125058. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125059. 14,14,16,18,
  125060. };
  125061. static static_codebook _huff_book__16c2_s_long = {
  125062. 2, 100,
  125063. _huff_lengthlist__16c2_s_long,
  125064. 0, 0, 0, 0, 0,
  125065. NULL,
  125066. NULL,
  125067. NULL,
  125068. NULL,
  125069. 0
  125070. };
  125071. static long _vq_quantlist__16c2_s_p1_0[] = {
  125072. 1,
  125073. 0,
  125074. 2,
  125075. };
  125076. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125077. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125078. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0,
  125083. };
  125084. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125085. -0.5, 0.5,
  125086. };
  125087. static long _vq_quantmap__16c2_s_p1_0[] = {
  125088. 1, 0, 2,
  125089. };
  125090. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125091. _vq_quantthresh__16c2_s_p1_0,
  125092. _vq_quantmap__16c2_s_p1_0,
  125093. 3,
  125094. 3
  125095. };
  125096. static static_codebook _16c2_s_p1_0 = {
  125097. 4, 81,
  125098. _vq_lengthlist__16c2_s_p1_0,
  125099. 1, -535822336, 1611661312, 2, 0,
  125100. _vq_quantlist__16c2_s_p1_0,
  125101. NULL,
  125102. &_vq_auxt__16c2_s_p1_0,
  125103. NULL,
  125104. 0
  125105. };
  125106. static long _vq_quantlist__16c2_s_p2_0[] = {
  125107. 2,
  125108. 1,
  125109. 3,
  125110. 0,
  125111. 4,
  125112. };
  125113. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125114. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125115. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125116. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125117. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125118. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125119. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125120. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125121. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  125127. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125128. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125129. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125135. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125136. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125137. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125142. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125143. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125144. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125145. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  125150. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125151. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125152. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125153. 13,
  125154. };
  125155. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125156. -1.5, -0.5, 0.5, 1.5,
  125157. };
  125158. static long _vq_quantmap__16c2_s_p2_0[] = {
  125159. 3, 1, 0, 2, 4,
  125160. };
  125161. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125162. _vq_quantthresh__16c2_s_p2_0,
  125163. _vq_quantmap__16c2_s_p2_0,
  125164. 5,
  125165. 5
  125166. };
  125167. static static_codebook _16c2_s_p2_0 = {
  125168. 4, 625,
  125169. _vq_lengthlist__16c2_s_p2_0,
  125170. 1, -533725184, 1611661312, 3, 0,
  125171. _vq_quantlist__16c2_s_p2_0,
  125172. NULL,
  125173. &_vq_auxt__16c2_s_p2_0,
  125174. NULL,
  125175. 0
  125176. };
  125177. static long _vq_quantlist__16c2_s_p3_0[] = {
  125178. 4,
  125179. 3,
  125180. 5,
  125181. 2,
  125182. 6,
  125183. 1,
  125184. 7,
  125185. 0,
  125186. 8,
  125187. };
  125188. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125189. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125190. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125191. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125192. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0,
  125195. };
  125196. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125197. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125198. };
  125199. static long _vq_quantmap__16c2_s_p3_0[] = {
  125200. 7, 5, 3, 1, 0, 2, 4, 6,
  125201. 8,
  125202. };
  125203. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125204. _vq_quantthresh__16c2_s_p3_0,
  125205. _vq_quantmap__16c2_s_p3_0,
  125206. 9,
  125207. 9
  125208. };
  125209. static static_codebook _16c2_s_p3_0 = {
  125210. 2, 81,
  125211. _vq_lengthlist__16c2_s_p3_0,
  125212. 1, -531628032, 1611661312, 4, 0,
  125213. _vq_quantlist__16c2_s_p3_0,
  125214. NULL,
  125215. &_vq_auxt__16c2_s_p3_0,
  125216. NULL,
  125217. 0
  125218. };
  125219. static long _vq_quantlist__16c2_s_p4_0[] = {
  125220. 8,
  125221. 7,
  125222. 9,
  125223. 6,
  125224. 10,
  125225. 5,
  125226. 11,
  125227. 4,
  125228. 12,
  125229. 3,
  125230. 13,
  125231. 2,
  125232. 14,
  125233. 1,
  125234. 15,
  125235. 0,
  125236. 16,
  125237. };
  125238. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125239. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125240. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125241. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125242. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125243. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125244. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125245. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125246. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125247. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125248. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125257. 0,
  125258. };
  125259. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125260. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125261. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125262. };
  125263. static long _vq_quantmap__16c2_s_p4_0[] = {
  125264. 15, 13, 11, 9, 7, 5, 3, 1,
  125265. 0, 2, 4, 6, 8, 10, 12, 14,
  125266. 16,
  125267. };
  125268. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125269. _vq_quantthresh__16c2_s_p4_0,
  125270. _vq_quantmap__16c2_s_p4_0,
  125271. 17,
  125272. 17
  125273. };
  125274. static static_codebook _16c2_s_p4_0 = {
  125275. 2, 289,
  125276. _vq_lengthlist__16c2_s_p4_0,
  125277. 1, -529530880, 1611661312, 5, 0,
  125278. _vq_quantlist__16c2_s_p4_0,
  125279. NULL,
  125280. &_vq_auxt__16c2_s_p4_0,
  125281. NULL,
  125282. 0
  125283. };
  125284. static long _vq_quantlist__16c2_s_p5_0[] = {
  125285. 1,
  125286. 0,
  125287. 2,
  125288. };
  125289. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125290. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125291. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125292. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125293. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125294. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125295. 12,
  125296. };
  125297. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125298. -5.5, 5.5,
  125299. };
  125300. static long _vq_quantmap__16c2_s_p5_0[] = {
  125301. 1, 0, 2,
  125302. };
  125303. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125304. _vq_quantthresh__16c2_s_p5_0,
  125305. _vq_quantmap__16c2_s_p5_0,
  125306. 3,
  125307. 3
  125308. };
  125309. static static_codebook _16c2_s_p5_0 = {
  125310. 4, 81,
  125311. _vq_lengthlist__16c2_s_p5_0,
  125312. 1, -529137664, 1618345984, 2, 0,
  125313. _vq_quantlist__16c2_s_p5_0,
  125314. NULL,
  125315. &_vq_auxt__16c2_s_p5_0,
  125316. NULL,
  125317. 0
  125318. };
  125319. static long _vq_quantlist__16c2_s_p5_1[] = {
  125320. 5,
  125321. 4,
  125322. 6,
  125323. 3,
  125324. 7,
  125325. 2,
  125326. 8,
  125327. 1,
  125328. 9,
  125329. 0,
  125330. 10,
  125331. };
  125332. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125333. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125334. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125335. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125336. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125337. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125338. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125339. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125340. 11,11,11, 7, 7, 8, 8, 8, 8,
  125341. };
  125342. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125343. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125344. 3.5, 4.5,
  125345. };
  125346. static long _vq_quantmap__16c2_s_p5_1[] = {
  125347. 9, 7, 5, 3, 1, 0, 2, 4,
  125348. 6, 8, 10,
  125349. };
  125350. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125351. _vq_quantthresh__16c2_s_p5_1,
  125352. _vq_quantmap__16c2_s_p5_1,
  125353. 11,
  125354. 11
  125355. };
  125356. static static_codebook _16c2_s_p5_1 = {
  125357. 2, 121,
  125358. _vq_lengthlist__16c2_s_p5_1,
  125359. 1, -531365888, 1611661312, 4, 0,
  125360. _vq_quantlist__16c2_s_p5_1,
  125361. NULL,
  125362. &_vq_auxt__16c2_s_p5_1,
  125363. NULL,
  125364. 0
  125365. };
  125366. static long _vq_quantlist__16c2_s_p6_0[] = {
  125367. 6,
  125368. 5,
  125369. 7,
  125370. 4,
  125371. 8,
  125372. 3,
  125373. 9,
  125374. 2,
  125375. 10,
  125376. 1,
  125377. 11,
  125378. 0,
  125379. 12,
  125380. };
  125381. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125382. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125383. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125384. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125385. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125386. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125387. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. };
  125394. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125395. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125396. 12.5, 17.5, 22.5, 27.5,
  125397. };
  125398. static long _vq_quantmap__16c2_s_p6_0[] = {
  125399. 11, 9, 7, 5, 3, 1, 0, 2,
  125400. 4, 6, 8, 10, 12,
  125401. };
  125402. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125403. _vq_quantthresh__16c2_s_p6_0,
  125404. _vq_quantmap__16c2_s_p6_0,
  125405. 13,
  125406. 13
  125407. };
  125408. static static_codebook _16c2_s_p6_0 = {
  125409. 2, 169,
  125410. _vq_lengthlist__16c2_s_p6_0,
  125411. 1, -526516224, 1616117760, 4, 0,
  125412. _vq_quantlist__16c2_s_p6_0,
  125413. NULL,
  125414. &_vq_auxt__16c2_s_p6_0,
  125415. NULL,
  125416. 0
  125417. };
  125418. static long _vq_quantlist__16c2_s_p6_1[] = {
  125419. 2,
  125420. 1,
  125421. 3,
  125422. 0,
  125423. 4,
  125424. };
  125425. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125426. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125427. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125428. };
  125429. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125430. -1.5, -0.5, 0.5, 1.5,
  125431. };
  125432. static long _vq_quantmap__16c2_s_p6_1[] = {
  125433. 3, 1, 0, 2, 4,
  125434. };
  125435. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125436. _vq_quantthresh__16c2_s_p6_1,
  125437. _vq_quantmap__16c2_s_p6_1,
  125438. 5,
  125439. 5
  125440. };
  125441. static static_codebook _16c2_s_p6_1 = {
  125442. 2, 25,
  125443. _vq_lengthlist__16c2_s_p6_1,
  125444. 1, -533725184, 1611661312, 3, 0,
  125445. _vq_quantlist__16c2_s_p6_1,
  125446. NULL,
  125447. &_vq_auxt__16c2_s_p6_1,
  125448. NULL,
  125449. 0
  125450. };
  125451. static long _vq_quantlist__16c2_s_p7_0[] = {
  125452. 6,
  125453. 5,
  125454. 7,
  125455. 4,
  125456. 8,
  125457. 3,
  125458. 9,
  125459. 2,
  125460. 10,
  125461. 1,
  125462. 11,
  125463. 0,
  125464. 12,
  125465. };
  125466. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125467. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125468. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125469. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125470. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125471. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125472. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125473. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125474. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125475. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125476. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125477. 18,13,14,13,13,14,13,15,14,
  125478. };
  125479. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125480. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125481. 27.5, 38.5, 49.5, 60.5,
  125482. };
  125483. static long _vq_quantmap__16c2_s_p7_0[] = {
  125484. 11, 9, 7, 5, 3, 1, 0, 2,
  125485. 4, 6, 8, 10, 12,
  125486. };
  125487. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125488. _vq_quantthresh__16c2_s_p7_0,
  125489. _vq_quantmap__16c2_s_p7_0,
  125490. 13,
  125491. 13
  125492. };
  125493. static static_codebook _16c2_s_p7_0 = {
  125494. 2, 169,
  125495. _vq_lengthlist__16c2_s_p7_0,
  125496. 1, -523206656, 1618345984, 4, 0,
  125497. _vq_quantlist__16c2_s_p7_0,
  125498. NULL,
  125499. &_vq_auxt__16c2_s_p7_0,
  125500. NULL,
  125501. 0
  125502. };
  125503. static long _vq_quantlist__16c2_s_p7_1[] = {
  125504. 5,
  125505. 4,
  125506. 6,
  125507. 3,
  125508. 7,
  125509. 2,
  125510. 8,
  125511. 1,
  125512. 9,
  125513. 0,
  125514. 10,
  125515. };
  125516. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125517. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125518. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125519. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125520. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125521. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125522. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125523. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125524. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125525. };
  125526. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125527. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125528. 3.5, 4.5,
  125529. };
  125530. static long _vq_quantmap__16c2_s_p7_1[] = {
  125531. 9, 7, 5, 3, 1, 0, 2, 4,
  125532. 6, 8, 10,
  125533. };
  125534. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125535. _vq_quantthresh__16c2_s_p7_1,
  125536. _vq_quantmap__16c2_s_p7_1,
  125537. 11,
  125538. 11
  125539. };
  125540. static static_codebook _16c2_s_p7_1 = {
  125541. 2, 121,
  125542. _vq_lengthlist__16c2_s_p7_1,
  125543. 1, -531365888, 1611661312, 4, 0,
  125544. _vq_quantlist__16c2_s_p7_1,
  125545. NULL,
  125546. &_vq_auxt__16c2_s_p7_1,
  125547. NULL,
  125548. 0
  125549. };
  125550. static long _vq_quantlist__16c2_s_p8_0[] = {
  125551. 7,
  125552. 6,
  125553. 8,
  125554. 5,
  125555. 9,
  125556. 4,
  125557. 10,
  125558. 3,
  125559. 11,
  125560. 2,
  125561. 12,
  125562. 1,
  125563. 13,
  125564. 0,
  125565. 14,
  125566. };
  125567. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125568. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125569. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125570. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125571. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125572. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125573. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125574. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125575. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125576. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125577. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125578. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125579. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125580. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125581. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125582. 13,
  125583. };
  125584. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125585. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125586. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125587. };
  125588. static long _vq_quantmap__16c2_s_p8_0[] = {
  125589. 13, 11, 9, 7, 5, 3, 1, 0,
  125590. 2, 4, 6, 8, 10, 12, 14,
  125591. };
  125592. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125593. _vq_quantthresh__16c2_s_p8_0,
  125594. _vq_quantmap__16c2_s_p8_0,
  125595. 15,
  125596. 15
  125597. };
  125598. static static_codebook _16c2_s_p8_0 = {
  125599. 2, 225,
  125600. _vq_lengthlist__16c2_s_p8_0,
  125601. 1, -520986624, 1620377600, 4, 0,
  125602. _vq_quantlist__16c2_s_p8_0,
  125603. NULL,
  125604. &_vq_auxt__16c2_s_p8_0,
  125605. NULL,
  125606. 0
  125607. };
  125608. static long _vq_quantlist__16c2_s_p8_1[] = {
  125609. 10,
  125610. 9,
  125611. 11,
  125612. 8,
  125613. 12,
  125614. 7,
  125615. 13,
  125616. 6,
  125617. 14,
  125618. 5,
  125619. 15,
  125620. 4,
  125621. 16,
  125622. 3,
  125623. 17,
  125624. 2,
  125625. 18,
  125626. 1,
  125627. 19,
  125628. 0,
  125629. 20,
  125630. };
  125631. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125632. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125633. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125634. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125635. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125636. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125637. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125638. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125639. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125640. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125641. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125642. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125643. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125644. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125645. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125646. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125647. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125648. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125649. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125650. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125651. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125652. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125653. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125654. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125655. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125656. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125657. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125658. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125659. 10,11,10,10,10,10,10,10,10,
  125660. };
  125661. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125662. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125663. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125664. 6.5, 7.5, 8.5, 9.5,
  125665. };
  125666. static long _vq_quantmap__16c2_s_p8_1[] = {
  125667. 19, 17, 15, 13, 11, 9, 7, 5,
  125668. 3, 1, 0, 2, 4, 6, 8, 10,
  125669. 12, 14, 16, 18, 20,
  125670. };
  125671. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125672. _vq_quantthresh__16c2_s_p8_1,
  125673. _vq_quantmap__16c2_s_p8_1,
  125674. 21,
  125675. 21
  125676. };
  125677. static static_codebook _16c2_s_p8_1 = {
  125678. 2, 441,
  125679. _vq_lengthlist__16c2_s_p8_1,
  125680. 1, -529268736, 1611661312, 5, 0,
  125681. _vq_quantlist__16c2_s_p8_1,
  125682. NULL,
  125683. &_vq_auxt__16c2_s_p8_1,
  125684. NULL,
  125685. 0
  125686. };
  125687. static long _vq_quantlist__16c2_s_p9_0[] = {
  125688. 6,
  125689. 5,
  125690. 7,
  125691. 4,
  125692. 8,
  125693. 3,
  125694. 9,
  125695. 2,
  125696. 10,
  125697. 1,
  125698. 11,
  125699. 0,
  125700. 12,
  125701. };
  125702. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125703. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125704. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125705. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125706. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125707. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125708. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125709. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125710. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125711. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125712. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125713. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125714. };
  125715. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125716. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125717. 2327.5, 3258.5, 4189.5, 5120.5,
  125718. };
  125719. static long _vq_quantmap__16c2_s_p9_0[] = {
  125720. 11, 9, 7, 5, 3, 1, 0, 2,
  125721. 4, 6, 8, 10, 12,
  125722. };
  125723. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125724. _vq_quantthresh__16c2_s_p9_0,
  125725. _vq_quantmap__16c2_s_p9_0,
  125726. 13,
  125727. 13
  125728. };
  125729. static static_codebook _16c2_s_p9_0 = {
  125730. 2, 169,
  125731. _vq_lengthlist__16c2_s_p9_0,
  125732. 1, -510275072, 1631393792, 4, 0,
  125733. _vq_quantlist__16c2_s_p9_0,
  125734. NULL,
  125735. &_vq_auxt__16c2_s_p9_0,
  125736. NULL,
  125737. 0
  125738. };
  125739. static long _vq_quantlist__16c2_s_p9_1[] = {
  125740. 8,
  125741. 7,
  125742. 9,
  125743. 6,
  125744. 10,
  125745. 5,
  125746. 11,
  125747. 4,
  125748. 12,
  125749. 3,
  125750. 13,
  125751. 2,
  125752. 14,
  125753. 1,
  125754. 15,
  125755. 0,
  125756. 16,
  125757. };
  125758. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125759. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125760. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125761. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125762. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125763. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125764. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125765. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125766. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125767. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125768. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125769. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125770. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125774. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125775. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125777. 10,
  125778. };
  125779. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125780. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125781. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125782. };
  125783. static long _vq_quantmap__16c2_s_p9_1[] = {
  125784. 15, 13, 11, 9, 7, 5, 3, 1,
  125785. 0, 2, 4, 6, 8, 10, 12, 14,
  125786. 16,
  125787. };
  125788. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125789. _vq_quantthresh__16c2_s_p9_1,
  125790. _vq_quantmap__16c2_s_p9_1,
  125791. 17,
  125792. 17
  125793. };
  125794. static static_codebook _16c2_s_p9_1 = {
  125795. 2, 289,
  125796. _vq_lengthlist__16c2_s_p9_1,
  125797. 1, -518488064, 1622704128, 5, 0,
  125798. _vq_quantlist__16c2_s_p9_1,
  125799. NULL,
  125800. &_vq_auxt__16c2_s_p9_1,
  125801. NULL,
  125802. 0
  125803. };
  125804. static long _vq_quantlist__16c2_s_p9_2[] = {
  125805. 13,
  125806. 12,
  125807. 14,
  125808. 11,
  125809. 15,
  125810. 10,
  125811. 16,
  125812. 9,
  125813. 17,
  125814. 8,
  125815. 18,
  125816. 7,
  125817. 19,
  125818. 6,
  125819. 20,
  125820. 5,
  125821. 21,
  125822. 4,
  125823. 22,
  125824. 3,
  125825. 23,
  125826. 2,
  125827. 24,
  125828. 1,
  125829. 25,
  125830. 0,
  125831. 26,
  125832. };
  125833. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125834. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125835. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125836. };
  125837. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125838. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125839. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125840. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125841. 11.5, 12.5,
  125842. };
  125843. static long _vq_quantmap__16c2_s_p9_2[] = {
  125844. 25, 23, 21, 19, 17, 15, 13, 11,
  125845. 9, 7, 5, 3, 1, 0, 2, 4,
  125846. 6, 8, 10, 12, 14, 16, 18, 20,
  125847. 22, 24, 26,
  125848. };
  125849. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125850. _vq_quantthresh__16c2_s_p9_2,
  125851. _vq_quantmap__16c2_s_p9_2,
  125852. 27,
  125853. 27
  125854. };
  125855. static static_codebook _16c2_s_p9_2 = {
  125856. 1, 27,
  125857. _vq_lengthlist__16c2_s_p9_2,
  125858. 1, -528875520, 1611661312, 5, 0,
  125859. _vq_quantlist__16c2_s_p9_2,
  125860. NULL,
  125861. &_vq_auxt__16c2_s_p9_2,
  125862. NULL,
  125863. 0
  125864. };
  125865. static long _huff_lengthlist__16c2_s_short[] = {
  125866. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125867. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125868. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125869. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125870. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125871. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125872. 15,12,14,14,
  125873. };
  125874. static static_codebook _huff_book__16c2_s_short = {
  125875. 2, 100,
  125876. _huff_lengthlist__16c2_s_short,
  125877. 0, 0, 0, 0, 0,
  125878. NULL,
  125879. NULL,
  125880. NULL,
  125881. NULL,
  125882. 0
  125883. };
  125884. static long _vq_quantlist__8c0_s_p1_0[] = {
  125885. 1,
  125886. 0,
  125887. 2,
  125888. };
  125889. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125890. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125891. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125896. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125901. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  125936. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125941. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125946. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125982. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125987. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125992. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 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,
  126301. };
  126302. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126303. -0.5, 0.5,
  126304. };
  126305. static long _vq_quantmap__8c0_s_p1_0[] = {
  126306. 1, 0, 2,
  126307. };
  126308. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126309. _vq_quantthresh__8c0_s_p1_0,
  126310. _vq_quantmap__8c0_s_p1_0,
  126311. 3,
  126312. 3
  126313. };
  126314. static static_codebook _8c0_s_p1_0 = {
  126315. 8, 6561,
  126316. _vq_lengthlist__8c0_s_p1_0,
  126317. 1, -535822336, 1611661312, 2, 0,
  126318. _vq_quantlist__8c0_s_p1_0,
  126319. NULL,
  126320. &_vq_auxt__8c0_s_p1_0,
  126321. NULL,
  126322. 0
  126323. };
  126324. static long _vq_quantlist__8c0_s_p2_0[] = {
  126325. 2,
  126326. 1,
  126327. 3,
  126328. 0,
  126329. 4,
  126330. };
  126331. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0,
  126372. };
  126373. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126374. -1.5, -0.5, 0.5, 1.5,
  126375. };
  126376. static long _vq_quantmap__8c0_s_p2_0[] = {
  126377. 3, 1, 0, 2, 4,
  126378. };
  126379. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126380. _vq_quantthresh__8c0_s_p2_0,
  126381. _vq_quantmap__8c0_s_p2_0,
  126382. 5,
  126383. 5
  126384. };
  126385. static static_codebook _8c0_s_p2_0 = {
  126386. 4, 625,
  126387. _vq_lengthlist__8c0_s_p2_0,
  126388. 1, -533725184, 1611661312, 3, 0,
  126389. _vq_quantlist__8c0_s_p2_0,
  126390. NULL,
  126391. &_vq_auxt__8c0_s_p2_0,
  126392. NULL,
  126393. 0
  126394. };
  126395. static long _vq_quantlist__8c0_s_p3_0[] = {
  126396. 2,
  126397. 1,
  126398. 3,
  126399. 0,
  126400. 4,
  126401. };
  126402. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126403. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0,
  126443. };
  126444. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126445. -1.5, -0.5, 0.5, 1.5,
  126446. };
  126447. static long _vq_quantmap__8c0_s_p3_0[] = {
  126448. 3, 1, 0, 2, 4,
  126449. };
  126450. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126451. _vq_quantthresh__8c0_s_p3_0,
  126452. _vq_quantmap__8c0_s_p3_0,
  126453. 5,
  126454. 5
  126455. };
  126456. static static_codebook _8c0_s_p3_0 = {
  126457. 4, 625,
  126458. _vq_lengthlist__8c0_s_p3_0,
  126459. 1, -533725184, 1611661312, 3, 0,
  126460. _vq_quantlist__8c0_s_p3_0,
  126461. NULL,
  126462. &_vq_auxt__8c0_s_p3_0,
  126463. NULL,
  126464. 0
  126465. };
  126466. static long _vq_quantlist__8c0_s_p4_0[] = {
  126467. 4,
  126468. 3,
  126469. 5,
  126470. 2,
  126471. 6,
  126472. 1,
  126473. 7,
  126474. 0,
  126475. 8,
  126476. };
  126477. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126478. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126479. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126480. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126481. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126482. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0,
  126484. };
  126485. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126486. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126487. };
  126488. static long _vq_quantmap__8c0_s_p4_0[] = {
  126489. 7, 5, 3, 1, 0, 2, 4, 6,
  126490. 8,
  126491. };
  126492. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126493. _vq_quantthresh__8c0_s_p4_0,
  126494. _vq_quantmap__8c0_s_p4_0,
  126495. 9,
  126496. 9
  126497. };
  126498. static static_codebook _8c0_s_p4_0 = {
  126499. 2, 81,
  126500. _vq_lengthlist__8c0_s_p4_0,
  126501. 1, -531628032, 1611661312, 4, 0,
  126502. _vq_quantlist__8c0_s_p4_0,
  126503. NULL,
  126504. &_vq_auxt__8c0_s_p4_0,
  126505. NULL,
  126506. 0
  126507. };
  126508. static long _vq_quantlist__8c0_s_p5_0[] = {
  126509. 4,
  126510. 3,
  126511. 5,
  126512. 2,
  126513. 6,
  126514. 1,
  126515. 7,
  126516. 0,
  126517. 8,
  126518. };
  126519. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126520. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126521. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126522. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126523. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126524. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126525. 10,
  126526. };
  126527. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126528. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126529. };
  126530. static long _vq_quantmap__8c0_s_p5_0[] = {
  126531. 7, 5, 3, 1, 0, 2, 4, 6,
  126532. 8,
  126533. };
  126534. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126535. _vq_quantthresh__8c0_s_p5_0,
  126536. _vq_quantmap__8c0_s_p5_0,
  126537. 9,
  126538. 9
  126539. };
  126540. static static_codebook _8c0_s_p5_0 = {
  126541. 2, 81,
  126542. _vq_lengthlist__8c0_s_p5_0,
  126543. 1, -531628032, 1611661312, 4, 0,
  126544. _vq_quantlist__8c0_s_p5_0,
  126545. NULL,
  126546. &_vq_auxt__8c0_s_p5_0,
  126547. NULL,
  126548. 0
  126549. };
  126550. static long _vq_quantlist__8c0_s_p6_0[] = {
  126551. 8,
  126552. 7,
  126553. 9,
  126554. 6,
  126555. 10,
  126556. 5,
  126557. 11,
  126558. 4,
  126559. 12,
  126560. 3,
  126561. 13,
  126562. 2,
  126563. 14,
  126564. 1,
  126565. 15,
  126566. 0,
  126567. 16,
  126568. };
  126569. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126570. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126571. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126572. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126573. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126574. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126575. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126576. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126577. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126578. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126579. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126580. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126581. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126582. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126583. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126584. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126585. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126586. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126588. 14,
  126589. };
  126590. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126591. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126592. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126593. };
  126594. static long _vq_quantmap__8c0_s_p6_0[] = {
  126595. 15, 13, 11, 9, 7, 5, 3, 1,
  126596. 0, 2, 4, 6, 8, 10, 12, 14,
  126597. 16,
  126598. };
  126599. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126600. _vq_quantthresh__8c0_s_p6_0,
  126601. _vq_quantmap__8c0_s_p6_0,
  126602. 17,
  126603. 17
  126604. };
  126605. static static_codebook _8c0_s_p6_0 = {
  126606. 2, 289,
  126607. _vq_lengthlist__8c0_s_p6_0,
  126608. 1, -529530880, 1611661312, 5, 0,
  126609. _vq_quantlist__8c0_s_p6_0,
  126610. NULL,
  126611. &_vq_auxt__8c0_s_p6_0,
  126612. NULL,
  126613. 0
  126614. };
  126615. static long _vq_quantlist__8c0_s_p7_0[] = {
  126616. 1,
  126617. 0,
  126618. 2,
  126619. };
  126620. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126621. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126622. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126623. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126624. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126625. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126626. 10,
  126627. };
  126628. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126629. -5.5, 5.5,
  126630. };
  126631. static long _vq_quantmap__8c0_s_p7_0[] = {
  126632. 1, 0, 2,
  126633. };
  126634. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126635. _vq_quantthresh__8c0_s_p7_0,
  126636. _vq_quantmap__8c0_s_p7_0,
  126637. 3,
  126638. 3
  126639. };
  126640. static static_codebook _8c0_s_p7_0 = {
  126641. 4, 81,
  126642. _vq_lengthlist__8c0_s_p7_0,
  126643. 1, -529137664, 1618345984, 2, 0,
  126644. _vq_quantlist__8c0_s_p7_0,
  126645. NULL,
  126646. &_vq_auxt__8c0_s_p7_0,
  126647. NULL,
  126648. 0
  126649. };
  126650. static long _vq_quantlist__8c0_s_p7_1[] = {
  126651. 5,
  126652. 4,
  126653. 6,
  126654. 3,
  126655. 7,
  126656. 2,
  126657. 8,
  126658. 1,
  126659. 9,
  126660. 0,
  126661. 10,
  126662. };
  126663. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126664. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126665. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126666. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126667. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126668. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126669. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126670. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126671. 10,10,10, 9, 9, 9,10,10,10,
  126672. };
  126673. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126674. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126675. 3.5, 4.5,
  126676. };
  126677. static long _vq_quantmap__8c0_s_p7_1[] = {
  126678. 9, 7, 5, 3, 1, 0, 2, 4,
  126679. 6, 8, 10,
  126680. };
  126681. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126682. _vq_quantthresh__8c0_s_p7_1,
  126683. _vq_quantmap__8c0_s_p7_1,
  126684. 11,
  126685. 11
  126686. };
  126687. static static_codebook _8c0_s_p7_1 = {
  126688. 2, 121,
  126689. _vq_lengthlist__8c0_s_p7_1,
  126690. 1, -531365888, 1611661312, 4, 0,
  126691. _vq_quantlist__8c0_s_p7_1,
  126692. NULL,
  126693. &_vq_auxt__8c0_s_p7_1,
  126694. NULL,
  126695. 0
  126696. };
  126697. static long _vq_quantlist__8c0_s_p8_0[] = {
  126698. 6,
  126699. 5,
  126700. 7,
  126701. 4,
  126702. 8,
  126703. 3,
  126704. 9,
  126705. 2,
  126706. 10,
  126707. 1,
  126708. 11,
  126709. 0,
  126710. 12,
  126711. };
  126712. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126713. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126714. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126715. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126716. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126717. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126718. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126719. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126720. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126721. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126722. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126723. 0, 0,13,13,11,13,13,11,12,
  126724. };
  126725. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126726. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126727. 12.5, 17.5, 22.5, 27.5,
  126728. };
  126729. static long _vq_quantmap__8c0_s_p8_0[] = {
  126730. 11, 9, 7, 5, 3, 1, 0, 2,
  126731. 4, 6, 8, 10, 12,
  126732. };
  126733. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126734. _vq_quantthresh__8c0_s_p8_0,
  126735. _vq_quantmap__8c0_s_p8_0,
  126736. 13,
  126737. 13
  126738. };
  126739. static static_codebook _8c0_s_p8_0 = {
  126740. 2, 169,
  126741. _vq_lengthlist__8c0_s_p8_0,
  126742. 1, -526516224, 1616117760, 4, 0,
  126743. _vq_quantlist__8c0_s_p8_0,
  126744. NULL,
  126745. &_vq_auxt__8c0_s_p8_0,
  126746. NULL,
  126747. 0
  126748. };
  126749. static long _vq_quantlist__8c0_s_p8_1[] = {
  126750. 2,
  126751. 1,
  126752. 3,
  126753. 0,
  126754. 4,
  126755. };
  126756. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126757. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126758. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126759. };
  126760. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126761. -1.5, -0.5, 0.5, 1.5,
  126762. };
  126763. static long _vq_quantmap__8c0_s_p8_1[] = {
  126764. 3, 1, 0, 2, 4,
  126765. };
  126766. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126767. _vq_quantthresh__8c0_s_p8_1,
  126768. _vq_quantmap__8c0_s_p8_1,
  126769. 5,
  126770. 5
  126771. };
  126772. static static_codebook _8c0_s_p8_1 = {
  126773. 2, 25,
  126774. _vq_lengthlist__8c0_s_p8_1,
  126775. 1, -533725184, 1611661312, 3, 0,
  126776. _vq_quantlist__8c0_s_p8_1,
  126777. NULL,
  126778. &_vq_auxt__8c0_s_p8_1,
  126779. NULL,
  126780. 0
  126781. };
  126782. static long _vq_quantlist__8c0_s_p9_0[] = {
  126783. 1,
  126784. 0,
  126785. 2,
  126786. };
  126787. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126788. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126789. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126790. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126791. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126792. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126793. 7,
  126794. };
  126795. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126796. -157.5, 157.5,
  126797. };
  126798. static long _vq_quantmap__8c0_s_p9_0[] = {
  126799. 1, 0, 2,
  126800. };
  126801. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126802. _vq_quantthresh__8c0_s_p9_0,
  126803. _vq_quantmap__8c0_s_p9_0,
  126804. 3,
  126805. 3
  126806. };
  126807. static static_codebook _8c0_s_p9_0 = {
  126808. 4, 81,
  126809. _vq_lengthlist__8c0_s_p9_0,
  126810. 1, -518803456, 1628680192, 2, 0,
  126811. _vq_quantlist__8c0_s_p9_0,
  126812. NULL,
  126813. &_vq_auxt__8c0_s_p9_0,
  126814. NULL,
  126815. 0
  126816. };
  126817. static long _vq_quantlist__8c0_s_p9_1[] = {
  126818. 7,
  126819. 6,
  126820. 8,
  126821. 5,
  126822. 9,
  126823. 4,
  126824. 10,
  126825. 3,
  126826. 11,
  126827. 2,
  126828. 12,
  126829. 1,
  126830. 13,
  126831. 0,
  126832. 14,
  126833. };
  126834. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126835. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126836. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126837. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126838. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126839. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126840. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126849. 11,
  126850. };
  126851. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126852. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126853. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126854. };
  126855. static long _vq_quantmap__8c0_s_p9_1[] = {
  126856. 13, 11, 9, 7, 5, 3, 1, 0,
  126857. 2, 4, 6, 8, 10, 12, 14,
  126858. };
  126859. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126860. _vq_quantthresh__8c0_s_p9_1,
  126861. _vq_quantmap__8c0_s_p9_1,
  126862. 15,
  126863. 15
  126864. };
  126865. static static_codebook _8c0_s_p9_1 = {
  126866. 2, 225,
  126867. _vq_lengthlist__8c0_s_p9_1,
  126868. 1, -520986624, 1620377600, 4, 0,
  126869. _vq_quantlist__8c0_s_p9_1,
  126870. NULL,
  126871. &_vq_auxt__8c0_s_p9_1,
  126872. NULL,
  126873. 0
  126874. };
  126875. static long _vq_quantlist__8c0_s_p9_2[] = {
  126876. 10,
  126877. 9,
  126878. 11,
  126879. 8,
  126880. 12,
  126881. 7,
  126882. 13,
  126883. 6,
  126884. 14,
  126885. 5,
  126886. 15,
  126887. 4,
  126888. 16,
  126889. 3,
  126890. 17,
  126891. 2,
  126892. 18,
  126893. 1,
  126894. 19,
  126895. 0,
  126896. 20,
  126897. };
  126898. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126899. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126900. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126901. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126902. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126903. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126904. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126905. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126906. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126907. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126908. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126909. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126910. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126911. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126912. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126913. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126914. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126915. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126916. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126917. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126918. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126919. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126920. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126921. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126922. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126923. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126924. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126925. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126926. 10,11, 9,11,10, 9,10, 9,10,
  126927. };
  126928. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126929. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126930. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126931. 6.5, 7.5, 8.5, 9.5,
  126932. };
  126933. static long _vq_quantmap__8c0_s_p9_2[] = {
  126934. 19, 17, 15, 13, 11, 9, 7, 5,
  126935. 3, 1, 0, 2, 4, 6, 8, 10,
  126936. 12, 14, 16, 18, 20,
  126937. };
  126938. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126939. _vq_quantthresh__8c0_s_p9_2,
  126940. _vq_quantmap__8c0_s_p9_2,
  126941. 21,
  126942. 21
  126943. };
  126944. static static_codebook _8c0_s_p9_2 = {
  126945. 2, 441,
  126946. _vq_lengthlist__8c0_s_p9_2,
  126947. 1, -529268736, 1611661312, 5, 0,
  126948. _vq_quantlist__8c0_s_p9_2,
  126949. NULL,
  126950. &_vq_auxt__8c0_s_p9_2,
  126951. NULL,
  126952. 0
  126953. };
  126954. static long _huff_lengthlist__8c0_s_single[] = {
  126955. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126956. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126957. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126958. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126959. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126960. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126961. 17,16,17,17,
  126962. };
  126963. static static_codebook _huff_book__8c0_s_single = {
  126964. 2, 100,
  126965. _huff_lengthlist__8c0_s_single,
  126966. 0, 0, 0, 0, 0,
  126967. NULL,
  126968. NULL,
  126969. NULL,
  126970. NULL,
  126971. 0
  126972. };
  126973. static long _vq_quantlist__8c1_s_p1_0[] = {
  126974. 1,
  126975. 0,
  126976. 2,
  126977. };
  126978. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126979. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126980. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126985. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126990. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  127025. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  127030. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  127035. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127071. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127076. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127081. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 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,
  127390. };
  127391. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127392. -0.5, 0.5,
  127393. };
  127394. static long _vq_quantmap__8c1_s_p1_0[] = {
  127395. 1, 0, 2,
  127396. };
  127397. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127398. _vq_quantthresh__8c1_s_p1_0,
  127399. _vq_quantmap__8c1_s_p1_0,
  127400. 3,
  127401. 3
  127402. };
  127403. static static_codebook _8c1_s_p1_0 = {
  127404. 8, 6561,
  127405. _vq_lengthlist__8c1_s_p1_0,
  127406. 1, -535822336, 1611661312, 2, 0,
  127407. _vq_quantlist__8c1_s_p1_0,
  127408. NULL,
  127409. &_vq_auxt__8c1_s_p1_0,
  127410. NULL,
  127411. 0
  127412. };
  127413. static long _vq_quantlist__8c1_s_p2_0[] = {
  127414. 2,
  127415. 1,
  127416. 3,
  127417. 0,
  127418. 4,
  127419. };
  127420. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0,
  127461. };
  127462. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127463. -1.5, -0.5, 0.5, 1.5,
  127464. };
  127465. static long _vq_quantmap__8c1_s_p2_0[] = {
  127466. 3, 1, 0, 2, 4,
  127467. };
  127468. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127469. _vq_quantthresh__8c1_s_p2_0,
  127470. _vq_quantmap__8c1_s_p2_0,
  127471. 5,
  127472. 5
  127473. };
  127474. static static_codebook _8c1_s_p2_0 = {
  127475. 4, 625,
  127476. _vq_lengthlist__8c1_s_p2_0,
  127477. 1, -533725184, 1611661312, 3, 0,
  127478. _vq_quantlist__8c1_s_p2_0,
  127479. NULL,
  127480. &_vq_auxt__8c1_s_p2_0,
  127481. NULL,
  127482. 0
  127483. };
  127484. static long _vq_quantlist__8c1_s_p3_0[] = {
  127485. 2,
  127486. 1,
  127487. 3,
  127488. 0,
  127489. 4,
  127490. };
  127491. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127492. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0,
  127532. };
  127533. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127534. -1.5, -0.5, 0.5, 1.5,
  127535. };
  127536. static long _vq_quantmap__8c1_s_p3_0[] = {
  127537. 3, 1, 0, 2, 4,
  127538. };
  127539. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127540. _vq_quantthresh__8c1_s_p3_0,
  127541. _vq_quantmap__8c1_s_p3_0,
  127542. 5,
  127543. 5
  127544. };
  127545. static static_codebook _8c1_s_p3_0 = {
  127546. 4, 625,
  127547. _vq_lengthlist__8c1_s_p3_0,
  127548. 1, -533725184, 1611661312, 3, 0,
  127549. _vq_quantlist__8c1_s_p3_0,
  127550. NULL,
  127551. &_vq_auxt__8c1_s_p3_0,
  127552. NULL,
  127553. 0
  127554. };
  127555. static long _vq_quantlist__8c1_s_p4_0[] = {
  127556. 4,
  127557. 3,
  127558. 5,
  127559. 2,
  127560. 6,
  127561. 1,
  127562. 7,
  127563. 0,
  127564. 8,
  127565. };
  127566. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127567. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127568. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127569. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127570. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127571. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0,
  127573. };
  127574. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127575. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127576. };
  127577. static long _vq_quantmap__8c1_s_p4_0[] = {
  127578. 7, 5, 3, 1, 0, 2, 4, 6,
  127579. 8,
  127580. };
  127581. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127582. _vq_quantthresh__8c1_s_p4_0,
  127583. _vq_quantmap__8c1_s_p4_0,
  127584. 9,
  127585. 9
  127586. };
  127587. static static_codebook _8c1_s_p4_0 = {
  127588. 2, 81,
  127589. _vq_lengthlist__8c1_s_p4_0,
  127590. 1, -531628032, 1611661312, 4, 0,
  127591. _vq_quantlist__8c1_s_p4_0,
  127592. NULL,
  127593. &_vq_auxt__8c1_s_p4_0,
  127594. NULL,
  127595. 0
  127596. };
  127597. static long _vq_quantlist__8c1_s_p5_0[] = {
  127598. 4,
  127599. 3,
  127600. 5,
  127601. 2,
  127602. 6,
  127603. 1,
  127604. 7,
  127605. 0,
  127606. 8,
  127607. };
  127608. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127609. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127610. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127611. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127612. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127613. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127614. 10,
  127615. };
  127616. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127617. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127618. };
  127619. static long _vq_quantmap__8c1_s_p5_0[] = {
  127620. 7, 5, 3, 1, 0, 2, 4, 6,
  127621. 8,
  127622. };
  127623. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127624. _vq_quantthresh__8c1_s_p5_0,
  127625. _vq_quantmap__8c1_s_p5_0,
  127626. 9,
  127627. 9
  127628. };
  127629. static static_codebook _8c1_s_p5_0 = {
  127630. 2, 81,
  127631. _vq_lengthlist__8c1_s_p5_0,
  127632. 1, -531628032, 1611661312, 4, 0,
  127633. _vq_quantlist__8c1_s_p5_0,
  127634. NULL,
  127635. &_vq_auxt__8c1_s_p5_0,
  127636. NULL,
  127637. 0
  127638. };
  127639. static long _vq_quantlist__8c1_s_p6_0[] = {
  127640. 8,
  127641. 7,
  127642. 9,
  127643. 6,
  127644. 10,
  127645. 5,
  127646. 11,
  127647. 4,
  127648. 12,
  127649. 3,
  127650. 13,
  127651. 2,
  127652. 14,
  127653. 1,
  127654. 15,
  127655. 0,
  127656. 16,
  127657. };
  127658. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127659. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127660. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127661. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127662. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127663. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127664. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127665. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127666. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127667. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127668. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127669. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127670. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127671. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127672. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127673. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127674. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127675. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127677. 14,
  127678. };
  127679. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127680. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127681. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127682. };
  127683. static long _vq_quantmap__8c1_s_p6_0[] = {
  127684. 15, 13, 11, 9, 7, 5, 3, 1,
  127685. 0, 2, 4, 6, 8, 10, 12, 14,
  127686. 16,
  127687. };
  127688. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127689. _vq_quantthresh__8c1_s_p6_0,
  127690. _vq_quantmap__8c1_s_p6_0,
  127691. 17,
  127692. 17
  127693. };
  127694. static static_codebook _8c1_s_p6_0 = {
  127695. 2, 289,
  127696. _vq_lengthlist__8c1_s_p6_0,
  127697. 1, -529530880, 1611661312, 5, 0,
  127698. _vq_quantlist__8c1_s_p6_0,
  127699. NULL,
  127700. &_vq_auxt__8c1_s_p6_0,
  127701. NULL,
  127702. 0
  127703. };
  127704. static long _vq_quantlist__8c1_s_p7_0[] = {
  127705. 1,
  127706. 0,
  127707. 2,
  127708. };
  127709. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127710. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127711. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127712. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127713. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127714. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127715. 9,
  127716. };
  127717. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127718. -5.5, 5.5,
  127719. };
  127720. static long _vq_quantmap__8c1_s_p7_0[] = {
  127721. 1, 0, 2,
  127722. };
  127723. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127724. _vq_quantthresh__8c1_s_p7_0,
  127725. _vq_quantmap__8c1_s_p7_0,
  127726. 3,
  127727. 3
  127728. };
  127729. static static_codebook _8c1_s_p7_0 = {
  127730. 4, 81,
  127731. _vq_lengthlist__8c1_s_p7_0,
  127732. 1, -529137664, 1618345984, 2, 0,
  127733. _vq_quantlist__8c1_s_p7_0,
  127734. NULL,
  127735. &_vq_auxt__8c1_s_p7_0,
  127736. NULL,
  127737. 0
  127738. };
  127739. static long _vq_quantlist__8c1_s_p7_1[] = {
  127740. 5,
  127741. 4,
  127742. 6,
  127743. 3,
  127744. 7,
  127745. 2,
  127746. 8,
  127747. 1,
  127748. 9,
  127749. 0,
  127750. 10,
  127751. };
  127752. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127753. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127754. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127755. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127756. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127757. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127758. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127759. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127760. 10,10,10, 8, 8, 8, 8, 8, 8,
  127761. };
  127762. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127763. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127764. 3.5, 4.5,
  127765. };
  127766. static long _vq_quantmap__8c1_s_p7_1[] = {
  127767. 9, 7, 5, 3, 1, 0, 2, 4,
  127768. 6, 8, 10,
  127769. };
  127770. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127771. _vq_quantthresh__8c1_s_p7_1,
  127772. _vq_quantmap__8c1_s_p7_1,
  127773. 11,
  127774. 11
  127775. };
  127776. static static_codebook _8c1_s_p7_1 = {
  127777. 2, 121,
  127778. _vq_lengthlist__8c1_s_p7_1,
  127779. 1, -531365888, 1611661312, 4, 0,
  127780. _vq_quantlist__8c1_s_p7_1,
  127781. NULL,
  127782. &_vq_auxt__8c1_s_p7_1,
  127783. NULL,
  127784. 0
  127785. };
  127786. static long _vq_quantlist__8c1_s_p8_0[] = {
  127787. 6,
  127788. 5,
  127789. 7,
  127790. 4,
  127791. 8,
  127792. 3,
  127793. 9,
  127794. 2,
  127795. 10,
  127796. 1,
  127797. 11,
  127798. 0,
  127799. 12,
  127800. };
  127801. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127802. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127803. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127804. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127805. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127806. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127807. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127808. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127809. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127810. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127811. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127812. 0,12,12,11,10,12,11,13,12,
  127813. };
  127814. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127815. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127816. 12.5, 17.5, 22.5, 27.5,
  127817. };
  127818. static long _vq_quantmap__8c1_s_p8_0[] = {
  127819. 11, 9, 7, 5, 3, 1, 0, 2,
  127820. 4, 6, 8, 10, 12,
  127821. };
  127822. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127823. _vq_quantthresh__8c1_s_p8_0,
  127824. _vq_quantmap__8c1_s_p8_0,
  127825. 13,
  127826. 13
  127827. };
  127828. static static_codebook _8c1_s_p8_0 = {
  127829. 2, 169,
  127830. _vq_lengthlist__8c1_s_p8_0,
  127831. 1, -526516224, 1616117760, 4, 0,
  127832. _vq_quantlist__8c1_s_p8_0,
  127833. NULL,
  127834. &_vq_auxt__8c1_s_p8_0,
  127835. NULL,
  127836. 0
  127837. };
  127838. static long _vq_quantlist__8c1_s_p8_1[] = {
  127839. 2,
  127840. 1,
  127841. 3,
  127842. 0,
  127843. 4,
  127844. };
  127845. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127846. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127847. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127848. };
  127849. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127850. -1.5, -0.5, 0.5, 1.5,
  127851. };
  127852. static long _vq_quantmap__8c1_s_p8_1[] = {
  127853. 3, 1, 0, 2, 4,
  127854. };
  127855. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127856. _vq_quantthresh__8c1_s_p8_1,
  127857. _vq_quantmap__8c1_s_p8_1,
  127858. 5,
  127859. 5
  127860. };
  127861. static static_codebook _8c1_s_p8_1 = {
  127862. 2, 25,
  127863. _vq_lengthlist__8c1_s_p8_1,
  127864. 1, -533725184, 1611661312, 3, 0,
  127865. _vq_quantlist__8c1_s_p8_1,
  127866. NULL,
  127867. &_vq_auxt__8c1_s_p8_1,
  127868. NULL,
  127869. 0
  127870. };
  127871. static long _vq_quantlist__8c1_s_p9_0[] = {
  127872. 6,
  127873. 5,
  127874. 7,
  127875. 4,
  127876. 8,
  127877. 3,
  127878. 9,
  127879. 2,
  127880. 10,
  127881. 1,
  127882. 11,
  127883. 0,
  127884. 12,
  127885. };
  127886. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127887. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127888. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127889. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127890. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127891. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127892. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127893. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127894. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127895. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127896. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127897. 10,10,10,10,10, 9, 9, 9, 9,
  127898. };
  127899. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127900. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127901. 787.5, 1102.5, 1417.5, 1732.5,
  127902. };
  127903. static long _vq_quantmap__8c1_s_p9_0[] = {
  127904. 11, 9, 7, 5, 3, 1, 0, 2,
  127905. 4, 6, 8, 10, 12,
  127906. };
  127907. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127908. _vq_quantthresh__8c1_s_p9_0,
  127909. _vq_quantmap__8c1_s_p9_0,
  127910. 13,
  127911. 13
  127912. };
  127913. static static_codebook _8c1_s_p9_0 = {
  127914. 2, 169,
  127915. _vq_lengthlist__8c1_s_p9_0,
  127916. 1, -513964032, 1628680192, 4, 0,
  127917. _vq_quantlist__8c1_s_p9_0,
  127918. NULL,
  127919. &_vq_auxt__8c1_s_p9_0,
  127920. NULL,
  127921. 0
  127922. };
  127923. static long _vq_quantlist__8c1_s_p9_1[] = {
  127924. 7,
  127925. 6,
  127926. 8,
  127927. 5,
  127928. 9,
  127929. 4,
  127930. 10,
  127931. 3,
  127932. 11,
  127933. 2,
  127934. 12,
  127935. 1,
  127936. 13,
  127937. 0,
  127938. 14,
  127939. };
  127940. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127941. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127942. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127943. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127944. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127945. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127946. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127947. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127948. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127949. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127950. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127951. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127952. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127953. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127954. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127955. 15,
  127956. };
  127957. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127958. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127959. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127960. };
  127961. static long _vq_quantmap__8c1_s_p9_1[] = {
  127962. 13, 11, 9, 7, 5, 3, 1, 0,
  127963. 2, 4, 6, 8, 10, 12, 14,
  127964. };
  127965. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127966. _vq_quantthresh__8c1_s_p9_1,
  127967. _vq_quantmap__8c1_s_p9_1,
  127968. 15,
  127969. 15
  127970. };
  127971. static static_codebook _8c1_s_p9_1 = {
  127972. 2, 225,
  127973. _vq_lengthlist__8c1_s_p9_1,
  127974. 1, -520986624, 1620377600, 4, 0,
  127975. _vq_quantlist__8c1_s_p9_1,
  127976. NULL,
  127977. &_vq_auxt__8c1_s_p9_1,
  127978. NULL,
  127979. 0
  127980. };
  127981. static long _vq_quantlist__8c1_s_p9_2[] = {
  127982. 10,
  127983. 9,
  127984. 11,
  127985. 8,
  127986. 12,
  127987. 7,
  127988. 13,
  127989. 6,
  127990. 14,
  127991. 5,
  127992. 15,
  127993. 4,
  127994. 16,
  127995. 3,
  127996. 17,
  127997. 2,
  127998. 18,
  127999. 1,
  128000. 19,
  128001. 0,
  128002. 20,
  128003. };
  128004. static long _vq_lengthlist__8c1_s_p9_2[] = {
  128005. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  128006. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  128007. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  128008. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  128009. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128010. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128011. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  128012. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  128013. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  128014. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  128015. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  128016. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  128017. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  128018. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  128019. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  128020. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  128021. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128022. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  128023. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  128024. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  128025. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128026. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  128027. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  128028. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128029. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128030. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128031. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128032. 10,10,10,10,10,10,10,10,10,
  128033. };
  128034. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128035. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128036. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128037. 6.5, 7.5, 8.5, 9.5,
  128038. };
  128039. static long _vq_quantmap__8c1_s_p9_2[] = {
  128040. 19, 17, 15, 13, 11, 9, 7, 5,
  128041. 3, 1, 0, 2, 4, 6, 8, 10,
  128042. 12, 14, 16, 18, 20,
  128043. };
  128044. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128045. _vq_quantthresh__8c1_s_p9_2,
  128046. _vq_quantmap__8c1_s_p9_2,
  128047. 21,
  128048. 21
  128049. };
  128050. static static_codebook _8c1_s_p9_2 = {
  128051. 2, 441,
  128052. _vq_lengthlist__8c1_s_p9_2,
  128053. 1, -529268736, 1611661312, 5, 0,
  128054. _vq_quantlist__8c1_s_p9_2,
  128055. NULL,
  128056. &_vq_auxt__8c1_s_p9_2,
  128057. NULL,
  128058. 0
  128059. };
  128060. static long _huff_lengthlist__8c1_s_single[] = {
  128061. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128062. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128063. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128064. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128065. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128066. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128067. 9, 7, 7, 8,
  128068. };
  128069. static static_codebook _huff_book__8c1_s_single = {
  128070. 2, 100,
  128071. _huff_lengthlist__8c1_s_single,
  128072. 0, 0, 0, 0, 0,
  128073. NULL,
  128074. NULL,
  128075. NULL,
  128076. NULL,
  128077. 0
  128078. };
  128079. static long _huff_lengthlist__44c2_s_long[] = {
  128080. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128081. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128082. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128083. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128084. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128085. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128086. 10, 8, 8, 9,
  128087. };
  128088. static static_codebook _huff_book__44c2_s_long = {
  128089. 2, 100,
  128090. _huff_lengthlist__44c2_s_long,
  128091. 0, 0, 0, 0, 0,
  128092. NULL,
  128093. NULL,
  128094. NULL,
  128095. NULL,
  128096. 0
  128097. };
  128098. static long _vq_quantlist__44c2_s_p1_0[] = {
  128099. 1,
  128100. 0,
  128101. 2,
  128102. };
  128103. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128104. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128105. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128110. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128115. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  128150. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128155. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128160. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128196. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128201. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128206. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  128515. };
  128516. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128517. -0.5, 0.5,
  128518. };
  128519. static long _vq_quantmap__44c2_s_p1_0[] = {
  128520. 1, 0, 2,
  128521. };
  128522. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128523. _vq_quantthresh__44c2_s_p1_0,
  128524. _vq_quantmap__44c2_s_p1_0,
  128525. 3,
  128526. 3
  128527. };
  128528. static static_codebook _44c2_s_p1_0 = {
  128529. 8, 6561,
  128530. _vq_lengthlist__44c2_s_p1_0,
  128531. 1, -535822336, 1611661312, 2, 0,
  128532. _vq_quantlist__44c2_s_p1_0,
  128533. NULL,
  128534. &_vq_auxt__44c2_s_p1_0,
  128535. NULL,
  128536. 0
  128537. };
  128538. static long _vq_quantlist__44c2_s_p2_0[] = {
  128539. 2,
  128540. 1,
  128541. 3,
  128542. 0,
  128543. 4,
  128544. };
  128545. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128546. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128547. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128548. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128549. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128550. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128556. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128557. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128558. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128564. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128565. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128572. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128573. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0,
  128586. };
  128587. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128588. -1.5, -0.5, 0.5, 1.5,
  128589. };
  128590. static long _vq_quantmap__44c2_s_p2_0[] = {
  128591. 3, 1, 0, 2, 4,
  128592. };
  128593. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128594. _vq_quantthresh__44c2_s_p2_0,
  128595. _vq_quantmap__44c2_s_p2_0,
  128596. 5,
  128597. 5
  128598. };
  128599. static static_codebook _44c2_s_p2_0 = {
  128600. 4, 625,
  128601. _vq_lengthlist__44c2_s_p2_0,
  128602. 1, -533725184, 1611661312, 3, 0,
  128603. _vq_quantlist__44c2_s_p2_0,
  128604. NULL,
  128605. &_vq_auxt__44c2_s_p2_0,
  128606. NULL,
  128607. 0
  128608. };
  128609. static long _vq_quantlist__44c2_s_p3_0[] = {
  128610. 2,
  128611. 1,
  128612. 3,
  128613. 0,
  128614. 4,
  128615. };
  128616. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128617. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128656. 0,
  128657. };
  128658. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128659. -1.5, -0.5, 0.5, 1.5,
  128660. };
  128661. static long _vq_quantmap__44c2_s_p3_0[] = {
  128662. 3, 1, 0, 2, 4,
  128663. };
  128664. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128665. _vq_quantthresh__44c2_s_p3_0,
  128666. _vq_quantmap__44c2_s_p3_0,
  128667. 5,
  128668. 5
  128669. };
  128670. static static_codebook _44c2_s_p3_0 = {
  128671. 4, 625,
  128672. _vq_lengthlist__44c2_s_p3_0,
  128673. 1, -533725184, 1611661312, 3, 0,
  128674. _vq_quantlist__44c2_s_p3_0,
  128675. NULL,
  128676. &_vq_auxt__44c2_s_p3_0,
  128677. NULL,
  128678. 0
  128679. };
  128680. static long _vq_quantlist__44c2_s_p4_0[] = {
  128681. 4,
  128682. 3,
  128683. 5,
  128684. 2,
  128685. 6,
  128686. 1,
  128687. 7,
  128688. 0,
  128689. 8,
  128690. };
  128691. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128692. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128693. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128694. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128695. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128696. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0,
  128698. };
  128699. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128700. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128701. };
  128702. static long _vq_quantmap__44c2_s_p4_0[] = {
  128703. 7, 5, 3, 1, 0, 2, 4, 6,
  128704. 8,
  128705. };
  128706. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128707. _vq_quantthresh__44c2_s_p4_0,
  128708. _vq_quantmap__44c2_s_p4_0,
  128709. 9,
  128710. 9
  128711. };
  128712. static static_codebook _44c2_s_p4_0 = {
  128713. 2, 81,
  128714. _vq_lengthlist__44c2_s_p4_0,
  128715. 1, -531628032, 1611661312, 4, 0,
  128716. _vq_quantlist__44c2_s_p4_0,
  128717. NULL,
  128718. &_vq_auxt__44c2_s_p4_0,
  128719. NULL,
  128720. 0
  128721. };
  128722. static long _vq_quantlist__44c2_s_p5_0[] = {
  128723. 4,
  128724. 3,
  128725. 5,
  128726. 2,
  128727. 6,
  128728. 1,
  128729. 7,
  128730. 0,
  128731. 8,
  128732. };
  128733. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128734. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128735. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128736. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128737. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128738. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128739. 11,
  128740. };
  128741. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128742. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128743. };
  128744. static long _vq_quantmap__44c2_s_p5_0[] = {
  128745. 7, 5, 3, 1, 0, 2, 4, 6,
  128746. 8,
  128747. };
  128748. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128749. _vq_quantthresh__44c2_s_p5_0,
  128750. _vq_quantmap__44c2_s_p5_0,
  128751. 9,
  128752. 9
  128753. };
  128754. static static_codebook _44c2_s_p5_0 = {
  128755. 2, 81,
  128756. _vq_lengthlist__44c2_s_p5_0,
  128757. 1, -531628032, 1611661312, 4, 0,
  128758. _vq_quantlist__44c2_s_p5_0,
  128759. NULL,
  128760. &_vq_auxt__44c2_s_p5_0,
  128761. NULL,
  128762. 0
  128763. };
  128764. static long _vq_quantlist__44c2_s_p6_0[] = {
  128765. 8,
  128766. 7,
  128767. 9,
  128768. 6,
  128769. 10,
  128770. 5,
  128771. 11,
  128772. 4,
  128773. 12,
  128774. 3,
  128775. 13,
  128776. 2,
  128777. 14,
  128778. 1,
  128779. 15,
  128780. 0,
  128781. 16,
  128782. };
  128783. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128784. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128785. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128786. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128787. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128788. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128789. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128790. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128791. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128792. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128793. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128794. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128795. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128796. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128797. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128798. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128799. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128800. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128802. 14,
  128803. };
  128804. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128805. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128806. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128807. };
  128808. static long _vq_quantmap__44c2_s_p6_0[] = {
  128809. 15, 13, 11, 9, 7, 5, 3, 1,
  128810. 0, 2, 4, 6, 8, 10, 12, 14,
  128811. 16,
  128812. };
  128813. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128814. _vq_quantthresh__44c2_s_p6_0,
  128815. _vq_quantmap__44c2_s_p6_0,
  128816. 17,
  128817. 17
  128818. };
  128819. static static_codebook _44c2_s_p6_0 = {
  128820. 2, 289,
  128821. _vq_lengthlist__44c2_s_p6_0,
  128822. 1, -529530880, 1611661312, 5, 0,
  128823. _vq_quantlist__44c2_s_p6_0,
  128824. NULL,
  128825. &_vq_auxt__44c2_s_p6_0,
  128826. NULL,
  128827. 0
  128828. };
  128829. static long _vq_quantlist__44c2_s_p7_0[] = {
  128830. 1,
  128831. 0,
  128832. 2,
  128833. };
  128834. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128835. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128836. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128837. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128838. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128839. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128840. 11,
  128841. };
  128842. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128843. -5.5, 5.5,
  128844. };
  128845. static long _vq_quantmap__44c2_s_p7_0[] = {
  128846. 1, 0, 2,
  128847. };
  128848. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128849. _vq_quantthresh__44c2_s_p7_0,
  128850. _vq_quantmap__44c2_s_p7_0,
  128851. 3,
  128852. 3
  128853. };
  128854. static static_codebook _44c2_s_p7_0 = {
  128855. 4, 81,
  128856. _vq_lengthlist__44c2_s_p7_0,
  128857. 1, -529137664, 1618345984, 2, 0,
  128858. _vq_quantlist__44c2_s_p7_0,
  128859. NULL,
  128860. &_vq_auxt__44c2_s_p7_0,
  128861. NULL,
  128862. 0
  128863. };
  128864. static long _vq_quantlist__44c2_s_p7_1[] = {
  128865. 5,
  128866. 4,
  128867. 6,
  128868. 3,
  128869. 7,
  128870. 2,
  128871. 8,
  128872. 1,
  128873. 9,
  128874. 0,
  128875. 10,
  128876. };
  128877. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128878. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128879. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128880. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128881. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128882. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128883. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128884. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128885. 10,10,10, 8, 8, 8, 8, 8, 8,
  128886. };
  128887. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128888. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128889. 3.5, 4.5,
  128890. };
  128891. static long _vq_quantmap__44c2_s_p7_1[] = {
  128892. 9, 7, 5, 3, 1, 0, 2, 4,
  128893. 6, 8, 10,
  128894. };
  128895. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128896. _vq_quantthresh__44c2_s_p7_1,
  128897. _vq_quantmap__44c2_s_p7_1,
  128898. 11,
  128899. 11
  128900. };
  128901. static static_codebook _44c2_s_p7_1 = {
  128902. 2, 121,
  128903. _vq_lengthlist__44c2_s_p7_1,
  128904. 1, -531365888, 1611661312, 4, 0,
  128905. _vq_quantlist__44c2_s_p7_1,
  128906. NULL,
  128907. &_vq_auxt__44c2_s_p7_1,
  128908. NULL,
  128909. 0
  128910. };
  128911. static long _vq_quantlist__44c2_s_p8_0[] = {
  128912. 6,
  128913. 5,
  128914. 7,
  128915. 4,
  128916. 8,
  128917. 3,
  128918. 9,
  128919. 2,
  128920. 10,
  128921. 1,
  128922. 11,
  128923. 0,
  128924. 12,
  128925. };
  128926. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128927. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128928. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128929. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128930. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128931. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128932. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128933. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128934. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128935. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128936. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128937. 0,12,12,12,12,13,12,14,14,
  128938. };
  128939. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128940. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128941. 12.5, 17.5, 22.5, 27.5,
  128942. };
  128943. static long _vq_quantmap__44c2_s_p8_0[] = {
  128944. 11, 9, 7, 5, 3, 1, 0, 2,
  128945. 4, 6, 8, 10, 12,
  128946. };
  128947. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128948. _vq_quantthresh__44c2_s_p8_0,
  128949. _vq_quantmap__44c2_s_p8_0,
  128950. 13,
  128951. 13
  128952. };
  128953. static static_codebook _44c2_s_p8_0 = {
  128954. 2, 169,
  128955. _vq_lengthlist__44c2_s_p8_0,
  128956. 1, -526516224, 1616117760, 4, 0,
  128957. _vq_quantlist__44c2_s_p8_0,
  128958. NULL,
  128959. &_vq_auxt__44c2_s_p8_0,
  128960. NULL,
  128961. 0
  128962. };
  128963. static long _vq_quantlist__44c2_s_p8_1[] = {
  128964. 2,
  128965. 1,
  128966. 3,
  128967. 0,
  128968. 4,
  128969. };
  128970. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128971. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128972. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128973. };
  128974. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128975. -1.5, -0.5, 0.5, 1.5,
  128976. };
  128977. static long _vq_quantmap__44c2_s_p8_1[] = {
  128978. 3, 1, 0, 2, 4,
  128979. };
  128980. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128981. _vq_quantthresh__44c2_s_p8_1,
  128982. _vq_quantmap__44c2_s_p8_1,
  128983. 5,
  128984. 5
  128985. };
  128986. static static_codebook _44c2_s_p8_1 = {
  128987. 2, 25,
  128988. _vq_lengthlist__44c2_s_p8_1,
  128989. 1, -533725184, 1611661312, 3, 0,
  128990. _vq_quantlist__44c2_s_p8_1,
  128991. NULL,
  128992. &_vq_auxt__44c2_s_p8_1,
  128993. NULL,
  128994. 0
  128995. };
  128996. static long _vq_quantlist__44c2_s_p9_0[] = {
  128997. 6,
  128998. 5,
  128999. 7,
  129000. 4,
  129001. 8,
  129002. 3,
  129003. 9,
  129004. 2,
  129005. 10,
  129006. 1,
  129007. 11,
  129008. 0,
  129009. 12,
  129010. };
  129011. static long _vq_lengthlist__44c2_s_p9_0[] = {
  129012. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129013. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  129014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129015. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  129016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129022. 11,11,11,11,11,11,11,11,11,
  129023. };
  129024. static float _vq_quantthresh__44c2_s_p9_0[] = {
  129025. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  129026. 552.5, 773.5, 994.5, 1215.5,
  129027. };
  129028. static long _vq_quantmap__44c2_s_p9_0[] = {
  129029. 11, 9, 7, 5, 3, 1, 0, 2,
  129030. 4, 6, 8, 10, 12,
  129031. };
  129032. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129033. _vq_quantthresh__44c2_s_p9_0,
  129034. _vq_quantmap__44c2_s_p9_0,
  129035. 13,
  129036. 13
  129037. };
  129038. static static_codebook _44c2_s_p9_0 = {
  129039. 2, 169,
  129040. _vq_lengthlist__44c2_s_p9_0,
  129041. 1, -514541568, 1627103232, 4, 0,
  129042. _vq_quantlist__44c2_s_p9_0,
  129043. NULL,
  129044. &_vq_auxt__44c2_s_p9_0,
  129045. NULL,
  129046. 0
  129047. };
  129048. static long _vq_quantlist__44c2_s_p9_1[] = {
  129049. 6,
  129050. 5,
  129051. 7,
  129052. 4,
  129053. 8,
  129054. 3,
  129055. 9,
  129056. 2,
  129057. 10,
  129058. 1,
  129059. 11,
  129060. 0,
  129061. 12,
  129062. };
  129063. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129064. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129065. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129066. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129067. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129068. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129069. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129070. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129071. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129072. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129073. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129074. 17,13,12,12,10,13,11,14,14,
  129075. };
  129076. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129077. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129078. 42.5, 59.5, 76.5, 93.5,
  129079. };
  129080. static long _vq_quantmap__44c2_s_p9_1[] = {
  129081. 11, 9, 7, 5, 3, 1, 0, 2,
  129082. 4, 6, 8, 10, 12,
  129083. };
  129084. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129085. _vq_quantthresh__44c2_s_p9_1,
  129086. _vq_quantmap__44c2_s_p9_1,
  129087. 13,
  129088. 13
  129089. };
  129090. static static_codebook _44c2_s_p9_1 = {
  129091. 2, 169,
  129092. _vq_lengthlist__44c2_s_p9_1,
  129093. 1, -522616832, 1620115456, 4, 0,
  129094. _vq_quantlist__44c2_s_p9_1,
  129095. NULL,
  129096. &_vq_auxt__44c2_s_p9_1,
  129097. NULL,
  129098. 0
  129099. };
  129100. static long _vq_quantlist__44c2_s_p9_2[] = {
  129101. 8,
  129102. 7,
  129103. 9,
  129104. 6,
  129105. 10,
  129106. 5,
  129107. 11,
  129108. 4,
  129109. 12,
  129110. 3,
  129111. 13,
  129112. 2,
  129113. 14,
  129114. 1,
  129115. 15,
  129116. 0,
  129117. 16,
  129118. };
  129119. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129120. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129121. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129122. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129123. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129124. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129125. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129126. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129127. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129128. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129129. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129130. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129131. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129132. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129133. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129134. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129135. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129136. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129137. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129138. 10,
  129139. };
  129140. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129141. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129142. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129143. };
  129144. static long _vq_quantmap__44c2_s_p9_2[] = {
  129145. 15, 13, 11, 9, 7, 5, 3, 1,
  129146. 0, 2, 4, 6, 8, 10, 12, 14,
  129147. 16,
  129148. };
  129149. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129150. _vq_quantthresh__44c2_s_p9_2,
  129151. _vq_quantmap__44c2_s_p9_2,
  129152. 17,
  129153. 17
  129154. };
  129155. static static_codebook _44c2_s_p9_2 = {
  129156. 2, 289,
  129157. _vq_lengthlist__44c2_s_p9_2,
  129158. 1, -529530880, 1611661312, 5, 0,
  129159. _vq_quantlist__44c2_s_p9_2,
  129160. NULL,
  129161. &_vq_auxt__44c2_s_p9_2,
  129162. NULL,
  129163. 0
  129164. };
  129165. static long _huff_lengthlist__44c2_s_short[] = {
  129166. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129167. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129168. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129169. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129170. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129171. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129172. 6, 8, 9,12,
  129173. };
  129174. static static_codebook _huff_book__44c2_s_short = {
  129175. 2, 100,
  129176. _huff_lengthlist__44c2_s_short,
  129177. 0, 0, 0, 0, 0,
  129178. NULL,
  129179. NULL,
  129180. NULL,
  129181. NULL,
  129182. 0
  129183. };
  129184. static long _huff_lengthlist__44c3_s_long[] = {
  129185. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129186. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129187. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129188. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129189. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129190. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129191. 9, 8, 8, 8,
  129192. };
  129193. static static_codebook _huff_book__44c3_s_long = {
  129194. 2, 100,
  129195. _huff_lengthlist__44c3_s_long,
  129196. 0, 0, 0, 0, 0,
  129197. NULL,
  129198. NULL,
  129199. NULL,
  129200. NULL,
  129201. 0
  129202. };
  129203. static long _vq_quantlist__44c3_s_p1_0[] = {
  129204. 1,
  129205. 0,
  129206. 2,
  129207. };
  129208. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129209. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129210. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129215. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129220. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  129255. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129260. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129265. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129301. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129306. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129311. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  129620. };
  129621. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129622. -0.5, 0.5,
  129623. };
  129624. static long _vq_quantmap__44c3_s_p1_0[] = {
  129625. 1, 0, 2,
  129626. };
  129627. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129628. _vq_quantthresh__44c3_s_p1_0,
  129629. _vq_quantmap__44c3_s_p1_0,
  129630. 3,
  129631. 3
  129632. };
  129633. static static_codebook _44c3_s_p1_0 = {
  129634. 8, 6561,
  129635. _vq_lengthlist__44c3_s_p1_0,
  129636. 1, -535822336, 1611661312, 2, 0,
  129637. _vq_quantlist__44c3_s_p1_0,
  129638. NULL,
  129639. &_vq_auxt__44c3_s_p1_0,
  129640. NULL,
  129641. 0
  129642. };
  129643. static long _vq_quantlist__44c3_s_p2_0[] = {
  129644. 2,
  129645. 1,
  129646. 3,
  129647. 0,
  129648. 4,
  129649. };
  129650. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129651. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129652. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129653. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129654. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129655. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129661. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129662. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129663. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129669. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129670. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129677. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129678. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0,
  129691. };
  129692. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129693. -1.5, -0.5, 0.5, 1.5,
  129694. };
  129695. static long _vq_quantmap__44c3_s_p2_0[] = {
  129696. 3, 1, 0, 2, 4,
  129697. };
  129698. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129699. _vq_quantthresh__44c3_s_p2_0,
  129700. _vq_quantmap__44c3_s_p2_0,
  129701. 5,
  129702. 5
  129703. };
  129704. static static_codebook _44c3_s_p2_0 = {
  129705. 4, 625,
  129706. _vq_lengthlist__44c3_s_p2_0,
  129707. 1, -533725184, 1611661312, 3, 0,
  129708. _vq_quantlist__44c3_s_p2_0,
  129709. NULL,
  129710. &_vq_auxt__44c3_s_p2_0,
  129711. NULL,
  129712. 0
  129713. };
  129714. static long _vq_quantlist__44c3_s_p3_0[] = {
  129715. 2,
  129716. 1,
  129717. 3,
  129718. 0,
  129719. 4,
  129720. };
  129721. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129722. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129761. 0,
  129762. };
  129763. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129764. -1.5, -0.5, 0.5, 1.5,
  129765. };
  129766. static long _vq_quantmap__44c3_s_p3_0[] = {
  129767. 3, 1, 0, 2, 4,
  129768. };
  129769. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129770. _vq_quantthresh__44c3_s_p3_0,
  129771. _vq_quantmap__44c3_s_p3_0,
  129772. 5,
  129773. 5
  129774. };
  129775. static static_codebook _44c3_s_p3_0 = {
  129776. 4, 625,
  129777. _vq_lengthlist__44c3_s_p3_0,
  129778. 1, -533725184, 1611661312, 3, 0,
  129779. _vq_quantlist__44c3_s_p3_0,
  129780. NULL,
  129781. &_vq_auxt__44c3_s_p3_0,
  129782. NULL,
  129783. 0
  129784. };
  129785. static long _vq_quantlist__44c3_s_p4_0[] = {
  129786. 4,
  129787. 3,
  129788. 5,
  129789. 2,
  129790. 6,
  129791. 1,
  129792. 7,
  129793. 0,
  129794. 8,
  129795. };
  129796. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129797. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129798. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129799. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129800. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129801. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0,
  129803. };
  129804. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129805. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129806. };
  129807. static long _vq_quantmap__44c3_s_p4_0[] = {
  129808. 7, 5, 3, 1, 0, 2, 4, 6,
  129809. 8,
  129810. };
  129811. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129812. _vq_quantthresh__44c3_s_p4_0,
  129813. _vq_quantmap__44c3_s_p4_0,
  129814. 9,
  129815. 9
  129816. };
  129817. static static_codebook _44c3_s_p4_0 = {
  129818. 2, 81,
  129819. _vq_lengthlist__44c3_s_p4_0,
  129820. 1, -531628032, 1611661312, 4, 0,
  129821. _vq_quantlist__44c3_s_p4_0,
  129822. NULL,
  129823. &_vq_auxt__44c3_s_p4_0,
  129824. NULL,
  129825. 0
  129826. };
  129827. static long _vq_quantlist__44c3_s_p5_0[] = {
  129828. 4,
  129829. 3,
  129830. 5,
  129831. 2,
  129832. 6,
  129833. 1,
  129834. 7,
  129835. 0,
  129836. 8,
  129837. };
  129838. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129839. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129840. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129841. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129842. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129843. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129844. 11,
  129845. };
  129846. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129847. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129848. };
  129849. static long _vq_quantmap__44c3_s_p5_0[] = {
  129850. 7, 5, 3, 1, 0, 2, 4, 6,
  129851. 8,
  129852. };
  129853. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129854. _vq_quantthresh__44c3_s_p5_0,
  129855. _vq_quantmap__44c3_s_p5_0,
  129856. 9,
  129857. 9
  129858. };
  129859. static static_codebook _44c3_s_p5_0 = {
  129860. 2, 81,
  129861. _vq_lengthlist__44c3_s_p5_0,
  129862. 1, -531628032, 1611661312, 4, 0,
  129863. _vq_quantlist__44c3_s_p5_0,
  129864. NULL,
  129865. &_vq_auxt__44c3_s_p5_0,
  129866. NULL,
  129867. 0
  129868. };
  129869. static long _vq_quantlist__44c3_s_p6_0[] = {
  129870. 8,
  129871. 7,
  129872. 9,
  129873. 6,
  129874. 10,
  129875. 5,
  129876. 11,
  129877. 4,
  129878. 12,
  129879. 3,
  129880. 13,
  129881. 2,
  129882. 14,
  129883. 1,
  129884. 15,
  129885. 0,
  129886. 16,
  129887. };
  129888. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129889. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129890. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129891. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129892. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129893. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129894. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129895. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129896. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129897. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129898. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129899. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129900. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129901. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129902. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129903. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129904. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129905. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129907. 13,
  129908. };
  129909. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129910. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129911. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129912. };
  129913. static long _vq_quantmap__44c3_s_p6_0[] = {
  129914. 15, 13, 11, 9, 7, 5, 3, 1,
  129915. 0, 2, 4, 6, 8, 10, 12, 14,
  129916. 16,
  129917. };
  129918. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129919. _vq_quantthresh__44c3_s_p6_0,
  129920. _vq_quantmap__44c3_s_p6_0,
  129921. 17,
  129922. 17
  129923. };
  129924. static static_codebook _44c3_s_p6_0 = {
  129925. 2, 289,
  129926. _vq_lengthlist__44c3_s_p6_0,
  129927. 1, -529530880, 1611661312, 5, 0,
  129928. _vq_quantlist__44c3_s_p6_0,
  129929. NULL,
  129930. &_vq_auxt__44c3_s_p6_0,
  129931. NULL,
  129932. 0
  129933. };
  129934. static long _vq_quantlist__44c3_s_p7_0[] = {
  129935. 1,
  129936. 0,
  129937. 2,
  129938. };
  129939. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129940. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129941. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129942. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129943. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129944. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129945. 10,
  129946. };
  129947. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129948. -5.5, 5.5,
  129949. };
  129950. static long _vq_quantmap__44c3_s_p7_0[] = {
  129951. 1, 0, 2,
  129952. };
  129953. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129954. _vq_quantthresh__44c3_s_p7_0,
  129955. _vq_quantmap__44c3_s_p7_0,
  129956. 3,
  129957. 3
  129958. };
  129959. static static_codebook _44c3_s_p7_0 = {
  129960. 4, 81,
  129961. _vq_lengthlist__44c3_s_p7_0,
  129962. 1, -529137664, 1618345984, 2, 0,
  129963. _vq_quantlist__44c3_s_p7_0,
  129964. NULL,
  129965. &_vq_auxt__44c3_s_p7_0,
  129966. NULL,
  129967. 0
  129968. };
  129969. static long _vq_quantlist__44c3_s_p7_1[] = {
  129970. 5,
  129971. 4,
  129972. 6,
  129973. 3,
  129974. 7,
  129975. 2,
  129976. 8,
  129977. 1,
  129978. 9,
  129979. 0,
  129980. 10,
  129981. };
  129982. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129983. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129984. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129985. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129986. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129987. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129988. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129989. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129990. 10,10,10, 8, 8, 8, 8, 8, 8,
  129991. };
  129992. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129993. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129994. 3.5, 4.5,
  129995. };
  129996. static long _vq_quantmap__44c3_s_p7_1[] = {
  129997. 9, 7, 5, 3, 1, 0, 2, 4,
  129998. 6, 8, 10,
  129999. };
  130000. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  130001. _vq_quantthresh__44c3_s_p7_1,
  130002. _vq_quantmap__44c3_s_p7_1,
  130003. 11,
  130004. 11
  130005. };
  130006. static static_codebook _44c3_s_p7_1 = {
  130007. 2, 121,
  130008. _vq_lengthlist__44c3_s_p7_1,
  130009. 1, -531365888, 1611661312, 4, 0,
  130010. _vq_quantlist__44c3_s_p7_1,
  130011. NULL,
  130012. &_vq_auxt__44c3_s_p7_1,
  130013. NULL,
  130014. 0
  130015. };
  130016. static long _vq_quantlist__44c3_s_p8_0[] = {
  130017. 6,
  130018. 5,
  130019. 7,
  130020. 4,
  130021. 8,
  130022. 3,
  130023. 9,
  130024. 2,
  130025. 10,
  130026. 1,
  130027. 11,
  130028. 0,
  130029. 12,
  130030. };
  130031. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130032. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130033. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130034. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130035. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130036. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130037. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130038. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130039. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130040. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130041. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130042. 0,13,13,12,12,13,12,14,13,
  130043. };
  130044. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130045. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130046. 12.5, 17.5, 22.5, 27.5,
  130047. };
  130048. static long _vq_quantmap__44c3_s_p8_0[] = {
  130049. 11, 9, 7, 5, 3, 1, 0, 2,
  130050. 4, 6, 8, 10, 12,
  130051. };
  130052. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130053. _vq_quantthresh__44c3_s_p8_0,
  130054. _vq_quantmap__44c3_s_p8_0,
  130055. 13,
  130056. 13
  130057. };
  130058. static static_codebook _44c3_s_p8_0 = {
  130059. 2, 169,
  130060. _vq_lengthlist__44c3_s_p8_0,
  130061. 1, -526516224, 1616117760, 4, 0,
  130062. _vq_quantlist__44c3_s_p8_0,
  130063. NULL,
  130064. &_vq_auxt__44c3_s_p8_0,
  130065. NULL,
  130066. 0
  130067. };
  130068. static long _vq_quantlist__44c3_s_p8_1[] = {
  130069. 2,
  130070. 1,
  130071. 3,
  130072. 0,
  130073. 4,
  130074. };
  130075. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130076. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130077. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130078. };
  130079. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130080. -1.5, -0.5, 0.5, 1.5,
  130081. };
  130082. static long _vq_quantmap__44c3_s_p8_1[] = {
  130083. 3, 1, 0, 2, 4,
  130084. };
  130085. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130086. _vq_quantthresh__44c3_s_p8_1,
  130087. _vq_quantmap__44c3_s_p8_1,
  130088. 5,
  130089. 5
  130090. };
  130091. static static_codebook _44c3_s_p8_1 = {
  130092. 2, 25,
  130093. _vq_lengthlist__44c3_s_p8_1,
  130094. 1, -533725184, 1611661312, 3, 0,
  130095. _vq_quantlist__44c3_s_p8_1,
  130096. NULL,
  130097. &_vq_auxt__44c3_s_p8_1,
  130098. NULL,
  130099. 0
  130100. };
  130101. static long _vq_quantlist__44c3_s_p9_0[] = {
  130102. 6,
  130103. 5,
  130104. 7,
  130105. 4,
  130106. 8,
  130107. 3,
  130108. 9,
  130109. 2,
  130110. 10,
  130111. 1,
  130112. 11,
  130113. 0,
  130114. 12,
  130115. };
  130116. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130117. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130118. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130119. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130120. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130121. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130122. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130123. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130124. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130125. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130127. 11,11,11,11,11,11,11,11,11,
  130128. };
  130129. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130130. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130131. 637.5, 892.5, 1147.5, 1402.5,
  130132. };
  130133. static long _vq_quantmap__44c3_s_p9_0[] = {
  130134. 11, 9, 7, 5, 3, 1, 0, 2,
  130135. 4, 6, 8, 10, 12,
  130136. };
  130137. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130138. _vq_quantthresh__44c3_s_p9_0,
  130139. _vq_quantmap__44c3_s_p9_0,
  130140. 13,
  130141. 13
  130142. };
  130143. static static_codebook _44c3_s_p9_0 = {
  130144. 2, 169,
  130145. _vq_lengthlist__44c3_s_p9_0,
  130146. 1, -514332672, 1627381760, 4, 0,
  130147. _vq_quantlist__44c3_s_p9_0,
  130148. NULL,
  130149. &_vq_auxt__44c3_s_p9_0,
  130150. NULL,
  130151. 0
  130152. };
  130153. static long _vq_quantlist__44c3_s_p9_1[] = {
  130154. 7,
  130155. 6,
  130156. 8,
  130157. 5,
  130158. 9,
  130159. 4,
  130160. 10,
  130161. 3,
  130162. 11,
  130163. 2,
  130164. 12,
  130165. 1,
  130166. 13,
  130167. 0,
  130168. 14,
  130169. };
  130170. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130171. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130172. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130173. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130174. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130175. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130176. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130177. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130178. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130179. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130180. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130181. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130182. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130183. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130184. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130185. 15,
  130186. };
  130187. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130188. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130189. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130190. };
  130191. static long _vq_quantmap__44c3_s_p9_1[] = {
  130192. 13, 11, 9, 7, 5, 3, 1, 0,
  130193. 2, 4, 6, 8, 10, 12, 14,
  130194. };
  130195. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130196. _vq_quantthresh__44c3_s_p9_1,
  130197. _vq_quantmap__44c3_s_p9_1,
  130198. 15,
  130199. 15
  130200. };
  130201. static static_codebook _44c3_s_p9_1 = {
  130202. 2, 225,
  130203. _vq_lengthlist__44c3_s_p9_1,
  130204. 1, -522338304, 1620115456, 4, 0,
  130205. _vq_quantlist__44c3_s_p9_1,
  130206. NULL,
  130207. &_vq_auxt__44c3_s_p9_1,
  130208. NULL,
  130209. 0
  130210. };
  130211. static long _vq_quantlist__44c3_s_p9_2[] = {
  130212. 8,
  130213. 7,
  130214. 9,
  130215. 6,
  130216. 10,
  130217. 5,
  130218. 11,
  130219. 4,
  130220. 12,
  130221. 3,
  130222. 13,
  130223. 2,
  130224. 14,
  130225. 1,
  130226. 15,
  130227. 0,
  130228. 16,
  130229. };
  130230. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130231. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130232. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130233. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130234. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130235. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130236. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130237. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130238. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130239. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130240. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130241. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130242. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130243. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130244. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130245. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130246. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130247. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130248. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130249. 10,
  130250. };
  130251. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130252. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130253. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130254. };
  130255. static long _vq_quantmap__44c3_s_p9_2[] = {
  130256. 15, 13, 11, 9, 7, 5, 3, 1,
  130257. 0, 2, 4, 6, 8, 10, 12, 14,
  130258. 16,
  130259. };
  130260. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130261. _vq_quantthresh__44c3_s_p9_2,
  130262. _vq_quantmap__44c3_s_p9_2,
  130263. 17,
  130264. 17
  130265. };
  130266. static static_codebook _44c3_s_p9_2 = {
  130267. 2, 289,
  130268. _vq_lengthlist__44c3_s_p9_2,
  130269. 1, -529530880, 1611661312, 5, 0,
  130270. _vq_quantlist__44c3_s_p9_2,
  130271. NULL,
  130272. &_vq_auxt__44c3_s_p9_2,
  130273. NULL,
  130274. 0
  130275. };
  130276. static long _huff_lengthlist__44c3_s_short[] = {
  130277. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130278. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130279. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130280. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130281. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130282. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130283. 6, 8, 9,11,
  130284. };
  130285. static static_codebook _huff_book__44c3_s_short = {
  130286. 2, 100,
  130287. _huff_lengthlist__44c3_s_short,
  130288. 0, 0, 0, 0, 0,
  130289. NULL,
  130290. NULL,
  130291. NULL,
  130292. NULL,
  130293. 0
  130294. };
  130295. static long _huff_lengthlist__44c4_s_long[] = {
  130296. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130297. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130298. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130299. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130300. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130301. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130302. 9, 8, 7, 7,
  130303. };
  130304. static static_codebook _huff_book__44c4_s_long = {
  130305. 2, 100,
  130306. _huff_lengthlist__44c4_s_long,
  130307. 0, 0, 0, 0, 0,
  130308. NULL,
  130309. NULL,
  130310. NULL,
  130311. NULL,
  130312. 0
  130313. };
  130314. static long _vq_quantlist__44c4_s_p1_0[] = {
  130315. 1,
  130316. 0,
  130317. 2,
  130318. };
  130319. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130320. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130321. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130326. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130331. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  130366. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130371. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130376. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130412. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130417. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130422. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  130731. };
  130732. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130733. -0.5, 0.5,
  130734. };
  130735. static long _vq_quantmap__44c4_s_p1_0[] = {
  130736. 1, 0, 2,
  130737. };
  130738. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130739. _vq_quantthresh__44c4_s_p1_0,
  130740. _vq_quantmap__44c4_s_p1_0,
  130741. 3,
  130742. 3
  130743. };
  130744. static static_codebook _44c4_s_p1_0 = {
  130745. 8, 6561,
  130746. _vq_lengthlist__44c4_s_p1_0,
  130747. 1, -535822336, 1611661312, 2, 0,
  130748. _vq_quantlist__44c4_s_p1_0,
  130749. NULL,
  130750. &_vq_auxt__44c4_s_p1_0,
  130751. NULL,
  130752. 0
  130753. };
  130754. static long _vq_quantlist__44c4_s_p2_0[] = {
  130755. 2,
  130756. 1,
  130757. 3,
  130758. 0,
  130759. 4,
  130760. };
  130761. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130762. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130763. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130764. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130765. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130766. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130772. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130773. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130774. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130780. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130781. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130787. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130788. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130789. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0,
  130802. };
  130803. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130804. -1.5, -0.5, 0.5, 1.5,
  130805. };
  130806. static long _vq_quantmap__44c4_s_p2_0[] = {
  130807. 3, 1, 0, 2, 4,
  130808. };
  130809. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130810. _vq_quantthresh__44c4_s_p2_0,
  130811. _vq_quantmap__44c4_s_p2_0,
  130812. 5,
  130813. 5
  130814. };
  130815. static static_codebook _44c4_s_p2_0 = {
  130816. 4, 625,
  130817. _vq_lengthlist__44c4_s_p2_0,
  130818. 1, -533725184, 1611661312, 3, 0,
  130819. _vq_quantlist__44c4_s_p2_0,
  130820. NULL,
  130821. &_vq_auxt__44c4_s_p2_0,
  130822. NULL,
  130823. 0
  130824. };
  130825. static long _vq_quantlist__44c4_s_p3_0[] = {
  130826. 2,
  130827. 1,
  130828. 3,
  130829. 0,
  130830. 4,
  130831. };
  130832. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130833. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0,
  130873. };
  130874. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130875. -1.5, -0.5, 0.5, 1.5,
  130876. };
  130877. static long _vq_quantmap__44c4_s_p3_0[] = {
  130878. 3, 1, 0, 2, 4,
  130879. };
  130880. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130881. _vq_quantthresh__44c4_s_p3_0,
  130882. _vq_quantmap__44c4_s_p3_0,
  130883. 5,
  130884. 5
  130885. };
  130886. static static_codebook _44c4_s_p3_0 = {
  130887. 4, 625,
  130888. _vq_lengthlist__44c4_s_p3_0,
  130889. 1, -533725184, 1611661312, 3, 0,
  130890. _vq_quantlist__44c4_s_p3_0,
  130891. NULL,
  130892. &_vq_auxt__44c4_s_p3_0,
  130893. NULL,
  130894. 0
  130895. };
  130896. static long _vq_quantlist__44c4_s_p4_0[] = {
  130897. 4,
  130898. 3,
  130899. 5,
  130900. 2,
  130901. 6,
  130902. 1,
  130903. 7,
  130904. 0,
  130905. 8,
  130906. };
  130907. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130908. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130909. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130910. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130911. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130912. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0,
  130914. };
  130915. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130916. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130917. };
  130918. static long _vq_quantmap__44c4_s_p4_0[] = {
  130919. 7, 5, 3, 1, 0, 2, 4, 6,
  130920. 8,
  130921. };
  130922. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130923. _vq_quantthresh__44c4_s_p4_0,
  130924. _vq_quantmap__44c4_s_p4_0,
  130925. 9,
  130926. 9
  130927. };
  130928. static static_codebook _44c4_s_p4_0 = {
  130929. 2, 81,
  130930. _vq_lengthlist__44c4_s_p4_0,
  130931. 1, -531628032, 1611661312, 4, 0,
  130932. _vq_quantlist__44c4_s_p4_0,
  130933. NULL,
  130934. &_vq_auxt__44c4_s_p4_0,
  130935. NULL,
  130936. 0
  130937. };
  130938. static long _vq_quantlist__44c4_s_p5_0[] = {
  130939. 4,
  130940. 3,
  130941. 5,
  130942. 2,
  130943. 6,
  130944. 1,
  130945. 7,
  130946. 0,
  130947. 8,
  130948. };
  130949. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130950. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130951. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130952. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130953. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130954. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130955. 10,
  130956. };
  130957. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130958. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130959. };
  130960. static long _vq_quantmap__44c4_s_p5_0[] = {
  130961. 7, 5, 3, 1, 0, 2, 4, 6,
  130962. 8,
  130963. };
  130964. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130965. _vq_quantthresh__44c4_s_p5_0,
  130966. _vq_quantmap__44c4_s_p5_0,
  130967. 9,
  130968. 9
  130969. };
  130970. static static_codebook _44c4_s_p5_0 = {
  130971. 2, 81,
  130972. _vq_lengthlist__44c4_s_p5_0,
  130973. 1, -531628032, 1611661312, 4, 0,
  130974. _vq_quantlist__44c4_s_p5_0,
  130975. NULL,
  130976. &_vq_auxt__44c4_s_p5_0,
  130977. NULL,
  130978. 0
  130979. };
  130980. static long _vq_quantlist__44c4_s_p6_0[] = {
  130981. 8,
  130982. 7,
  130983. 9,
  130984. 6,
  130985. 10,
  130986. 5,
  130987. 11,
  130988. 4,
  130989. 12,
  130990. 3,
  130991. 13,
  130992. 2,
  130993. 14,
  130994. 1,
  130995. 15,
  130996. 0,
  130997. 16,
  130998. };
  130999. static long _vq_lengthlist__44c4_s_p6_0[] = {
  131000. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  131001. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131002. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131003. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131004. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131005. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131006. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  131007. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131008. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131009. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  131010. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  131011. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  131012. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  131013. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  131014. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  131015. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131016. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  131018. 13,
  131019. };
  131020. static float _vq_quantthresh__44c4_s_p6_0[] = {
  131021. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131022. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131023. };
  131024. static long _vq_quantmap__44c4_s_p6_0[] = {
  131025. 15, 13, 11, 9, 7, 5, 3, 1,
  131026. 0, 2, 4, 6, 8, 10, 12, 14,
  131027. 16,
  131028. };
  131029. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131030. _vq_quantthresh__44c4_s_p6_0,
  131031. _vq_quantmap__44c4_s_p6_0,
  131032. 17,
  131033. 17
  131034. };
  131035. static static_codebook _44c4_s_p6_0 = {
  131036. 2, 289,
  131037. _vq_lengthlist__44c4_s_p6_0,
  131038. 1, -529530880, 1611661312, 5, 0,
  131039. _vq_quantlist__44c4_s_p6_0,
  131040. NULL,
  131041. &_vq_auxt__44c4_s_p6_0,
  131042. NULL,
  131043. 0
  131044. };
  131045. static long _vq_quantlist__44c4_s_p7_0[] = {
  131046. 1,
  131047. 0,
  131048. 2,
  131049. };
  131050. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131051. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131052. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131053. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131054. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131055. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131056. 10,
  131057. };
  131058. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131059. -5.5, 5.5,
  131060. };
  131061. static long _vq_quantmap__44c4_s_p7_0[] = {
  131062. 1, 0, 2,
  131063. };
  131064. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131065. _vq_quantthresh__44c4_s_p7_0,
  131066. _vq_quantmap__44c4_s_p7_0,
  131067. 3,
  131068. 3
  131069. };
  131070. static static_codebook _44c4_s_p7_0 = {
  131071. 4, 81,
  131072. _vq_lengthlist__44c4_s_p7_0,
  131073. 1, -529137664, 1618345984, 2, 0,
  131074. _vq_quantlist__44c4_s_p7_0,
  131075. NULL,
  131076. &_vq_auxt__44c4_s_p7_0,
  131077. NULL,
  131078. 0
  131079. };
  131080. static long _vq_quantlist__44c4_s_p7_1[] = {
  131081. 5,
  131082. 4,
  131083. 6,
  131084. 3,
  131085. 7,
  131086. 2,
  131087. 8,
  131088. 1,
  131089. 9,
  131090. 0,
  131091. 10,
  131092. };
  131093. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131094. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131095. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131096. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131097. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131098. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131099. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131100. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131101. 10,10,10, 8, 8, 8, 8, 9, 9,
  131102. };
  131103. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131104. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131105. 3.5, 4.5,
  131106. };
  131107. static long _vq_quantmap__44c4_s_p7_1[] = {
  131108. 9, 7, 5, 3, 1, 0, 2, 4,
  131109. 6, 8, 10,
  131110. };
  131111. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131112. _vq_quantthresh__44c4_s_p7_1,
  131113. _vq_quantmap__44c4_s_p7_1,
  131114. 11,
  131115. 11
  131116. };
  131117. static static_codebook _44c4_s_p7_1 = {
  131118. 2, 121,
  131119. _vq_lengthlist__44c4_s_p7_1,
  131120. 1, -531365888, 1611661312, 4, 0,
  131121. _vq_quantlist__44c4_s_p7_1,
  131122. NULL,
  131123. &_vq_auxt__44c4_s_p7_1,
  131124. NULL,
  131125. 0
  131126. };
  131127. static long _vq_quantlist__44c4_s_p8_0[] = {
  131128. 6,
  131129. 5,
  131130. 7,
  131131. 4,
  131132. 8,
  131133. 3,
  131134. 9,
  131135. 2,
  131136. 10,
  131137. 1,
  131138. 11,
  131139. 0,
  131140. 12,
  131141. };
  131142. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131143. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131144. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131145. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131146. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131147. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131148. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131149. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131150. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131151. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131152. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131153. 0,13,12,12,12,12,12,13,13,
  131154. };
  131155. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131156. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131157. 12.5, 17.5, 22.5, 27.5,
  131158. };
  131159. static long _vq_quantmap__44c4_s_p8_0[] = {
  131160. 11, 9, 7, 5, 3, 1, 0, 2,
  131161. 4, 6, 8, 10, 12,
  131162. };
  131163. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131164. _vq_quantthresh__44c4_s_p8_0,
  131165. _vq_quantmap__44c4_s_p8_0,
  131166. 13,
  131167. 13
  131168. };
  131169. static static_codebook _44c4_s_p8_0 = {
  131170. 2, 169,
  131171. _vq_lengthlist__44c4_s_p8_0,
  131172. 1, -526516224, 1616117760, 4, 0,
  131173. _vq_quantlist__44c4_s_p8_0,
  131174. NULL,
  131175. &_vq_auxt__44c4_s_p8_0,
  131176. NULL,
  131177. 0
  131178. };
  131179. static long _vq_quantlist__44c4_s_p8_1[] = {
  131180. 2,
  131181. 1,
  131182. 3,
  131183. 0,
  131184. 4,
  131185. };
  131186. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131187. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131188. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131189. };
  131190. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131191. -1.5, -0.5, 0.5, 1.5,
  131192. };
  131193. static long _vq_quantmap__44c4_s_p8_1[] = {
  131194. 3, 1, 0, 2, 4,
  131195. };
  131196. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131197. _vq_quantthresh__44c4_s_p8_1,
  131198. _vq_quantmap__44c4_s_p8_1,
  131199. 5,
  131200. 5
  131201. };
  131202. static static_codebook _44c4_s_p8_1 = {
  131203. 2, 25,
  131204. _vq_lengthlist__44c4_s_p8_1,
  131205. 1, -533725184, 1611661312, 3, 0,
  131206. _vq_quantlist__44c4_s_p8_1,
  131207. NULL,
  131208. &_vq_auxt__44c4_s_p8_1,
  131209. NULL,
  131210. 0
  131211. };
  131212. static long _vq_quantlist__44c4_s_p9_0[] = {
  131213. 6,
  131214. 5,
  131215. 7,
  131216. 4,
  131217. 8,
  131218. 3,
  131219. 9,
  131220. 2,
  131221. 10,
  131222. 1,
  131223. 11,
  131224. 0,
  131225. 12,
  131226. };
  131227. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131228. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131229. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131230. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131231. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131232. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131233. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131234. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131235. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131236. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131237. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131238. 12,12,12,12,12,12,12,12,12,
  131239. };
  131240. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131241. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131242. 787.5, 1102.5, 1417.5, 1732.5,
  131243. };
  131244. static long _vq_quantmap__44c4_s_p9_0[] = {
  131245. 11, 9, 7, 5, 3, 1, 0, 2,
  131246. 4, 6, 8, 10, 12,
  131247. };
  131248. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131249. _vq_quantthresh__44c4_s_p9_0,
  131250. _vq_quantmap__44c4_s_p9_0,
  131251. 13,
  131252. 13
  131253. };
  131254. static static_codebook _44c4_s_p9_0 = {
  131255. 2, 169,
  131256. _vq_lengthlist__44c4_s_p9_0,
  131257. 1, -513964032, 1628680192, 4, 0,
  131258. _vq_quantlist__44c4_s_p9_0,
  131259. NULL,
  131260. &_vq_auxt__44c4_s_p9_0,
  131261. NULL,
  131262. 0
  131263. };
  131264. static long _vq_quantlist__44c4_s_p9_1[] = {
  131265. 7,
  131266. 6,
  131267. 8,
  131268. 5,
  131269. 9,
  131270. 4,
  131271. 10,
  131272. 3,
  131273. 11,
  131274. 2,
  131275. 12,
  131276. 1,
  131277. 13,
  131278. 0,
  131279. 14,
  131280. };
  131281. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131282. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131283. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131284. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131285. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131286. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131287. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131288. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131289. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131290. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131291. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131292. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131293. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131294. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131295. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131296. 15,
  131297. };
  131298. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131299. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131300. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131301. };
  131302. static long _vq_quantmap__44c4_s_p9_1[] = {
  131303. 13, 11, 9, 7, 5, 3, 1, 0,
  131304. 2, 4, 6, 8, 10, 12, 14,
  131305. };
  131306. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131307. _vq_quantthresh__44c4_s_p9_1,
  131308. _vq_quantmap__44c4_s_p9_1,
  131309. 15,
  131310. 15
  131311. };
  131312. static static_codebook _44c4_s_p9_1 = {
  131313. 2, 225,
  131314. _vq_lengthlist__44c4_s_p9_1,
  131315. 1, -520986624, 1620377600, 4, 0,
  131316. _vq_quantlist__44c4_s_p9_1,
  131317. NULL,
  131318. &_vq_auxt__44c4_s_p9_1,
  131319. NULL,
  131320. 0
  131321. };
  131322. static long _vq_quantlist__44c4_s_p9_2[] = {
  131323. 10,
  131324. 9,
  131325. 11,
  131326. 8,
  131327. 12,
  131328. 7,
  131329. 13,
  131330. 6,
  131331. 14,
  131332. 5,
  131333. 15,
  131334. 4,
  131335. 16,
  131336. 3,
  131337. 17,
  131338. 2,
  131339. 18,
  131340. 1,
  131341. 19,
  131342. 0,
  131343. 20,
  131344. };
  131345. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131346. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131347. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131348. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131349. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131350. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131351. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131352. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131353. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131354. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131355. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131356. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131357. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131358. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131359. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131360. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131361. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131362. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131363. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131364. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131365. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131366. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131367. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131368. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131369. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131370. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131371. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131372. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131373. 10,10,10,10,10,10,10,10,10,
  131374. };
  131375. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131376. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131377. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131378. 6.5, 7.5, 8.5, 9.5,
  131379. };
  131380. static long _vq_quantmap__44c4_s_p9_2[] = {
  131381. 19, 17, 15, 13, 11, 9, 7, 5,
  131382. 3, 1, 0, 2, 4, 6, 8, 10,
  131383. 12, 14, 16, 18, 20,
  131384. };
  131385. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131386. _vq_quantthresh__44c4_s_p9_2,
  131387. _vq_quantmap__44c4_s_p9_2,
  131388. 21,
  131389. 21
  131390. };
  131391. static static_codebook _44c4_s_p9_2 = {
  131392. 2, 441,
  131393. _vq_lengthlist__44c4_s_p9_2,
  131394. 1, -529268736, 1611661312, 5, 0,
  131395. _vq_quantlist__44c4_s_p9_2,
  131396. NULL,
  131397. &_vq_auxt__44c4_s_p9_2,
  131398. NULL,
  131399. 0
  131400. };
  131401. static long _huff_lengthlist__44c4_s_short[] = {
  131402. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131403. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131404. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131405. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131406. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131407. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131408. 7, 9,12,17,
  131409. };
  131410. static static_codebook _huff_book__44c4_s_short = {
  131411. 2, 100,
  131412. _huff_lengthlist__44c4_s_short,
  131413. 0, 0, 0, 0, 0,
  131414. NULL,
  131415. NULL,
  131416. NULL,
  131417. NULL,
  131418. 0
  131419. };
  131420. static long _huff_lengthlist__44c5_s_long[] = {
  131421. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131422. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131423. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131424. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131425. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131426. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131427. 9, 8, 7, 7,
  131428. };
  131429. static static_codebook _huff_book__44c5_s_long = {
  131430. 2, 100,
  131431. _huff_lengthlist__44c5_s_long,
  131432. 0, 0, 0, 0, 0,
  131433. NULL,
  131434. NULL,
  131435. NULL,
  131436. NULL,
  131437. 0
  131438. };
  131439. static long _vq_quantlist__44c5_s_p1_0[] = {
  131440. 1,
  131441. 0,
  131442. 2,
  131443. };
  131444. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131445. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131446. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131451. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131456. 0, 0, 0, 0, 7, 9, 9, 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, 4, 7, 7, 0, 0, 0, 0,
  131491. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131496. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131501. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131537. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131542. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131547. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0,
  131856. };
  131857. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131858. -0.5, 0.5,
  131859. };
  131860. static long _vq_quantmap__44c5_s_p1_0[] = {
  131861. 1, 0, 2,
  131862. };
  131863. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131864. _vq_quantthresh__44c5_s_p1_0,
  131865. _vq_quantmap__44c5_s_p1_0,
  131866. 3,
  131867. 3
  131868. };
  131869. static static_codebook _44c5_s_p1_0 = {
  131870. 8, 6561,
  131871. _vq_lengthlist__44c5_s_p1_0,
  131872. 1, -535822336, 1611661312, 2, 0,
  131873. _vq_quantlist__44c5_s_p1_0,
  131874. NULL,
  131875. &_vq_auxt__44c5_s_p1_0,
  131876. NULL,
  131877. 0
  131878. };
  131879. static long _vq_quantlist__44c5_s_p2_0[] = {
  131880. 2,
  131881. 1,
  131882. 3,
  131883. 0,
  131884. 4,
  131885. };
  131886. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131887. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131888. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131889. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131890. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131891. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131896. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131897. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131898. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131899. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131905. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131906. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131912. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131913. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131914. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131926. 0,
  131927. };
  131928. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131929. -1.5, -0.5, 0.5, 1.5,
  131930. };
  131931. static long _vq_quantmap__44c5_s_p2_0[] = {
  131932. 3, 1, 0, 2, 4,
  131933. };
  131934. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131935. _vq_quantthresh__44c5_s_p2_0,
  131936. _vq_quantmap__44c5_s_p2_0,
  131937. 5,
  131938. 5
  131939. };
  131940. static static_codebook _44c5_s_p2_0 = {
  131941. 4, 625,
  131942. _vq_lengthlist__44c5_s_p2_0,
  131943. 1, -533725184, 1611661312, 3, 0,
  131944. _vq_quantlist__44c5_s_p2_0,
  131945. NULL,
  131946. &_vq_auxt__44c5_s_p2_0,
  131947. NULL,
  131948. 0
  131949. };
  131950. static long _vq_quantlist__44c5_s_p3_0[] = {
  131951. 2,
  131952. 1,
  131953. 3,
  131954. 0,
  131955. 4,
  131956. };
  131957. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131958. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0,
  131998. };
  131999. static float _vq_quantthresh__44c5_s_p3_0[] = {
  132000. -1.5, -0.5, 0.5, 1.5,
  132001. };
  132002. static long _vq_quantmap__44c5_s_p3_0[] = {
  132003. 3, 1, 0, 2, 4,
  132004. };
  132005. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  132006. _vq_quantthresh__44c5_s_p3_0,
  132007. _vq_quantmap__44c5_s_p3_0,
  132008. 5,
  132009. 5
  132010. };
  132011. static static_codebook _44c5_s_p3_0 = {
  132012. 4, 625,
  132013. _vq_lengthlist__44c5_s_p3_0,
  132014. 1, -533725184, 1611661312, 3, 0,
  132015. _vq_quantlist__44c5_s_p3_0,
  132016. NULL,
  132017. &_vq_auxt__44c5_s_p3_0,
  132018. NULL,
  132019. 0
  132020. };
  132021. static long _vq_quantlist__44c5_s_p4_0[] = {
  132022. 4,
  132023. 3,
  132024. 5,
  132025. 2,
  132026. 6,
  132027. 1,
  132028. 7,
  132029. 0,
  132030. 8,
  132031. };
  132032. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132033. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132034. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132035. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132036. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132037. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132038. 0,
  132039. };
  132040. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132041. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132042. };
  132043. static long _vq_quantmap__44c5_s_p4_0[] = {
  132044. 7, 5, 3, 1, 0, 2, 4, 6,
  132045. 8,
  132046. };
  132047. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132048. _vq_quantthresh__44c5_s_p4_0,
  132049. _vq_quantmap__44c5_s_p4_0,
  132050. 9,
  132051. 9
  132052. };
  132053. static static_codebook _44c5_s_p4_0 = {
  132054. 2, 81,
  132055. _vq_lengthlist__44c5_s_p4_0,
  132056. 1, -531628032, 1611661312, 4, 0,
  132057. _vq_quantlist__44c5_s_p4_0,
  132058. NULL,
  132059. &_vq_auxt__44c5_s_p4_0,
  132060. NULL,
  132061. 0
  132062. };
  132063. static long _vq_quantlist__44c5_s_p5_0[] = {
  132064. 4,
  132065. 3,
  132066. 5,
  132067. 2,
  132068. 6,
  132069. 1,
  132070. 7,
  132071. 0,
  132072. 8,
  132073. };
  132074. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132075. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132076. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132077. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132078. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132079. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132080. 10,
  132081. };
  132082. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132083. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132084. };
  132085. static long _vq_quantmap__44c5_s_p5_0[] = {
  132086. 7, 5, 3, 1, 0, 2, 4, 6,
  132087. 8,
  132088. };
  132089. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132090. _vq_quantthresh__44c5_s_p5_0,
  132091. _vq_quantmap__44c5_s_p5_0,
  132092. 9,
  132093. 9
  132094. };
  132095. static static_codebook _44c5_s_p5_0 = {
  132096. 2, 81,
  132097. _vq_lengthlist__44c5_s_p5_0,
  132098. 1, -531628032, 1611661312, 4, 0,
  132099. _vq_quantlist__44c5_s_p5_0,
  132100. NULL,
  132101. &_vq_auxt__44c5_s_p5_0,
  132102. NULL,
  132103. 0
  132104. };
  132105. static long _vq_quantlist__44c5_s_p6_0[] = {
  132106. 8,
  132107. 7,
  132108. 9,
  132109. 6,
  132110. 10,
  132111. 5,
  132112. 11,
  132113. 4,
  132114. 12,
  132115. 3,
  132116. 13,
  132117. 2,
  132118. 14,
  132119. 1,
  132120. 15,
  132121. 0,
  132122. 16,
  132123. };
  132124. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132125. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132126. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132127. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132128. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132129. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132130. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132131. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132132. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132133. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132134. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132135. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132136. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132137. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132138. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132139. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132140. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132141. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132142. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132143. 13,
  132144. };
  132145. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132146. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132147. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132148. };
  132149. static long _vq_quantmap__44c5_s_p6_0[] = {
  132150. 15, 13, 11, 9, 7, 5, 3, 1,
  132151. 0, 2, 4, 6, 8, 10, 12, 14,
  132152. 16,
  132153. };
  132154. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132155. _vq_quantthresh__44c5_s_p6_0,
  132156. _vq_quantmap__44c5_s_p6_0,
  132157. 17,
  132158. 17
  132159. };
  132160. static static_codebook _44c5_s_p6_0 = {
  132161. 2, 289,
  132162. _vq_lengthlist__44c5_s_p6_0,
  132163. 1, -529530880, 1611661312, 5, 0,
  132164. _vq_quantlist__44c5_s_p6_0,
  132165. NULL,
  132166. &_vq_auxt__44c5_s_p6_0,
  132167. NULL,
  132168. 0
  132169. };
  132170. static long _vq_quantlist__44c5_s_p7_0[] = {
  132171. 1,
  132172. 0,
  132173. 2,
  132174. };
  132175. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132176. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132177. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132178. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132179. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132180. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132181. 10,
  132182. };
  132183. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132184. -5.5, 5.5,
  132185. };
  132186. static long _vq_quantmap__44c5_s_p7_0[] = {
  132187. 1, 0, 2,
  132188. };
  132189. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132190. _vq_quantthresh__44c5_s_p7_0,
  132191. _vq_quantmap__44c5_s_p7_0,
  132192. 3,
  132193. 3
  132194. };
  132195. static static_codebook _44c5_s_p7_0 = {
  132196. 4, 81,
  132197. _vq_lengthlist__44c5_s_p7_0,
  132198. 1, -529137664, 1618345984, 2, 0,
  132199. _vq_quantlist__44c5_s_p7_0,
  132200. NULL,
  132201. &_vq_auxt__44c5_s_p7_0,
  132202. NULL,
  132203. 0
  132204. };
  132205. static long _vq_quantlist__44c5_s_p7_1[] = {
  132206. 5,
  132207. 4,
  132208. 6,
  132209. 3,
  132210. 7,
  132211. 2,
  132212. 8,
  132213. 1,
  132214. 9,
  132215. 0,
  132216. 10,
  132217. };
  132218. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132219. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132220. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132221. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132222. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132223. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132224. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132225. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132226. 10,10,10, 8, 8, 8, 8, 8, 8,
  132227. };
  132228. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132229. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132230. 3.5, 4.5,
  132231. };
  132232. static long _vq_quantmap__44c5_s_p7_1[] = {
  132233. 9, 7, 5, 3, 1, 0, 2, 4,
  132234. 6, 8, 10,
  132235. };
  132236. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132237. _vq_quantthresh__44c5_s_p7_1,
  132238. _vq_quantmap__44c5_s_p7_1,
  132239. 11,
  132240. 11
  132241. };
  132242. static static_codebook _44c5_s_p7_1 = {
  132243. 2, 121,
  132244. _vq_lengthlist__44c5_s_p7_1,
  132245. 1, -531365888, 1611661312, 4, 0,
  132246. _vq_quantlist__44c5_s_p7_1,
  132247. NULL,
  132248. &_vq_auxt__44c5_s_p7_1,
  132249. NULL,
  132250. 0
  132251. };
  132252. static long _vq_quantlist__44c5_s_p8_0[] = {
  132253. 6,
  132254. 5,
  132255. 7,
  132256. 4,
  132257. 8,
  132258. 3,
  132259. 9,
  132260. 2,
  132261. 10,
  132262. 1,
  132263. 11,
  132264. 0,
  132265. 12,
  132266. };
  132267. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132268. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132269. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132270. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132271. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132272. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132273. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132274. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132275. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132276. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132277. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132278. 0,12,12,12,12,12,12,13,13,
  132279. };
  132280. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132281. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132282. 12.5, 17.5, 22.5, 27.5,
  132283. };
  132284. static long _vq_quantmap__44c5_s_p8_0[] = {
  132285. 11, 9, 7, 5, 3, 1, 0, 2,
  132286. 4, 6, 8, 10, 12,
  132287. };
  132288. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132289. _vq_quantthresh__44c5_s_p8_0,
  132290. _vq_quantmap__44c5_s_p8_0,
  132291. 13,
  132292. 13
  132293. };
  132294. static static_codebook _44c5_s_p8_0 = {
  132295. 2, 169,
  132296. _vq_lengthlist__44c5_s_p8_0,
  132297. 1, -526516224, 1616117760, 4, 0,
  132298. _vq_quantlist__44c5_s_p8_0,
  132299. NULL,
  132300. &_vq_auxt__44c5_s_p8_0,
  132301. NULL,
  132302. 0
  132303. };
  132304. static long _vq_quantlist__44c5_s_p8_1[] = {
  132305. 2,
  132306. 1,
  132307. 3,
  132308. 0,
  132309. 4,
  132310. };
  132311. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132312. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132313. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132314. };
  132315. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132316. -1.5, -0.5, 0.5, 1.5,
  132317. };
  132318. static long _vq_quantmap__44c5_s_p8_1[] = {
  132319. 3, 1, 0, 2, 4,
  132320. };
  132321. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132322. _vq_quantthresh__44c5_s_p8_1,
  132323. _vq_quantmap__44c5_s_p8_1,
  132324. 5,
  132325. 5
  132326. };
  132327. static static_codebook _44c5_s_p8_1 = {
  132328. 2, 25,
  132329. _vq_lengthlist__44c5_s_p8_1,
  132330. 1, -533725184, 1611661312, 3, 0,
  132331. _vq_quantlist__44c5_s_p8_1,
  132332. NULL,
  132333. &_vq_auxt__44c5_s_p8_1,
  132334. NULL,
  132335. 0
  132336. };
  132337. static long _vq_quantlist__44c5_s_p9_0[] = {
  132338. 7,
  132339. 6,
  132340. 8,
  132341. 5,
  132342. 9,
  132343. 4,
  132344. 10,
  132345. 3,
  132346. 11,
  132347. 2,
  132348. 12,
  132349. 1,
  132350. 13,
  132351. 0,
  132352. 14,
  132353. };
  132354. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132355. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132356. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132357. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132358. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132359. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132360. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132361. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132362. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132363. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132364. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132365. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132366. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132367. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132368. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132369. 12,
  132370. };
  132371. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132372. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132373. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132374. };
  132375. static long _vq_quantmap__44c5_s_p9_0[] = {
  132376. 13, 11, 9, 7, 5, 3, 1, 0,
  132377. 2, 4, 6, 8, 10, 12, 14,
  132378. };
  132379. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132380. _vq_quantthresh__44c5_s_p9_0,
  132381. _vq_quantmap__44c5_s_p9_0,
  132382. 15,
  132383. 15
  132384. };
  132385. static static_codebook _44c5_s_p9_0 = {
  132386. 2, 225,
  132387. _vq_lengthlist__44c5_s_p9_0,
  132388. 1, -512522752, 1628852224, 4, 0,
  132389. _vq_quantlist__44c5_s_p9_0,
  132390. NULL,
  132391. &_vq_auxt__44c5_s_p9_0,
  132392. NULL,
  132393. 0
  132394. };
  132395. static long _vq_quantlist__44c5_s_p9_1[] = {
  132396. 8,
  132397. 7,
  132398. 9,
  132399. 6,
  132400. 10,
  132401. 5,
  132402. 11,
  132403. 4,
  132404. 12,
  132405. 3,
  132406. 13,
  132407. 2,
  132408. 14,
  132409. 1,
  132410. 15,
  132411. 0,
  132412. 16,
  132413. };
  132414. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132415. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132416. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132417. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132418. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132419. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132420. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132421. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132422. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132423. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132424. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132425. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132426. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132427. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132428. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132429. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132430. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132431. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132432. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132433. 15,
  132434. };
  132435. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132436. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132437. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132438. };
  132439. static long _vq_quantmap__44c5_s_p9_1[] = {
  132440. 15, 13, 11, 9, 7, 5, 3, 1,
  132441. 0, 2, 4, 6, 8, 10, 12, 14,
  132442. 16,
  132443. };
  132444. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132445. _vq_quantthresh__44c5_s_p9_1,
  132446. _vq_quantmap__44c5_s_p9_1,
  132447. 17,
  132448. 17
  132449. };
  132450. static static_codebook _44c5_s_p9_1 = {
  132451. 2, 289,
  132452. _vq_lengthlist__44c5_s_p9_1,
  132453. 1, -520814592, 1620377600, 5, 0,
  132454. _vq_quantlist__44c5_s_p9_1,
  132455. NULL,
  132456. &_vq_auxt__44c5_s_p9_1,
  132457. NULL,
  132458. 0
  132459. };
  132460. static long _vq_quantlist__44c5_s_p9_2[] = {
  132461. 10,
  132462. 9,
  132463. 11,
  132464. 8,
  132465. 12,
  132466. 7,
  132467. 13,
  132468. 6,
  132469. 14,
  132470. 5,
  132471. 15,
  132472. 4,
  132473. 16,
  132474. 3,
  132475. 17,
  132476. 2,
  132477. 18,
  132478. 1,
  132479. 19,
  132480. 0,
  132481. 20,
  132482. };
  132483. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132484. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132485. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132486. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132487. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132488. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132489. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132490. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132491. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132492. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132493. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132494. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132495. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132496. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132497. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132498. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132499. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132500. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132501. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132502. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132503. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132504. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132505. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132506. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132507. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132508. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132509. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132510. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132511. 10,10,10,10,10,10,10,10,10,
  132512. };
  132513. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132514. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132515. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132516. 6.5, 7.5, 8.5, 9.5,
  132517. };
  132518. static long _vq_quantmap__44c5_s_p9_2[] = {
  132519. 19, 17, 15, 13, 11, 9, 7, 5,
  132520. 3, 1, 0, 2, 4, 6, 8, 10,
  132521. 12, 14, 16, 18, 20,
  132522. };
  132523. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132524. _vq_quantthresh__44c5_s_p9_2,
  132525. _vq_quantmap__44c5_s_p9_2,
  132526. 21,
  132527. 21
  132528. };
  132529. static static_codebook _44c5_s_p9_2 = {
  132530. 2, 441,
  132531. _vq_lengthlist__44c5_s_p9_2,
  132532. 1, -529268736, 1611661312, 5, 0,
  132533. _vq_quantlist__44c5_s_p9_2,
  132534. NULL,
  132535. &_vq_auxt__44c5_s_p9_2,
  132536. NULL,
  132537. 0
  132538. };
  132539. static long _huff_lengthlist__44c5_s_short[] = {
  132540. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132541. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132542. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132543. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132544. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132545. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132546. 6, 8,11,16,
  132547. };
  132548. static static_codebook _huff_book__44c5_s_short = {
  132549. 2, 100,
  132550. _huff_lengthlist__44c5_s_short,
  132551. 0, 0, 0, 0, 0,
  132552. NULL,
  132553. NULL,
  132554. NULL,
  132555. NULL,
  132556. 0
  132557. };
  132558. static long _huff_lengthlist__44c6_s_long[] = {
  132559. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132560. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132561. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132562. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132563. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132564. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132565. 11,10,10,12,
  132566. };
  132567. static static_codebook _huff_book__44c6_s_long = {
  132568. 2, 100,
  132569. _huff_lengthlist__44c6_s_long,
  132570. 0, 0, 0, 0, 0,
  132571. NULL,
  132572. NULL,
  132573. NULL,
  132574. NULL,
  132575. 0
  132576. };
  132577. static long _vq_quantlist__44c6_s_p1_0[] = {
  132578. 1,
  132579. 0,
  132580. 2,
  132581. };
  132582. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132583. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132584. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132585. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132586. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132587. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132588. 8,
  132589. };
  132590. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132591. -0.5, 0.5,
  132592. };
  132593. static long _vq_quantmap__44c6_s_p1_0[] = {
  132594. 1, 0, 2,
  132595. };
  132596. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132597. _vq_quantthresh__44c6_s_p1_0,
  132598. _vq_quantmap__44c6_s_p1_0,
  132599. 3,
  132600. 3
  132601. };
  132602. static static_codebook _44c6_s_p1_0 = {
  132603. 4, 81,
  132604. _vq_lengthlist__44c6_s_p1_0,
  132605. 1, -535822336, 1611661312, 2, 0,
  132606. _vq_quantlist__44c6_s_p1_0,
  132607. NULL,
  132608. &_vq_auxt__44c6_s_p1_0,
  132609. NULL,
  132610. 0
  132611. };
  132612. static long _vq_quantlist__44c6_s_p2_0[] = {
  132613. 2,
  132614. 1,
  132615. 3,
  132616. 0,
  132617. 4,
  132618. };
  132619. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132620. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132621. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132622. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132623. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132624. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132625. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132626. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132627. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132630. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132631. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132632. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132633. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132634. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132635. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132637. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132638. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132639. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132640. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132641. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132642. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132643. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132645. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132646. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132647. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132648. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132649. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132650. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132651. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132656. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132657. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132658. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132659. 13,
  132660. };
  132661. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132662. -1.5, -0.5, 0.5, 1.5,
  132663. };
  132664. static long _vq_quantmap__44c6_s_p2_0[] = {
  132665. 3, 1, 0, 2, 4,
  132666. };
  132667. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132668. _vq_quantthresh__44c6_s_p2_0,
  132669. _vq_quantmap__44c6_s_p2_0,
  132670. 5,
  132671. 5
  132672. };
  132673. static static_codebook _44c6_s_p2_0 = {
  132674. 4, 625,
  132675. _vq_lengthlist__44c6_s_p2_0,
  132676. 1, -533725184, 1611661312, 3, 0,
  132677. _vq_quantlist__44c6_s_p2_0,
  132678. NULL,
  132679. &_vq_auxt__44c6_s_p2_0,
  132680. NULL,
  132681. 0
  132682. };
  132683. static long _vq_quantlist__44c6_s_p3_0[] = {
  132684. 4,
  132685. 3,
  132686. 5,
  132687. 2,
  132688. 6,
  132689. 1,
  132690. 7,
  132691. 0,
  132692. 8,
  132693. };
  132694. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132695. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132696. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132697. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132698. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132700. 0,
  132701. };
  132702. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132703. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132704. };
  132705. static long _vq_quantmap__44c6_s_p3_0[] = {
  132706. 7, 5, 3, 1, 0, 2, 4, 6,
  132707. 8,
  132708. };
  132709. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132710. _vq_quantthresh__44c6_s_p3_0,
  132711. _vq_quantmap__44c6_s_p3_0,
  132712. 9,
  132713. 9
  132714. };
  132715. static static_codebook _44c6_s_p3_0 = {
  132716. 2, 81,
  132717. _vq_lengthlist__44c6_s_p3_0,
  132718. 1, -531628032, 1611661312, 4, 0,
  132719. _vq_quantlist__44c6_s_p3_0,
  132720. NULL,
  132721. &_vq_auxt__44c6_s_p3_0,
  132722. NULL,
  132723. 0
  132724. };
  132725. static long _vq_quantlist__44c6_s_p4_0[] = {
  132726. 8,
  132727. 7,
  132728. 9,
  132729. 6,
  132730. 10,
  132731. 5,
  132732. 11,
  132733. 4,
  132734. 12,
  132735. 3,
  132736. 13,
  132737. 2,
  132738. 14,
  132739. 1,
  132740. 15,
  132741. 0,
  132742. 16,
  132743. };
  132744. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132745. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132746. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132747. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132748. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132749. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132750. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132751. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132752. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132753. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132754. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132763. 0,
  132764. };
  132765. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132766. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132767. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132768. };
  132769. static long _vq_quantmap__44c6_s_p4_0[] = {
  132770. 15, 13, 11, 9, 7, 5, 3, 1,
  132771. 0, 2, 4, 6, 8, 10, 12, 14,
  132772. 16,
  132773. };
  132774. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132775. _vq_quantthresh__44c6_s_p4_0,
  132776. _vq_quantmap__44c6_s_p4_0,
  132777. 17,
  132778. 17
  132779. };
  132780. static static_codebook _44c6_s_p4_0 = {
  132781. 2, 289,
  132782. _vq_lengthlist__44c6_s_p4_0,
  132783. 1, -529530880, 1611661312, 5, 0,
  132784. _vq_quantlist__44c6_s_p4_0,
  132785. NULL,
  132786. &_vq_auxt__44c6_s_p4_0,
  132787. NULL,
  132788. 0
  132789. };
  132790. static long _vq_quantlist__44c6_s_p5_0[] = {
  132791. 1,
  132792. 0,
  132793. 2,
  132794. };
  132795. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132796. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132797. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132798. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132799. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132800. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132801. 12,
  132802. };
  132803. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132804. -5.5, 5.5,
  132805. };
  132806. static long _vq_quantmap__44c6_s_p5_0[] = {
  132807. 1, 0, 2,
  132808. };
  132809. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132810. _vq_quantthresh__44c6_s_p5_0,
  132811. _vq_quantmap__44c6_s_p5_0,
  132812. 3,
  132813. 3
  132814. };
  132815. static static_codebook _44c6_s_p5_0 = {
  132816. 4, 81,
  132817. _vq_lengthlist__44c6_s_p5_0,
  132818. 1, -529137664, 1618345984, 2, 0,
  132819. _vq_quantlist__44c6_s_p5_0,
  132820. NULL,
  132821. &_vq_auxt__44c6_s_p5_0,
  132822. NULL,
  132823. 0
  132824. };
  132825. static long _vq_quantlist__44c6_s_p5_1[] = {
  132826. 5,
  132827. 4,
  132828. 6,
  132829. 3,
  132830. 7,
  132831. 2,
  132832. 8,
  132833. 1,
  132834. 9,
  132835. 0,
  132836. 10,
  132837. };
  132838. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132839. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132840. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132841. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132842. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132843. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132844. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132845. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132846. 11,10,10, 7, 7, 8, 8, 8, 8,
  132847. };
  132848. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132849. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132850. 3.5, 4.5,
  132851. };
  132852. static long _vq_quantmap__44c6_s_p5_1[] = {
  132853. 9, 7, 5, 3, 1, 0, 2, 4,
  132854. 6, 8, 10,
  132855. };
  132856. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132857. _vq_quantthresh__44c6_s_p5_1,
  132858. _vq_quantmap__44c6_s_p5_1,
  132859. 11,
  132860. 11
  132861. };
  132862. static static_codebook _44c6_s_p5_1 = {
  132863. 2, 121,
  132864. _vq_lengthlist__44c6_s_p5_1,
  132865. 1, -531365888, 1611661312, 4, 0,
  132866. _vq_quantlist__44c6_s_p5_1,
  132867. NULL,
  132868. &_vq_auxt__44c6_s_p5_1,
  132869. NULL,
  132870. 0
  132871. };
  132872. static long _vq_quantlist__44c6_s_p6_0[] = {
  132873. 6,
  132874. 5,
  132875. 7,
  132876. 4,
  132877. 8,
  132878. 3,
  132879. 9,
  132880. 2,
  132881. 10,
  132882. 1,
  132883. 11,
  132884. 0,
  132885. 12,
  132886. };
  132887. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132888. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132889. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132890. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132891. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132892. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132893. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132898. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132899. };
  132900. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132901. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132902. 12.5, 17.5, 22.5, 27.5,
  132903. };
  132904. static long _vq_quantmap__44c6_s_p6_0[] = {
  132905. 11, 9, 7, 5, 3, 1, 0, 2,
  132906. 4, 6, 8, 10, 12,
  132907. };
  132908. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132909. _vq_quantthresh__44c6_s_p6_0,
  132910. _vq_quantmap__44c6_s_p6_0,
  132911. 13,
  132912. 13
  132913. };
  132914. static static_codebook _44c6_s_p6_0 = {
  132915. 2, 169,
  132916. _vq_lengthlist__44c6_s_p6_0,
  132917. 1, -526516224, 1616117760, 4, 0,
  132918. _vq_quantlist__44c6_s_p6_0,
  132919. NULL,
  132920. &_vq_auxt__44c6_s_p6_0,
  132921. NULL,
  132922. 0
  132923. };
  132924. static long _vq_quantlist__44c6_s_p6_1[] = {
  132925. 2,
  132926. 1,
  132927. 3,
  132928. 0,
  132929. 4,
  132930. };
  132931. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132932. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132933. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132934. };
  132935. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132936. -1.5, -0.5, 0.5, 1.5,
  132937. };
  132938. static long _vq_quantmap__44c6_s_p6_1[] = {
  132939. 3, 1, 0, 2, 4,
  132940. };
  132941. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132942. _vq_quantthresh__44c6_s_p6_1,
  132943. _vq_quantmap__44c6_s_p6_1,
  132944. 5,
  132945. 5
  132946. };
  132947. static static_codebook _44c6_s_p6_1 = {
  132948. 2, 25,
  132949. _vq_lengthlist__44c6_s_p6_1,
  132950. 1, -533725184, 1611661312, 3, 0,
  132951. _vq_quantlist__44c6_s_p6_1,
  132952. NULL,
  132953. &_vq_auxt__44c6_s_p6_1,
  132954. NULL,
  132955. 0
  132956. };
  132957. static long _vq_quantlist__44c6_s_p7_0[] = {
  132958. 6,
  132959. 5,
  132960. 7,
  132961. 4,
  132962. 8,
  132963. 3,
  132964. 9,
  132965. 2,
  132966. 10,
  132967. 1,
  132968. 11,
  132969. 0,
  132970. 12,
  132971. };
  132972. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132973. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132974. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132975. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132976. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132977. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132978. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132979. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132980. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132981. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132982. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132983. 20,13,13,13,13,13,13,14,14,
  132984. };
  132985. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132986. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132987. 27.5, 38.5, 49.5, 60.5,
  132988. };
  132989. static long _vq_quantmap__44c6_s_p7_0[] = {
  132990. 11, 9, 7, 5, 3, 1, 0, 2,
  132991. 4, 6, 8, 10, 12,
  132992. };
  132993. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132994. _vq_quantthresh__44c6_s_p7_0,
  132995. _vq_quantmap__44c6_s_p7_0,
  132996. 13,
  132997. 13
  132998. };
  132999. static static_codebook _44c6_s_p7_0 = {
  133000. 2, 169,
  133001. _vq_lengthlist__44c6_s_p7_0,
  133002. 1, -523206656, 1618345984, 4, 0,
  133003. _vq_quantlist__44c6_s_p7_0,
  133004. NULL,
  133005. &_vq_auxt__44c6_s_p7_0,
  133006. NULL,
  133007. 0
  133008. };
  133009. static long _vq_quantlist__44c6_s_p7_1[] = {
  133010. 5,
  133011. 4,
  133012. 6,
  133013. 3,
  133014. 7,
  133015. 2,
  133016. 8,
  133017. 1,
  133018. 9,
  133019. 0,
  133020. 10,
  133021. };
  133022. static long _vq_lengthlist__44c6_s_p7_1[] = {
  133023. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  133024. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  133025. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  133026. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  133027. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  133028. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  133029. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133030. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133031. };
  133032. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133033. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133034. 3.5, 4.5,
  133035. };
  133036. static long _vq_quantmap__44c6_s_p7_1[] = {
  133037. 9, 7, 5, 3, 1, 0, 2, 4,
  133038. 6, 8, 10,
  133039. };
  133040. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133041. _vq_quantthresh__44c6_s_p7_1,
  133042. _vq_quantmap__44c6_s_p7_1,
  133043. 11,
  133044. 11
  133045. };
  133046. static static_codebook _44c6_s_p7_1 = {
  133047. 2, 121,
  133048. _vq_lengthlist__44c6_s_p7_1,
  133049. 1, -531365888, 1611661312, 4, 0,
  133050. _vq_quantlist__44c6_s_p7_1,
  133051. NULL,
  133052. &_vq_auxt__44c6_s_p7_1,
  133053. NULL,
  133054. 0
  133055. };
  133056. static long _vq_quantlist__44c6_s_p8_0[] = {
  133057. 7,
  133058. 6,
  133059. 8,
  133060. 5,
  133061. 9,
  133062. 4,
  133063. 10,
  133064. 3,
  133065. 11,
  133066. 2,
  133067. 12,
  133068. 1,
  133069. 13,
  133070. 0,
  133071. 14,
  133072. };
  133073. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133074. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133075. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133076. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133077. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133078. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133079. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133080. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133081. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133082. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133083. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133084. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133085. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133086. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133087. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133088. 14,
  133089. };
  133090. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133091. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133092. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133093. };
  133094. static long _vq_quantmap__44c6_s_p8_0[] = {
  133095. 13, 11, 9, 7, 5, 3, 1, 0,
  133096. 2, 4, 6, 8, 10, 12, 14,
  133097. };
  133098. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133099. _vq_quantthresh__44c6_s_p8_0,
  133100. _vq_quantmap__44c6_s_p8_0,
  133101. 15,
  133102. 15
  133103. };
  133104. static static_codebook _44c6_s_p8_0 = {
  133105. 2, 225,
  133106. _vq_lengthlist__44c6_s_p8_0,
  133107. 1, -520986624, 1620377600, 4, 0,
  133108. _vq_quantlist__44c6_s_p8_0,
  133109. NULL,
  133110. &_vq_auxt__44c6_s_p8_0,
  133111. NULL,
  133112. 0
  133113. };
  133114. static long _vq_quantlist__44c6_s_p8_1[] = {
  133115. 10,
  133116. 9,
  133117. 11,
  133118. 8,
  133119. 12,
  133120. 7,
  133121. 13,
  133122. 6,
  133123. 14,
  133124. 5,
  133125. 15,
  133126. 4,
  133127. 16,
  133128. 3,
  133129. 17,
  133130. 2,
  133131. 18,
  133132. 1,
  133133. 19,
  133134. 0,
  133135. 20,
  133136. };
  133137. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133138. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133139. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133140. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133141. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133142. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133143. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133144. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133145. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133146. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133147. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133148. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133149. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133150. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133151. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133152. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133153. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133154. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133155. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133156. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133157. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133158. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133159. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133160. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133161. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133162. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133163. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133164. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133165. 10,10,10,10,10,10,10,10,10,
  133166. };
  133167. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133168. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133169. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133170. 6.5, 7.5, 8.5, 9.5,
  133171. };
  133172. static long _vq_quantmap__44c6_s_p8_1[] = {
  133173. 19, 17, 15, 13, 11, 9, 7, 5,
  133174. 3, 1, 0, 2, 4, 6, 8, 10,
  133175. 12, 14, 16, 18, 20,
  133176. };
  133177. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133178. _vq_quantthresh__44c6_s_p8_1,
  133179. _vq_quantmap__44c6_s_p8_1,
  133180. 21,
  133181. 21
  133182. };
  133183. static static_codebook _44c6_s_p8_1 = {
  133184. 2, 441,
  133185. _vq_lengthlist__44c6_s_p8_1,
  133186. 1, -529268736, 1611661312, 5, 0,
  133187. _vq_quantlist__44c6_s_p8_1,
  133188. NULL,
  133189. &_vq_auxt__44c6_s_p8_1,
  133190. NULL,
  133191. 0
  133192. };
  133193. static long _vq_quantlist__44c6_s_p9_0[] = {
  133194. 6,
  133195. 5,
  133196. 7,
  133197. 4,
  133198. 8,
  133199. 3,
  133200. 9,
  133201. 2,
  133202. 10,
  133203. 1,
  133204. 11,
  133205. 0,
  133206. 12,
  133207. };
  133208. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133209. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133210. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133211. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133212. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133213. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133214. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133215. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133216. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133217. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133218. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133219. 10,10,10,10,10,10,10,10,10,
  133220. };
  133221. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133222. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133223. 1592.5, 2229.5, 2866.5, 3503.5,
  133224. };
  133225. static long _vq_quantmap__44c6_s_p9_0[] = {
  133226. 11, 9, 7, 5, 3, 1, 0, 2,
  133227. 4, 6, 8, 10, 12,
  133228. };
  133229. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133230. _vq_quantthresh__44c6_s_p9_0,
  133231. _vq_quantmap__44c6_s_p9_0,
  133232. 13,
  133233. 13
  133234. };
  133235. static static_codebook _44c6_s_p9_0 = {
  133236. 2, 169,
  133237. _vq_lengthlist__44c6_s_p9_0,
  133238. 1, -511845376, 1630791680, 4, 0,
  133239. _vq_quantlist__44c6_s_p9_0,
  133240. NULL,
  133241. &_vq_auxt__44c6_s_p9_0,
  133242. NULL,
  133243. 0
  133244. };
  133245. static long _vq_quantlist__44c6_s_p9_1[] = {
  133246. 6,
  133247. 5,
  133248. 7,
  133249. 4,
  133250. 8,
  133251. 3,
  133252. 9,
  133253. 2,
  133254. 10,
  133255. 1,
  133256. 11,
  133257. 0,
  133258. 12,
  133259. };
  133260. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133261. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133262. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133263. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133264. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133265. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133266. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133267. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133268. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133269. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133270. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133271. 15,12,10,11,11,13,11,12,13,
  133272. };
  133273. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133274. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133275. 122.5, 171.5, 220.5, 269.5,
  133276. };
  133277. static long _vq_quantmap__44c6_s_p9_1[] = {
  133278. 11, 9, 7, 5, 3, 1, 0, 2,
  133279. 4, 6, 8, 10, 12,
  133280. };
  133281. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133282. _vq_quantthresh__44c6_s_p9_1,
  133283. _vq_quantmap__44c6_s_p9_1,
  133284. 13,
  133285. 13
  133286. };
  133287. static static_codebook _44c6_s_p9_1 = {
  133288. 2, 169,
  133289. _vq_lengthlist__44c6_s_p9_1,
  133290. 1, -518889472, 1622704128, 4, 0,
  133291. _vq_quantlist__44c6_s_p9_1,
  133292. NULL,
  133293. &_vq_auxt__44c6_s_p9_1,
  133294. NULL,
  133295. 0
  133296. };
  133297. static long _vq_quantlist__44c6_s_p9_2[] = {
  133298. 24,
  133299. 23,
  133300. 25,
  133301. 22,
  133302. 26,
  133303. 21,
  133304. 27,
  133305. 20,
  133306. 28,
  133307. 19,
  133308. 29,
  133309. 18,
  133310. 30,
  133311. 17,
  133312. 31,
  133313. 16,
  133314. 32,
  133315. 15,
  133316. 33,
  133317. 14,
  133318. 34,
  133319. 13,
  133320. 35,
  133321. 12,
  133322. 36,
  133323. 11,
  133324. 37,
  133325. 10,
  133326. 38,
  133327. 9,
  133328. 39,
  133329. 8,
  133330. 40,
  133331. 7,
  133332. 41,
  133333. 6,
  133334. 42,
  133335. 5,
  133336. 43,
  133337. 4,
  133338. 44,
  133339. 3,
  133340. 45,
  133341. 2,
  133342. 46,
  133343. 1,
  133344. 47,
  133345. 0,
  133346. 48,
  133347. };
  133348. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133349. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133350. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133351. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133352. 7,
  133353. };
  133354. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133355. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133356. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133357. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133358. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133359. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133360. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133361. };
  133362. static long _vq_quantmap__44c6_s_p9_2[] = {
  133363. 47, 45, 43, 41, 39, 37, 35, 33,
  133364. 31, 29, 27, 25, 23, 21, 19, 17,
  133365. 15, 13, 11, 9, 7, 5, 3, 1,
  133366. 0, 2, 4, 6, 8, 10, 12, 14,
  133367. 16, 18, 20, 22, 24, 26, 28, 30,
  133368. 32, 34, 36, 38, 40, 42, 44, 46,
  133369. 48,
  133370. };
  133371. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133372. _vq_quantthresh__44c6_s_p9_2,
  133373. _vq_quantmap__44c6_s_p9_2,
  133374. 49,
  133375. 49
  133376. };
  133377. static static_codebook _44c6_s_p9_2 = {
  133378. 1, 49,
  133379. _vq_lengthlist__44c6_s_p9_2,
  133380. 1, -526909440, 1611661312, 6, 0,
  133381. _vq_quantlist__44c6_s_p9_2,
  133382. NULL,
  133383. &_vq_auxt__44c6_s_p9_2,
  133384. NULL,
  133385. 0
  133386. };
  133387. static long _huff_lengthlist__44c6_s_short[] = {
  133388. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133389. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133390. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133391. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133392. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133393. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133394. 9,10,17,18,
  133395. };
  133396. static static_codebook _huff_book__44c6_s_short = {
  133397. 2, 100,
  133398. _huff_lengthlist__44c6_s_short,
  133399. 0, 0, 0, 0, 0,
  133400. NULL,
  133401. NULL,
  133402. NULL,
  133403. NULL,
  133404. 0
  133405. };
  133406. static long _huff_lengthlist__44c7_s_long[] = {
  133407. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133408. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133409. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133410. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133411. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133412. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133413. 11,10,10,12,
  133414. };
  133415. static static_codebook _huff_book__44c7_s_long = {
  133416. 2, 100,
  133417. _huff_lengthlist__44c7_s_long,
  133418. 0, 0, 0, 0, 0,
  133419. NULL,
  133420. NULL,
  133421. NULL,
  133422. NULL,
  133423. 0
  133424. };
  133425. static long _vq_quantlist__44c7_s_p1_0[] = {
  133426. 1,
  133427. 0,
  133428. 2,
  133429. };
  133430. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133431. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133432. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133433. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133434. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133435. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133436. 8,
  133437. };
  133438. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133439. -0.5, 0.5,
  133440. };
  133441. static long _vq_quantmap__44c7_s_p1_0[] = {
  133442. 1, 0, 2,
  133443. };
  133444. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133445. _vq_quantthresh__44c7_s_p1_0,
  133446. _vq_quantmap__44c7_s_p1_0,
  133447. 3,
  133448. 3
  133449. };
  133450. static static_codebook _44c7_s_p1_0 = {
  133451. 4, 81,
  133452. _vq_lengthlist__44c7_s_p1_0,
  133453. 1, -535822336, 1611661312, 2, 0,
  133454. _vq_quantlist__44c7_s_p1_0,
  133455. NULL,
  133456. &_vq_auxt__44c7_s_p1_0,
  133457. NULL,
  133458. 0
  133459. };
  133460. static long _vq_quantlist__44c7_s_p2_0[] = {
  133461. 2,
  133462. 1,
  133463. 3,
  133464. 0,
  133465. 4,
  133466. };
  133467. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133468. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133469. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133470. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133471. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133472. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133473. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133474. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133475. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133478. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133479. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133480. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133481. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133482. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133483. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133485. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133486. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133487. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133488. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133489. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133490. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133491. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133493. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133494. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133495. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133496. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133497. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133498. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133499. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133504. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133505. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133506. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133507. 13,
  133508. };
  133509. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133510. -1.5, -0.5, 0.5, 1.5,
  133511. };
  133512. static long _vq_quantmap__44c7_s_p2_0[] = {
  133513. 3, 1, 0, 2, 4,
  133514. };
  133515. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133516. _vq_quantthresh__44c7_s_p2_0,
  133517. _vq_quantmap__44c7_s_p2_0,
  133518. 5,
  133519. 5
  133520. };
  133521. static static_codebook _44c7_s_p2_0 = {
  133522. 4, 625,
  133523. _vq_lengthlist__44c7_s_p2_0,
  133524. 1, -533725184, 1611661312, 3, 0,
  133525. _vq_quantlist__44c7_s_p2_0,
  133526. NULL,
  133527. &_vq_auxt__44c7_s_p2_0,
  133528. NULL,
  133529. 0
  133530. };
  133531. static long _vq_quantlist__44c7_s_p3_0[] = {
  133532. 4,
  133533. 3,
  133534. 5,
  133535. 2,
  133536. 6,
  133537. 1,
  133538. 7,
  133539. 0,
  133540. 8,
  133541. };
  133542. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133543. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133544. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133545. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133546. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133548. 0,
  133549. };
  133550. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133551. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133552. };
  133553. static long _vq_quantmap__44c7_s_p3_0[] = {
  133554. 7, 5, 3, 1, 0, 2, 4, 6,
  133555. 8,
  133556. };
  133557. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133558. _vq_quantthresh__44c7_s_p3_0,
  133559. _vq_quantmap__44c7_s_p3_0,
  133560. 9,
  133561. 9
  133562. };
  133563. static static_codebook _44c7_s_p3_0 = {
  133564. 2, 81,
  133565. _vq_lengthlist__44c7_s_p3_0,
  133566. 1, -531628032, 1611661312, 4, 0,
  133567. _vq_quantlist__44c7_s_p3_0,
  133568. NULL,
  133569. &_vq_auxt__44c7_s_p3_0,
  133570. NULL,
  133571. 0
  133572. };
  133573. static long _vq_quantlist__44c7_s_p4_0[] = {
  133574. 8,
  133575. 7,
  133576. 9,
  133577. 6,
  133578. 10,
  133579. 5,
  133580. 11,
  133581. 4,
  133582. 12,
  133583. 3,
  133584. 13,
  133585. 2,
  133586. 14,
  133587. 1,
  133588. 15,
  133589. 0,
  133590. 16,
  133591. };
  133592. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133593. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133594. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133595. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133596. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133597. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133598. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133599. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133600. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133601. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133602. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133611. 0,
  133612. };
  133613. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133614. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133615. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133616. };
  133617. static long _vq_quantmap__44c7_s_p4_0[] = {
  133618. 15, 13, 11, 9, 7, 5, 3, 1,
  133619. 0, 2, 4, 6, 8, 10, 12, 14,
  133620. 16,
  133621. };
  133622. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133623. _vq_quantthresh__44c7_s_p4_0,
  133624. _vq_quantmap__44c7_s_p4_0,
  133625. 17,
  133626. 17
  133627. };
  133628. static static_codebook _44c7_s_p4_0 = {
  133629. 2, 289,
  133630. _vq_lengthlist__44c7_s_p4_0,
  133631. 1, -529530880, 1611661312, 5, 0,
  133632. _vq_quantlist__44c7_s_p4_0,
  133633. NULL,
  133634. &_vq_auxt__44c7_s_p4_0,
  133635. NULL,
  133636. 0
  133637. };
  133638. static long _vq_quantlist__44c7_s_p5_0[] = {
  133639. 1,
  133640. 0,
  133641. 2,
  133642. };
  133643. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133644. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133645. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133646. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133647. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133648. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133649. 12,
  133650. };
  133651. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133652. -5.5, 5.5,
  133653. };
  133654. static long _vq_quantmap__44c7_s_p5_0[] = {
  133655. 1, 0, 2,
  133656. };
  133657. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133658. _vq_quantthresh__44c7_s_p5_0,
  133659. _vq_quantmap__44c7_s_p5_0,
  133660. 3,
  133661. 3
  133662. };
  133663. static static_codebook _44c7_s_p5_0 = {
  133664. 4, 81,
  133665. _vq_lengthlist__44c7_s_p5_0,
  133666. 1, -529137664, 1618345984, 2, 0,
  133667. _vq_quantlist__44c7_s_p5_0,
  133668. NULL,
  133669. &_vq_auxt__44c7_s_p5_0,
  133670. NULL,
  133671. 0
  133672. };
  133673. static long _vq_quantlist__44c7_s_p5_1[] = {
  133674. 5,
  133675. 4,
  133676. 6,
  133677. 3,
  133678. 7,
  133679. 2,
  133680. 8,
  133681. 1,
  133682. 9,
  133683. 0,
  133684. 10,
  133685. };
  133686. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133687. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133688. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133689. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133690. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133691. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133692. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133693. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133694. 11,11,11, 7, 7, 8, 8, 8, 8,
  133695. };
  133696. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133697. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133698. 3.5, 4.5,
  133699. };
  133700. static long _vq_quantmap__44c7_s_p5_1[] = {
  133701. 9, 7, 5, 3, 1, 0, 2, 4,
  133702. 6, 8, 10,
  133703. };
  133704. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133705. _vq_quantthresh__44c7_s_p5_1,
  133706. _vq_quantmap__44c7_s_p5_1,
  133707. 11,
  133708. 11
  133709. };
  133710. static static_codebook _44c7_s_p5_1 = {
  133711. 2, 121,
  133712. _vq_lengthlist__44c7_s_p5_1,
  133713. 1, -531365888, 1611661312, 4, 0,
  133714. _vq_quantlist__44c7_s_p5_1,
  133715. NULL,
  133716. &_vq_auxt__44c7_s_p5_1,
  133717. NULL,
  133718. 0
  133719. };
  133720. static long _vq_quantlist__44c7_s_p6_0[] = {
  133721. 6,
  133722. 5,
  133723. 7,
  133724. 4,
  133725. 8,
  133726. 3,
  133727. 9,
  133728. 2,
  133729. 10,
  133730. 1,
  133731. 11,
  133732. 0,
  133733. 12,
  133734. };
  133735. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133736. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133737. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133738. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133739. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133740. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133741. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133746. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133747. };
  133748. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133749. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133750. 12.5, 17.5, 22.5, 27.5,
  133751. };
  133752. static long _vq_quantmap__44c7_s_p6_0[] = {
  133753. 11, 9, 7, 5, 3, 1, 0, 2,
  133754. 4, 6, 8, 10, 12,
  133755. };
  133756. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133757. _vq_quantthresh__44c7_s_p6_0,
  133758. _vq_quantmap__44c7_s_p6_0,
  133759. 13,
  133760. 13
  133761. };
  133762. static static_codebook _44c7_s_p6_0 = {
  133763. 2, 169,
  133764. _vq_lengthlist__44c7_s_p6_0,
  133765. 1, -526516224, 1616117760, 4, 0,
  133766. _vq_quantlist__44c7_s_p6_0,
  133767. NULL,
  133768. &_vq_auxt__44c7_s_p6_0,
  133769. NULL,
  133770. 0
  133771. };
  133772. static long _vq_quantlist__44c7_s_p6_1[] = {
  133773. 2,
  133774. 1,
  133775. 3,
  133776. 0,
  133777. 4,
  133778. };
  133779. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133780. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133781. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133782. };
  133783. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133784. -1.5, -0.5, 0.5, 1.5,
  133785. };
  133786. static long _vq_quantmap__44c7_s_p6_1[] = {
  133787. 3, 1, 0, 2, 4,
  133788. };
  133789. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133790. _vq_quantthresh__44c7_s_p6_1,
  133791. _vq_quantmap__44c7_s_p6_1,
  133792. 5,
  133793. 5
  133794. };
  133795. static static_codebook _44c7_s_p6_1 = {
  133796. 2, 25,
  133797. _vq_lengthlist__44c7_s_p6_1,
  133798. 1, -533725184, 1611661312, 3, 0,
  133799. _vq_quantlist__44c7_s_p6_1,
  133800. NULL,
  133801. &_vq_auxt__44c7_s_p6_1,
  133802. NULL,
  133803. 0
  133804. };
  133805. static long _vq_quantlist__44c7_s_p7_0[] = {
  133806. 6,
  133807. 5,
  133808. 7,
  133809. 4,
  133810. 8,
  133811. 3,
  133812. 9,
  133813. 2,
  133814. 10,
  133815. 1,
  133816. 11,
  133817. 0,
  133818. 12,
  133819. };
  133820. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133821. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133822. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133823. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133824. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133825. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133826. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133827. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133828. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133829. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133830. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133831. 19,13,13,13,13,14,14,15,15,
  133832. };
  133833. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133834. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133835. 27.5, 38.5, 49.5, 60.5,
  133836. };
  133837. static long _vq_quantmap__44c7_s_p7_0[] = {
  133838. 11, 9, 7, 5, 3, 1, 0, 2,
  133839. 4, 6, 8, 10, 12,
  133840. };
  133841. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133842. _vq_quantthresh__44c7_s_p7_0,
  133843. _vq_quantmap__44c7_s_p7_0,
  133844. 13,
  133845. 13
  133846. };
  133847. static static_codebook _44c7_s_p7_0 = {
  133848. 2, 169,
  133849. _vq_lengthlist__44c7_s_p7_0,
  133850. 1, -523206656, 1618345984, 4, 0,
  133851. _vq_quantlist__44c7_s_p7_0,
  133852. NULL,
  133853. &_vq_auxt__44c7_s_p7_0,
  133854. NULL,
  133855. 0
  133856. };
  133857. static long _vq_quantlist__44c7_s_p7_1[] = {
  133858. 5,
  133859. 4,
  133860. 6,
  133861. 3,
  133862. 7,
  133863. 2,
  133864. 8,
  133865. 1,
  133866. 9,
  133867. 0,
  133868. 10,
  133869. };
  133870. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133871. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133872. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133873. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133874. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133875. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133876. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133877. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133878. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133879. };
  133880. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133881. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133882. 3.5, 4.5,
  133883. };
  133884. static long _vq_quantmap__44c7_s_p7_1[] = {
  133885. 9, 7, 5, 3, 1, 0, 2, 4,
  133886. 6, 8, 10,
  133887. };
  133888. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133889. _vq_quantthresh__44c7_s_p7_1,
  133890. _vq_quantmap__44c7_s_p7_1,
  133891. 11,
  133892. 11
  133893. };
  133894. static static_codebook _44c7_s_p7_1 = {
  133895. 2, 121,
  133896. _vq_lengthlist__44c7_s_p7_1,
  133897. 1, -531365888, 1611661312, 4, 0,
  133898. _vq_quantlist__44c7_s_p7_1,
  133899. NULL,
  133900. &_vq_auxt__44c7_s_p7_1,
  133901. NULL,
  133902. 0
  133903. };
  133904. static long _vq_quantlist__44c7_s_p8_0[] = {
  133905. 7,
  133906. 6,
  133907. 8,
  133908. 5,
  133909. 9,
  133910. 4,
  133911. 10,
  133912. 3,
  133913. 11,
  133914. 2,
  133915. 12,
  133916. 1,
  133917. 13,
  133918. 0,
  133919. 14,
  133920. };
  133921. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133922. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133923. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133924. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133925. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133926. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133927. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133928. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133929. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133930. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133931. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133932. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133933. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133934. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133935. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133936. 14,
  133937. };
  133938. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133939. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133940. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133941. };
  133942. static long _vq_quantmap__44c7_s_p8_0[] = {
  133943. 13, 11, 9, 7, 5, 3, 1, 0,
  133944. 2, 4, 6, 8, 10, 12, 14,
  133945. };
  133946. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133947. _vq_quantthresh__44c7_s_p8_0,
  133948. _vq_quantmap__44c7_s_p8_0,
  133949. 15,
  133950. 15
  133951. };
  133952. static static_codebook _44c7_s_p8_0 = {
  133953. 2, 225,
  133954. _vq_lengthlist__44c7_s_p8_0,
  133955. 1, -520986624, 1620377600, 4, 0,
  133956. _vq_quantlist__44c7_s_p8_0,
  133957. NULL,
  133958. &_vq_auxt__44c7_s_p8_0,
  133959. NULL,
  133960. 0
  133961. };
  133962. static long _vq_quantlist__44c7_s_p8_1[] = {
  133963. 10,
  133964. 9,
  133965. 11,
  133966. 8,
  133967. 12,
  133968. 7,
  133969. 13,
  133970. 6,
  133971. 14,
  133972. 5,
  133973. 15,
  133974. 4,
  133975. 16,
  133976. 3,
  133977. 17,
  133978. 2,
  133979. 18,
  133980. 1,
  133981. 19,
  133982. 0,
  133983. 20,
  133984. };
  133985. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133986. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133987. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133988. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133989. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133990. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133991. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133992. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133993. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133994. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133995. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133996. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133997. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133998. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133999. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  134000. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  134001. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  134002. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  134003. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  134004. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  134005. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  134006. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  134007. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  134008. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  134009. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  134010. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  134011. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  134012. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  134013. 10,10,10,10,10,10,10,10,10,
  134014. };
  134015. static float _vq_quantthresh__44c7_s_p8_1[] = {
  134016. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134017. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134018. 6.5, 7.5, 8.5, 9.5,
  134019. };
  134020. static long _vq_quantmap__44c7_s_p8_1[] = {
  134021. 19, 17, 15, 13, 11, 9, 7, 5,
  134022. 3, 1, 0, 2, 4, 6, 8, 10,
  134023. 12, 14, 16, 18, 20,
  134024. };
  134025. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  134026. _vq_quantthresh__44c7_s_p8_1,
  134027. _vq_quantmap__44c7_s_p8_1,
  134028. 21,
  134029. 21
  134030. };
  134031. static static_codebook _44c7_s_p8_1 = {
  134032. 2, 441,
  134033. _vq_lengthlist__44c7_s_p8_1,
  134034. 1, -529268736, 1611661312, 5, 0,
  134035. _vq_quantlist__44c7_s_p8_1,
  134036. NULL,
  134037. &_vq_auxt__44c7_s_p8_1,
  134038. NULL,
  134039. 0
  134040. };
  134041. static long _vq_quantlist__44c7_s_p9_0[] = {
  134042. 6,
  134043. 5,
  134044. 7,
  134045. 4,
  134046. 8,
  134047. 3,
  134048. 9,
  134049. 2,
  134050. 10,
  134051. 1,
  134052. 11,
  134053. 0,
  134054. 12,
  134055. };
  134056. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134057. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134058. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134060. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134061. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134062. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134063. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134064. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134065. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134066. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134067. 11,11,11,11,11,11,11,11,11,
  134068. };
  134069. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134070. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134071. 1592.5, 2229.5, 2866.5, 3503.5,
  134072. };
  134073. static long _vq_quantmap__44c7_s_p9_0[] = {
  134074. 11, 9, 7, 5, 3, 1, 0, 2,
  134075. 4, 6, 8, 10, 12,
  134076. };
  134077. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134078. _vq_quantthresh__44c7_s_p9_0,
  134079. _vq_quantmap__44c7_s_p9_0,
  134080. 13,
  134081. 13
  134082. };
  134083. static static_codebook _44c7_s_p9_0 = {
  134084. 2, 169,
  134085. _vq_lengthlist__44c7_s_p9_0,
  134086. 1, -511845376, 1630791680, 4, 0,
  134087. _vq_quantlist__44c7_s_p9_0,
  134088. NULL,
  134089. &_vq_auxt__44c7_s_p9_0,
  134090. NULL,
  134091. 0
  134092. };
  134093. static long _vq_quantlist__44c7_s_p9_1[] = {
  134094. 6,
  134095. 5,
  134096. 7,
  134097. 4,
  134098. 8,
  134099. 3,
  134100. 9,
  134101. 2,
  134102. 10,
  134103. 1,
  134104. 11,
  134105. 0,
  134106. 12,
  134107. };
  134108. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134109. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134110. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134111. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134112. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134113. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134114. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134115. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134116. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134117. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134118. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134119. 15,11,11,10,10,12,12,12,12,
  134120. };
  134121. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134122. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134123. 122.5, 171.5, 220.5, 269.5,
  134124. };
  134125. static long _vq_quantmap__44c7_s_p9_1[] = {
  134126. 11, 9, 7, 5, 3, 1, 0, 2,
  134127. 4, 6, 8, 10, 12,
  134128. };
  134129. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134130. _vq_quantthresh__44c7_s_p9_1,
  134131. _vq_quantmap__44c7_s_p9_1,
  134132. 13,
  134133. 13
  134134. };
  134135. static static_codebook _44c7_s_p9_1 = {
  134136. 2, 169,
  134137. _vq_lengthlist__44c7_s_p9_1,
  134138. 1, -518889472, 1622704128, 4, 0,
  134139. _vq_quantlist__44c7_s_p9_1,
  134140. NULL,
  134141. &_vq_auxt__44c7_s_p9_1,
  134142. NULL,
  134143. 0
  134144. };
  134145. static long _vq_quantlist__44c7_s_p9_2[] = {
  134146. 24,
  134147. 23,
  134148. 25,
  134149. 22,
  134150. 26,
  134151. 21,
  134152. 27,
  134153. 20,
  134154. 28,
  134155. 19,
  134156. 29,
  134157. 18,
  134158. 30,
  134159. 17,
  134160. 31,
  134161. 16,
  134162. 32,
  134163. 15,
  134164. 33,
  134165. 14,
  134166. 34,
  134167. 13,
  134168. 35,
  134169. 12,
  134170. 36,
  134171. 11,
  134172. 37,
  134173. 10,
  134174. 38,
  134175. 9,
  134176. 39,
  134177. 8,
  134178. 40,
  134179. 7,
  134180. 41,
  134181. 6,
  134182. 42,
  134183. 5,
  134184. 43,
  134185. 4,
  134186. 44,
  134187. 3,
  134188. 45,
  134189. 2,
  134190. 46,
  134191. 1,
  134192. 47,
  134193. 0,
  134194. 48,
  134195. };
  134196. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134197. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134198. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134199. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134200. 7,
  134201. };
  134202. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134203. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134204. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134205. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134206. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134207. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134208. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134209. };
  134210. static long _vq_quantmap__44c7_s_p9_2[] = {
  134211. 47, 45, 43, 41, 39, 37, 35, 33,
  134212. 31, 29, 27, 25, 23, 21, 19, 17,
  134213. 15, 13, 11, 9, 7, 5, 3, 1,
  134214. 0, 2, 4, 6, 8, 10, 12, 14,
  134215. 16, 18, 20, 22, 24, 26, 28, 30,
  134216. 32, 34, 36, 38, 40, 42, 44, 46,
  134217. 48,
  134218. };
  134219. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134220. _vq_quantthresh__44c7_s_p9_2,
  134221. _vq_quantmap__44c7_s_p9_2,
  134222. 49,
  134223. 49
  134224. };
  134225. static static_codebook _44c7_s_p9_2 = {
  134226. 1, 49,
  134227. _vq_lengthlist__44c7_s_p9_2,
  134228. 1, -526909440, 1611661312, 6, 0,
  134229. _vq_quantlist__44c7_s_p9_2,
  134230. NULL,
  134231. &_vq_auxt__44c7_s_p9_2,
  134232. NULL,
  134233. 0
  134234. };
  134235. static long _huff_lengthlist__44c7_s_short[] = {
  134236. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134237. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134238. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134239. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134240. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134241. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134242. 10, 9,11,14,
  134243. };
  134244. static static_codebook _huff_book__44c7_s_short = {
  134245. 2, 100,
  134246. _huff_lengthlist__44c7_s_short,
  134247. 0, 0, 0, 0, 0,
  134248. NULL,
  134249. NULL,
  134250. NULL,
  134251. NULL,
  134252. 0
  134253. };
  134254. static long _huff_lengthlist__44c8_s_long[] = {
  134255. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134256. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134257. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134258. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134259. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134260. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134261. 11, 9, 9,10,
  134262. };
  134263. static static_codebook _huff_book__44c8_s_long = {
  134264. 2, 100,
  134265. _huff_lengthlist__44c8_s_long,
  134266. 0, 0, 0, 0, 0,
  134267. NULL,
  134268. NULL,
  134269. NULL,
  134270. NULL,
  134271. 0
  134272. };
  134273. static long _vq_quantlist__44c8_s_p1_0[] = {
  134274. 1,
  134275. 0,
  134276. 2,
  134277. };
  134278. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134279. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134280. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134281. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134282. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134283. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134284. 8,
  134285. };
  134286. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134287. -0.5, 0.5,
  134288. };
  134289. static long _vq_quantmap__44c8_s_p1_0[] = {
  134290. 1, 0, 2,
  134291. };
  134292. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134293. _vq_quantthresh__44c8_s_p1_0,
  134294. _vq_quantmap__44c8_s_p1_0,
  134295. 3,
  134296. 3
  134297. };
  134298. static static_codebook _44c8_s_p1_0 = {
  134299. 4, 81,
  134300. _vq_lengthlist__44c8_s_p1_0,
  134301. 1, -535822336, 1611661312, 2, 0,
  134302. _vq_quantlist__44c8_s_p1_0,
  134303. NULL,
  134304. &_vq_auxt__44c8_s_p1_0,
  134305. NULL,
  134306. 0
  134307. };
  134308. static long _vq_quantlist__44c8_s_p2_0[] = {
  134309. 2,
  134310. 1,
  134311. 3,
  134312. 0,
  134313. 4,
  134314. };
  134315. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134316. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134317. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134318. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134319. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134320. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134321. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134322. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134323. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134326. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134327. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134328. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134329. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134330. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134331. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134333. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134334. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134335. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134336. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134337. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134338. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134339. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134341. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134342. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134343. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134344. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134345. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134346. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134347. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134352. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134353. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134354. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134355. 13,
  134356. };
  134357. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134358. -1.5, -0.5, 0.5, 1.5,
  134359. };
  134360. static long _vq_quantmap__44c8_s_p2_0[] = {
  134361. 3, 1, 0, 2, 4,
  134362. };
  134363. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134364. _vq_quantthresh__44c8_s_p2_0,
  134365. _vq_quantmap__44c8_s_p2_0,
  134366. 5,
  134367. 5
  134368. };
  134369. static static_codebook _44c8_s_p2_0 = {
  134370. 4, 625,
  134371. _vq_lengthlist__44c8_s_p2_0,
  134372. 1, -533725184, 1611661312, 3, 0,
  134373. _vq_quantlist__44c8_s_p2_0,
  134374. NULL,
  134375. &_vq_auxt__44c8_s_p2_0,
  134376. NULL,
  134377. 0
  134378. };
  134379. static long _vq_quantlist__44c8_s_p3_0[] = {
  134380. 4,
  134381. 3,
  134382. 5,
  134383. 2,
  134384. 6,
  134385. 1,
  134386. 7,
  134387. 0,
  134388. 8,
  134389. };
  134390. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134391. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134392. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134393. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134394. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134396. 0,
  134397. };
  134398. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134399. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134400. };
  134401. static long _vq_quantmap__44c8_s_p3_0[] = {
  134402. 7, 5, 3, 1, 0, 2, 4, 6,
  134403. 8,
  134404. };
  134405. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134406. _vq_quantthresh__44c8_s_p3_0,
  134407. _vq_quantmap__44c8_s_p3_0,
  134408. 9,
  134409. 9
  134410. };
  134411. static static_codebook _44c8_s_p3_0 = {
  134412. 2, 81,
  134413. _vq_lengthlist__44c8_s_p3_0,
  134414. 1, -531628032, 1611661312, 4, 0,
  134415. _vq_quantlist__44c8_s_p3_0,
  134416. NULL,
  134417. &_vq_auxt__44c8_s_p3_0,
  134418. NULL,
  134419. 0
  134420. };
  134421. static long _vq_quantlist__44c8_s_p4_0[] = {
  134422. 8,
  134423. 7,
  134424. 9,
  134425. 6,
  134426. 10,
  134427. 5,
  134428. 11,
  134429. 4,
  134430. 12,
  134431. 3,
  134432. 13,
  134433. 2,
  134434. 14,
  134435. 1,
  134436. 15,
  134437. 0,
  134438. 16,
  134439. };
  134440. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134441. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134442. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134443. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134444. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134445. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134446. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134447. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134448. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134449. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134450. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134459. 0,
  134460. };
  134461. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134462. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134463. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134464. };
  134465. static long _vq_quantmap__44c8_s_p4_0[] = {
  134466. 15, 13, 11, 9, 7, 5, 3, 1,
  134467. 0, 2, 4, 6, 8, 10, 12, 14,
  134468. 16,
  134469. };
  134470. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134471. _vq_quantthresh__44c8_s_p4_0,
  134472. _vq_quantmap__44c8_s_p4_0,
  134473. 17,
  134474. 17
  134475. };
  134476. static static_codebook _44c8_s_p4_0 = {
  134477. 2, 289,
  134478. _vq_lengthlist__44c8_s_p4_0,
  134479. 1, -529530880, 1611661312, 5, 0,
  134480. _vq_quantlist__44c8_s_p4_0,
  134481. NULL,
  134482. &_vq_auxt__44c8_s_p4_0,
  134483. NULL,
  134484. 0
  134485. };
  134486. static long _vq_quantlist__44c8_s_p5_0[] = {
  134487. 1,
  134488. 0,
  134489. 2,
  134490. };
  134491. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134492. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134493. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134494. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134495. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134496. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134497. 12,
  134498. };
  134499. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134500. -5.5, 5.5,
  134501. };
  134502. static long _vq_quantmap__44c8_s_p5_0[] = {
  134503. 1, 0, 2,
  134504. };
  134505. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134506. _vq_quantthresh__44c8_s_p5_0,
  134507. _vq_quantmap__44c8_s_p5_0,
  134508. 3,
  134509. 3
  134510. };
  134511. static static_codebook _44c8_s_p5_0 = {
  134512. 4, 81,
  134513. _vq_lengthlist__44c8_s_p5_0,
  134514. 1, -529137664, 1618345984, 2, 0,
  134515. _vq_quantlist__44c8_s_p5_0,
  134516. NULL,
  134517. &_vq_auxt__44c8_s_p5_0,
  134518. NULL,
  134519. 0
  134520. };
  134521. static long _vq_quantlist__44c8_s_p5_1[] = {
  134522. 5,
  134523. 4,
  134524. 6,
  134525. 3,
  134526. 7,
  134527. 2,
  134528. 8,
  134529. 1,
  134530. 9,
  134531. 0,
  134532. 10,
  134533. };
  134534. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134535. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134536. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134537. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134538. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134539. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134540. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134541. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134542. 11,11,11, 7, 7, 7, 7, 8, 8,
  134543. };
  134544. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134545. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134546. 3.5, 4.5,
  134547. };
  134548. static long _vq_quantmap__44c8_s_p5_1[] = {
  134549. 9, 7, 5, 3, 1, 0, 2, 4,
  134550. 6, 8, 10,
  134551. };
  134552. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134553. _vq_quantthresh__44c8_s_p5_1,
  134554. _vq_quantmap__44c8_s_p5_1,
  134555. 11,
  134556. 11
  134557. };
  134558. static static_codebook _44c8_s_p5_1 = {
  134559. 2, 121,
  134560. _vq_lengthlist__44c8_s_p5_1,
  134561. 1, -531365888, 1611661312, 4, 0,
  134562. _vq_quantlist__44c8_s_p5_1,
  134563. NULL,
  134564. &_vq_auxt__44c8_s_p5_1,
  134565. NULL,
  134566. 0
  134567. };
  134568. static long _vq_quantlist__44c8_s_p6_0[] = {
  134569. 6,
  134570. 5,
  134571. 7,
  134572. 4,
  134573. 8,
  134574. 3,
  134575. 9,
  134576. 2,
  134577. 10,
  134578. 1,
  134579. 11,
  134580. 0,
  134581. 12,
  134582. };
  134583. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134584. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134585. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134586. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134587. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134588. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134589. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134594. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134595. };
  134596. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134597. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134598. 12.5, 17.5, 22.5, 27.5,
  134599. };
  134600. static long _vq_quantmap__44c8_s_p6_0[] = {
  134601. 11, 9, 7, 5, 3, 1, 0, 2,
  134602. 4, 6, 8, 10, 12,
  134603. };
  134604. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134605. _vq_quantthresh__44c8_s_p6_0,
  134606. _vq_quantmap__44c8_s_p6_0,
  134607. 13,
  134608. 13
  134609. };
  134610. static static_codebook _44c8_s_p6_0 = {
  134611. 2, 169,
  134612. _vq_lengthlist__44c8_s_p6_0,
  134613. 1, -526516224, 1616117760, 4, 0,
  134614. _vq_quantlist__44c8_s_p6_0,
  134615. NULL,
  134616. &_vq_auxt__44c8_s_p6_0,
  134617. NULL,
  134618. 0
  134619. };
  134620. static long _vq_quantlist__44c8_s_p6_1[] = {
  134621. 2,
  134622. 1,
  134623. 3,
  134624. 0,
  134625. 4,
  134626. };
  134627. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134628. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134629. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134630. };
  134631. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134632. -1.5, -0.5, 0.5, 1.5,
  134633. };
  134634. static long _vq_quantmap__44c8_s_p6_1[] = {
  134635. 3, 1, 0, 2, 4,
  134636. };
  134637. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134638. _vq_quantthresh__44c8_s_p6_1,
  134639. _vq_quantmap__44c8_s_p6_1,
  134640. 5,
  134641. 5
  134642. };
  134643. static static_codebook _44c8_s_p6_1 = {
  134644. 2, 25,
  134645. _vq_lengthlist__44c8_s_p6_1,
  134646. 1, -533725184, 1611661312, 3, 0,
  134647. _vq_quantlist__44c8_s_p6_1,
  134648. NULL,
  134649. &_vq_auxt__44c8_s_p6_1,
  134650. NULL,
  134651. 0
  134652. };
  134653. static long _vq_quantlist__44c8_s_p7_0[] = {
  134654. 6,
  134655. 5,
  134656. 7,
  134657. 4,
  134658. 8,
  134659. 3,
  134660. 9,
  134661. 2,
  134662. 10,
  134663. 1,
  134664. 11,
  134665. 0,
  134666. 12,
  134667. };
  134668. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134669. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134670. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134671. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134672. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134673. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134674. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134675. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134676. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134677. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134678. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134679. 20,13,13,13,13,14,13,15,15,
  134680. };
  134681. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134682. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134683. 27.5, 38.5, 49.5, 60.5,
  134684. };
  134685. static long _vq_quantmap__44c8_s_p7_0[] = {
  134686. 11, 9, 7, 5, 3, 1, 0, 2,
  134687. 4, 6, 8, 10, 12,
  134688. };
  134689. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134690. _vq_quantthresh__44c8_s_p7_0,
  134691. _vq_quantmap__44c8_s_p7_0,
  134692. 13,
  134693. 13
  134694. };
  134695. static static_codebook _44c8_s_p7_0 = {
  134696. 2, 169,
  134697. _vq_lengthlist__44c8_s_p7_0,
  134698. 1, -523206656, 1618345984, 4, 0,
  134699. _vq_quantlist__44c8_s_p7_0,
  134700. NULL,
  134701. &_vq_auxt__44c8_s_p7_0,
  134702. NULL,
  134703. 0
  134704. };
  134705. static long _vq_quantlist__44c8_s_p7_1[] = {
  134706. 5,
  134707. 4,
  134708. 6,
  134709. 3,
  134710. 7,
  134711. 2,
  134712. 8,
  134713. 1,
  134714. 9,
  134715. 0,
  134716. 10,
  134717. };
  134718. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134719. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134720. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134721. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134722. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134723. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134724. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134725. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134726. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134727. };
  134728. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134729. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134730. 3.5, 4.5,
  134731. };
  134732. static long _vq_quantmap__44c8_s_p7_1[] = {
  134733. 9, 7, 5, 3, 1, 0, 2, 4,
  134734. 6, 8, 10,
  134735. };
  134736. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134737. _vq_quantthresh__44c8_s_p7_1,
  134738. _vq_quantmap__44c8_s_p7_1,
  134739. 11,
  134740. 11
  134741. };
  134742. static static_codebook _44c8_s_p7_1 = {
  134743. 2, 121,
  134744. _vq_lengthlist__44c8_s_p7_1,
  134745. 1, -531365888, 1611661312, 4, 0,
  134746. _vq_quantlist__44c8_s_p7_1,
  134747. NULL,
  134748. &_vq_auxt__44c8_s_p7_1,
  134749. NULL,
  134750. 0
  134751. };
  134752. static long _vq_quantlist__44c8_s_p8_0[] = {
  134753. 7,
  134754. 6,
  134755. 8,
  134756. 5,
  134757. 9,
  134758. 4,
  134759. 10,
  134760. 3,
  134761. 11,
  134762. 2,
  134763. 12,
  134764. 1,
  134765. 13,
  134766. 0,
  134767. 14,
  134768. };
  134769. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134770. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134771. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134772. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134773. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134774. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134775. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134776. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134777. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134778. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134779. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134780. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134781. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134782. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134783. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134784. 15,
  134785. };
  134786. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134787. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134788. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134789. };
  134790. static long _vq_quantmap__44c8_s_p8_0[] = {
  134791. 13, 11, 9, 7, 5, 3, 1, 0,
  134792. 2, 4, 6, 8, 10, 12, 14,
  134793. };
  134794. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134795. _vq_quantthresh__44c8_s_p8_0,
  134796. _vq_quantmap__44c8_s_p8_0,
  134797. 15,
  134798. 15
  134799. };
  134800. static static_codebook _44c8_s_p8_0 = {
  134801. 2, 225,
  134802. _vq_lengthlist__44c8_s_p8_0,
  134803. 1, -520986624, 1620377600, 4, 0,
  134804. _vq_quantlist__44c8_s_p8_0,
  134805. NULL,
  134806. &_vq_auxt__44c8_s_p8_0,
  134807. NULL,
  134808. 0
  134809. };
  134810. static long _vq_quantlist__44c8_s_p8_1[] = {
  134811. 10,
  134812. 9,
  134813. 11,
  134814. 8,
  134815. 12,
  134816. 7,
  134817. 13,
  134818. 6,
  134819. 14,
  134820. 5,
  134821. 15,
  134822. 4,
  134823. 16,
  134824. 3,
  134825. 17,
  134826. 2,
  134827. 18,
  134828. 1,
  134829. 19,
  134830. 0,
  134831. 20,
  134832. };
  134833. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134834. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134835. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134836. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134837. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134838. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134839. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134840. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134841. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134842. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134843. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134844. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134845. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134846. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134847. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134848. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134849. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134850. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134851. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134852. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134853. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134854. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134856. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134857. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134858. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134859. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134860. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134861. 10, 9, 9,10,10, 9,10, 9, 9,
  134862. };
  134863. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134864. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134865. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134866. 6.5, 7.5, 8.5, 9.5,
  134867. };
  134868. static long _vq_quantmap__44c8_s_p8_1[] = {
  134869. 19, 17, 15, 13, 11, 9, 7, 5,
  134870. 3, 1, 0, 2, 4, 6, 8, 10,
  134871. 12, 14, 16, 18, 20,
  134872. };
  134873. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134874. _vq_quantthresh__44c8_s_p8_1,
  134875. _vq_quantmap__44c8_s_p8_1,
  134876. 21,
  134877. 21
  134878. };
  134879. static static_codebook _44c8_s_p8_1 = {
  134880. 2, 441,
  134881. _vq_lengthlist__44c8_s_p8_1,
  134882. 1, -529268736, 1611661312, 5, 0,
  134883. _vq_quantlist__44c8_s_p8_1,
  134884. NULL,
  134885. &_vq_auxt__44c8_s_p8_1,
  134886. NULL,
  134887. 0
  134888. };
  134889. static long _vq_quantlist__44c8_s_p9_0[] = {
  134890. 8,
  134891. 7,
  134892. 9,
  134893. 6,
  134894. 10,
  134895. 5,
  134896. 11,
  134897. 4,
  134898. 12,
  134899. 3,
  134900. 13,
  134901. 2,
  134902. 14,
  134903. 1,
  134904. 15,
  134905. 0,
  134906. 16,
  134907. };
  134908. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134909. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134910. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134911. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134915. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134921. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134923. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134924. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134925. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134926. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134927. 10,
  134928. };
  134929. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134930. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134931. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134932. };
  134933. static long _vq_quantmap__44c8_s_p9_0[] = {
  134934. 15, 13, 11, 9, 7, 5, 3, 1,
  134935. 0, 2, 4, 6, 8, 10, 12, 14,
  134936. 16,
  134937. };
  134938. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134939. _vq_quantthresh__44c8_s_p9_0,
  134940. _vq_quantmap__44c8_s_p9_0,
  134941. 17,
  134942. 17
  134943. };
  134944. static static_codebook _44c8_s_p9_0 = {
  134945. 2, 289,
  134946. _vq_lengthlist__44c8_s_p9_0,
  134947. 1, -509798400, 1631393792, 5, 0,
  134948. _vq_quantlist__44c8_s_p9_0,
  134949. NULL,
  134950. &_vq_auxt__44c8_s_p9_0,
  134951. NULL,
  134952. 0
  134953. };
  134954. static long _vq_quantlist__44c8_s_p9_1[] = {
  134955. 9,
  134956. 8,
  134957. 10,
  134958. 7,
  134959. 11,
  134960. 6,
  134961. 12,
  134962. 5,
  134963. 13,
  134964. 4,
  134965. 14,
  134966. 3,
  134967. 15,
  134968. 2,
  134969. 16,
  134970. 1,
  134971. 17,
  134972. 0,
  134973. 18,
  134974. };
  134975. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134976. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134977. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134978. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134979. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134980. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134981. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134982. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134983. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134984. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134985. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134986. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134987. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134988. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134989. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134990. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134991. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134992. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134993. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134994. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134995. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134996. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134997. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134998. 14,13,13,14,14,15,14,15,14,
  134999. };
  135000. static float _vq_quantthresh__44c8_s_p9_1[] = {
  135001. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135002. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135003. 367.5, 416.5,
  135004. };
  135005. static long _vq_quantmap__44c8_s_p9_1[] = {
  135006. 17, 15, 13, 11, 9, 7, 5, 3,
  135007. 1, 0, 2, 4, 6, 8, 10, 12,
  135008. 14, 16, 18,
  135009. };
  135010. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  135011. _vq_quantthresh__44c8_s_p9_1,
  135012. _vq_quantmap__44c8_s_p9_1,
  135013. 19,
  135014. 19
  135015. };
  135016. static static_codebook _44c8_s_p9_1 = {
  135017. 2, 361,
  135018. _vq_lengthlist__44c8_s_p9_1,
  135019. 1, -518287360, 1622704128, 5, 0,
  135020. _vq_quantlist__44c8_s_p9_1,
  135021. NULL,
  135022. &_vq_auxt__44c8_s_p9_1,
  135023. NULL,
  135024. 0
  135025. };
  135026. static long _vq_quantlist__44c8_s_p9_2[] = {
  135027. 24,
  135028. 23,
  135029. 25,
  135030. 22,
  135031. 26,
  135032. 21,
  135033. 27,
  135034. 20,
  135035. 28,
  135036. 19,
  135037. 29,
  135038. 18,
  135039. 30,
  135040. 17,
  135041. 31,
  135042. 16,
  135043. 32,
  135044. 15,
  135045. 33,
  135046. 14,
  135047. 34,
  135048. 13,
  135049. 35,
  135050. 12,
  135051. 36,
  135052. 11,
  135053. 37,
  135054. 10,
  135055. 38,
  135056. 9,
  135057. 39,
  135058. 8,
  135059. 40,
  135060. 7,
  135061. 41,
  135062. 6,
  135063. 42,
  135064. 5,
  135065. 43,
  135066. 4,
  135067. 44,
  135068. 3,
  135069. 45,
  135070. 2,
  135071. 46,
  135072. 1,
  135073. 47,
  135074. 0,
  135075. 48,
  135076. };
  135077. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135078. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135079. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135080. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135081. 7,
  135082. };
  135083. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135084. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135085. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135086. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135087. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135088. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135089. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135090. };
  135091. static long _vq_quantmap__44c8_s_p9_2[] = {
  135092. 47, 45, 43, 41, 39, 37, 35, 33,
  135093. 31, 29, 27, 25, 23, 21, 19, 17,
  135094. 15, 13, 11, 9, 7, 5, 3, 1,
  135095. 0, 2, 4, 6, 8, 10, 12, 14,
  135096. 16, 18, 20, 22, 24, 26, 28, 30,
  135097. 32, 34, 36, 38, 40, 42, 44, 46,
  135098. 48,
  135099. };
  135100. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135101. _vq_quantthresh__44c8_s_p9_2,
  135102. _vq_quantmap__44c8_s_p9_2,
  135103. 49,
  135104. 49
  135105. };
  135106. static static_codebook _44c8_s_p9_2 = {
  135107. 1, 49,
  135108. _vq_lengthlist__44c8_s_p9_2,
  135109. 1, -526909440, 1611661312, 6, 0,
  135110. _vq_quantlist__44c8_s_p9_2,
  135111. NULL,
  135112. &_vq_auxt__44c8_s_p9_2,
  135113. NULL,
  135114. 0
  135115. };
  135116. static long _huff_lengthlist__44c8_s_short[] = {
  135117. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135118. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135119. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135120. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135121. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135122. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135123. 10, 9,11,14,
  135124. };
  135125. static static_codebook _huff_book__44c8_s_short = {
  135126. 2, 100,
  135127. _huff_lengthlist__44c8_s_short,
  135128. 0, 0, 0, 0, 0,
  135129. NULL,
  135130. NULL,
  135131. NULL,
  135132. NULL,
  135133. 0
  135134. };
  135135. static long _huff_lengthlist__44c9_s_long[] = {
  135136. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135137. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135138. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135139. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135140. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135141. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135142. 10, 9, 8, 9,
  135143. };
  135144. static static_codebook _huff_book__44c9_s_long = {
  135145. 2, 100,
  135146. _huff_lengthlist__44c9_s_long,
  135147. 0, 0, 0, 0, 0,
  135148. NULL,
  135149. NULL,
  135150. NULL,
  135151. NULL,
  135152. 0
  135153. };
  135154. static long _vq_quantlist__44c9_s_p1_0[] = {
  135155. 1,
  135156. 0,
  135157. 2,
  135158. };
  135159. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135160. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135161. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135163. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135164. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135165. 7,
  135166. };
  135167. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135168. -0.5, 0.5,
  135169. };
  135170. static long _vq_quantmap__44c9_s_p1_0[] = {
  135171. 1, 0, 2,
  135172. };
  135173. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135174. _vq_quantthresh__44c9_s_p1_0,
  135175. _vq_quantmap__44c9_s_p1_0,
  135176. 3,
  135177. 3
  135178. };
  135179. static static_codebook _44c9_s_p1_0 = {
  135180. 4, 81,
  135181. _vq_lengthlist__44c9_s_p1_0,
  135182. 1, -535822336, 1611661312, 2, 0,
  135183. _vq_quantlist__44c9_s_p1_0,
  135184. NULL,
  135185. &_vq_auxt__44c9_s_p1_0,
  135186. NULL,
  135187. 0
  135188. };
  135189. static long _vq_quantlist__44c9_s_p2_0[] = {
  135190. 2,
  135191. 1,
  135192. 3,
  135193. 0,
  135194. 4,
  135195. };
  135196. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135197. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135198. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135199. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135200. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135201. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135202. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135203. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135204. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 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, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135207. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135208. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135209. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135210. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135211. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135212. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135215. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135216. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135217. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135218. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135219. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135220. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135223. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135224. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135225. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135226. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135227. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135228. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135233. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135234. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135235. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135236. 12,
  135237. };
  135238. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135239. -1.5, -0.5, 0.5, 1.5,
  135240. };
  135241. static long _vq_quantmap__44c9_s_p2_0[] = {
  135242. 3, 1, 0, 2, 4,
  135243. };
  135244. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135245. _vq_quantthresh__44c9_s_p2_0,
  135246. _vq_quantmap__44c9_s_p2_0,
  135247. 5,
  135248. 5
  135249. };
  135250. static static_codebook _44c9_s_p2_0 = {
  135251. 4, 625,
  135252. _vq_lengthlist__44c9_s_p2_0,
  135253. 1, -533725184, 1611661312, 3, 0,
  135254. _vq_quantlist__44c9_s_p2_0,
  135255. NULL,
  135256. &_vq_auxt__44c9_s_p2_0,
  135257. NULL,
  135258. 0
  135259. };
  135260. static long _vq_quantlist__44c9_s_p3_0[] = {
  135261. 4,
  135262. 3,
  135263. 5,
  135264. 2,
  135265. 6,
  135266. 1,
  135267. 7,
  135268. 0,
  135269. 8,
  135270. };
  135271. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135272. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135273. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135274. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135275. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0,
  135278. };
  135279. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135280. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135281. };
  135282. static long _vq_quantmap__44c9_s_p3_0[] = {
  135283. 7, 5, 3, 1, 0, 2, 4, 6,
  135284. 8,
  135285. };
  135286. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135287. _vq_quantthresh__44c9_s_p3_0,
  135288. _vq_quantmap__44c9_s_p3_0,
  135289. 9,
  135290. 9
  135291. };
  135292. static static_codebook _44c9_s_p3_0 = {
  135293. 2, 81,
  135294. _vq_lengthlist__44c9_s_p3_0,
  135295. 1, -531628032, 1611661312, 4, 0,
  135296. _vq_quantlist__44c9_s_p3_0,
  135297. NULL,
  135298. &_vq_auxt__44c9_s_p3_0,
  135299. NULL,
  135300. 0
  135301. };
  135302. static long _vq_quantlist__44c9_s_p4_0[] = {
  135303. 8,
  135304. 7,
  135305. 9,
  135306. 6,
  135307. 10,
  135308. 5,
  135309. 11,
  135310. 4,
  135311. 12,
  135312. 3,
  135313. 13,
  135314. 2,
  135315. 14,
  135316. 1,
  135317. 15,
  135318. 0,
  135319. 16,
  135320. };
  135321. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135322. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135323. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135324. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135325. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135326. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135327. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135328. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135329. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135330. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135331. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0,
  135341. };
  135342. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135343. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135344. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135345. };
  135346. static long _vq_quantmap__44c9_s_p4_0[] = {
  135347. 15, 13, 11, 9, 7, 5, 3, 1,
  135348. 0, 2, 4, 6, 8, 10, 12, 14,
  135349. 16,
  135350. };
  135351. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135352. _vq_quantthresh__44c9_s_p4_0,
  135353. _vq_quantmap__44c9_s_p4_0,
  135354. 17,
  135355. 17
  135356. };
  135357. static static_codebook _44c9_s_p4_0 = {
  135358. 2, 289,
  135359. _vq_lengthlist__44c9_s_p4_0,
  135360. 1, -529530880, 1611661312, 5, 0,
  135361. _vq_quantlist__44c9_s_p4_0,
  135362. NULL,
  135363. &_vq_auxt__44c9_s_p4_0,
  135364. NULL,
  135365. 0
  135366. };
  135367. static long _vq_quantlist__44c9_s_p5_0[] = {
  135368. 1,
  135369. 0,
  135370. 2,
  135371. };
  135372. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135373. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135374. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135375. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135376. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135377. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135378. 12,
  135379. };
  135380. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135381. -5.5, 5.5,
  135382. };
  135383. static long _vq_quantmap__44c9_s_p5_0[] = {
  135384. 1, 0, 2,
  135385. };
  135386. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135387. _vq_quantthresh__44c9_s_p5_0,
  135388. _vq_quantmap__44c9_s_p5_0,
  135389. 3,
  135390. 3
  135391. };
  135392. static static_codebook _44c9_s_p5_0 = {
  135393. 4, 81,
  135394. _vq_lengthlist__44c9_s_p5_0,
  135395. 1, -529137664, 1618345984, 2, 0,
  135396. _vq_quantlist__44c9_s_p5_0,
  135397. NULL,
  135398. &_vq_auxt__44c9_s_p5_0,
  135399. NULL,
  135400. 0
  135401. };
  135402. static long _vq_quantlist__44c9_s_p5_1[] = {
  135403. 5,
  135404. 4,
  135405. 6,
  135406. 3,
  135407. 7,
  135408. 2,
  135409. 8,
  135410. 1,
  135411. 9,
  135412. 0,
  135413. 10,
  135414. };
  135415. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135416. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135417. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135418. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135419. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135420. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135421. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135422. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135423. 11,11,11, 7, 7, 7, 7, 7, 7,
  135424. };
  135425. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135426. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135427. 3.5, 4.5,
  135428. };
  135429. static long _vq_quantmap__44c9_s_p5_1[] = {
  135430. 9, 7, 5, 3, 1, 0, 2, 4,
  135431. 6, 8, 10,
  135432. };
  135433. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135434. _vq_quantthresh__44c9_s_p5_1,
  135435. _vq_quantmap__44c9_s_p5_1,
  135436. 11,
  135437. 11
  135438. };
  135439. static static_codebook _44c9_s_p5_1 = {
  135440. 2, 121,
  135441. _vq_lengthlist__44c9_s_p5_1,
  135442. 1, -531365888, 1611661312, 4, 0,
  135443. _vq_quantlist__44c9_s_p5_1,
  135444. NULL,
  135445. &_vq_auxt__44c9_s_p5_1,
  135446. NULL,
  135447. 0
  135448. };
  135449. static long _vq_quantlist__44c9_s_p6_0[] = {
  135450. 6,
  135451. 5,
  135452. 7,
  135453. 4,
  135454. 8,
  135455. 3,
  135456. 9,
  135457. 2,
  135458. 10,
  135459. 1,
  135460. 11,
  135461. 0,
  135462. 12,
  135463. };
  135464. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135465. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135466. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135467. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135468. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135469. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135470. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. };
  135477. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135478. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135479. 12.5, 17.5, 22.5, 27.5,
  135480. };
  135481. static long _vq_quantmap__44c9_s_p6_0[] = {
  135482. 11, 9, 7, 5, 3, 1, 0, 2,
  135483. 4, 6, 8, 10, 12,
  135484. };
  135485. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135486. _vq_quantthresh__44c9_s_p6_0,
  135487. _vq_quantmap__44c9_s_p6_0,
  135488. 13,
  135489. 13
  135490. };
  135491. static static_codebook _44c9_s_p6_0 = {
  135492. 2, 169,
  135493. _vq_lengthlist__44c9_s_p6_0,
  135494. 1, -526516224, 1616117760, 4, 0,
  135495. _vq_quantlist__44c9_s_p6_0,
  135496. NULL,
  135497. &_vq_auxt__44c9_s_p6_0,
  135498. NULL,
  135499. 0
  135500. };
  135501. static long _vq_quantlist__44c9_s_p6_1[] = {
  135502. 2,
  135503. 1,
  135504. 3,
  135505. 0,
  135506. 4,
  135507. };
  135508. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135509. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135510. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135511. };
  135512. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135513. -1.5, -0.5, 0.5, 1.5,
  135514. };
  135515. static long _vq_quantmap__44c9_s_p6_1[] = {
  135516. 3, 1, 0, 2, 4,
  135517. };
  135518. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135519. _vq_quantthresh__44c9_s_p6_1,
  135520. _vq_quantmap__44c9_s_p6_1,
  135521. 5,
  135522. 5
  135523. };
  135524. static static_codebook _44c9_s_p6_1 = {
  135525. 2, 25,
  135526. _vq_lengthlist__44c9_s_p6_1,
  135527. 1, -533725184, 1611661312, 3, 0,
  135528. _vq_quantlist__44c9_s_p6_1,
  135529. NULL,
  135530. &_vq_auxt__44c9_s_p6_1,
  135531. NULL,
  135532. 0
  135533. };
  135534. static long _vq_quantlist__44c9_s_p7_0[] = {
  135535. 6,
  135536. 5,
  135537. 7,
  135538. 4,
  135539. 8,
  135540. 3,
  135541. 9,
  135542. 2,
  135543. 10,
  135544. 1,
  135545. 11,
  135546. 0,
  135547. 12,
  135548. };
  135549. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135550. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135551. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135552. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135553. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135554. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135555. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135556. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135557. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135558. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135559. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135560. 19,12,12,12,12,13,13,14,14,
  135561. };
  135562. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135563. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135564. 27.5, 38.5, 49.5, 60.5,
  135565. };
  135566. static long _vq_quantmap__44c9_s_p7_0[] = {
  135567. 11, 9, 7, 5, 3, 1, 0, 2,
  135568. 4, 6, 8, 10, 12,
  135569. };
  135570. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135571. _vq_quantthresh__44c9_s_p7_0,
  135572. _vq_quantmap__44c9_s_p7_0,
  135573. 13,
  135574. 13
  135575. };
  135576. static static_codebook _44c9_s_p7_0 = {
  135577. 2, 169,
  135578. _vq_lengthlist__44c9_s_p7_0,
  135579. 1, -523206656, 1618345984, 4, 0,
  135580. _vq_quantlist__44c9_s_p7_0,
  135581. NULL,
  135582. &_vq_auxt__44c9_s_p7_0,
  135583. NULL,
  135584. 0
  135585. };
  135586. static long _vq_quantlist__44c9_s_p7_1[] = {
  135587. 5,
  135588. 4,
  135589. 6,
  135590. 3,
  135591. 7,
  135592. 2,
  135593. 8,
  135594. 1,
  135595. 9,
  135596. 0,
  135597. 10,
  135598. };
  135599. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135600. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135601. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135602. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135603. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135604. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135605. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135606. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135607. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135608. };
  135609. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135610. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135611. 3.5, 4.5,
  135612. };
  135613. static long _vq_quantmap__44c9_s_p7_1[] = {
  135614. 9, 7, 5, 3, 1, 0, 2, 4,
  135615. 6, 8, 10,
  135616. };
  135617. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135618. _vq_quantthresh__44c9_s_p7_1,
  135619. _vq_quantmap__44c9_s_p7_1,
  135620. 11,
  135621. 11
  135622. };
  135623. static static_codebook _44c9_s_p7_1 = {
  135624. 2, 121,
  135625. _vq_lengthlist__44c9_s_p7_1,
  135626. 1, -531365888, 1611661312, 4, 0,
  135627. _vq_quantlist__44c9_s_p7_1,
  135628. NULL,
  135629. &_vq_auxt__44c9_s_p7_1,
  135630. NULL,
  135631. 0
  135632. };
  135633. static long _vq_quantlist__44c9_s_p8_0[] = {
  135634. 7,
  135635. 6,
  135636. 8,
  135637. 5,
  135638. 9,
  135639. 4,
  135640. 10,
  135641. 3,
  135642. 11,
  135643. 2,
  135644. 12,
  135645. 1,
  135646. 13,
  135647. 0,
  135648. 14,
  135649. };
  135650. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135651. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135652. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135653. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135654. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135655. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135656. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135657. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135658. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135659. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135660. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135661. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135662. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135663. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135664. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135665. 14,
  135666. };
  135667. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135668. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135669. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135670. };
  135671. static long _vq_quantmap__44c9_s_p8_0[] = {
  135672. 13, 11, 9, 7, 5, 3, 1, 0,
  135673. 2, 4, 6, 8, 10, 12, 14,
  135674. };
  135675. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135676. _vq_quantthresh__44c9_s_p8_0,
  135677. _vq_quantmap__44c9_s_p8_0,
  135678. 15,
  135679. 15
  135680. };
  135681. static static_codebook _44c9_s_p8_0 = {
  135682. 2, 225,
  135683. _vq_lengthlist__44c9_s_p8_0,
  135684. 1, -520986624, 1620377600, 4, 0,
  135685. _vq_quantlist__44c9_s_p8_0,
  135686. NULL,
  135687. &_vq_auxt__44c9_s_p8_0,
  135688. NULL,
  135689. 0
  135690. };
  135691. static long _vq_quantlist__44c9_s_p8_1[] = {
  135692. 10,
  135693. 9,
  135694. 11,
  135695. 8,
  135696. 12,
  135697. 7,
  135698. 13,
  135699. 6,
  135700. 14,
  135701. 5,
  135702. 15,
  135703. 4,
  135704. 16,
  135705. 3,
  135706. 17,
  135707. 2,
  135708. 18,
  135709. 1,
  135710. 19,
  135711. 0,
  135712. 20,
  135713. };
  135714. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135715. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135716. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135717. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135718. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135719. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135720. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135721. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135722. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135723. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135724. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135725. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135726. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135727. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135728. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135729. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135730. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135731. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135732. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135733. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135734. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135735. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135736. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135737. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135738. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135739. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135740. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135741. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135742. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135743. };
  135744. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135745. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135746. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135747. 6.5, 7.5, 8.5, 9.5,
  135748. };
  135749. static long _vq_quantmap__44c9_s_p8_1[] = {
  135750. 19, 17, 15, 13, 11, 9, 7, 5,
  135751. 3, 1, 0, 2, 4, 6, 8, 10,
  135752. 12, 14, 16, 18, 20,
  135753. };
  135754. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135755. _vq_quantthresh__44c9_s_p8_1,
  135756. _vq_quantmap__44c9_s_p8_1,
  135757. 21,
  135758. 21
  135759. };
  135760. static static_codebook _44c9_s_p8_1 = {
  135761. 2, 441,
  135762. _vq_lengthlist__44c9_s_p8_1,
  135763. 1, -529268736, 1611661312, 5, 0,
  135764. _vq_quantlist__44c9_s_p8_1,
  135765. NULL,
  135766. &_vq_auxt__44c9_s_p8_1,
  135767. NULL,
  135768. 0
  135769. };
  135770. static long _vq_quantlist__44c9_s_p9_0[] = {
  135771. 9,
  135772. 8,
  135773. 10,
  135774. 7,
  135775. 11,
  135776. 6,
  135777. 12,
  135778. 5,
  135779. 13,
  135780. 4,
  135781. 14,
  135782. 3,
  135783. 15,
  135784. 2,
  135785. 16,
  135786. 1,
  135787. 17,
  135788. 0,
  135789. 18,
  135790. };
  135791. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135792. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135793. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135794. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135795. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135796. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135797. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135798. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135799. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135800. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135801. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135802. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135803. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135804. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135805. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135806. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135807. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135808. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135810. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135814. 11,11,11,11,11,11,11,11,11,
  135815. };
  135816. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135817. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135818. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135819. 6982.5, 7913.5,
  135820. };
  135821. static long _vq_quantmap__44c9_s_p9_0[] = {
  135822. 17, 15, 13, 11, 9, 7, 5, 3,
  135823. 1, 0, 2, 4, 6, 8, 10, 12,
  135824. 14, 16, 18,
  135825. };
  135826. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135827. _vq_quantthresh__44c9_s_p9_0,
  135828. _vq_quantmap__44c9_s_p9_0,
  135829. 19,
  135830. 19
  135831. };
  135832. static static_codebook _44c9_s_p9_0 = {
  135833. 2, 361,
  135834. _vq_lengthlist__44c9_s_p9_0,
  135835. 1, -508535424, 1631393792, 5, 0,
  135836. _vq_quantlist__44c9_s_p9_0,
  135837. NULL,
  135838. &_vq_auxt__44c9_s_p9_0,
  135839. NULL,
  135840. 0
  135841. };
  135842. static long _vq_quantlist__44c9_s_p9_1[] = {
  135843. 9,
  135844. 8,
  135845. 10,
  135846. 7,
  135847. 11,
  135848. 6,
  135849. 12,
  135850. 5,
  135851. 13,
  135852. 4,
  135853. 14,
  135854. 3,
  135855. 15,
  135856. 2,
  135857. 16,
  135858. 1,
  135859. 17,
  135860. 0,
  135861. 18,
  135862. };
  135863. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135864. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135865. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135866. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135867. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135868. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135869. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135870. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135871. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135872. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135873. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135874. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135875. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135876. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135877. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135878. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135879. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135880. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135881. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135882. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135883. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135884. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135885. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135886. 13,13,13,14,13,14,15,15,15,
  135887. };
  135888. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135889. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135890. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135891. 367.5, 416.5,
  135892. };
  135893. static long _vq_quantmap__44c9_s_p9_1[] = {
  135894. 17, 15, 13, 11, 9, 7, 5, 3,
  135895. 1, 0, 2, 4, 6, 8, 10, 12,
  135896. 14, 16, 18,
  135897. };
  135898. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135899. _vq_quantthresh__44c9_s_p9_1,
  135900. _vq_quantmap__44c9_s_p9_1,
  135901. 19,
  135902. 19
  135903. };
  135904. static static_codebook _44c9_s_p9_1 = {
  135905. 2, 361,
  135906. _vq_lengthlist__44c9_s_p9_1,
  135907. 1, -518287360, 1622704128, 5, 0,
  135908. _vq_quantlist__44c9_s_p9_1,
  135909. NULL,
  135910. &_vq_auxt__44c9_s_p9_1,
  135911. NULL,
  135912. 0
  135913. };
  135914. static long _vq_quantlist__44c9_s_p9_2[] = {
  135915. 24,
  135916. 23,
  135917. 25,
  135918. 22,
  135919. 26,
  135920. 21,
  135921. 27,
  135922. 20,
  135923. 28,
  135924. 19,
  135925. 29,
  135926. 18,
  135927. 30,
  135928. 17,
  135929. 31,
  135930. 16,
  135931. 32,
  135932. 15,
  135933. 33,
  135934. 14,
  135935. 34,
  135936. 13,
  135937. 35,
  135938. 12,
  135939. 36,
  135940. 11,
  135941. 37,
  135942. 10,
  135943. 38,
  135944. 9,
  135945. 39,
  135946. 8,
  135947. 40,
  135948. 7,
  135949. 41,
  135950. 6,
  135951. 42,
  135952. 5,
  135953. 43,
  135954. 4,
  135955. 44,
  135956. 3,
  135957. 45,
  135958. 2,
  135959. 46,
  135960. 1,
  135961. 47,
  135962. 0,
  135963. 48,
  135964. };
  135965. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135966. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135967. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135968. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135969. 7,
  135970. };
  135971. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135972. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135973. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135974. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135975. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135976. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135977. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135978. };
  135979. static long _vq_quantmap__44c9_s_p9_2[] = {
  135980. 47, 45, 43, 41, 39, 37, 35, 33,
  135981. 31, 29, 27, 25, 23, 21, 19, 17,
  135982. 15, 13, 11, 9, 7, 5, 3, 1,
  135983. 0, 2, 4, 6, 8, 10, 12, 14,
  135984. 16, 18, 20, 22, 24, 26, 28, 30,
  135985. 32, 34, 36, 38, 40, 42, 44, 46,
  135986. 48,
  135987. };
  135988. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135989. _vq_quantthresh__44c9_s_p9_2,
  135990. _vq_quantmap__44c9_s_p9_2,
  135991. 49,
  135992. 49
  135993. };
  135994. static static_codebook _44c9_s_p9_2 = {
  135995. 1, 49,
  135996. _vq_lengthlist__44c9_s_p9_2,
  135997. 1, -526909440, 1611661312, 6, 0,
  135998. _vq_quantlist__44c9_s_p9_2,
  135999. NULL,
  136000. &_vq_auxt__44c9_s_p9_2,
  136001. NULL,
  136002. 0
  136003. };
  136004. static long _huff_lengthlist__44c9_s_short[] = {
  136005. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  136006. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  136007. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  136008. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  136009. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  136010. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  136011. 9, 8,10,13,
  136012. };
  136013. static static_codebook _huff_book__44c9_s_short = {
  136014. 2, 100,
  136015. _huff_lengthlist__44c9_s_short,
  136016. 0, 0, 0, 0, 0,
  136017. NULL,
  136018. NULL,
  136019. NULL,
  136020. NULL,
  136021. 0
  136022. };
  136023. static long _huff_lengthlist__44c0_s_long[] = {
  136024. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  136025. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  136026. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  136027. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  136028. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  136029. 12,
  136030. };
  136031. static static_codebook _huff_book__44c0_s_long = {
  136032. 2, 81,
  136033. _huff_lengthlist__44c0_s_long,
  136034. 0, 0, 0, 0, 0,
  136035. NULL,
  136036. NULL,
  136037. NULL,
  136038. NULL,
  136039. 0
  136040. };
  136041. static long _vq_quantlist__44c0_s_p1_0[] = {
  136042. 1,
  136043. 0,
  136044. 2,
  136045. };
  136046. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136047. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136048. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136053. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136058. 0, 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0,
  136093. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136098. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  136103. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136139. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136144. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136149. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0,
  136458. };
  136459. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136460. -0.5, 0.5,
  136461. };
  136462. static long _vq_quantmap__44c0_s_p1_0[] = {
  136463. 1, 0, 2,
  136464. };
  136465. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136466. _vq_quantthresh__44c0_s_p1_0,
  136467. _vq_quantmap__44c0_s_p1_0,
  136468. 3,
  136469. 3
  136470. };
  136471. static static_codebook _44c0_s_p1_0 = {
  136472. 8, 6561,
  136473. _vq_lengthlist__44c0_s_p1_0,
  136474. 1, -535822336, 1611661312, 2, 0,
  136475. _vq_quantlist__44c0_s_p1_0,
  136476. NULL,
  136477. &_vq_auxt__44c0_s_p1_0,
  136478. NULL,
  136479. 0
  136480. };
  136481. static long _vq_quantlist__44c0_s_p2_0[] = {
  136482. 2,
  136483. 1,
  136484. 3,
  136485. 0,
  136486. 4,
  136487. };
  136488. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136489. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0,
  136529. };
  136530. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136531. -1.5, -0.5, 0.5, 1.5,
  136532. };
  136533. static long _vq_quantmap__44c0_s_p2_0[] = {
  136534. 3, 1, 0, 2, 4,
  136535. };
  136536. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136537. _vq_quantthresh__44c0_s_p2_0,
  136538. _vq_quantmap__44c0_s_p2_0,
  136539. 5,
  136540. 5
  136541. };
  136542. static static_codebook _44c0_s_p2_0 = {
  136543. 4, 625,
  136544. _vq_lengthlist__44c0_s_p2_0,
  136545. 1, -533725184, 1611661312, 3, 0,
  136546. _vq_quantlist__44c0_s_p2_0,
  136547. NULL,
  136548. &_vq_auxt__44c0_s_p2_0,
  136549. NULL,
  136550. 0
  136551. };
  136552. static long _vq_quantlist__44c0_s_p3_0[] = {
  136553. 4,
  136554. 3,
  136555. 5,
  136556. 2,
  136557. 6,
  136558. 1,
  136559. 7,
  136560. 0,
  136561. 8,
  136562. };
  136563. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136564. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136565. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136566. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136567. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136568. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0,
  136570. };
  136571. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136572. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136573. };
  136574. static long _vq_quantmap__44c0_s_p3_0[] = {
  136575. 7, 5, 3, 1, 0, 2, 4, 6,
  136576. 8,
  136577. };
  136578. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136579. _vq_quantthresh__44c0_s_p3_0,
  136580. _vq_quantmap__44c0_s_p3_0,
  136581. 9,
  136582. 9
  136583. };
  136584. static static_codebook _44c0_s_p3_0 = {
  136585. 2, 81,
  136586. _vq_lengthlist__44c0_s_p3_0,
  136587. 1, -531628032, 1611661312, 4, 0,
  136588. _vq_quantlist__44c0_s_p3_0,
  136589. NULL,
  136590. &_vq_auxt__44c0_s_p3_0,
  136591. NULL,
  136592. 0
  136593. };
  136594. static long _vq_quantlist__44c0_s_p4_0[] = {
  136595. 4,
  136596. 3,
  136597. 5,
  136598. 2,
  136599. 6,
  136600. 1,
  136601. 7,
  136602. 0,
  136603. 8,
  136604. };
  136605. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136606. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136607. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136608. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136609. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136610. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136611. 10,
  136612. };
  136613. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136614. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136615. };
  136616. static long _vq_quantmap__44c0_s_p4_0[] = {
  136617. 7, 5, 3, 1, 0, 2, 4, 6,
  136618. 8,
  136619. };
  136620. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136621. _vq_quantthresh__44c0_s_p4_0,
  136622. _vq_quantmap__44c0_s_p4_0,
  136623. 9,
  136624. 9
  136625. };
  136626. static static_codebook _44c0_s_p4_0 = {
  136627. 2, 81,
  136628. _vq_lengthlist__44c0_s_p4_0,
  136629. 1, -531628032, 1611661312, 4, 0,
  136630. _vq_quantlist__44c0_s_p4_0,
  136631. NULL,
  136632. &_vq_auxt__44c0_s_p4_0,
  136633. NULL,
  136634. 0
  136635. };
  136636. static long _vq_quantlist__44c0_s_p5_0[] = {
  136637. 8,
  136638. 7,
  136639. 9,
  136640. 6,
  136641. 10,
  136642. 5,
  136643. 11,
  136644. 4,
  136645. 12,
  136646. 3,
  136647. 13,
  136648. 2,
  136649. 14,
  136650. 1,
  136651. 15,
  136652. 0,
  136653. 16,
  136654. };
  136655. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136656. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136657. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136658. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136659. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136660. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136661. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136662. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136663. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136664. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136665. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136666. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136667. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136668. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136669. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136670. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136671. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136672. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136674. 14,
  136675. };
  136676. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136677. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136678. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136679. };
  136680. static long _vq_quantmap__44c0_s_p5_0[] = {
  136681. 15, 13, 11, 9, 7, 5, 3, 1,
  136682. 0, 2, 4, 6, 8, 10, 12, 14,
  136683. 16,
  136684. };
  136685. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136686. _vq_quantthresh__44c0_s_p5_0,
  136687. _vq_quantmap__44c0_s_p5_0,
  136688. 17,
  136689. 17
  136690. };
  136691. static static_codebook _44c0_s_p5_0 = {
  136692. 2, 289,
  136693. _vq_lengthlist__44c0_s_p5_0,
  136694. 1, -529530880, 1611661312, 5, 0,
  136695. _vq_quantlist__44c0_s_p5_0,
  136696. NULL,
  136697. &_vq_auxt__44c0_s_p5_0,
  136698. NULL,
  136699. 0
  136700. };
  136701. static long _vq_quantlist__44c0_s_p6_0[] = {
  136702. 1,
  136703. 0,
  136704. 2,
  136705. };
  136706. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136707. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136708. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136709. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136710. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136711. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136712. 10,
  136713. };
  136714. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136715. -5.5, 5.5,
  136716. };
  136717. static long _vq_quantmap__44c0_s_p6_0[] = {
  136718. 1, 0, 2,
  136719. };
  136720. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136721. _vq_quantthresh__44c0_s_p6_0,
  136722. _vq_quantmap__44c0_s_p6_0,
  136723. 3,
  136724. 3
  136725. };
  136726. static static_codebook _44c0_s_p6_0 = {
  136727. 4, 81,
  136728. _vq_lengthlist__44c0_s_p6_0,
  136729. 1, -529137664, 1618345984, 2, 0,
  136730. _vq_quantlist__44c0_s_p6_0,
  136731. NULL,
  136732. &_vq_auxt__44c0_s_p6_0,
  136733. NULL,
  136734. 0
  136735. };
  136736. static long _vq_quantlist__44c0_s_p6_1[] = {
  136737. 5,
  136738. 4,
  136739. 6,
  136740. 3,
  136741. 7,
  136742. 2,
  136743. 8,
  136744. 1,
  136745. 9,
  136746. 0,
  136747. 10,
  136748. };
  136749. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136750. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136751. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136752. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136753. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136754. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136755. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136756. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136757. 10,10,10, 8, 8, 8, 8, 8, 8,
  136758. };
  136759. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136760. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136761. 3.5, 4.5,
  136762. };
  136763. static long _vq_quantmap__44c0_s_p6_1[] = {
  136764. 9, 7, 5, 3, 1, 0, 2, 4,
  136765. 6, 8, 10,
  136766. };
  136767. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136768. _vq_quantthresh__44c0_s_p6_1,
  136769. _vq_quantmap__44c0_s_p6_1,
  136770. 11,
  136771. 11
  136772. };
  136773. static static_codebook _44c0_s_p6_1 = {
  136774. 2, 121,
  136775. _vq_lengthlist__44c0_s_p6_1,
  136776. 1, -531365888, 1611661312, 4, 0,
  136777. _vq_quantlist__44c0_s_p6_1,
  136778. NULL,
  136779. &_vq_auxt__44c0_s_p6_1,
  136780. NULL,
  136781. 0
  136782. };
  136783. static long _vq_quantlist__44c0_s_p7_0[] = {
  136784. 6,
  136785. 5,
  136786. 7,
  136787. 4,
  136788. 8,
  136789. 3,
  136790. 9,
  136791. 2,
  136792. 10,
  136793. 1,
  136794. 11,
  136795. 0,
  136796. 12,
  136797. };
  136798. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136799. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136800. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136801. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136802. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136803. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136804. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136805. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136806. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136807. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136808. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136809. 0,12,12,11,11,12,12,13,13,
  136810. };
  136811. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136812. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136813. 12.5, 17.5, 22.5, 27.5,
  136814. };
  136815. static long _vq_quantmap__44c0_s_p7_0[] = {
  136816. 11, 9, 7, 5, 3, 1, 0, 2,
  136817. 4, 6, 8, 10, 12,
  136818. };
  136819. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136820. _vq_quantthresh__44c0_s_p7_0,
  136821. _vq_quantmap__44c0_s_p7_0,
  136822. 13,
  136823. 13
  136824. };
  136825. static static_codebook _44c0_s_p7_0 = {
  136826. 2, 169,
  136827. _vq_lengthlist__44c0_s_p7_0,
  136828. 1, -526516224, 1616117760, 4, 0,
  136829. _vq_quantlist__44c0_s_p7_0,
  136830. NULL,
  136831. &_vq_auxt__44c0_s_p7_0,
  136832. NULL,
  136833. 0
  136834. };
  136835. static long _vq_quantlist__44c0_s_p7_1[] = {
  136836. 2,
  136837. 1,
  136838. 3,
  136839. 0,
  136840. 4,
  136841. };
  136842. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136843. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136844. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136845. };
  136846. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136847. -1.5, -0.5, 0.5, 1.5,
  136848. };
  136849. static long _vq_quantmap__44c0_s_p7_1[] = {
  136850. 3, 1, 0, 2, 4,
  136851. };
  136852. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136853. _vq_quantthresh__44c0_s_p7_1,
  136854. _vq_quantmap__44c0_s_p7_1,
  136855. 5,
  136856. 5
  136857. };
  136858. static static_codebook _44c0_s_p7_1 = {
  136859. 2, 25,
  136860. _vq_lengthlist__44c0_s_p7_1,
  136861. 1, -533725184, 1611661312, 3, 0,
  136862. _vq_quantlist__44c0_s_p7_1,
  136863. NULL,
  136864. &_vq_auxt__44c0_s_p7_1,
  136865. NULL,
  136866. 0
  136867. };
  136868. static long _vq_quantlist__44c0_s_p8_0[] = {
  136869. 2,
  136870. 1,
  136871. 3,
  136872. 0,
  136873. 4,
  136874. };
  136875. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136876. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136877. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136878. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136879. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136880. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136881. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136882. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136883. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136884. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136885. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136886. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136887. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136888. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136891. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136897. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136898. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136899. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136902. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136915. 11,
  136916. };
  136917. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136918. -331.5, -110.5, 110.5, 331.5,
  136919. };
  136920. static long _vq_quantmap__44c0_s_p8_0[] = {
  136921. 3, 1, 0, 2, 4,
  136922. };
  136923. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136924. _vq_quantthresh__44c0_s_p8_0,
  136925. _vq_quantmap__44c0_s_p8_0,
  136926. 5,
  136927. 5
  136928. };
  136929. static static_codebook _44c0_s_p8_0 = {
  136930. 4, 625,
  136931. _vq_lengthlist__44c0_s_p8_0,
  136932. 1, -518283264, 1627103232, 3, 0,
  136933. _vq_quantlist__44c0_s_p8_0,
  136934. NULL,
  136935. &_vq_auxt__44c0_s_p8_0,
  136936. NULL,
  136937. 0
  136938. };
  136939. static long _vq_quantlist__44c0_s_p8_1[] = {
  136940. 6,
  136941. 5,
  136942. 7,
  136943. 4,
  136944. 8,
  136945. 3,
  136946. 9,
  136947. 2,
  136948. 10,
  136949. 1,
  136950. 11,
  136951. 0,
  136952. 12,
  136953. };
  136954. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136955. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136956. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136957. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136958. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136959. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136960. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136961. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136962. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136963. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136964. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136965. 16,13,13,12,12,14,14,15,13,
  136966. };
  136967. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136968. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136969. 42.5, 59.5, 76.5, 93.5,
  136970. };
  136971. static long _vq_quantmap__44c0_s_p8_1[] = {
  136972. 11, 9, 7, 5, 3, 1, 0, 2,
  136973. 4, 6, 8, 10, 12,
  136974. };
  136975. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136976. _vq_quantthresh__44c0_s_p8_1,
  136977. _vq_quantmap__44c0_s_p8_1,
  136978. 13,
  136979. 13
  136980. };
  136981. static static_codebook _44c0_s_p8_1 = {
  136982. 2, 169,
  136983. _vq_lengthlist__44c0_s_p8_1,
  136984. 1, -522616832, 1620115456, 4, 0,
  136985. _vq_quantlist__44c0_s_p8_1,
  136986. NULL,
  136987. &_vq_auxt__44c0_s_p8_1,
  136988. NULL,
  136989. 0
  136990. };
  136991. static long _vq_quantlist__44c0_s_p8_2[] = {
  136992. 8,
  136993. 7,
  136994. 9,
  136995. 6,
  136996. 10,
  136997. 5,
  136998. 11,
  136999. 4,
  137000. 12,
  137001. 3,
  137002. 13,
  137003. 2,
  137004. 14,
  137005. 1,
  137006. 15,
  137007. 0,
  137008. 16,
  137009. };
  137010. static long _vq_lengthlist__44c0_s_p8_2[] = {
  137011. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137012. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  137013. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  137014. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137015. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137016. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  137017. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  137018. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  137019. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  137020. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  137021. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  137022. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137023. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  137024. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  137025. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  137026. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  137027. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  137028. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  137029. 10,
  137030. };
  137031. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137032. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137033. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137034. };
  137035. static long _vq_quantmap__44c0_s_p8_2[] = {
  137036. 15, 13, 11, 9, 7, 5, 3, 1,
  137037. 0, 2, 4, 6, 8, 10, 12, 14,
  137038. 16,
  137039. };
  137040. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137041. _vq_quantthresh__44c0_s_p8_2,
  137042. _vq_quantmap__44c0_s_p8_2,
  137043. 17,
  137044. 17
  137045. };
  137046. static static_codebook _44c0_s_p8_2 = {
  137047. 2, 289,
  137048. _vq_lengthlist__44c0_s_p8_2,
  137049. 1, -529530880, 1611661312, 5, 0,
  137050. _vq_quantlist__44c0_s_p8_2,
  137051. NULL,
  137052. &_vq_auxt__44c0_s_p8_2,
  137053. NULL,
  137054. 0
  137055. };
  137056. static long _huff_lengthlist__44c0_s_short[] = {
  137057. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137058. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137059. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137060. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137061. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137062. 12,
  137063. };
  137064. static static_codebook _huff_book__44c0_s_short = {
  137065. 2, 81,
  137066. _huff_lengthlist__44c0_s_short,
  137067. 0, 0, 0, 0, 0,
  137068. NULL,
  137069. NULL,
  137070. NULL,
  137071. NULL,
  137072. 0
  137073. };
  137074. static long _huff_lengthlist__44c0_sm_long[] = {
  137075. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137076. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137077. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137078. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137079. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137080. 13,
  137081. };
  137082. static static_codebook _huff_book__44c0_sm_long = {
  137083. 2, 81,
  137084. _huff_lengthlist__44c0_sm_long,
  137085. 0, 0, 0, 0, 0,
  137086. NULL,
  137087. NULL,
  137088. NULL,
  137089. NULL,
  137090. 0
  137091. };
  137092. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137093. 1,
  137094. 0,
  137095. 2,
  137096. };
  137097. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137098. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137099. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137104. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137109. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  137144. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  137149. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137154. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137190. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137195. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137200. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0,
  137509. };
  137510. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137511. -0.5, 0.5,
  137512. };
  137513. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137514. 1, 0, 2,
  137515. };
  137516. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137517. _vq_quantthresh__44c0_sm_p1_0,
  137518. _vq_quantmap__44c0_sm_p1_0,
  137519. 3,
  137520. 3
  137521. };
  137522. static static_codebook _44c0_sm_p1_0 = {
  137523. 8, 6561,
  137524. _vq_lengthlist__44c0_sm_p1_0,
  137525. 1, -535822336, 1611661312, 2, 0,
  137526. _vq_quantlist__44c0_sm_p1_0,
  137527. NULL,
  137528. &_vq_auxt__44c0_sm_p1_0,
  137529. NULL,
  137530. 0
  137531. };
  137532. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137533. 2,
  137534. 1,
  137535. 3,
  137536. 0,
  137537. 4,
  137538. };
  137539. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137540. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137579. 0,
  137580. };
  137581. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137582. -1.5, -0.5, 0.5, 1.5,
  137583. };
  137584. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137585. 3, 1, 0, 2, 4,
  137586. };
  137587. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137588. _vq_quantthresh__44c0_sm_p2_0,
  137589. _vq_quantmap__44c0_sm_p2_0,
  137590. 5,
  137591. 5
  137592. };
  137593. static static_codebook _44c0_sm_p2_0 = {
  137594. 4, 625,
  137595. _vq_lengthlist__44c0_sm_p2_0,
  137596. 1, -533725184, 1611661312, 3, 0,
  137597. _vq_quantlist__44c0_sm_p2_0,
  137598. NULL,
  137599. &_vq_auxt__44c0_sm_p2_0,
  137600. NULL,
  137601. 0
  137602. };
  137603. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137604. 4,
  137605. 3,
  137606. 5,
  137607. 2,
  137608. 6,
  137609. 1,
  137610. 7,
  137611. 0,
  137612. 8,
  137613. };
  137614. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137615. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137616. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137617. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137618. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137619. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0,
  137621. };
  137622. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137623. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137624. };
  137625. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137626. 7, 5, 3, 1, 0, 2, 4, 6,
  137627. 8,
  137628. };
  137629. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137630. _vq_quantthresh__44c0_sm_p3_0,
  137631. _vq_quantmap__44c0_sm_p3_0,
  137632. 9,
  137633. 9
  137634. };
  137635. static static_codebook _44c0_sm_p3_0 = {
  137636. 2, 81,
  137637. _vq_lengthlist__44c0_sm_p3_0,
  137638. 1, -531628032, 1611661312, 4, 0,
  137639. _vq_quantlist__44c0_sm_p3_0,
  137640. NULL,
  137641. &_vq_auxt__44c0_sm_p3_0,
  137642. NULL,
  137643. 0
  137644. };
  137645. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137646. 4,
  137647. 3,
  137648. 5,
  137649. 2,
  137650. 6,
  137651. 1,
  137652. 7,
  137653. 0,
  137654. 8,
  137655. };
  137656. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137657. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137658. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137659. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137660. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137661. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137662. 11,
  137663. };
  137664. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137665. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137666. };
  137667. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137668. 7, 5, 3, 1, 0, 2, 4, 6,
  137669. 8,
  137670. };
  137671. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137672. _vq_quantthresh__44c0_sm_p4_0,
  137673. _vq_quantmap__44c0_sm_p4_0,
  137674. 9,
  137675. 9
  137676. };
  137677. static static_codebook _44c0_sm_p4_0 = {
  137678. 2, 81,
  137679. _vq_lengthlist__44c0_sm_p4_0,
  137680. 1, -531628032, 1611661312, 4, 0,
  137681. _vq_quantlist__44c0_sm_p4_0,
  137682. NULL,
  137683. &_vq_auxt__44c0_sm_p4_0,
  137684. NULL,
  137685. 0
  137686. };
  137687. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137688. 8,
  137689. 7,
  137690. 9,
  137691. 6,
  137692. 10,
  137693. 5,
  137694. 11,
  137695. 4,
  137696. 12,
  137697. 3,
  137698. 13,
  137699. 2,
  137700. 14,
  137701. 1,
  137702. 15,
  137703. 0,
  137704. 16,
  137705. };
  137706. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137707. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137708. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137709. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137710. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137711. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137712. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137713. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137714. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137715. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137716. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137717. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137718. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137719. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137720. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137721. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137722. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137723. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137725. 14,
  137726. };
  137727. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137728. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137729. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137730. };
  137731. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137732. 15, 13, 11, 9, 7, 5, 3, 1,
  137733. 0, 2, 4, 6, 8, 10, 12, 14,
  137734. 16,
  137735. };
  137736. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137737. _vq_quantthresh__44c0_sm_p5_0,
  137738. _vq_quantmap__44c0_sm_p5_0,
  137739. 17,
  137740. 17
  137741. };
  137742. static static_codebook _44c0_sm_p5_0 = {
  137743. 2, 289,
  137744. _vq_lengthlist__44c0_sm_p5_0,
  137745. 1, -529530880, 1611661312, 5, 0,
  137746. _vq_quantlist__44c0_sm_p5_0,
  137747. NULL,
  137748. &_vq_auxt__44c0_sm_p5_0,
  137749. NULL,
  137750. 0
  137751. };
  137752. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137753. 1,
  137754. 0,
  137755. 2,
  137756. };
  137757. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137758. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137759. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137760. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137761. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137762. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137763. 11,
  137764. };
  137765. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137766. -5.5, 5.5,
  137767. };
  137768. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137769. 1, 0, 2,
  137770. };
  137771. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137772. _vq_quantthresh__44c0_sm_p6_0,
  137773. _vq_quantmap__44c0_sm_p6_0,
  137774. 3,
  137775. 3
  137776. };
  137777. static static_codebook _44c0_sm_p6_0 = {
  137778. 4, 81,
  137779. _vq_lengthlist__44c0_sm_p6_0,
  137780. 1, -529137664, 1618345984, 2, 0,
  137781. _vq_quantlist__44c0_sm_p6_0,
  137782. NULL,
  137783. &_vq_auxt__44c0_sm_p6_0,
  137784. NULL,
  137785. 0
  137786. };
  137787. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137788. 5,
  137789. 4,
  137790. 6,
  137791. 3,
  137792. 7,
  137793. 2,
  137794. 8,
  137795. 1,
  137796. 9,
  137797. 0,
  137798. 10,
  137799. };
  137800. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137801. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137802. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137803. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137804. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137805. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137806. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137807. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137808. 10,10,10, 8, 8, 8, 8, 8, 8,
  137809. };
  137810. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137811. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137812. 3.5, 4.5,
  137813. };
  137814. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137815. 9, 7, 5, 3, 1, 0, 2, 4,
  137816. 6, 8, 10,
  137817. };
  137818. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137819. _vq_quantthresh__44c0_sm_p6_1,
  137820. _vq_quantmap__44c0_sm_p6_1,
  137821. 11,
  137822. 11
  137823. };
  137824. static static_codebook _44c0_sm_p6_1 = {
  137825. 2, 121,
  137826. _vq_lengthlist__44c0_sm_p6_1,
  137827. 1, -531365888, 1611661312, 4, 0,
  137828. _vq_quantlist__44c0_sm_p6_1,
  137829. NULL,
  137830. &_vq_auxt__44c0_sm_p6_1,
  137831. NULL,
  137832. 0
  137833. };
  137834. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137835. 6,
  137836. 5,
  137837. 7,
  137838. 4,
  137839. 8,
  137840. 3,
  137841. 9,
  137842. 2,
  137843. 10,
  137844. 1,
  137845. 11,
  137846. 0,
  137847. 12,
  137848. };
  137849. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137850. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137851. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137852. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137853. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137854. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137855. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137856. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137857. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137858. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137859. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137860. 0,12,12,11,11,13,12,14,14,
  137861. };
  137862. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137863. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137864. 12.5, 17.5, 22.5, 27.5,
  137865. };
  137866. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137867. 11, 9, 7, 5, 3, 1, 0, 2,
  137868. 4, 6, 8, 10, 12,
  137869. };
  137870. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137871. _vq_quantthresh__44c0_sm_p7_0,
  137872. _vq_quantmap__44c0_sm_p7_0,
  137873. 13,
  137874. 13
  137875. };
  137876. static static_codebook _44c0_sm_p7_0 = {
  137877. 2, 169,
  137878. _vq_lengthlist__44c0_sm_p7_0,
  137879. 1, -526516224, 1616117760, 4, 0,
  137880. _vq_quantlist__44c0_sm_p7_0,
  137881. NULL,
  137882. &_vq_auxt__44c0_sm_p7_0,
  137883. NULL,
  137884. 0
  137885. };
  137886. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137887. 2,
  137888. 1,
  137889. 3,
  137890. 0,
  137891. 4,
  137892. };
  137893. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137894. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137895. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137896. };
  137897. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137898. -1.5, -0.5, 0.5, 1.5,
  137899. };
  137900. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137901. 3, 1, 0, 2, 4,
  137902. };
  137903. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137904. _vq_quantthresh__44c0_sm_p7_1,
  137905. _vq_quantmap__44c0_sm_p7_1,
  137906. 5,
  137907. 5
  137908. };
  137909. static static_codebook _44c0_sm_p7_1 = {
  137910. 2, 25,
  137911. _vq_lengthlist__44c0_sm_p7_1,
  137912. 1, -533725184, 1611661312, 3, 0,
  137913. _vq_quantlist__44c0_sm_p7_1,
  137914. NULL,
  137915. &_vq_auxt__44c0_sm_p7_1,
  137916. NULL,
  137917. 0
  137918. };
  137919. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137920. 4,
  137921. 3,
  137922. 5,
  137923. 2,
  137924. 6,
  137925. 1,
  137926. 7,
  137927. 0,
  137928. 8,
  137929. };
  137930. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137931. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137932. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137934. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137936. 12,
  137937. };
  137938. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137939. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137940. };
  137941. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137942. 7, 5, 3, 1, 0, 2, 4, 6,
  137943. 8,
  137944. };
  137945. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137946. _vq_quantthresh__44c0_sm_p8_0,
  137947. _vq_quantmap__44c0_sm_p8_0,
  137948. 9,
  137949. 9
  137950. };
  137951. static static_codebook _44c0_sm_p8_0 = {
  137952. 2, 81,
  137953. _vq_lengthlist__44c0_sm_p8_0,
  137954. 1, -516186112, 1627103232, 4, 0,
  137955. _vq_quantlist__44c0_sm_p8_0,
  137956. NULL,
  137957. &_vq_auxt__44c0_sm_p8_0,
  137958. NULL,
  137959. 0
  137960. };
  137961. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137962. 6,
  137963. 5,
  137964. 7,
  137965. 4,
  137966. 8,
  137967. 3,
  137968. 9,
  137969. 2,
  137970. 10,
  137971. 1,
  137972. 11,
  137973. 0,
  137974. 12,
  137975. };
  137976. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137977. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137978. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137979. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137980. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137981. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137982. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137983. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137984. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137985. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137986. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137987. 20,13,13,12,12,16,13,15,13,
  137988. };
  137989. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137990. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137991. 42.5, 59.5, 76.5, 93.5,
  137992. };
  137993. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137994. 11, 9, 7, 5, 3, 1, 0, 2,
  137995. 4, 6, 8, 10, 12,
  137996. };
  137997. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137998. _vq_quantthresh__44c0_sm_p8_1,
  137999. _vq_quantmap__44c0_sm_p8_1,
  138000. 13,
  138001. 13
  138002. };
  138003. static static_codebook _44c0_sm_p8_1 = {
  138004. 2, 169,
  138005. _vq_lengthlist__44c0_sm_p8_1,
  138006. 1, -522616832, 1620115456, 4, 0,
  138007. _vq_quantlist__44c0_sm_p8_1,
  138008. NULL,
  138009. &_vq_auxt__44c0_sm_p8_1,
  138010. NULL,
  138011. 0
  138012. };
  138013. static long _vq_quantlist__44c0_sm_p8_2[] = {
  138014. 8,
  138015. 7,
  138016. 9,
  138017. 6,
  138018. 10,
  138019. 5,
  138020. 11,
  138021. 4,
  138022. 12,
  138023. 3,
  138024. 13,
  138025. 2,
  138026. 14,
  138027. 1,
  138028. 15,
  138029. 0,
  138030. 16,
  138031. };
  138032. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138033. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138034. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138035. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138036. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138037. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138038. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138039. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138040. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138041. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138042. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138043. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138044. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138045. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138046. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138047. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138048. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138049. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138050. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138051. 9,
  138052. };
  138053. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138054. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138055. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138056. };
  138057. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138058. 15, 13, 11, 9, 7, 5, 3, 1,
  138059. 0, 2, 4, 6, 8, 10, 12, 14,
  138060. 16,
  138061. };
  138062. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138063. _vq_quantthresh__44c0_sm_p8_2,
  138064. _vq_quantmap__44c0_sm_p8_2,
  138065. 17,
  138066. 17
  138067. };
  138068. static static_codebook _44c0_sm_p8_2 = {
  138069. 2, 289,
  138070. _vq_lengthlist__44c0_sm_p8_2,
  138071. 1, -529530880, 1611661312, 5, 0,
  138072. _vq_quantlist__44c0_sm_p8_2,
  138073. NULL,
  138074. &_vq_auxt__44c0_sm_p8_2,
  138075. NULL,
  138076. 0
  138077. };
  138078. static long _huff_lengthlist__44c0_sm_short[] = {
  138079. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138080. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138081. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138082. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138083. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138084. 12,
  138085. };
  138086. static static_codebook _huff_book__44c0_sm_short = {
  138087. 2, 81,
  138088. _huff_lengthlist__44c0_sm_short,
  138089. 0, 0, 0, 0, 0,
  138090. NULL,
  138091. NULL,
  138092. NULL,
  138093. NULL,
  138094. 0
  138095. };
  138096. static long _huff_lengthlist__44c1_s_long[] = {
  138097. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138098. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138099. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138100. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138101. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138102. 11,
  138103. };
  138104. static static_codebook _huff_book__44c1_s_long = {
  138105. 2, 81,
  138106. _huff_lengthlist__44c1_s_long,
  138107. 0, 0, 0, 0, 0,
  138108. NULL,
  138109. NULL,
  138110. NULL,
  138111. NULL,
  138112. 0
  138113. };
  138114. static long _vq_quantlist__44c1_s_p1_0[] = {
  138115. 1,
  138116. 0,
  138117. 2,
  138118. };
  138119. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138120. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138121. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138126. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138131. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  138166. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  138171. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  138176. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138212. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138217. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138222. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138530. 0,
  138531. };
  138532. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138533. -0.5, 0.5,
  138534. };
  138535. static long _vq_quantmap__44c1_s_p1_0[] = {
  138536. 1, 0, 2,
  138537. };
  138538. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138539. _vq_quantthresh__44c1_s_p1_0,
  138540. _vq_quantmap__44c1_s_p1_0,
  138541. 3,
  138542. 3
  138543. };
  138544. static static_codebook _44c1_s_p1_0 = {
  138545. 8, 6561,
  138546. _vq_lengthlist__44c1_s_p1_0,
  138547. 1, -535822336, 1611661312, 2, 0,
  138548. _vq_quantlist__44c1_s_p1_0,
  138549. NULL,
  138550. &_vq_auxt__44c1_s_p1_0,
  138551. NULL,
  138552. 0
  138553. };
  138554. static long _vq_quantlist__44c1_s_p2_0[] = {
  138555. 2,
  138556. 1,
  138557. 3,
  138558. 0,
  138559. 4,
  138560. };
  138561. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138562. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138601. 0,
  138602. };
  138603. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138604. -1.5, -0.5, 0.5, 1.5,
  138605. };
  138606. static long _vq_quantmap__44c1_s_p2_0[] = {
  138607. 3, 1, 0, 2, 4,
  138608. };
  138609. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138610. _vq_quantthresh__44c1_s_p2_0,
  138611. _vq_quantmap__44c1_s_p2_0,
  138612. 5,
  138613. 5
  138614. };
  138615. static static_codebook _44c1_s_p2_0 = {
  138616. 4, 625,
  138617. _vq_lengthlist__44c1_s_p2_0,
  138618. 1, -533725184, 1611661312, 3, 0,
  138619. _vq_quantlist__44c1_s_p2_0,
  138620. NULL,
  138621. &_vq_auxt__44c1_s_p2_0,
  138622. NULL,
  138623. 0
  138624. };
  138625. static long _vq_quantlist__44c1_s_p3_0[] = {
  138626. 4,
  138627. 3,
  138628. 5,
  138629. 2,
  138630. 6,
  138631. 1,
  138632. 7,
  138633. 0,
  138634. 8,
  138635. };
  138636. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138637. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138638. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138639. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138640. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138641. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0,
  138643. };
  138644. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138645. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138646. };
  138647. static long _vq_quantmap__44c1_s_p3_0[] = {
  138648. 7, 5, 3, 1, 0, 2, 4, 6,
  138649. 8,
  138650. };
  138651. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138652. _vq_quantthresh__44c1_s_p3_0,
  138653. _vq_quantmap__44c1_s_p3_0,
  138654. 9,
  138655. 9
  138656. };
  138657. static static_codebook _44c1_s_p3_0 = {
  138658. 2, 81,
  138659. _vq_lengthlist__44c1_s_p3_0,
  138660. 1, -531628032, 1611661312, 4, 0,
  138661. _vq_quantlist__44c1_s_p3_0,
  138662. NULL,
  138663. &_vq_auxt__44c1_s_p3_0,
  138664. NULL,
  138665. 0
  138666. };
  138667. static long _vq_quantlist__44c1_s_p4_0[] = {
  138668. 4,
  138669. 3,
  138670. 5,
  138671. 2,
  138672. 6,
  138673. 1,
  138674. 7,
  138675. 0,
  138676. 8,
  138677. };
  138678. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138679. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138680. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138681. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138682. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138683. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138684. 11,
  138685. };
  138686. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138687. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138688. };
  138689. static long _vq_quantmap__44c1_s_p4_0[] = {
  138690. 7, 5, 3, 1, 0, 2, 4, 6,
  138691. 8,
  138692. };
  138693. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138694. _vq_quantthresh__44c1_s_p4_0,
  138695. _vq_quantmap__44c1_s_p4_0,
  138696. 9,
  138697. 9
  138698. };
  138699. static static_codebook _44c1_s_p4_0 = {
  138700. 2, 81,
  138701. _vq_lengthlist__44c1_s_p4_0,
  138702. 1, -531628032, 1611661312, 4, 0,
  138703. _vq_quantlist__44c1_s_p4_0,
  138704. NULL,
  138705. &_vq_auxt__44c1_s_p4_0,
  138706. NULL,
  138707. 0
  138708. };
  138709. static long _vq_quantlist__44c1_s_p5_0[] = {
  138710. 8,
  138711. 7,
  138712. 9,
  138713. 6,
  138714. 10,
  138715. 5,
  138716. 11,
  138717. 4,
  138718. 12,
  138719. 3,
  138720. 13,
  138721. 2,
  138722. 14,
  138723. 1,
  138724. 15,
  138725. 0,
  138726. 16,
  138727. };
  138728. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138729. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138730. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138731. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138732. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138733. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138734. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138735. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138736. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138737. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138738. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138739. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138740. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138741. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138742. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138743. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138744. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138745. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138747. 14,
  138748. };
  138749. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138750. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138751. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138752. };
  138753. static long _vq_quantmap__44c1_s_p5_0[] = {
  138754. 15, 13, 11, 9, 7, 5, 3, 1,
  138755. 0, 2, 4, 6, 8, 10, 12, 14,
  138756. 16,
  138757. };
  138758. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138759. _vq_quantthresh__44c1_s_p5_0,
  138760. _vq_quantmap__44c1_s_p5_0,
  138761. 17,
  138762. 17
  138763. };
  138764. static static_codebook _44c1_s_p5_0 = {
  138765. 2, 289,
  138766. _vq_lengthlist__44c1_s_p5_0,
  138767. 1, -529530880, 1611661312, 5, 0,
  138768. _vq_quantlist__44c1_s_p5_0,
  138769. NULL,
  138770. &_vq_auxt__44c1_s_p5_0,
  138771. NULL,
  138772. 0
  138773. };
  138774. static long _vq_quantlist__44c1_s_p6_0[] = {
  138775. 1,
  138776. 0,
  138777. 2,
  138778. };
  138779. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138780. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138781. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138782. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138783. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138784. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138785. 11,
  138786. };
  138787. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138788. -5.5, 5.5,
  138789. };
  138790. static long _vq_quantmap__44c1_s_p6_0[] = {
  138791. 1, 0, 2,
  138792. };
  138793. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138794. _vq_quantthresh__44c1_s_p6_0,
  138795. _vq_quantmap__44c1_s_p6_0,
  138796. 3,
  138797. 3
  138798. };
  138799. static static_codebook _44c1_s_p6_0 = {
  138800. 4, 81,
  138801. _vq_lengthlist__44c1_s_p6_0,
  138802. 1, -529137664, 1618345984, 2, 0,
  138803. _vq_quantlist__44c1_s_p6_0,
  138804. NULL,
  138805. &_vq_auxt__44c1_s_p6_0,
  138806. NULL,
  138807. 0
  138808. };
  138809. static long _vq_quantlist__44c1_s_p6_1[] = {
  138810. 5,
  138811. 4,
  138812. 6,
  138813. 3,
  138814. 7,
  138815. 2,
  138816. 8,
  138817. 1,
  138818. 9,
  138819. 0,
  138820. 10,
  138821. };
  138822. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138823. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138824. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138825. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138826. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138827. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138828. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138829. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138830. 10,10,10, 8, 8, 8, 8, 8, 8,
  138831. };
  138832. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138833. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138834. 3.5, 4.5,
  138835. };
  138836. static long _vq_quantmap__44c1_s_p6_1[] = {
  138837. 9, 7, 5, 3, 1, 0, 2, 4,
  138838. 6, 8, 10,
  138839. };
  138840. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138841. _vq_quantthresh__44c1_s_p6_1,
  138842. _vq_quantmap__44c1_s_p6_1,
  138843. 11,
  138844. 11
  138845. };
  138846. static static_codebook _44c1_s_p6_1 = {
  138847. 2, 121,
  138848. _vq_lengthlist__44c1_s_p6_1,
  138849. 1, -531365888, 1611661312, 4, 0,
  138850. _vq_quantlist__44c1_s_p6_1,
  138851. NULL,
  138852. &_vq_auxt__44c1_s_p6_1,
  138853. NULL,
  138854. 0
  138855. };
  138856. static long _vq_quantlist__44c1_s_p7_0[] = {
  138857. 6,
  138858. 5,
  138859. 7,
  138860. 4,
  138861. 8,
  138862. 3,
  138863. 9,
  138864. 2,
  138865. 10,
  138866. 1,
  138867. 11,
  138868. 0,
  138869. 12,
  138870. };
  138871. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138872. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138873. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138874. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138875. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138876. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138877. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138878. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138879. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138880. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138881. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138882. 0,12,11,11,11,13,10,14,13,
  138883. };
  138884. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138885. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138886. 12.5, 17.5, 22.5, 27.5,
  138887. };
  138888. static long _vq_quantmap__44c1_s_p7_0[] = {
  138889. 11, 9, 7, 5, 3, 1, 0, 2,
  138890. 4, 6, 8, 10, 12,
  138891. };
  138892. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138893. _vq_quantthresh__44c1_s_p7_0,
  138894. _vq_quantmap__44c1_s_p7_0,
  138895. 13,
  138896. 13
  138897. };
  138898. static static_codebook _44c1_s_p7_0 = {
  138899. 2, 169,
  138900. _vq_lengthlist__44c1_s_p7_0,
  138901. 1, -526516224, 1616117760, 4, 0,
  138902. _vq_quantlist__44c1_s_p7_0,
  138903. NULL,
  138904. &_vq_auxt__44c1_s_p7_0,
  138905. NULL,
  138906. 0
  138907. };
  138908. static long _vq_quantlist__44c1_s_p7_1[] = {
  138909. 2,
  138910. 1,
  138911. 3,
  138912. 0,
  138913. 4,
  138914. };
  138915. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138916. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138917. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138918. };
  138919. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138920. -1.5, -0.5, 0.5, 1.5,
  138921. };
  138922. static long _vq_quantmap__44c1_s_p7_1[] = {
  138923. 3, 1, 0, 2, 4,
  138924. };
  138925. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138926. _vq_quantthresh__44c1_s_p7_1,
  138927. _vq_quantmap__44c1_s_p7_1,
  138928. 5,
  138929. 5
  138930. };
  138931. static static_codebook _44c1_s_p7_1 = {
  138932. 2, 25,
  138933. _vq_lengthlist__44c1_s_p7_1,
  138934. 1, -533725184, 1611661312, 3, 0,
  138935. _vq_quantlist__44c1_s_p7_1,
  138936. NULL,
  138937. &_vq_auxt__44c1_s_p7_1,
  138938. NULL,
  138939. 0
  138940. };
  138941. static long _vq_quantlist__44c1_s_p8_0[] = {
  138942. 6,
  138943. 5,
  138944. 7,
  138945. 4,
  138946. 8,
  138947. 3,
  138948. 9,
  138949. 2,
  138950. 10,
  138951. 1,
  138952. 11,
  138953. 0,
  138954. 12,
  138955. };
  138956. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138957. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138958. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138959. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138960. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138961. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138962. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138963. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138964. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138965. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138966. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138967. 10,10,10,10,10,10,10,10,10,
  138968. };
  138969. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138970. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138971. 552.5, 773.5, 994.5, 1215.5,
  138972. };
  138973. static long _vq_quantmap__44c1_s_p8_0[] = {
  138974. 11, 9, 7, 5, 3, 1, 0, 2,
  138975. 4, 6, 8, 10, 12,
  138976. };
  138977. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138978. _vq_quantthresh__44c1_s_p8_0,
  138979. _vq_quantmap__44c1_s_p8_0,
  138980. 13,
  138981. 13
  138982. };
  138983. static static_codebook _44c1_s_p8_0 = {
  138984. 2, 169,
  138985. _vq_lengthlist__44c1_s_p8_0,
  138986. 1, -514541568, 1627103232, 4, 0,
  138987. _vq_quantlist__44c1_s_p8_0,
  138988. NULL,
  138989. &_vq_auxt__44c1_s_p8_0,
  138990. NULL,
  138991. 0
  138992. };
  138993. static long _vq_quantlist__44c1_s_p8_1[] = {
  138994. 6,
  138995. 5,
  138996. 7,
  138997. 4,
  138998. 8,
  138999. 3,
  139000. 9,
  139001. 2,
  139002. 10,
  139003. 1,
  139004. 11,
  139005. 0,
  139006. 12,
  139007. };
  139008. static long _vq_lengthlist__44c1_s_p8_1[] = {
  139009. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  139010. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  139011. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  139012. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  139013. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  139014. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  139015. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  139016. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  139017. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  139018. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  139019. 16,13,12,12,11,14,12,15,13,
  139020. };
  139021. static float _vq_quantthresh__44c1_s_p8_1[] = {
  139022. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139023. 42.5, 59.5, 76.5, 93.5,
  139024. };
  139025. static long _vq_quantmap__44c1_s_p8_1[] = {
  139026. 11, 9, 7, 5, 3, 1, 0, 2,
  139027. 4, 6, 8, 10, 12,
  139028. };
  139029. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139030. _vq_quantthresh__44c1_s_p8_1,
  139031. _vq_quantmap__44c1_s_p8_1,
  139032. 13,
  139033. 13
  139034. };
  139035. static static_codebook _44c1_s_p8_1 = {
  139036. 2, 169,
  139037. _vq_lengthlist__44c1_s_p8_1,
  139038. 1, -522616832, 1620115456, 4, 0,
  139039. _vq_quantlist__44c1_s_p8_1,
  139040. NULL,
  139041. &_vq_auxt__44c1_s_p8_1,
  139042. NULL,
  139043. 0
  139044. };
  139045. static long _vq_quantlist__44c1_s_p8_2[] = {
  139046. 8,
  139047. 7,
  139048. 9,
  139049. 6,
  139050. 10,
  139051. 5,
  139052. 11,
  139053. 4,
  139054. 12,
  139055. 3,
  139056. 13,
  139057. 2,
  139058. 14,
  139059. 1,
  139060. 15,
  139061. 0,
  139062. 16,
  139063. };
  139064. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139065. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139066. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139067. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139068. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139069. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139070. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139071. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139072. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139073. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139074. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139076. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139077. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139078. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139079. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139080. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139081. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139082. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139083. 9,
  139084. };
  139085. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139086. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139087. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139088. };
  139089. static long _vq_quantmap__44c1_s_p8_2[] = {
  139090. 15, 13, 11, 9, 7, 5, 3, 1,
  139091. 0, 2, 4, 6, 8, 10, 12, 14,
  139092. 16,
  139093. };
  139094. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139095. _vq_quantthresh__44c1_s_p8_2,
  139096. _vq_quantmap__44c1_s_p8_2,
  139097. 17,
  139098. 17
  139099. };
  139100. static static_codebook _44c1_s_p8_2 = {
  139101. 2, 289,
  139102. _vq_lengthlist__44c1_s_p8_2,
  139103. 1, -529530880, 1611661312, 5, 0,
  139104. _vq_quantlist__44c1_s_p8_2,
  139105. NULL,
  139106. &_vq_auxt__44c1_s_p8_2,
  139107. NULL,
  139108. 0
  139109. };
  139110. static long _huff_lengthlist__44c1_s_short[] = {
  139111. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139112. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139113. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139114. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139115. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139116. 11,
  139117. };
  139118. static static_codebook _huff_book__44c1_s_short = {
  139119. 2, 81,
  139120. _huff_lengthlist__44c1_s_short,
  139121. 0, 0, 0, 0, 0,
  139122. NULL,
  139123. NULL,
  139124. NULL,
  139125. NULL,
  139126. 0
  139127. };
  139128. static long _huff_lengthlist__44c1_sm_long[] = {
  139129. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139130. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139131. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139132. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139133. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139134. 11,
  139135. };
  139136. static static_codebook _huff_book__44c1_sm_long = {
  139137. 2, 81,
  139138. _huff_lengthlist__44c1_sm_long,
  139139. 0, 0, 0, 0, 0,
  139140. NULL,
  139141. NULL,
  139142. NULL,
  139143. NULL,
  139144. 0
  139145. };
  139146. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139147. 1,
  139148. 0,
  139149. 2,
  139150. };
  139151. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139152. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139153. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139158. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139163. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  139198. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  139203. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  139208. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139244. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139249. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139254. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139562. 0,
  139563. };
  139564. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139565. -0.5, 0.5,
  139566. };
  139567. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139568. 1, 0, 2,
  139569. };
  139570. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139571. _vq_quantthresh__44c1_sm_p1_0,
  139572. _vq_quantmap__44c1_sm_p1_0,
  139573. 3,
  139574. 3
  139575. };
  139576. static static_codebook _44c1_sm_p1_0 = {
  139577. 8, 6561,
  139578. _vq_lengthlist__44c1_sm_p1_0,
  139579. 1, -535822336, 1611661312, 2, 0,
  139580. _vq_quantlist__44c1_sm_p1_0,
  139581. NULL,
  139582. &_vq_auxt__44c1_sm_p1_0,
  139583. NULL,
  139584. 0
  139585. };
  139586. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139587. 2,
  139588. 1,
  139589. 3,
  139590. 0,
  139591. 4,
  139592. };
  139593. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139594. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139633. 0,
  139634. };
  139635. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139636. -1.5, -0.5, 0.5, 1.5,
  139637. };
  139638. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139639. 3, 1, 0, 2, 4,
  139640. };
  139641. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139642. _vq_quantthresh__44c1_sm_p2_0,
  139643. _vq_quantmap__44c1_sm_p2_0,
  139644. 5,
  139645. 5
  139646. };
  139647. static static_codebook _44c1_sm_p2_0 = {
  139648. 4, 625,
  139649. _vq_lengthlist__44c1_sm_p2_0,
  139650. 1, -533725184, 1611661312, 3, 0,
  139651. _vq_quantlist__44c1_sm_p2_0,
  139652. NULL,
  139653. &_vq_auxt__44c1_sm_p2_0,
  139654. NULL,
  139655. 0
  139656. };
  139657. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139658. 4,
  139659. 3,
  139660. 5,
  139661. 2,
  139662. 6,
  139663. 1,
  139664. 7,
  139665. 0,
  139666. 8,
  139667. };
  139668. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139669. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139670. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139671. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139672. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139673. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0,
  139675. };
  139676. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139677. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139678. };
  139679. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139680. 7, 5, 3, 1, 0, 2, 4, 6,
  139681. 8,
  139682. };
  139683. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139684. _vq_quantthresh__44c1_sm_p3_0,
  139685. _vq_quantmap__44c1_sm_p3_0,
  139686. 9,
  139687. 9
  139688. };
  139689. static static_codebook _44c1_sm_p3_0 = {
  139690. 2, 81,
  139691. _vq_lengthlist__44c1_sm_p3_0,
  139692. 1, -531628032, 1611661312, 4, 0,
  139693. _vq_quantlist__44c1_sm_p3_0,
  139694. NULL,
  139695. &_vq_auxt__44c1_sm_p3_0,
  139696. NULL,
  139697. 0
  139698. };
  139699. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139700. 4,
  139701. 3,
  139702. 5,
  139703. 2,
  139704. 6,
  139705. 1,
  139706. 7,
  139707. 0,
  139708. 8,
  139709. };
  139710. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139711. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139712. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139713. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139714. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139715. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139716. 11,
  139717. };
  139718. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139719. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139720. };
  139721. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139722. 7, 5, 3, 1, 0, 2, 4, 6,
  139723. 8,
  139724. };
  139725. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139726. _vq_quantthresh__44c1_sm_p4_0,
  139727. _vq_quantmap__44c1_sm_p4_0,
  139728. 9,
  139729. 9
  139730. };
  139731. static static_codebook _44c1_sm_p4_0 = {
  139732. 2, 81,
  139733. _vq_lengthlist__44c1_sm_p4_0,
  139734. 1, -531628032, 1611661312, 4, 0,
  139735. _vq_quantlist__44c1_sm_p4_0,
  139736. NULL,
  139737. &_vq_auxt__44c1_sm_p4_0,
  139738. NULL,
  139739. 0
  139740. };
  139741. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139742. 8,
  139743. 7,
  139744. 9,
  139745. 6,
  139746. 10,
  139747. 5,
  139748. 11,
  139749. 4,
  139750. 12,
  139751. 3,
  139752. 13,
  139753. 2,
  139754. 14,
  139755. 1,
  139756. 15,
  139757. 0,
  139758. 16,
  139759. };
  139760. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139761. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139762. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139763. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139764. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139765. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139766. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139767. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139768. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139769. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139770. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139771. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139772. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139773. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139774. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139775. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139776. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139777. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139779. 14,
  139780. };
  139781. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139782. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139783. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139784. };
  139785. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139786. 15, 13, 11, 9, 7, 5, 3, 1,
  139787. 0, 2, 4, 6, 8, 10, 12, 14,
  139788. 16,
  139789. };
  139790. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139791. _vq_quantthresh__44c1_sm_p5_0,
  139792. _vq_quantmap__44c1_sm_p5_0,
  139793. 17,
  139794. 17
  139795. };
  139796. static static_codebook _44c1_sm_p5_0 = {
  139797. 2, 289,
  139798. _vq_lengthlist__44c1_sm_p5_0,
  139799. 1, -529530880, 1611661312, 5, 0,
  139800. _vq_quantlist__44c1_sm_p5_0,
  139801. NULL,
  139802. &_vq_auxt__44c1_sm_p5_0,
  139803. NULL,
  139804. 0
  139805. };
  139806. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139807. 1,
  139808. 0,
  139809. 2,
  139810. };
  139811. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139812. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139813. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139814. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139815. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139816. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139817. 11,
  139818. };
  139819. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139820. -5.5, 5.5,
  139821. };
  139822. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139823. 1, 0, 2,
  139824. };
  139825. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139826. _vq_quantthresh__44c1_sm_p6_0,
  139827. _vq_quantmap__44c1_sm_p6_0,
  139828. 3,
  139829. 3
  139830. };
  139831. static static_codebook _44c1_sm_p6_0 = {
  139832. 4, 81,
  139833. _vq_lengthlist__44c1_sm_p6_0,
  139834. 1, -529137664, 1618345984, 2, 0,
  139835. _vq_quantlist__44c1_sm_p6_0,
  139836. NULL,
  139837. &_vq_auxt__44c1_sm_p6_0,
  139838. NULL,
  139839. 0
  139840. };
  139841. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139842. 5,
  139843. 4,
  139844. 6,
  139845. 3,
  139846. 7,
  139847. 2,
  139848. 8,
  139849. 1,
  139850. 9,
  139851. 0,
  139852. 10,
  139853. };
  139854. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139855. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139856. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139857. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139858. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139859. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139860. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139861. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139862. 10,10,10, 8, 8, 8, 8, 8, 8,
  139863. };
  139864. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139865. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139866. 3.5, 4.5,
  139867. };
  139868. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139869. 9, 7, 5, 3, 1, 0, 2, 4,
  139870. 6, 8, 10,
  139871. };
  139872. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139873. _vq_quantthresh__44c1_sm_p6_1,
  139874. _vq_quantmap__44c1_sm_p6_1,
  139875. 11,
  139876. 11
  139877. };
  139878. static static_codebook _44c1_sm_p6_1 = {
  139879. 2, 121,
  139880. _vq_lengthlist__44c1_sm_p6_1,
  139881. 1, -531365888, 1611661312, 4, 0,
  139882. _vq_quantlist__44c1_sm_p6_1,
  139883. NULL,
  139884. &_vq_auxt__44c1_sm_p6_1,
  139885. NULL,
  139886. 0
  139887. };
  139888. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139889. 6,
  139890. 5,
  139891. 7,
  139892. 4,
  139893. 8,
  139894. 3,
  139895. 9,
  139896. 2,
  139897. 10,
  139898. 1,
  139899. 11,
  139900. 0,
  139901. 12,
  139902. };
  139903. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139904. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139905. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139906. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139907. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139908. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139909. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139910. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139911. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139912. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139913. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139914. 0,12,12,11,11,13,12,14,13,
  139915. };
  139916. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139917. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139918. 12.5, 17.5, 22.5, 27.5,
  139919. };
  139920. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139921. 11, 9, 7, 5, 3, 1, 0, 2,
  139922. 4, 6, 8, 10, 12,
  139923. };
  139924. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139925. _vq_quantthresh__44c1_sm_p7_0,
  139926. _vq_quantmap__44c1_sm_p7_0,
  139927. 13,
  139928. 13
  139929. };
  139930. static static_codebook _44c1_sm_p7_0 = {
  139931. 2, 169,
  139932. _vq_lengthlist__44c1_sm_p7_0,
  139933. 1, -526516224, 1616117760, 4, 0,
  139934. _vq_quantlist__44c1_sm_p7_0,
  139935. NULL,
  139936. &_vq_auxt__44c1_sm_p7_0,
  139937. NULL,
  139938. 0
  139939. };
  139940. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139941. 2,
  139942. 1,
  139943. 3,
  139944. 0,
  139945. 4,
  139946. };
  139947. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139948. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139949. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139950. };
  139951. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139952. -1.5, -0.5, 0.5, 1.5,
  139953. };
  139954. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139955. 3, 1, 0, 2, 4,
  139956. };
  139957. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139958. _vq_quantthresh__44c1_sm_p7_1,
  139959. _vq_quantmap__44c1_sm_p7_1,
  139960. 5,
  139961. 5
  139962. };
  139963. static static_codebook _44c1_sm_p7_1 = {
  139964. 2, 25,
  139965. _vq_lengthlist__44c1_sm_p7_1,
  139966. 1, -533725184, 1611661312, 3, 0,
  139967. _vq_quantlist__44c1_sm_p7_1,
  139968. NULL,
  139969. &_vq_auxt__44c1_sm_p7_1,
  139970. NULL,
  139971. 0
  139972. };
  139973. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139974. 6,
  139975. 5,
  139976. 7,
  139977. 4,
  139978. 8,
  139979. 3,
  139980. 9,
  139981. 2,
  139982. 10,
  139983. 1,
  139984. 11,
  139985. 0,
  139986. 12,
  139987. };
  139988. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139989. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139990. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139991. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139992. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139993. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139994. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139995. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139996. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139997. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139998. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139999. 13,13,13,13,13,13,13,13,13,
  140000. };
  140001. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  140002. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  140003. 552.5, 773.5, 994.5, 1215.5,
  140004. };
  140005. static long _vq_quantmap__44c1_sm_p8_0[] = {
  140006. 11, 9, 7, 5, 3, 1, 0, 2,
  140007. 4, 6, 8, 10, 12,
  140008. };
  140009. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  140010. _vq_quantthresh__44c1_sm_p8_0,
  140011. _vq_quantmap__44c1_sm_p8_0,
  140012. 13,
  140013. 13
  140014. };
  140015. static static_codebook _44c1_sm_p8_0 = {
  140016. 2, 169,
  140017. _vq_lengthlist__44c1_sm_p8_0,
  140018. 1, -514541568, 1627103232, 4, 0,
  140019. _vq_quantlist__44c1_sm_p8_0,
  140020. NULL,
  140021. &_vq_auxt__44c1_sm_p8_0,
  140022. NULL,
  140023. 0
  140024. };
  140025. static long _vq_quantlist__44c1_sm_p8_1[] = {
  140026. 6,
  140027. 5,
  140028. 7,
  140029. 4,
  140030. 8,
  140031. 3,
  140032. 9,
  140033. 2,
  140034. 10,
  140035. 1,
  140036. 11,
  140037. 0,
  140038. 12,
  140039. };
  140040. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140041. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140042. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140043. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140044. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140045. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140046. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140047. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140048. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140049. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140050. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140051. 20,13,12,12,12,14,12,14,13,
  140052. };
  140053. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140054. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140055. 42.5, 59.5, 76.5, 93.5,
  140056. };
  140057. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140058. 11, 9, 7, 5, 3, 1, 0, 2,
  140059. 4, 6, 8, 10, 12,
  140060. };
  140061. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140062. _vq_quantthresh__44c1_sm_p8_1,
  140063. _vq_quantmap__44c1_sm_p8_1,
  140064. 13,
  140065. 13
  140066. };
  140067. static static_codebook _44c1_sm_p8_1 = {
  140068. 2, 169,
  140069. _vq_lengthlist__44c1_sm_p8_1,
  140070. 1, -522616832, 1620115456, 4, 0,
  140071. _vq_quantlist__44c1_sm_p8_1,
  140072. NULL,
  140073. &_vq_auxt__44c1_sm_p8_1,
  140074. NULL,
  140075. 0
  140076. };
  140077. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140078. 8,
  140079. 7,
  140080. 9,
  140081. 6,
  140082. 10,
  140083. 5,
  140084. 11,
  140085. 4,
  140086. 12,
  140087. 3,
  140088. 13,
  140089. 2,
  140090. 14,
  140091. 1,
  140092. 15,
  140093. 0,
  140094. 16,
  140095. };
  140096. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140097. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140098. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140099. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140100. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140101. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140102. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140103. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140104. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140105. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140106. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140107. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140108. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140109. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140110. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140111. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140112. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140113. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140114. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140115. 9,
  140116. };
  140117. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140118. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140119. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140120. };
  140121. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140122. 15, 13, 11, 9, 7, 5, 3, 1,
  140123. 0, 2, 4, 6, 8, 10, 12, 14,
  140124. 16,
  140125. };
  140126. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140127. _vq_quantthresh__44c1_sm_p8_2,
  140128. _vq_quantmap__44c1_sm_p8_2,
  140129. 17,
  140130. 17
  140131. };
  140132. static static_codebook _44c1_sm_p8_2 = {
  140133. 2, 289,
  140134. _vq_lengthlist__44c1_sm_p8_2,
  140135. 1, -529530880, 1611661312, 5, 0,
  140136. _vq_quantlist__44c1_sm_p8_2,
  140137. NULL,
  140138. &_vq_auxt__44c1_sm_p8_2,
  140139. NULL,
  140140. 0
  140141. };
  140142. static long _huff_lengthlist__44c1_sm_short[] = {
  140143. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140144. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140145. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140146. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140147. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140148. 11,
  140149. };
  140150. static static_codebook _huff_book__44c1_sm_short = {
  140151. 2, 81,
  140152. _huff_lengthlist__44c1_sm_short,
  140153. 0, 0, 0, 0, 0,
  140154. NULL,
  140155. NULL,
  140156. NULL,
  140157. NULL,
  140158. 0
  140159. };
  140160. static long _huff_lengthlist__44cn1_s_long[] = {
  140161. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140162. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140163. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140164. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140165. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140166. 20,
  140167. };
  140168. static static_codebook _huff_book__44cn1_s_long = {
  140169. 2, 81,
  140170. _huff_lengthlist__44cn1_s_long,
  140171. 0, 0, 0, 0, 0,
  140172. NULL,
  140173. NULL,
  140174. NULL,
  140175. NULL,
  140176. 0
  140177. };
  140178. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140179. 1,
  140180. 0,
  140181. 2,
  140182. };
  140183. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140184. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140185. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140190. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140195. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  140230. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140235. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140240. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140276. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140281. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140286. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0,
  140595. };
  140596. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140597. -0.5, 0.5,
  140598. };
  140599. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140600. 1, 0, 2,
  140601. };
  140602. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140603. _vq_quantthresh__44cn1_s_p1_0,
  140604. _vq_quantmap__44cn1_s_p1_0,
  140605. 3,
  140606. 3
  140607. };
  140608. static static_codebook _44cn1_s_p1_0 = {
  140609. 8, 6561,
  140610. _vq_lengthlist__44cn1_s_p1_0,
  140611. 1, -535822336, 1611661312, 2, 0,
  140612. _vq_quantlist__44cn1_s_p1_0,
  140613. NULL,
  140614. &_vq_auxt__44cn1_s_p1_0,
  140615. NULL,
  140616. 0
  140617. };
  140618. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140619. 2,
  140620. 1,
  140621. 3,
  140622. 0,
  140623. 4,
  140624. };
  140625. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140626. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140665. 0,
  140666. };
  140667. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140668. -1.5, -0.5, 0.5, 1.5,
  140669. };
  140670. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140671. 3, 1, 0, 2, 4,
  140672. };
  140673. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140674. _vq_quantthresh__44cn1_s_p2_0,
  140675. _vq_quantmap__44cn1_s_p2_0,
  140676. 5,
  140677. 5
  140678. };
  140679. static static_codebook _44cn1_s_p2_0 = {
  140680. 4, 625,
  140681. _vq_lengthlist__44cn1_s_p2_0,
  140682. 1, -533725184, 1611661312, 3, 0,
  140683. _vq_quantlist__44cn1_s_p2_0,
  140684. NULL,
  140685. &_vq_auxt__44cn1_s_p2_0,
  140686. NULL,
  140687. 0
  140688. };
  140689. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140690. 4,
  140691. 3,
  140692. 5,
  140693. 2,
  140694. 6,
  140695. 1,
  140696. 7,
  140697. 0,
  140698. 8,
  140699. };
  140700. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140701. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140702. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140703. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140704. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140705. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0,
  140707. };
  140708. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140709. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140710. };
  140711. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140712. 7, 5, 3, 1, 0, 2, 4, 6,
  140713. 8,
  140714. };
  140715. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140716. _vq_quantthresh__44cn1_s_p3_0,
  140717. _vq_quantmap__44cn1_s_p3_0,
  140718. 9,
  140719. 9
  140720. };
  140721. static static_codebook _44cn1_s_p3_0 = {
  140722. 2, 81,
  140723. _vq_lengthlist__44cn1_s_p3_0,
  140724. 1, -531628032, 1611661312, 4, 0,
  140725. _vq_quantlist__44cn1_s_p3_0,
  140726. NULL,
  140727. &_vq_auxt__44cn1_s_p3_0,
  140728. NULL,
  140729. 0
  140730. };
  140731. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140732. 4,
  140733. 3,
  140734. 5,
  140735. 2,
  140736. 6,
  140737. 1,
  140738. 7,
  140739. 0,
  140740. 8,
  140741. };
  140742. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140743. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140744. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140745. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140746. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140747. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140748. 11,
  140749. };
  140750. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140751. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140752. };
  140753. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140754. 7, 5, 3, 1, 0, 2, 4, 6,
  140755. 8,
  140756. };
  140757. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140758. _vq_quantthresh__44cn1_s_p4_0,
  140759. _vq_quantmap__44cn1_s_p4_0,
  140760. 9,
  140761. 9
  140762. };
  140763. static static_codebook _44cn1_s_p4_0 = {
  140764. 2, 81,
  140765. _vq_lengthlist__44cn1_s_p4_0,
  140766. 1, -531628032, 1611661312, 4, 0,
  140767. _vq_quantlist__44cn1_s_p4_0,
  140768. NULL,
  140769. &_vq_auxt__44cn1_s_p4_0,
  140770. NULL,
  140771. 0
  140772. };
  140773. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140774. 8,
  140775. 7,
  140776. 9,
  140777. 6,
  140778. 10,
  140779. 5,
  140780. 11,
  140781. 4,
  140782. 12,
  140783. 3,
  140784. 13,
  140785. 2,
  140786. 14,
  140787. 1,
  140788. 15,
  140789. 0,
  140790. 16,
  140791. };
  140792. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140793. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140794. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140795. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140796. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140797. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140798. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140799. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140800. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140801. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140802. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140803. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140804. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140805. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140806. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140807. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140808. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140809. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140811. 14,
  140812. };
  140813. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140814. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140815. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140816. };
  140817. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140818. 15, 13, 11, 9, 7, 5, 3, 1,
  140819. 0, 2, 4, 6, 8, 10, 12, 14,
  140820. 16,
  140821. };
  140822. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140823. _vq_quantthresh__44cn1_s_p5_0,
  140824. _vq_quantmap__44cn1_s_p5_0,
  140825. 17,
  140826. 17
  140827. };
  140828. static static_codebook _44cn1_s_p5_0 = {
  140829. 2, 289,
  140830. _vq_lengthlist__44cn1_s_p5_0,
  140831. 1, -529530880, 1611661312, 5, 0,
  140832. _vq_quantlist__44cn1_s_p5_0,
  140833. NULL,
  140834. &_vq_auxt__44cn1_s_p5_0,
  140835. NULL,
  140836. 0
  140837. };
  140838. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140839. 1,
  140840. 0,
  140841. 2,
  140842. };
  140843. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140844. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140845. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140846. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140847. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140848. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140849. 10,
  140850. };
  140851. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140852. -5.5, 5.5,
  140853. };
  140854. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140855. 1, 0, 2,
  140856. };
  140857. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140858. _vq_quantthresh__44cn1_s_p6_0,
  140859. _vq_quantmap__44cn1_s_p6_0,
  140860. 3,
  140861. 3
  140862. };
  140863. static static_codebook _44cn1_s_p6_0 = {
  140864. 4, 81,
  140865. _vq_lengthlist__44cn1_s_p6_0,
  140866. 1, -529137664, 1618345984, 2, 0,
  140867. _vq_quantlist__44cn1_s_p6_0,
  140868. NULL,
  140869. &_vq_auxt__44cn1_s_p6_0,
  140870. NULL,
  140871. 0
  140872. };
  140873. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140874. 5,
  140875. 4,
  140876. 6,
  140877. 3,
  140878. 7,
  140879. 2,
  140880. 8,
  140881. 1,
  140882. 9,
  140883. 0,
  140884. 10,
  140885. };
  140886. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140887. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140888. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140889. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140890. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140891. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140892. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140893. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140894. 10,10,10, 9, 9, 9, 9, 9, 9,
  140895. };
  140896. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140897. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140898. 3.5, 4.5,
  140899. };
  140900. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140901. 9, 7, 5, 3, 1, 0, 2, 4,
  140902. 6, 8, 10,
  140903. };
  140904. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140905. _vq_quantthresh__44cn1_s_p6_1,
  140906. _vq_quantmap__44cn1_s_p6_1,
  140907. 11,
  140908. 11
  140909. };
  140910. static static_codebook _44cn1_s_p6_1 = {
  140911. 2, 121,
  140912. _vq_lengthlist__44cn1_s_p6_1,
  140913. 1, -531365888, 1611661312, 4, 0,
  140914. _vq_quantlist__44cn1_s_p6_1,
  140915. NULL,
  140916. &_vq_auxt__44cn1_s_p6_1,
  140917. NULL,
  140918. 0
  140919. };
  140920. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140921. 6,
  140922. 5,
  140923. 7,
  140924. 4,
  140925. 8,
  140926. 3,
  140927. 9,
  140928. 2,
  140929. 10,
  140930. 1,
  140931. 11,
  140932. 0,
  140933. 12,
  140934. };
  140935. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140936. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140937. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140938. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140939. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140940. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140941. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140942. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140943. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140944. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140945. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140946. 0,13,13,12,12,13,13,13,14,
  140947. };
  140948. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140949. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140950. 12.5, 17.5, 22.5, 27.5,
  140951. };
  140952. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140953. 11, 9, 7, 5, 3, 1, 0, 2,
  140954. 4, 6, 8, 10, 12,
  140955. };
  140956. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140957. _vq_quantthresh__44cn1_s_p7_0,
  140958. _vq_quantmap__44cn1_s_p7_0,
  140959. 13,
  140960. 13
  140961. };
  140962. static static_codebook _44cn1_s_p7_0 = {
  140963. 2, 169,
  140964. _vq_lengthlist__44cn1_s_p7_0,
  140965. 1, -526516224, 1616117760, 4, 0,
  140966. _vq_quantlist__44cn1_s_p7_0,
  140967. NULL,
  140968. &_vq_auxt__44cn1_s_p7_0,
  140969. NULL,
  140970. 0
  140971. };
  140972. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140973. 2,
  140974. 1,
  140975. 3,
  140976. 0,
  140977. 4,
  140978. };
  140979. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140980. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140981. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140982. };
  140983. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140984. -1.5, -0.5, 0.5, 1.5,
  140985. };
  140986. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140987. 3, 1, 0, 2, 4,
  140988. };
  140989. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140990. _vq_quantthresh__44cn1_s_p7_1,
  140991. _vq_quantmap__44cn1_s_p7_1,
  140992. 5,
  140993. 5
  140994. };
  140995. static static_codebook _44cn1_s_p7_1 = {
  140996. 2, 25,
  140997. _vq_lengthlist__44cn1_s_p7_1,
  140998. 1, -533725184, 1611661312, 3, 0,
  140999. _vq_quantlist__44cn1_s_p7_1,
  141000. NULL,
  141001. &_vq_auxt__44cn1_s_p7_1,
  141002. NULL,
  141003. 0
  141004. };
  141005. static long _vq_quantlist__44cn1_s_p8_0[] = {
  141006. 2,
  141007. 1,
  141008. 3,
  141009. 0,
  141010. 4,
  141011. };
  141012. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  141013. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  141014. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  141015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141016. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  141017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141020. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  141021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141022. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  141023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141028. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  141029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141046. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141047. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141048. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141049. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141050. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141051. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141052. 12,
  141053. };
  141054. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141055. -331.5, -110.5, 110.5, 331.5,
  141056. };
  141057. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141058. 3, 1, 0, 2, 4,
  141059. };
  141060. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141061. _vq_quantthresh__44cn1_s_p8_0,
  141062. _vq_quantmap__44cn1_s_p8_0,
  141063. 5,
  141064. 5
  141065. };
  141066. static static_codebook _44cn1_s_p8_0 = {
  141067. 4, 625,
  141068. _vq_lengthlist__44cn1_s_p8_0,
  141069. 1, -518283264, 1627103232, 3, 0,
  141070. _vq_quantlist__44cn1_s_p8_0,
  141071. NULL,
  141072. &_vq_auxt__44cn1_s_p8_0,
  141073. NULL,
  141074. 0
  141075. };
  141076. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141077. 6,
  141078. 5,
  141079. 7,
  141080. 4,
  141081. 8,
  141082. 3,
  141083. 9,
  141084. 2,
  141085. 10,
  141086. 1,
  141087. 11,
  141088. 0,
  141089. 12,
  141090. };
  141091. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141092. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141093. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141094. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141095. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141096. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141097. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141098. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141099. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141100. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141101. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141102. 15,12,12,11,11,14,12,13,14,
  141103. };
  141104. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141105. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141106. 42.5, 59.5, 76.5, 93.5,
  141107. };
  141108. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141109. 11, 9, 7, 5, 3, 1, 0, 2,
  141110. 4, 6, 8, 10, 12,
  141111. };
  141112. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141113. _vq_quantthresh__44cn1_s_p8_1,
  141114. _vq_quantmap__44cn1_s_p8_1,
  141115. 13,
  141116. 13
  141117. };
  141118. static static_codebook _44cn1_s_p8_1 = {
  141119. 2, 169,
  141120. _vq_lengthlist__44cn1_s_p8_1,
  141121. 1, -522616832, 1620115456, 4, 0,
  141122. _vq_quantlist__44cn1_s_p8_1,
  141123. NULL,
  141124. &_vq_auxt__44cn1_s_p8_1,
  141125. NULL,
  141126. 0
  141127. };
  141128. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141129. 8,
  141130. 7,
  141131. 9,
  141132. 6,
  141133. 10,
  141134. 5,
  141135. 11,
  141136. 4,
  141137. 12,
  141138. 3,
  141139. 13,
  141140. 2,
  141141. 14,
  141142. 1,
  141143. 15,
  141144. 0,
  141145. 16,
  141146. };
  141147. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141148. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141149. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141150. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141151. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141152. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141153. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141154. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141155. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141156. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141157. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141158. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141159. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141160. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141161. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141162. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141163. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141164. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141165. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141166. 9,
  141167. };
  141168. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141169. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141170. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141171. };
  141172. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141173. 15, 13, 11, 9, 7, 5, 3, 1,
  141174. 0, 2, 4, 6, 8, 10, 12, 14,
  141175. 16,
  141176. };
  141177. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141178. _vq_quantthresh__44cn1_s_p8_2,
  141179. _vq_quantmap__44cn1_s_p8_2,
  141180. 17,
  141181. 17
  141182. };
  141183. static static_codebook _44cn1_s_p8_2 = {
  141184. 2, 289,
  141185. _vq_lengthlist__44cn1_s_p8_2,
  141186. 1, -529530880, 1611661312, 5, 0,
  141187. _vq_quantlist__44cn1_s_p8_2,
  141188. NULL,
  141189. &_vq_auxt__44cn1_s_p8_2,
  141190. NULL,
  141191. 0
  141192. };
  141193. static long _huff_lengthlist__44cn1_s_short[] = {
  141194. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141195. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141196. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141197. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141198. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141199. 10,
  141200. };
  141201. static static_codebook _huff_book__44cn1_s_short = {
  141202. 2, 81,
  141203. _huff_lengthlist__44cn1_s_short,
  141204. 0, 0, 0, 0, 0,
  141205. NULL,
  141206. NULL,
  141207. NULL,
  141208. NULL,
  141209. 0
  141210. };
  141211. static long _huff_lengthlist__44cn1_sm_long[] = {
  141212. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141213. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141214. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141215. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141216. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141217. 17,
  141218. };
  141219. static static_codebook _huff_book__44cn1_sm_long = {
  141220. 2, 81,
  141221. _huff_lengthlist__44cn1_sm_long,
  141222. 0, 0, 0, 0, 0,
  141223. NULL,
  141224. NULL,
  141225. NULL,
  141226. NULL,
  141227. 0
  141228. };
  141229. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141230. 1,
  141231. 0,
  141232. 2,
  141233. };
  141234. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141235. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141236. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141241. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141246. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  141281. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  141286. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141291. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141327. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141332. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141337. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141645. 0,
  141646. };
  141647. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141648. -0.5, 0.5,
  141649. };
  141650. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141651. 1, 0, 2,
  141652. };
  141653. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141654. _vq_quantthresh__44cn1_sm_p1_0,
  141655. _vq_quantmap__44cn1_sm_p1_0,
  141656. 3,
  141657. 3
  141658. };
  141659. static static_codebook _44cn1_sm_p1_0 = {
  141660. 8, 6561,
  141661. _vq_lengthlist__44cn1_sm_p1_0,
  141662. 1, -535822336, 1611661312, 2, 0,
  141663. _vq_quantlist__44cn1_sm_p1_0,
  141664. NULL,
  141665. &_vq_auxt__44cn1_sm_p1_0,
  141666. NULL,
  141667. 0
  141668. };
  141669. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141670. 2,
  141671. 1,
  141672. 3,
  141673. 0,
  141674. 4,
  141675. };
  141676. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141677. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141680. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141683. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141716. 0,
  141717. };
  141718. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141719. -1.5, -0.5, 0.5, 1.5,
  141720. };
  141721. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141722. 3, 1, 0, 2, 4,
  141723. };
  141724. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141725. _vq_quantthresh__44cn1_sm_p2_0,
  141726. _vq_quantmap__44cn1_sm_p2_0,
  141727. 5,
  141728. 5
  141729. };
  141730. static static_codebook _44cn1_sm_p2_0 = {
  141731. 4, 625,
  141732. _vq_lengthlist__44cn1_sm_p2_0,
  141733. 1, -533725184, 1611661312, 3, 0,
  141734. _vq_quantlist__44cn1_sm_p2_0,
  141735. NULL,
  141736. &_vq_auxt__44cn1_sm_p2_0,
  141737. NULL,
  141738. 0
  141739. };
  141740. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141741. 4,
  141742. 3,
  141743. 5,
  141744. 2,
  141745. 6,
  141746. 1,
  141747. 7,
  141748. 0,
  141749. 8,
  141750. };
  141751. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141752. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141753. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141754. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141755. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141756. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141757. 0,
  141758. };
  141759. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141760. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141761. };
  141762. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141763. 7, 5, 3, 1, 0, 2, 4, 6,
  141764. 8,
  141765. };
  141766. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141767. _vq_quantthresh__44cn1_sm_p3_0,
  141768. _vq_quantmap__44cn1_sm_p3_0,
  141769. 9,
  141770. 9
  141771. };
  141772. static static_codebook _44cn1_sm_p3_0 = {
  141773. 2, 81,
  141774. _vq_lengthlist__44cn1_sm_p3_0,
  141775. 1, -531628032, 1611661312, 4, 0,
  141776. _vq_quantlist__44cn1_sm_p3_0,
  141777. NULL,
  141778. &_vq_auxt__44cn1_sm_p3_0,
  141779. NULL,
  141780. 0
  141781. };
  141782. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141783. 4,
  141784. 3,
  141785. 5,
  141786. 2,
  141787. 6,
  141788. 1,
  141789. 7,
  141790. 0,
  141791. 8,
  141792. };
  141793. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141794. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141795. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141796. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141797. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141798. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141799. 11,
  141800. };
  141801. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141802. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141803. };
  141804. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141805. 7, 5, 3, 1, 0, 2, 4, 6,
  141806. 8,
  141807. };
  141808. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141809. _vq_quantthresh__44cn1_sm_p4_0,
  141810. _vq_quantmap__44cn1_sm_p4_0,
  141811. 9,
  141812. 9
  141813. };
  141814. static static_codebook _44cn1_sm_p4_0 = {
  141815. 2, 81,
  141816. _vq_lengthlist__44cn1_sm_p4_0,
  141817. 1, -531628032, 1611661312, 4, 0,
  141818. _vq_quantlist__44cn1_sm_p4_0,
  141819. NULL,
  141820. &_vq_auxt__44cn1_sm_p4_0,
  141821. NULL,
  141822. 0
  141823. };
  141824. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141825. 8,
  141826. 7,
  141827. 9,
  141828. 6,
  141829. 10,
  141830. 5,
  141831. 11,
  141832. 4,
  141833. 12,
  141834. 3,
  141835. 13,
  141836. 2,
  141837. 14,
  141838. 1,
  141839. 15,
  141840. 0,
  141841. 16,
  141842. };
  141843. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141844. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141845. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141846. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141847. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141848. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141849. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141850. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141851. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141852. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141853. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141854. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141855. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141856. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141857. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141858. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141859. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141860. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141861. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141862. 14,
  141863. };
  141864. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141865. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141866. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141867. };
  141868. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141869. 15, 13, 11, 9, 7, 5, 3, 1,
  141870. 0, 2, 4, 6, 8, 10, 12, 14,
  141871. 16,
  141872. };
  141873. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141874. _vq_quantthresh__44cn1_sm_p5_0,
  141875. _vq_quantmap__44cn1_sm_p5_0,
  141876. 17,
  141877. 17
  141878. };
  141879. static static_codebook _44cn1_sm_p5_0 = {
  141880. 2, 289,
  141881. _vq_lengthlist__44cn1_sm_p5_0,
  141882. 1, -529530880, 1611661312, 5, 0,
  141883. _vq_quantlist__44cn1_sm_p5_0,
  141884. NULL,
  141885. &_vq_auxt__44cn1_sm_p5_0,
  141886. NULL,
  141887. 0
  141888. };
  141889. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141890. 1,
  141891. 0,
  141892. 2,
  141893. };
  141894. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141895. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141896. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141897. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141898. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141899. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141900. 10,
  141901. };
  141902. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141903. -5.5, 5.5,
  141904. };
  141905. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141906. 1, 0, 2,
  141907. };
  141908. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141909. _vq_quantthresh__44cn1_sm_p6_0,
  141910. _vq_quantmap__44cn1_sm_p6_0,
  141911. 3,
  141912. 3
  141913. };
  141914. static static_codebook _44cn1_sm_p6_0 = {
  141915. 4, 81,
  141916. _vq_lengthlist__44cn1_sm_p6_0,
  141917. 1, -529137664, 1618345984, 2, 0,
  141918. _vq_quantlist__44cn1_sm_p6_0,
  141919. NULL,
  141920. &_vq_auxt__44cn1_sm_p6_0,
  141921. NULL,
  141922. 0
  141923. };
  141924. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141925. 5,
  141926. 4,
  141927. 6,
  141928. 3,
  141929. 7,
  141930. 2,
  141931. 8,
  141932. 1,
  141933. 9,
  141934. 0,
  141935. 10,
  141936. };
  141937. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141938. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141939. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141940. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141941. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141942. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141943. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141944. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141945. 10,10,10, 8, 9, 8, 8, 9, 8,
  141946. };
  141947. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141948. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141949. 3.5, 4.5,
  141950. };
  141951. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141952. 9, 7, 5, 3, 1, 0, 2, 4,
  141953. 6, 8, 10,
  141954. };
  141955. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141956. _vq_quantthresh__44cn1_sm_p6_1,
  141957. _vq_quantmap__44cn1_sm_p6_1,
  141958. 11,
  141959. 11
  141960. };
  141961. static static_codebook _44cn1_sm_p6_1 = {
  141962. 2, 121,
  141963. _vq_lengthlist__44cn1_sm_p6_1,
  141964. 1, -531365888, 1611661312, 4, 0,
  141965. _vq_quantlist__44cn1_sm_p6_1,
  141966. NULL,
  141967. &_vq_auxt__44cn1_sm_p6_1,
  141968. NULL,
  141969. 0
  141970. };
  141971. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141972. 6,
  141973. 5,
  141974. 7,
  141975. 4,
  141976. 8,
  141977. 3,
  141978. 9,
  141979. 2,
  141980. 10,
  141981. 1,
  141982. 11,
  141983. 0,
  141984. 12,
  141985. };
  141986. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141987. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141988. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141989. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141990. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141991. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141992. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141993. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141994. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141995. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141996. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141997. 0,13,12,12,12,13,13,13,14,
  141998. };
  141999. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  142000. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142001. 12.5, 17.5, 22.5, 27.5,
  142002. };
  142003. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  142004. 11, 9, 7, 5, 3, 1, 0, 2,
  142005. 4, 6, 8, 10, 12,
  142006. };
  142007. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  142008. _vq_quantthresh__44cn1_sm_p7_0,
  142009. _vq_quantmap__44cn1_sm_p7_0,
  142010. 13,
  142011. 13
  142012. };
  142013. static static_codebook _44cn1_sm_p7_0 = {
  142014. 2, 169,
  142015. _vq_lengthlist__44cn1_sm_p7_0,
  142016. 1, -526516224, 1616117760, 4, 0,
  142017. _vq_quantlist__44cn1_sm_p7_0,
  142018. NULL,
  142019. &_vq_auxt__44cn1_sm_p7_0,
  142020. NULL,
  142021. 0
  142022. };
  142023. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  142024. 2,
  142025. 1,
  142026. 3,
  142027. 0,
  142028. 4,
  142029. };
  142030. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142031. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142032. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142033. };
  142034. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142035. -1.5, -0.5, 0.5, 1.5,
  142036. };
  142037. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142038. 3, 1, 0, 2, 4,
  142039. };
  142040. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142041. _vq_quantthresh__44cn1_sm_p7_1,
  142042. _vq_quantmap__44cn1_sm_p7_1,
  142043. 5,
  142044. 5
  142045. };
  142046. static static_codebook _44cn1_sm_p7_1 = {
  142047. 2, 25,
  142048. _vq_lengthlist__44cn1_sm_p7_1,
  142049. 1, -533725184, 1611661312, 3, 0,
  142050. _vq_quantlist__44cn1_sm_p7_1,
  142051. NULL,
  142052. &_vq_auxt__44cn1_sm_p7_1,
  142053. NULL,
  142054. 0
  142055. };
  142056. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142057. 4,
  142058. 3,
  142059. 5,
  142060. 2,
  142061. 6,
  142062. 1,
  142063. 7,
  142064. 0,
  142065. 8,
  142066. };
  142067. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142068. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142069. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142070. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142071. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142072. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142073. 14,
  142074. };
  142075. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142076. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142077. };
  142078. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142079. 7, 5, 3, 1, 0, 2, 4, 6,
  142080. 8,
  142081. };
  142082. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142083. _vq_quantthresh__44cn1_sm_p8_0,
  142084. _vq_quantmap__44cn1_sm_p8_0,
  142085. 9,
  142086. 9
  142087. };
  142088. static static_codebook _44cn1_sm_p8_0 = {
  142089. 2, 81,
  142090. _vq_lengthlist__44cn1_sm_p8_0,
  142091. 1, -516186112, 1627103232, 4, 0,
  142092. _vq_quantlist__44cn1_sm_p8_0,
  142093. NULL,
  142094. &_vq_auxt__44cn1_sm_p8_0,
  142095. NULL,
  142096. 0
  142097. };
  142098. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142099. 6,
  142100. 5,
  142101. 7,
  142102. 4,
  142103. 8,
  142104. 3,
  142105. 9,
  142106. 2,
  142107. 10,
  142108. 1,
  142109. 11,
  142110. 0,
  142111. 12,
  142112. };
  142113. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142114. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142115. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142116. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142117. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142118. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142119. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142120. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142121. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142122. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142123. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142124. 17,12,12,11,10,13,11,13,13,
  142125. };
  142126. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142127. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142128. 42.5, 59.5, 76.5, 93.5,
  142129. };
  142130. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142131. 11, 9, 7, 5, 3, 1, 0, 2,
  142132. 4, 6, 8, 10, 12,
  142133. };
  142134. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142135. _vq_quantthresh__44cn1_sm_p8_1,
  142136. _vq_quantmap__44cn1_sm_p8_1,
  142137. 13,
  142138. 13
  142139. };
  142140. static static_codebook _44cn1_sm_p8_1 = {
  142141. 2, 169,
  142142. _vq_lengthlist__44cn1_sm_p8_1,
  142143. 1, -522616832, 1620115456, 4, 0,
  142144. _vq_quantlist__44cn1_sm_p8_1,
  142145. NULL,
  142146. &_vq_auxt__44cn1_sm_p8_1,
  142147. NULL,
  142148. 0
  142149. };
  142150. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142151. 8,
  142152. 7,
  142153. 9,
  142154. 6,
  142155. 10,
  142156. 5,
  142157. 11,
  142158. 4,
  142159. 12,
  142160. 3,
  142161. 13,
  142162. 2,
  142163. 14,
  142164. 1,
  142165. 15,
  142166. 0,
  142167. 16,
  142168. };
  142169. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142170. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142171. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142172. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142173. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142174. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142175. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142176. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142177. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142178. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142179. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142180. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142181. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142182. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142183. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142184. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142185. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142186. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142187. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142188. 9,
  142189. };
  142190. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142191. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142192. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142193. };
  142194. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142195. 15, 13, 11, 9, 7, 5, 3, 1,
  142196. 0, 2, 4, 6, 8, 10, 12, 14,
  142197. 16,
  142198. };
  142199. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142200. _vq_quantthresh__44cn1_sm_p8_2,
  142201. _vq_quantmap__44cn1_sm_p8_2,
  142202. 17,
  142203. 17
  142204. };
  142205. static static_codebook _44cn1_sm_p8_2 = {
  142206. 2, 289,
  142207. _vq_lengthlist__44cn1_sm_p8_2,
  142208. 1, -529530880, 1611661312, 5, 0,
  142209. _vq_quantlist__44cn1_sm_p8_2,
  142210. NULL,
  142211. &_vq_auxt__44cn1_sm_p8_2,
  142212. NULL,
  142213. 0
  142214. };
  142215. static long _huff_lengthlist__44cn1_sm_short[] = {
  142216. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142217. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142218. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142219. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142220. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142221. 9,
  142222. };
  142223. static static_codebook _huff_book__44cn1_sm_short = {
  142224. 2, 81,
  142225. _huff_lengthlist__44cn1_sm_short,
  142226. 0, 0, 0, 0, 0,
  142227. NULL,
  142228. NULL,
  142229. NULL,
  142230. NULL,
  142231. 0
  142232. };
  142233. /*** End of inlined file: res_books_stereo.h ***/
  142234. /***** residue backends *********************************************/
  142235. static vorbis_info_residue0 _residue_44_low={
  142236. 0,-1, -1, 9,-1,
  142237. /* 0 1 2 3 4 5 6 7 */
  142238. {0},
  142239. {-1},
  142240. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142241. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142242. };
  142243. static vorbis_info_residue0 _residue_44_mid={
  142244. 0,-1, -1, 10,-1,
  142245. /* 0 1 2 3 4 5 6 7 8 */
  142246. {0},
  142247. {-1},
  142248. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142249. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142250. };
  142251. static vorbis_info_residue0 _residue_44_high={
  142252. 0,-1, -1, 10,-1,
  142253. /* 0 1 2 3 4 5 6 7 8 */
  142254. {0},
  142255. {-1},
  142256. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142257. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142258. };
  142259. static static_bookblock _resbook_44s_n1={
  142260. {
  142261. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142262. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142263. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142264. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142265. }
  142266. };
  142267. static static_bookblock _resbook_44sm_n1={
  142268. {
  142269. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142270. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142271. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142272. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142273. }
  142274. };
  142275. static static_bookblock _resbook_44s_0={
  142276. {
  142277. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142278. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142279. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142280. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142281. }
  142282. };
  142283. static static_bookblock _resbook_44sm_0={
  142284. {
  142285. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142286. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142287. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142288. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142289. }
  142290. };
  142291. static static_bookblock _resbook_44s_1={
  142292. {
  142293. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142294. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142295. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142296. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142297. }
  142298. };
  142299. static static_bookblock _resbook_44sm_1={
  142300. {
  142301. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142302. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142303. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142304. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142305. }
  142306. };
  142307. static static_bookblock _resbook_44s_2={
  142308. {
  142309. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142310. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142311. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142312. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142313. }
  142314. };
  142315. static static_bookblock _resbook_44s_3={
  142316. {
  142317. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142318. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142319. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142320. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142321. }
  142322. };
  142323. static static_bookblock _resbook_44s_4={
  142324. {
  142325. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142326. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142327. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142328. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142329. }
  142330. };
  142331. static static_bookblock _resbook_44s_5={
  142332. {
  142333. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142334. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142335. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142336. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142337. }
  142338. };
  142339. static static_bookblock _resbook_44s_6={
  142340. {
  142341. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142342. {0,0,&_44c6_s_p4_0},
  142343. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142344. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142345. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142346. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142347. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142348. }
  142349. };
  142350. static static_bookblock _resbook_44s_7={
  142351. {
  142352. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142353. {0,0,&_44c7_s_p4_0},
  142354. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142355. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142356. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142357. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142358. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142359. }
  142360. };
  142361. static static_bookblock _resbook_44s_8={
  142362. {
  142363. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142364. {0,0,&_44c8_s_p4_0},
  142365. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142366. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142367. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142368. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142369. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142370. }
  142371. };
  142372. static static_bookblock _resbook_44s_9={
  142373. {
  142374. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142375. {0,0,&_44c9_s_p4_0},
  142376. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142377. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142378. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142379. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142380. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142381. }
  142382. };
  142383. static vorbis_residue_template _res_44s_n1[]={
  142384. {2,0, &_residue_44_low,
  142385. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142386. &_resbook_44s_n1,&_resbook_44sm_n1},
  142387. {2,0, &_residue_44_low,
  142388. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142389. &_resbook_44s_n1,&_resbook_44sm_n1}
  142390. };
  142391. static vorbis_residue_template _res_44s_0[]={
  142392. {2,0, &_residue_44_low,
  142393. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142394. &_resbook_44s_0,&_resbook_44sm_0},
  142395. {2,0, &_residue_44_low,
  142396. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142397. &_resbook_44s_0,&_resbook_44sm_0}
  142398. };
  142399. static vorbis_residue_template _res_44s_1[]={
  142400. {2,0, &_residue_44_low,
  142401. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142402. &_resbook_44s_1,&_resbook_44sm_1},
  142403. {2,0, &_residue_44_low,
  142404. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142405. &_resbook_44s_1,&_resbook_44sm_1}
  142406. };
  142407. static vorbis_residue_template _res_44s_2[]={
  142408. {2,0, &_residue_44_mid,
  142409. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142410. &_resbook_44s_2,&_resbook_44s_2},
  142411. {2,0, &_residue_44_mid,
  142412. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142413. &_resbook_44s_2,&_resbook_44s_2}
  142414. };
  142415. static vorbis_residue_template _res_44s_3[]={
  142416. {2,0, &_residue_44_mid,
  142417. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142418. &_resbook_44s_3,&_resbook_44s_3},
  142419. {2,0, &_residue_44_mid,
  142420. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142421. &_resbook_44s_3,&_resbook_44s_3}
  142422. };
  142423. static vorbis_residue_template _res_44s_4[]={
  142424. {2,0, &_residue_44_mid,
  142425. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142426. &_resbook_44s_4,&_resbook_44s_4},
  142427. {2,0, &_residue_44_mid,
  142428. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142429. &_resbook_44s_4,&_resbook_44s_4}
  142430. };
  142431. static vorbis_residue_template _res_44s_5[]={
  142432. {2,0, &_residue_44_mid,
  142433. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142434. &_resbook_44s_5,&_resbook_44s_5},
  142435. {2,0, &_residue_44_mid,
  142436. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142437. &_resbook_44s_5,&_resbook_44s_5}
  142438. };
  142439. static vorbis_residue_template _res_44s_6[]={
  142440. {2,0, &_residue_44_high,
  142441. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142442. &_resbook_44s_6,&_resbook_44s_6},
  142443. {2,0, &_residue_44_high,
  142444. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142445. &_resbook_44s_6,&_resbook_44s_6}
  142446. };
  142447. static vorbis_residue_template _res_44s_7[]={
  142448. {2,0, &_residue_44_high,
  142449. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142450. &_resbook_44s_7,&_resbook_44s_7},
  142451. {2,0, &_residue_44_high,
  142452. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142453. &_resbook_44s_7,&_resbook_44s_7}
  142454. };
  142455. static vorbis_residue_template _res_44s_8[]={
  142456. {2,0, &_residue_44_high,
  142457. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142458. &_resbook_44s_8,&_resbook_44s_8},
  142459. {2,0, &_residue_44_high,
  142460. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142461. &_resbook_44s_8,&_resbook_44s_8}
  142462. };
  142463. static vorbis_residue_template _res_44s_9[]={
  142464. {2,0, &_residue_44_high,
  142465. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142466. &_resbook_44s_9,&_resbook_44s_9},
  142467. {2,0, &_residue_44_high,
  142468. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142469. &_resbook_44s_9,&_resbook_44s_9}
  142470. };
  142471. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142472. { _map_nominal, _res_44s_n1 }, /* -1 */
  142473. { _map_nominal, _res_44s_0 }, /* 0 */
  142474. { _map_nominal, _res_44s_1 }, /* 1 */
  142475. { _map_nominal, _res_44s_2 }, /* 2 */
  142476. { _map_nominal, _res_44s_3 }, /* 3 */
  142477. { _map_nominal, _res_44s_4 }, /* 4 */
  142478. { _map_nominal, _res_44s_5 }, /* 5 */
  142479. { _map_nominal, _res_44s_6 }, /* 6 */
  142480. { _map_nominal, _res_44s_7 }, /* 7 */
  142481. { _map_nominal, _res_44s_8 }, /* 8 */
  142482. { _map_nominal, _res_44s_9 }, /* 9 */
  142483. };
  142484. /*** End of inlined file: residue_44.h ***/
  142485. /*** Start of inlined file: psych_44.h ***/
  142486. /* preecho trigger settings *****************************************/
  142487. static vorbis_info_psy_global _psy_global_44[5]={
  142488. {8, /* lines per eighth octave */
  142489. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142490. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142491. -6.f,
  142492. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142493. },
  142494. {8, /* lines per eighth octave */
  142495. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142496. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142497. -6.f,
  142498. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142499. },
  142500. {8, /* lines per eighth octave */
  142501. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142502. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142503. -6.f,
  142504. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142505. },
  142506. {8, /* lines per eighth octave */
  142507. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142508. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142509. -6.f,
  142510. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142511. },
  142512. {8, /* lines per eighth octave */
  142513. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142514. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142515. -6.f,
  142516. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142517. },
  142518. };
  142519. /* noise compander lookups * low, mid, high quality ****************/
  142520. static compandblock _psy_compand_44[6]={
  142521. /* sub-mode Z short */
  142522. {{
  142523. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142524. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142525. 16,17,18,19,20,21,22, 23, /* 23dB */
  142526. 24,25,26,27,28,29,30, 31, /* 31dB */
  142527. 32,33,34,35,36,37,38, 39, /* 39dB */
  142528. }},
  142529. /* mode_Z nominal short */
  142530. {{
  142531. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142532. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142533. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142534. 15,16,17,17,17,18,18, 19, /* 31dB */
  142535. 19,19,20,21,22,23,24, 25, /* 39dB */
  142536. }},
  142537. /* mode A short */
  142538. {{
  142539. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142540. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142541. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142542. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142543. 11,12,13,14,15,16,17, 18, /* 39dB */
  142544. }},
  142545. /* sub-mode Z long */
  142546. {{
  142547. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142548. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142549. 16,17,18,19,20,21,22, 23, /* 23dB */
  142550. 24,25,26,27,28,29,30, 31, /* 31dB */
  142551. 32,33,34,35,36,37,38, 39, /* 39dB */
  142552. }},
  142553. /* mode_Z nominal long */
  142554. {{
  142555. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142556. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142557. 13,14,14,14,15,15,15, 15, /* 23dB */
  142558. 16,16,17,17,17,18,18, 19, /* 31dB */
  142559. 19,19,20,21,22,23,24, 25, /* 39dB */
  142560. }},
  142561. /* mode A long */
  142562. {{
  142563. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142564. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142565. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142566. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142567. 11,12,13,14,15,16,17, 18, /* 39dB */
  142568. }}
  142569. };
  142570. /* tonal masking curve level adjustments *************************/
  142571. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142572. /* 63 125 250 500 1 2 4 8 16 */
  142573. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142574. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142575. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142576. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142577. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142578. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142579. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142580. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142581. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142582. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142583. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142584. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142585. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142586. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142587. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142588. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142589. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142590. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142591. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142592. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142593. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142594. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142595. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142596. };
  142597. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142598. /* 63 125 250 500 1 2 4 8 16 */
  142599. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142600. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142601. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142602. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142603. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142604. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142605. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142606. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142607. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142608. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142609. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142610. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142611. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142612. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142613. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142614. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142615. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142616. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142617. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142618. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142619. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142620. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142621. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142622. };
  142623. /* noise bias (transition block) */
  142624. static noise3 _psy_noisebias_trans[12]={
  142625. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142626. /* -1 */
  142627. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142628. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142629. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142630. /* 0
  142631. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142632. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142633. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142634. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142635. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142636. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142637. /* 1
  142638. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142639. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142640. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142641. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142642. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142643. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142644. /* 2
  142645. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142646. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142647. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142648. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142649. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142650. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142651. /* 3
  142652. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142653. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142654. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142655. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142656. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142657. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142658. /* 4
  142659. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142660. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142661. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142662. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142663. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142664. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142665. /* 5
  142666. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142667. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142668. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142669. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142670. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142671. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142672. /* 6
  142673. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142674. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142675. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142676. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142677. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142678. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142679. /* 7
  142680. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142681. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142682. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142683. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142684. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142685. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142686. /* 8
  142687. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142688. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142689. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142690. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142691. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142692. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142693. /* 9
  142694. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142695. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142696. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142697. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142698. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142699. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142700. /* 10 */
  142701. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142702. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142703. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142704. };
  142705. /* noise bias (long block) */
  142706. static noise3 _psy_noisebias_long[12]={
  142707. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142708. /* -1 */
  142709. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142710. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142711. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142712. /* 0 */
  142713. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142714. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142715. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142716. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142717. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142718. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142719. /* 1 */
  142720. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142721. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142722. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142723. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142724. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142725. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142726. /* 2 */
  142727. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142728. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142729. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142730. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142731. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142732. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142733. /* 3 */
  142734. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142735. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142736. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142737. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142738. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142739. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142740. /* 4 */
  142741. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142742. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142743. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142744. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142745. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142746. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142747. /* 5 */
  142748. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142749. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142750. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142751. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142752. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142753. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142754. /* 6 */
  142755. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142756. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142757. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142758. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142759. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142760. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142761. /* 7 */
  142762. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142763. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142764. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142765. /* 8 */
  142766. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142767. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142768. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142769. /* 9 */
  142770. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142771. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142772. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142773. /* 10 */
  142774. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142775. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142776. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142777. };
  142778. /* noise bias (impulse block) */
  142779. static noise3 _psy_noisebias_impulse[12]={
  142780. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142781. /* -1 */
  142782. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142783. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142784. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142785. /* 0 */
  142786. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142787. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142788. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142789. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142790. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142791. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142792. /* 1 */
  142793. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142794. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142795. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142796. /* 2 */
  142797. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142798. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142799. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142800. /* 3 */
  142801. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142802. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142803. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142804. /* 4 */
  142805. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142806. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142807. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142808. /* 5 */
  142809. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142810. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142811. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142812. /* 6
  142813. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142814. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142815. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142816. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142817. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142818. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142819. /* 7 */
  142820. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142821. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142822. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142823. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142824. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142825. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142826. /* 8 */
  142827. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142828. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142829. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142830. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142831. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142832. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142833. /* 9 */
  142834. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142835. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142836. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142837. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142838. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142839. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142840. /* 10 */
  142841. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142842. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142843. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142844. };
  142845. /* noise bias (padding block) */
  142846. static noise3 _psy_noisebias_padding[12]={
  142847. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142848. /* -1 */
  142849. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142850. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142851. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142852. /* 0 */
  142853. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142854. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142855. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142856. /* 1 */
  142857. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142858. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142859. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142860. /* 2 */
  142861. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142862. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142863. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142864. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142865. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142866. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142867. /* 3 */
  142868. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142869. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142870. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142871. /* 4 */
  142872. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142873. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142874. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142875. /* 5 */
  142876. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142877. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142878. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142879. /* 6 */
  142880. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142881. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142882. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142883. /* 7 */
  142884. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142885. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142886. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142887. /* 8 */
  142888. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142889. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142890. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142891. /* 9 */
  142892. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142893. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142894. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142895. /* 10 */
  142896. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142897. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142898. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142899. };
  142900. static noiseguard _psy_noiseguards_44[4]={
  142901. {3,3,15},
  142902. {3,3,15},
  142903. {10,10,100},
  142904. {10,10,100},
  142905. };
  142906. static int _psy_tone_suppress[12]={
  142907. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142908. };
  142909. static int _psy_tone_0dB[12]={
  142910. 90,90,95,95,95,95,105,105,105,105,105,105,
  142911. };
  142912. static int _psy_noise_suppress[12]={
  142913. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142914. };
  142915. static vorbis_info_psy _psy_info_template={
  142916. /* blockflag */
  142917. -1,
  142918. /* ath_adjatt, ath_maxatt */
  142919. -140.,-140.,
  142920. /* tonemask att boost/decay,suppr,curves */
  142921. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142922. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142923. 1, -0.f, .5f, .5f, 0,0,0,
  142924. /* noiseoffset*3, noisecompand, max_curve_dB */
  142925. {{-1},{-1},{-1}},{-1},105.f,
  142926. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142927. 0,0,-1,-1,0.,
  142928. };
  142929. /* ath ****************/
  142930. static int _psy_ath_floater[12]={
  142931. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142932. };
  142933. static int _psy_ath_abs[12]={
  142934. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142935. };
  142936. /* stereo setup. These don't map directly to quality level, there's
  142937. an additional indirection as several of the below may be used in a
  142938. single bitmanaged stream
  142939. ****************/
  142940. /* various stereo possibilities */
  142941. /* stereo mode by base quality level */
  142942. static adj_stereo _psy_stereo_modes_44[12]={
  142943. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142944. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142945. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142946. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142947. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142948. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142949. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142950. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142951. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142952. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142953. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142954. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142955. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142956. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142957. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142958. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142959. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142960. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142961. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142962. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142963. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142964. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142965. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142966. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142967. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142968. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142969. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142970. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142971. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142972. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142973. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142974. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142975. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142976. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142977. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142978. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142979. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142980. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142981. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142982. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142983. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142984. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142985. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142986. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142987. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142988. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142989. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142990. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142991. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142992. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142993. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142994. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142995. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142996. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142997. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142998. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142999. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  143000. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143001. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143002. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143003. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143004. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143005. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143006. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143007. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143008. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  143009. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143010. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143011. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143012. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143013. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143014. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143015. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143016. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143017. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  143018. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143019. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143020. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143021. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143022. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  143023. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143024. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143025. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143026. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143027. };
  143028. /* tone master attenuation by base quality mode and bitrate tweak */
  143029. static att3 _psy_tone_masteratt_44[12]={
  143030. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143031. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143032. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143033. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143034. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143035. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143036. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143037. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143038. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143039. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143040. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143041. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143042. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143043. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143044. };
  143045. /* lowpass by mode **************/
  143046. static double _psy_lowpass_44[12]={
  143047. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143048. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143049. };
  143050. /* noise normalization **********/
  143051. static int _noise_start_short_44[11]={
  143052. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143053. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143054. };
  143055. static int _noise_start_long_44[11]={
  143056. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143057. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143058. };
  143059. static int _noise_part_short_44[11]={
  143060. 8,8,8,8,8,8,8,8,8,8,8
  143061. };
  143062. static int _noise_part_long_44[11]={
  143063. 32,32,32,32,32,32,32,32,32,32,32
  143064. };
  143065. static double _noise_thresh_44[11]={
  143066. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143067. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143068. };
  143069. static double _noise_thresh_5only[2]={
  143070. .5,.5,
  143071. };
  143072. /*** End of inlined file: psych_44.h ***/
  143073. static double rate_mapping_44_stereo[12]={
  143074. 22500.,32000.,40000.,48000.,56000.,64000.,
  143075. 80000.,96000.,112000.,128000.,160000.,250001.
  143076. };
  143077. static double quality_mapping_44[12]={
  143078. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143079. };
  143080. static int blocksize_short_44[11]={
  143081. 512,256,256,256,256,256,256,256,256,256,256
  143082. };
  143083. static int blocksize_long_44[11]={
  143084. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143085. };
  143086. static double _psy_compand_short_mapping[12]={
  143087. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143088. };
  143089. static double _psy_compand_long_mapping[12]={
  143090. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143091. };
  143092. static double _global_mapping_44[12]={
  143093. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143094. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143095. };
  143096. static int _floor_short_mapping_44[11]={
  143097. 1,0,0,2,2,4,5,5,5,5,5
  143098. };
  143099. static int _floor_long_mapping_44[11]={
  143100. 8,7,7,7,7,7,7,7,7,7,7
  143101. };
  143102. ve_setup_data_template ve_setup_44_stereo={
  143103. 11,
  143104. rate_mapping_44_stereo,
  143105. quality_mapping_44,
  143106. 2,
  143107. 40000,
  143108. 50000,
  143109. blocksize_short_44,
  143110. blocksize_long_44,
  143111. _psy_tone_masteratt_44,
  143112. _psy_tone_0dB,
  143113. _psy_tone_suppress,
  143114. _vp_tonemask_adj_otherblock,
  143115. _vp_tonemask_adj_longblock,
  143116. _vp_tonemask_adj_otherblock,
  143117. _psy_noiseguards_44,
  143118. _psy_noisebias_impulse,
  143119. _psy_noisebias_padding,
  143120. _psy_noisebias_trans,
  143121. _psy_noisebias_long,
  143122. _psy_noise_suppress,
  143123. _psy_compand_44,
  143124. _psy_compand_short_mapping,
  143125. _psy_compand_long_mapping,
  143126. {_noise_start_short_44,_noise_start_long_44},
  143127. {_noise_part_short_44,_noise_part_long_44},
  143128. _noise_thresh_44,
  143129. _psy_ath_floater,
  143130. _psy_ath_abs,
  143131. _psy_lowpass_44,
  143132. _psy_global_44,
  143133. _global_mapping_44,
  143134. _psy_stereo_modes_44,
  143135. _floor_books,
  143136. _floor,
  143137. _floor_short_mapping_44,
  143138. _floor_long_mapping_44,
  143139. _mapres_template_44_stereo
  143140. };
  143141. /*** End of inlined file: setup_44.h ***/
  143142. /*** Start of inlined file: setup_44u.h ***/
  143143. /*** Start of inlined file: residue_44u.h ***/
  143144. /*** Start of inlined file: res_books_uncoupled.h ***/
  143145. static long _vq_quantlist__16u0__p1_0[] = {
  143146. 1,
  143147. 0,
  143148. 2,
  143149. };
  143150. static long _vq_lengthlist__16u0__p1_0[] = {
  143151. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143152. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143153. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143154. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143155. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143156. 12,
  143157. };
  143158. static float _vq_quantthresh__16u0__p1_0[] = {
  143159. -0.5, 0.5,
  143160. };
  143161. static long _vq_quantmap__16u0__p1_0[] = {
  143162. 1, 0, 2,
  143163. };
  143164. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143165. _vq_quantthresh__16u0__p1_0,
  143166. _vq_quantmap__16u0__p1_0,
  143167. 3,
  143168. 3
  143169. };
  143170. static static_codebook _16u0__p1_0 = {
  143171. 4, 81,
  143172. _vq_lengthlist__16u0__p1_0,
  143173. 1, -535822336, 1611661312, 2, 0,
  143174. _vq_quantlist__16u0__p1_0,
  143175. NULL,
  143176. &_vq_auxt__16u0__p1_0,
  143177. NULL,
  143178. 0
  143179. };
  143180. static long _vq_quantlist__16u0__p2_0[] = {
  143181. 1,
  143182. 0,
  143183. 2,
  143184. };
  143185. static long _vq_lengthlist__16u0__p2_0[] = {
  143186. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143187. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143188. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143189. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143190. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143191. 8,
  143192. };
  143193. static float _vq_quantthresh__16u0__p2_0[] = {
  143194. -0.5, 0.5,
  143195. };
  143196. static long _vq_quantmap__16u0__p2_0[] = {
  143197. 1, 0, 2,
  143198. };
  143199. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143200. _vq_quantthresh__16u0__p2_0,
  143201. _vq_quantmap__16u0__p2_0,
  143202. 3,
  143203. 3
  143204. };
  143205. static static_codebook _16u0__p2_0 = {
  143206. 4, 81,
  143207. _vq_lengthlist__16u0__p2_0,
  143208. 1, -535822336, 1611661312, 2, 0,
  143209. _vq_quantlist__16u0__p2_0,
  143210. NULL,
  143211. &_vq_auxt__16u0__p2_0,
  143212. NULL,
  143213. 0
  143214. };
  143215. static long _vq_quantlist__16u0__p3_0[] = {
  143216. 2,
  143217. 1,
  143218. 3,
  143219. 0,
  143220. 4,
  143221. };
  143222. static long _vq_lengthlist__16u0__p3_0[] = {
  143223. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143224. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143225. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143226. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143227. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143228. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143229. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143230. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143231. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143232. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143233. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143234. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143235. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143236. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143237. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143238. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143239. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143240. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143241. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143242. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143243. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143244. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143245. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143246. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143247. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143248. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143249. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143250. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143251. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143252. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143253. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143254. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143255. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143256. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143257. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143258. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143259. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143260. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143261. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143262. 18,
  143263. };
  143264. static float _vq_quantthresh__16u0__p3_0[] = {
  143265. -1.5, -0.5, 0.5, 1.5,
  143266. };
  143267. static long _vq_quantmap__16u0__p3_0[] = {
  143268. 3, 1, 0, 2, 4,
  143269. };
  143270. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143271. _vq_quantthresh__16u0__p3_0,
  143272. _vq_quantmap__16u0__p3_0,
  143273. 5,
  143274. 5
  143275. };
  143276. static static_codebook _16u0__p3_0 = {
  143277. 4, 625,
  143278. _vq_lengthlist__16u0__p3_0,
  143279. 1, -533725184, 1611661312, 3, 0,
  143280. _vq_quantlist__16u0__p3_0,
  143281. NULL,
  143282. &_vq_auxt__16u0__p3_0,
  143283. NULL,
  143284. 0
  143285. };
  143286. static long _vq_quantlist__16u0__p4_0[] = {
  143287. 2,
  143288. 1,
  143289. 3,
  143290. 0,
  143291. 4,
  143292. };
  143293. static long _vq_lengthlist__16u0__p4_0[] = {
  143294. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143295. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143296. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143297. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143298. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143299. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143300. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143301. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143302. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143303. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143304. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143305. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143306. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143307. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143308. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143309. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143310. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143311. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143312. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143313. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143314. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143315. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143316. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143317. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143318. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143319. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143320. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143321. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143322. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143323. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143324. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143325. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143326. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143327. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143328. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143329. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143330. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143331. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143332. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143333. 11,
  143334. };
  143335. static float _vq_quantthresh__16u0__p4_0[] = {
  143336. -1.5, -0.5, 0.5, 1.5,
  143337. };
  143338. static long _vq_quantmap__16u0__p4_0[] = {
  143339. 3, 1, 0, 2, 4,
  143340. };
  143341. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143342. _vq_quantthresh__16u0__p4_0,
  143343. _vq_quantmap__16u0__p4_0,
  143344. 5,
  143345. 5
  143346. };
  143347. static static_codebook _16u0__p4_0 = {
  143348. 4, 625,
  143349. _vq_lengthlist__16u0__p4_0,
  143350. 1, -533725184, 1611661312, 3, 0,
  143351. _vq_quantlist__16u0__p4_0,
  143352. NULL,
  143353. &_vq_auxt__16u0__p4_0,
  143354. NULL,
  143355. 0
  143356. };
  143357. static long _vq_quantlist__16u0__p5_0[] = {
  143358. 4,
  143359. 3,
  143360. 5,
  143361. 2,
  143362. 6,
  143363. 1,
  143364. 7,
  143365. 0,
  143366. 8,
  143367. };
  143368. static long _vq_lengthlist__16u0__p5_0[] = {
  143369. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143370. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143371. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143372. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143373. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143374. 12,
  143375. };
  143376. static float _vq_quantthresh__16u0__p5_0[] = {
  143377. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143378. };
  143379. static long _vq_quantmap__16u0__p5_0[] = {
  143380. 7, 5, 3, 1, 0, 2, 4, 6,
  143381. 8,
  143382. };
  143383. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143384. _vq_quantthresh__16u0__p5_0,
  143385. _vq_quantmap__16u0__p5_0,
  143386. 9,
  143387. 9
  143388. };
  143389. static static_codebook _16u0__p5_0 = {
  143390. 2, 81,
  143391. _vq_lengthlist__16u0__p5_0,
  143392. 1, -531628032, 1611661312, 4, 0,
  143393. _vq_quantlist__16u0__p5_0,
  143394. NULL,
  143395. &_vq_auxt__16u0__p5_0,
  143396. NULL,
  143397. 0
  143398. };
  143399. static long _vq_quantlist__16u0__p6_0[] = {
  143400. 6,
  143401. 5,
  143402. 7,
  143403. 4,
  143404. 8,
  143405. 3,
  143406. 9,
  143407. 2,
  143408. 10,
  143409. 1,
  143410. 11,
  143411. 0,
  143412. 12,
  143413. };
  143414. static long _vq_lengthlist__16u0__p6_0[] = {
  143415. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143416. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143417. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143418. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143419. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143420. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143421. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143422. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143423. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143424. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143425. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143426. };
  143427. static float _vq_quantthresh__16u0__p6_0[] = {
  143428. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143429. 12.5, 17.5, 22.5, 27.5,
  143430. };
  143431. static long _vq_quantmap__16u0__p6_0[] = {
  143432. 11, 9, 7, 5, 3, 1, 0, 2,
  143433. 4, 6, 8, 10, 12,
  143434. };
  143435. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143436. _vq_quantthresh__16u0__p6_0,
  143437. _vq_quantmap__16u0__p6_0,
  143438. 13,
  143439. 13
  143440. };
  143441. static static_codebook _16u0__p6_0 = {
  143442. 2, 169,
  143443. _vq_lengthlist__16u0__p6_0,
  143444. 1, -526516224, 1616117760, 4, 0,
  143445. _vq_quantlist__16u0__p6_0,
  143446. NULL,
  143447. &_vq_auxt__16u0__p6_0,
  143448. NULL,
  143449. 0
  143450. };
  143451. static long _vq_quantlist__16u0__p6_1[] = {
  143452. 2,
  143453. 1,
  143454. 3,
  143455. 0,
  143456. 4,
  143457. };
  143458. static long _vq_lengthlist__16u0__p6_1[] = {
  143459. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143460. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143461. };
  143462. static float _vq_quantthresh__16u0__p6_1[] = {
  143463. -1.5, -0.5, 0.5, 1.5,
  143464. };
  143465. static long _vq_quantmap__16u0__p6_1[] = {
  143466. 3, 1, 0, 2, 4,
  143467. };
  143468. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143469. _vq_quantthresh__16u0__p6_1,
  143470. _vq_quantmap__16u0__p6_1,
  143471. 5,
  143472. 5
  143473. };
  143474. static static_codebook _16u0__p6_1 = {
  143475. 2, 25,
  143476. _vq_lengthlist__16u0__p6_1,
  143477. 1, -533725184, 1611661312, 3, 0,
  143478. _vq_quantlist__16u0__p6_1,
  143479. NULL,
  143480. &_vq_auxt__16u0__p6_1,
  143481. NULL,
  143482. 0
  143483. };
  143484. static long _vq_quantlist__16u0__p7_0[] = {
  143485. 1,
  143486. 0,
  143487. 2,
  143488. };
  143489. static long _vq_lengthlist__16u0__p7_0[] = {
  143490. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143491. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143492. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143493. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143494. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143495. 7,
  143496. };
  143497. static float _vq_quantthresh__16u0__p7_0[] = {
  143498. -157.5, 157.5,
  143499. };
  143500. static long _vq_quantmap__16u0__p7_0[] = {
  143501. 1, 0, 2,
  143502. };
  143503. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143504. _vq_quantthresh__16u0__p7_0,
  143505. _vq_quantmap__16u0__p7_0,
  143506. 3,
  143507. 3
  143508. };
  143509. static static_codebook _16u0__p7_0 = {
  143510. 4, 81,
  143511. _vq_lengthlist__16u0__p7_0,
  143512. 1, -518803456, 1628680192, 2, 0,
  143513. _vq_quantlist__16u0__p7_0,
  143514. NULL,
  143515. &_vq_auxt__16u0__p7_0,
  143516. NULL,
  143517. 0
  143518. };
  143519. static long _vq_quantlist__16u0__p7_1[] = {
  143520. 7,
  143521. 6,
  143522. 8,
  143523. 5,
  143524. 9,
  143525. 4,
  143526. 10,
  143527. 3,
  143528. 11,
  143529. 2,
  143530. 12,
  143531. 1,
  143532. 13,
  143533. 0,
  143534. 14,
  143535. };
  143536. static long _vq_lengthlist__16u0__p7_1[] = {
  143537. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143538. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143539. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143540. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143541. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143542. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143543. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143544. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143545. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143546. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143547. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143548. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143549. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143550. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143551. 10,
  143552. };
  143553. static float _vq_quantthresh__16u0__p7_1[] = {
  143554. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143555. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143556. };
  143557. static long _vq_quantmap__16u0__p7_1[] = {
  143558. 13, 11, 9, 7, 5, 3, 1, 0,
  143559. 2, 4, 6, 8, 10, 12, 14,
  143560. };
  143561. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143562. _vq_quantthresh__16u0__p7_1,
  143563. _vq_quantmap__16u0__p7_1,
  143564. 15,
  143565. 15
  143566. };
  143567. static static_codebook _16u0__p7_1 = {
  143568. 2, 225,
  143569. _vq_lengthlist__16u0__p7_1,
  143570. 1, -520986624, 1620377600, 4, 0,
  143571. _vq_quantlist__16u0__p7_1,
  143572. NULL,
  143573. &_vq_auxt__16u0__p7_1,
  143574. NULL,
  143575. 0
  143576. };
  143577. static long _vq_quantlist__16u0__p7_2[] = {
  143578. 10,
  143579. 9,
  143580. 11,
  143581. 8,
  143582. 12,
  143583. 7,
  143584. 13,
  143585. 6,
  143586. 14,
  143587. 5,
  143588. 15,
  143589. 4,
  143590. 16,
  143591. 3,
  143592. 17,
  143593. 2,
  143594. 18,
  143595. 1,
  143596. 19,
  143597. 0,
  143598. 20,
  143599. };
  143600. static long _vq_lengthlist__16u0__p7_2[] = {
  143601. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143602. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143603. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143604. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143605. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143606. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143607. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143608. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143609. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143610. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143611. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143612. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143613. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143614. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143615. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143616. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143617. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143618. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143619. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143620. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143621. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143622. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143623. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143624. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143625. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143626. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143627. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143628. 10,10,12,11,10,11,11,11,10,
  143629. };
  143630. static float _vq_quantthresh__16u0__p7_2[] = {
  143631. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143632. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143633. 6.5, 7.5, 8.5, 9.5,
  143634. };
  143635. static long _vq_quantmap__16u0__p7_2[] = {
  143636. 19, 17, 15, 13, 11, 9, 7, 5,
  143637. 3, 1, 0, 2, 4, 6, 8, 10,
  143638. 12, 14, 16, 18, 20,
  143639. };
  143640. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143641. _vq_quantthresh__16u0__p7_2,
  143642. _vq_quantmap__16u0__p7_2,
  143643. 21,
  143644. 21
  143645. };
  143646. static static_codebook _16u0__p7_2 = {
  143647. 2, 441,
  143648. _vq_lengthlist__16u0__p7_2,
  143649. 1, -529268736, 1611661312, 5, 0,
  143650. _vq_quantlist__16u0__p7_2,
  143651. NULL,
  143652. &_vq_auxt__16u0__p7_2,
  143653. NULL,
  143654. 0
  143655. };
  143656. static long _huff_lengthlist__16u0__single[] = {
  143657. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143658. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143659. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143660. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143661. };
  143662. static static_codebook _huff_book__16u0__single = {
  143663. 2, 64,
  143664. _huff_lengthlist__16u0__single,
  143665. 0, 0, 0, 0, 0,
  143666. NULL,
  143667. NULL,
  143668. NULL,
  143669. NULL,
  143670. 0
  143671. };
  143672. static long _huff_lengthlist__16u1__long[] = {
  143673. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143674. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143675. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143676. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143677. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143678. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143679. 16,13,16,18,
  143680. };
  143681. static static_codebook _huff_book__16u1__long = {
  143682. 2, 100,
  143683. _huff_lengthlist__16u1__long,
  143684. 0, 0, 0, 0, 0,
  143685. NULL,
  143686. NULL,
  143687. NULL,
  143688. NULL,
  143689. 0
  143690. };
  143691. static long _vq_quantlist__16u1__p1_0[] = {
  143692. 1,
  143693. 0,
  143694. 2,
  143695. };
  143696. static long _vq_lengthlist__16u1__p1_0[] = {
  143697. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143698. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143699. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143700. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143701. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143702. 11,
  143703. };
  143704. static float _vq_quantthresh__16u1__p1_0[] = {
  143705. -0.5, 0.5,
  143706. };
  143707. static long _vq_quantmap__16u1__p1_0[] = {
  143708. 1, 0, 2,
  143709. };
  143710. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143711. _vq_quantthresh__16u1__p1_0,
  143712. _vq_quantmap__16u1__p1_0,
  143713. 3,
  143714. 3
  143715. };
  143716. static static_codebook _16u1__p1_0 = {
  143717. 4, 81,
  143718. _vq_lengthlist__16u1__p1_0,
  143719. 1, -535822336, 1611661312, 2, 0,
  143720. _vq_quantlist__16u1__p1_0,
  143721. NULL,
  143722. &_vq_auxt__16u1__p1_0,
  143723. NULL,
  143724. 0
  143725. };
  143726. static long _vq_quantlist__16u1__p2_0[] = {
  143727. 1,
  143728. 0,
  143729. 2,
  143730. };
  143731. static long _vq_lengthlist__16u1__p2_0[] = {
  143732. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143733. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143734. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143735. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143736. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143737. 8,
  143738. };
  143739. static float _vq_quantthresh__16u1__p2_0[] = {
  143740. -0.5, 0.5,
  143741. };
  143742. static long _vq_quantmap__16u1__p2_0[] = {
  143743. 1, 0, 2,
  143744. };
  143745. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143746. _vq_quantthresh__16u1__p2_0,
  143747. _vq_quantmap__16u1__p2_0,
  143748. 3,
  143749. 3
  143750. };
  143751. static static_codebook _16u1__p2_0 = {
  143752. 4, 81,
  143753. _vq_lengthlist__16u1__p2_0,
  143754. 1, -535822336, 1611661312, 2, 0,
  143755. _vq_quantlist__16u1__p2_0,
  143756. NULL,
  143757. &_vq_auxt__16u1__p2_0,
  143758. NULL,
  143759. 0
  143760. };
  143761. static long _vq_quantlist__16u1__p3_0[] = {
  143762. 2,
  143763. 1,
  143764. 3,
  143765. 0,
  143766. 4,
  143767. };
  143768. static long _vq_lengthlist__16u1__p3_0[] = {
  143769. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143770. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143771. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143772. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143773. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143774. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143775. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143776. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143777. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143778. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143779. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143780. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143781. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143782. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143783. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143784. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143785. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143786. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143787. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143788. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143789. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143790. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143791. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143792. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143793. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143794. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143795. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143796. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143797. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143798. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143799. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143800. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143801. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143802. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143803. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143804. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143805. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143806. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143807. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143808. 16,
  143809. };
  143810. static float _vq_quantthresh__16u1__p3_0[] = {
  143811. -1.5, -0.5, 0.5, 1.5,
  143812. };
  143813. static long _vq_quantmap__16u1__p3_0[] = {
  143814. 3, 1, 0, 2, 4,
  143815. };
  143816. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143817. _vq_quantthresh__16u1__p3_0,
  143818. _vq_quantmap__16u1__p3_0,
  143819. 5,
  143820. 5
  143821. };
  143822. static static_codebook _16u1__p3_0 = {
  143823. 4, 625,
  143824. _vq_lengthlist__16u1__p3_0,
  143825. 1, -533725184, 1611661312, 3, 0,
  143826. _vq_quantlist__16u1__p3_0,
  143827. NULL,
  143828. &_vq_auxt__16u1__p3_0,
  143829. NULL,
  143830. 0
  143831. };
  143832. static long _vq_quantlist__16u1__p4_0[] = {
  143833. 2,
  143834. 1,
  143835. 3,
  143836. 0,
  143837. 4,
  143838. };
  143839. static long _vq_lengthlist__16u1__p4_0[] = {
  143840. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143841. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143842. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143843. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143844. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143845. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143846. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143847. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143848. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143849. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143850. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143851. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143852. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143853. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143854. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143855. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143856. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143857. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143858. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143859. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143860. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143861. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143862. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143863. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143864. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143865. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143866. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143867. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143868. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143869. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143870. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143871. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143872. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143873. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143874. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143875. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143876. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143877. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143878. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143879. 11,
  143880. };
  143881. static float _vq_quantthresh__16u1__p4_0[] = {
  143882. -1.5, -0.5, 0.5, 1.5,
  143883. };
  143884. static long _vq_quantmap__16u1__p4_0[] = {
  143885. 3, 1, 0, 2, 4,
  143886. };
  143887. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143888. _vq_quantthresh__16u1__p4_0,
  143889. _vq_quantmap__16u1__p4_0,
  143890. 5,
  143891. 5
  143892. };
  143893. static static_codebook _16u1__p4_0 = {
  143894. 4, 625,
  143895. _vq_lengthlist__16u1__p4_0,
  143896. 1, -533725184, 1611661312, 3, 0,
  143897. _vq_quantlist__16u1__p4_0,
  143898. NULL,
  143899. &_vq_auxt__16u1__p4_0,
  143900. NULL,
  143901. 0
  143902. };
  143903. static long _vq_quantlist__16u1__p5_0[] = {
  143904. 4,
  143905. 3,
  143906. 5,
  143907. 2,
  143908. 6,
  143909. 1,
  143910. 7,
  143911. 0,
  143912. 8,
  143913. };
  143914. static long _vq_lengthlist__16u1__p5_0[] = {
  143915. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143916. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143917. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143918. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143919. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143920. 13,
  143921. };
  143922. static float _vq_quantthresh__16u1__p5_0[] = {
  143923. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143924. };
  143925. static long _vq_quantmap__16u1__p5_0[] = {
  143926. 7, 5, 3, 1, 0, 2, 4, 6,
  143927. 8,
  143928. };
  143929. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143930. _vq_quantthresh__16u1__p5_0,
  143931. _vq_quantmap__16u1__p5_0,
  143932. 9,
  143933. 9
  143934. };
  143935. static static_codebook _16u1__p5_0 = {
  143936. 2, 81,
  143937. _vq_lengthlist__16u1__p5_0,
  143938. 1, -531628032, 1611661312, 4, 0,
  143939. _vq_quantlist__16u1__p5_0,
  143940. NULL,
  143941. &_vq_auxt__16u1__p5_0,
  143942. NULL,
  143943. 0
  143944. };
  143945. static long _vq_quantlist__16u1__p6_0[] = {
  143946. 4,
  143947. 3,
  143948. 5,
  143949. 2,
  143950. 6,
  143951. 1,
  143952. 7,
  143953. 0,
  143954. 8,
  143955. };
  143956. static long _vq_lengthlist__16u1__p6_0[] = {
  143957. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143958. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143959. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143960. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143961. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143962. 11,
  143963. };
  143964. static float _vq_quantthresh__16u1__p6_0[] = {
  143965. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143966. };
  143967. static long _vq_quantmap__16u1__p6_0[] = {
  143968. 7, 5, 3, 1, 0, 2, 4, 6,
  143969. 8,
  143970. };
  143971. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143972. _vq_quantthresh__16u1__p6_0,
  143973. _vq_quantmap__16u1__p6_0,
  143974. 9,
  143975. 9
  143976. };
  143977. static static_codebook _16u1__p6_0 = {
  143978. 2, 81,
  143979. _vq_lengthlist__16u1__p6_0,
  143980. 1, -531628032, 1611661312, 4, 0,
  143981. _vq_quantlist__16u1__p6_0,
  143982. NULL,
  143983. &_vq_auxt__16u1__p6_0,
  143984. NULL,
  143985. 0
  143986. };
  143987. static long _vq_quantlist__16u1__p7_0[] = {
  143988. 1,
  143989. 0,
  143990. 2,
  143991. };
  143992. static long _vq_lengthlist__16u1__p7_0[] = {
  143993. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143994. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143995. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143996. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143997. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143998. 13,
  143999. };
  144000. static float _vq_quantthresh__16u1__p7_0[] = {
  144001. -5.5, 5.5,
  144002. };
  144003. static long _vq_quantmap__16u1__p7_0[] = {
  144004. 1, 0, 2,
  144005. };
  144006. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  144007. _vq_quantthresh__16u1__p7_0,
  144008. _vq_quantmap__16u1__p7_0,
  144009. 3,
  144010. 3
  144011. };
  144012. static static_codebook _16u1__p7_0 = {
  144013. 4, 81,
  144014. _vq_lengthlist__16u1__p7_0,
  144015. 1, -529137664, 1618345984, 2, 0,
  144016. _vq_quantlist__16u1__p7_0,
  144017. NULL,
  144018. &_vq_auxt__16u1__p7_0,
  144019. NULL,
  144020. 0
  144021. };
  144022. static long _vq_quantlist__16u1__p7_1[] = {
  144023. 5,
  144024. 4,
  144025. 6,
  144026. 3,
  144027. 7,
  144028. 2,
  144029. 8,
  144030. 1,
  144031. 9,
  144032. 0,
  144033. 10,
  144034. };
  144035. static long _vq_lengthlist__16u1__p7_1[] = {
  144036. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144037. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144038. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144039. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144040. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144041. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144042. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144043. 8, 9, 9,10,10,10,10,10,10,
  144044. };
  144045. static float _vq_quantthresh__16u1__p7_1[] = {
  144046. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144047. 3.5, 4.5,
  144048. };
  144049. static long _vq_quantmap__16u1__p7_1[] = {
  144050. 9, 7, 5, 3, 1, 0, 2, 4,
  144051. 6, 8, 10,
  144052. };
  144053. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144054. _vq_quantthresh__16u1__p7_1,
  144055. _vq_quantmap__16u1__p7_1,
  144056. 11,
  144057. 11
  144058. };
  144059. static static_codebook _16u1__p7_1 = {
  144060. 2, 121,
  144061. _vq_lengthlist__16u1__p7_1,
  144062. 1, -531365888, 1611661312, 4, 0,
  144063. _vq_quantlist__16u1__p7_1,
  144064. NULL,
  144065. &_vq_auxt__16u1__p7_1,
  144066. NULL,
  144067. 0
  144068. };
  144069. static long _vq_quantlist__16u1__p8_0[] = {
  144070. 5,
  144071. 4,
  144072. 6,
  144073. 3,
  144074. 7,
  144075. 2,
  144076. 8,
  144077. 1,
  144078. 9,
  144079. 0,
  144080. 10,
  144081. };
  144082. static long _vq_lengthlist__16u1__p8_0[] = {
  144083. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144084. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144085. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144086. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144087. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144088. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144089. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144090. 13,14,14,15,15,16,16,15,16,
  144091. };
  144092. static float _vq_quantthresh__16u1__p8_0[] = {
  144093. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144094. 38.5, 49.5,
  144095. };
  144096. static long _vq_quantmap__16u1__p8_0[] = {
  144097. 9, 7, 5, 3, 1, 0, 2, 4,
  144098. 6, 8, 10,
  144099. };
  144100. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144101. _vq_quantthresh__16u1__p8_0,
  144102. _vq_quantmap__16u1__p8_0,
  144103. 11,
  144104. 11
  144105. };
  144106. static static_codebook _16u1__p8_0 = {
  144107. 2, 121,
  144108. _vq_lengthlist__16u1__p8_0,
  144109. 1, -524582912, 1618345984, 4, 0,
  144110. _vq_quantlist__16u1__p8_0,
  144111. NULL,
  144112. &_vq_auxt__16u1__p8_0,
  144113. NULL,
  144114. 0
  144115. };
  144116. static long _vq_quantlist__16u1__p8_1[] = {
  144117. 5,
  144118. 4,
  144119. 6,
  144120. 3,
  144121. 7,
  144122. 2,
  144123. 8,
  144124. 1,
  144125. 9,
  144126. 0,
  144127. 10,
  144128. };
  144129. static long _vq_lengthlist__16u1__p8_1[] = {
  144130. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144131. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144132. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144133. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144134. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144135. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144136. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144137. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144138. };
  144139. static float _vq_quantthresh__16u1__p8_1[] = {
  144140. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144141. 3.5, 4.5,
  144142. };
  144143. static long _vq_quantmap__16u1__p8_1[] = {
  144144. 9, 7, 5, 3, 1, 0, 2, 4,
  144145. 6, 8, 10,
  144146. };
  144147. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144148. _vq_quantthresh__16u1__p8_1,
  144149. _vq_quantmap__16u1__p8_1,
  144150. 11,
  144151. 11
  144152. };
  144153. static static_codebook _16u1__p8_1 = {
  144154. 2, 121,
  144155. _vq_lengthlist__16u1__p8_1,
  144156. 1, -531365888, 1611661312, 4, 0,
  144157. _vq_quantlist__16u1__p8_1,
  144158. NULL,
  144159. &_vq_auxt__16u1__p8_1,
  144160. NULL,
  144161. 0
  144162. };
  144163. static long _vq_quantlist__16u1__p9_0[] = {
  144164. 7,
  144165. 6,
  144166. 8,
  144167. 5,
  144168. 9,
  144169. 4,
  144170. 10,
  144171. 3,
  144172. 11,
  144173. 2,
  144174. 12,
  144175. 1,
  144176. 13,
  144177. 0,
  144178. 14,
  144179. };
  144180. static long _vq_lengthlist__16u1__p9_0[] = {
  144181. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144182. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144183. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144184. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144185. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144186. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144187. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144188. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144189. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144190. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144191. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144192. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144193. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144194. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144195. 8,
  144196. };
  144197. static float _vq_quantthresh__16u1__p9_0[] = {
  144198. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144199. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144200. };
  144201. static long _vq_quantmap__16u1__p9_0[] = {
  144202. 13, 11, 9, 7, 5, 3, 1, 0,
  144203. 2, 4, 6, 8, 10, 12, 14,
  144204. };
  144205. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144206. _vq_quantthresh__16u1__p9_0,
  144207. _vq_quantmap__16u1__p9_0,
  144208. 15,
  144209. 15
  144210. };
  144211. static static_codebook _16u1__p9_0 = {
  144212. 2, 225,
  144213. _vq_lengthlist__16u1__p9_0,
  144214. 1, -514071552, 1627381760, 4, 0,
  144215. _vq_quantlist__16u1__p9_0,
  144216. NULL,
  144217. &_vq_auxt__16u1__p9_0,
  144218. NULL,
  144219. 0
  144220. };
  144221. static long _vq_quantlist__16u1__p9_1[] = {
  144222. 7,
  144223. 6,
  144224. 8,
  144225. 5,
  144226. 9,
  144227. 4,
  144228. 10,
  144229. 3,
  144230. 11,
  144231. 2,
  144232. 12,
  144233. 1,
  144234. 13,
  144235. 0,
  144236. 14,
  144237. };
  144238. static long _vq_lengthlist__16u1__p9_1[] = {
  144239. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144240. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144241. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144242. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144243. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144244. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144245. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144246. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144247. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144248. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144249. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144250. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144251. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144252. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144253. 9,
  144254. };
  144255. static float _vq_quantthresh__16u1__p9_1[] = {
  144256. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144257. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144258. };
  144259. static long _vq_quantmap__16u1__p9_1[] = {
  144260. 13, 11, 9, 7, 5, 3, 1, 0,
  144261. 2, 4, 6, 8, 10, 12, 14,
  144262. };
  144263. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144264. _vq_quantthresh__16u1__p9_1,
  144265. _vq_quantmap__16u1__p9_1,
  144266. 15,
  144267. 15
  144268. };
  144269. static static_codebook _16u1__p9_1 = {
  144270. 2, 225,
  144271. _vq_lengthlist__16u1__p9_1,
  144272. 1, -522338304, 1620115456, 4, 0,
  144273. _vq_quantlist__16u1__p9_1,
  144274. NULL,
  144275. &_vq_auxt__16u1__p9_1,
  144276. NULL,
  144277. 0
  144278. };
  144279. static long _vq_quantlist__16u1__p9_2[] = {
  144280. 8,
  144281. 7,
  144282. 9,
  144283. 6,
  144284. 10,
  144285. 5,
  144286. 11,
  144287. 4,
  144288. 12,
  144289. 3,
  144290. 13,
  144291. 2,
  144292. 14,
  144293. 1,
  144294. 15,
  144295. 0,
  144296. 16,
  144297. };
  144298. static long _vq_lengthlist__16u1__p9_2[] = {
  144299. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144300. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144301. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144302. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144303. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144304. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144305. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144306. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144307. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144308. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144309. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144310. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144311. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144312. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144313. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144314. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144315. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144316. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144317. 10,
  144318. };
  144319. static float _vq_quantthresh__16u1__p9_2[] = {
  144320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144322. };
  144323. static long _vq_quantmap__16u1__p9_2[] = {
  144324. 15, 13, 11, 9, 7, 5, 3, 1,
  144325. 0, 2, 4, 6, 8, 10, 12, 14,
  144326. 16,
  144327. };
  144328. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144329. _vq_quantthresh__16u1__p9_2,
  144330. _vq_quantmap__16u1__p9_2,
  144331. 17,
  144332. 17
  144333. };
  144334. static static_codebook _16u1__p9_2 = {
  144335. 2, 289,
  144336. _vq_lengthlist__16u1__p9_2,
  144337. 1, -529530880, 1611661312, 5, 0,
  144338. _vq_quantlist__16u1__p9_2,
  144339. NULL,
  144340. &_vq_auxt__16u1__p9_2,
  144341. NULL,
  144342. 0
  144343. };
  144344. static long _huff_lengthlist__16u1__short[] = {
  144345. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144346. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144347. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144348. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144349. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144350. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144351. 16,16,16,16,
  144352. };
  144353. static static_codebook _huff_book__16u1__short = {
  144354. 2, 100,
  144355. _huff_lengthlist__16u1__short,
  144356. 0, 0, 0, 0, 0,
  144357. NULL,
  144358. NULL,
  144359. NULL,
  144360. NULL,
  144361. 0
  144362. };
  144363. static long _huff_lengthlist__16u2__long[] = {
  144364. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144365. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144366. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144367. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144368. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144369. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144370. 13,14,18,18,
  144371. };
  144372. static static_codebook _huff_book__16u2__long = {
  144373. 2, 100,
  144374. _huff_lengthlist__16u2__long,
  144375. 0, 0, 0, 0, 0,
  144376. NULL,
  144377. NULL,
  144378. NULL,
  144379. NULL,
  144380. 0
  144381. };
  144382. static long _huff_lengthlist__16u2__short[] = {
  144383. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144384. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144385. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144386. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144387. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144388. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144389. 16,16,16,16,
  144390. };
  144391. static static_codebook _huff_book__16u2__short = {
  144392. 2, 100,
  144393. _huff_lengthlist__16u2__short,
  144394. 0, 0, 0, 0, 0,
  144395. NULL,
  144396. NULL,
  144397. NULL,
  144398. NULL,
  144399. 0
  144400. };
  144401. static long _vq_quantlist__16u2_p1_0[] = {
  144402. 1,
  144403. 0,
  144404. 2,
  144405. };
  144406. static long _vq_lengthlist__16u2_p1_0[] = {
  144407. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144408. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144409. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144410. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144411. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144412. 10,
  144413. };
  144414. static float _vq_quantthresh__16u2_p1_0[] = {
  144415. -0.5, 0.5,
  144416. };
  144417. static long _vq_quantmap__16u2_p1_0[] = {
  144418. 1, 0, 2,
  144419. };
  144420. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144421. _vq_quantthresh__16u2_p1_0,
  144422. _vq_quantmap__16u2_p1_0,
  144423. 3,
  144424. 3
  144425. };
  144426. static static_codebook _16u2_p1_0 = {
  144427. 4, 81,
  144428. _vq_lengthlist__16u2_p1_0,
  144429. 1, -535822336, 1611661312, 2, 0,
  144430. _vq_quantlist__16u2_p1_0,
  144431. NULL,
  144432. &_vq_auxt__16u2_p1_0,
  144433. NULL,
  144434. 0
  144435. };
  144436. static long _vq_quantlist__16u2_p2_0[] = {
  144437. 2,
  144438. 1,
  144439. 3,
  144440. 0,
  144441. 4,
  144442. };
  144443. static long _vq_lengthlist__16u2_p2_0[] = {
  144444. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144445. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144446. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144447. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144448. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144449. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144450. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144451. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144452. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144453. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144454. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144455. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144456. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144457. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144458. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144459. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144460. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144461. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144462. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144463. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144464. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144465. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144466. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144467. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144468. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144469. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144470. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144471. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144472. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144473. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144474. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144475. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144476. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144477. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144478. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144479. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144480. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144481. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144482. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144483. 13,
  144484. };
  144485. static float _vq_quantthresh__16u2_p2_0[] = {
  144486. -1.5, -0.5, 0.5, 1.5,
  144487. };
  144488. static long _vq_quantmap__16u2_p2_0[] = {
  144489. 3, 1, 0, 2, 4,
  144490. };
  144491. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144492. _vq_quantthresh__16u2_p2_0,
  144493. _vq_quantmap__16u2_p2_0,
  144494. 5,
  144495. 5
  144496. };
  144497. static static_codebook _16u2_p2_0 = {
  144498. 4, 625,
  144499. _vq_lengthlist__16u2_p2_0,
  144500. 1, -533725184, 1611661312, 3, 0,
  144501. _vq_quantlist__16u2_p2_0,
  144502. NULL,
  144503. &_vq_auxt__16u2_p2_0,
  144504. NULL,
  144505. 0
  144506. };
  144507. static long _vq_quantlist__16u2_p3_0[] = {
  144508. 4,
  144509. 3,
  144510. 5,
  144511. 2,
  144512. 6,
  144513. 1,
  144514. 7,
  144515. 0,
  144516. 8,
  144517. };
  144518. static long _vq_lengthlist__16u2_p3_0[] = {
  144519. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144520. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144521. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144522. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144523. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144524. 11,
  144525. };
  144526. static float _vq_quantthresh__16u2_p3_0[] = {
  144527. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144528. };
  144529. static long _vq_quantmap__16u2_p3_0[] = {
  144530. 7, 5, 3, 1, 0, 2, 4, 6,
  144531. 8,
  144532. };
  144533. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144534. _vq_quantthresh__16u2_p3_0,
  144535. _vq_quantmap__16u2_p3_0,
  144536. 9,
  144537. 9
  144538. };
  144539. static static_codebook _16u2_p3_0 = {
  144540. 2, 81,
  144541. _vq_lengthlist__16u2_p3_0,
  144542. 1, -531628032, 1611661312, 4, 0,
  144543. _vq_quantlist__16u2_p3_0,
  144544. NULL,
  144545. &_vq_auxt__16u2_p3_0,
  144546. NULL,
  144547. 0
  144548. };
  144549. static long _vq_quantlist__16u2_p4_0[] = {
  144550. 8,
  144551. 7,
  144552. 9,
  144553. 6,
  144554. 10,
  144555. 5,
  144556. 11,
  144557. 4,
  144558. 12,
  144559. 3,
  144560. 13,
  144561. 2,
  144562. 14,
  144563. 1,
  144564. 15,
  144565. 0,
  144566. 16,
  144567. };
  144568. static long _vq_lengthlist__16u2_p4_0[] = {
  144569. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144570. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144571. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144572. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144573. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144574. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144575. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144576. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144577. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144578. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144579. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144580. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144581. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144582. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144583. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144584. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144585. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144586. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144587. 14,
  144588. };
  144589. static float _vq_quantthresh__16u2_p4_0[] = {
  144590. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144591. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144592. };
  144593. static long _vq_quantmap__16u2_p4_0[] = {
  144594. 15, 13, 11, 9, 7, 5, 3, 1,
  144595. 0, 2, 4, 6, 8, 10, 12, 14,
  144596. 16,
  144597. };
  144598. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144599. _vq_quantthresh__16u2_p4_0,
  144600. _vq_quantmap__16u2_p4_0,
  144601. 17,
  144602. 17
  144603. };
  144604. static static_codebook _16u2_p4_0 = {
  144605. 2, 289,
  144606. _vq_lengthlist__16u2_p4_0,
  144607. 1, -529530880, 1611661312, 5, 0,
  144608. _vq_quantlist__16u2_p4_0,
  144609. NULL,
  144610. &_vq_auxt__16u2_p4_0,
  144611. NULL,
  144612. 0
  144613. };
  144614. static long _vq_quantlist__16u2_p5_0[] = {
  144615. 1,
  144616. 0,
  144617. 2,
  144618. };
  144619. static long _vq_lengthlist__16u2_p5_0[] = {
  144620. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144621. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144622. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144623. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144624. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144625. 10,
  144626. };
  144627. static float _vq_quantthresh__16u2_p5_0[] = {
  144628. -5.5, 5.5,
  144629. };
  144630. static long _vq_quantmap__16u2_p5_0[] = {
  144631. 1, 0, 2,
  144632. };
  144633. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144634. _vq_quantthresh__16u2_p5_0,
  144635. _vq_quantmap__16u2_p5_0,
  144636. 3,
  144637. 3
  144638. };
  144639. static static_codebook _16u2_p5_0 = {
  144640. 4, 81,
  144641. _vq_lengthlist__16u2_p5_0,
  144642. 1, -529137664, 1618345984, 2, 0,
  144643. _vq_quantlist__16u2_p5_0,
  144644. NULL,
  144645. &_vq_auxt__16u2_p5_0,
  144646. NULL,
  144647. 0
  144648. };
  144649. static long _vq_quantlist__16u2_p5_1[] = {
  144650. 5,
  144651. 4,
  144652. 6,
  144653. 3,
  144654. 7,
  144655. 2,
  144656. 8,
  144657. 1,
  144658. 9,
  144659. 0,
  144660. 10,
  144661. };
  144662. static long _vq_lengthlist__16u2_p5_1[] = {
  144663. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144664. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144665. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144666. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144667. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144668. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144669. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144670. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144671. };
  144672. static float _vq_quantthresh__16u2_p5_1[] = {
  144673. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144674. 3.5, 4.5,
  144675. };
  144676. static long _vq_quantmap__16u2_p5_1[] = {
  144677. 9, 7, 5, 3, 1, 0, 2, 4,
  144678. 6, 8, 10,
  144679. };
  144680. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144681. _vq_quantthresh__16u2_p5_1,
  144682. _vq_quantmap__16u2_p5_1,
  144683. 11,
  144684. 11
  144685. };
  144686. static static_codebook _16u2_p5_1 = {
  144687. 2, 121,
  144688. _vq_lengthlist__16u2_p5_1,
  144689. 1, -531365888, 1611661312, 4, 0,
  144690. _vq_quantlist__16u2_p5_1,
  144691. NULL,
  144692. &_vq_auxt__16u2_p5_1,
  144693. NULL,
  144694. 0
  144695. };
  144696. static long _vq_quantlist__16u2_p6_0[] = {
  144697. 6,
  144698. 5,
  144699. 7,
  144700. 4,
  144701. 8,
  144702. 3,
  144703. 9,
  144704. 2,
  144705. 10,
  144706. 1,
  144707. 11,
  144708. 0,
  144709. 12,
  144710. };
  144711. static long _vq_lengthlist__16u2_p6_0[] = {
  144712. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144713. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144714. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144715. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144716. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144717. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144718. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144719. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144720. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144721. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144722. 12,13,13,14,14,14,14,15,15,
  144723. };
  144724. static float _vq_quantthresh__16u2_p6_0[] = {
  144725. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144726. 12.5, 17.5, 22.5, 27.5,
  144727. };
  144728. static long _vq_quantmap__16u2_p6_0[] = {
  144729. 11, 9, 7, 5, 3, 1, 0, 2,
  144730. 4, 6, 8, 10, 12,
  144731. };
  144732. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144733. _vq_quantthresh__16u2_p6_0,
  144734. _vq_quantmap__16u2_p6_0,
  144735. 13,
  144736. 13
  144737. };
  144738. static static_codebook _16u2_p6_0 = {
  144739. 2, 169,
  144740. _vq_lengthlist__16u2_p6_0,
  144741. 1, -526516224, 1616117760, 4, 0,
  144742. _vq_quantlist__16u2_p6_0,
  144743. NULL,
  144744. &_vq_auxt__16u2_p6_0,
  144745. NULL,
  144746. 0
  144747. };
  144748. static long _vq_quantlist__16u2_p6_1[] = {
  144749. 2,
  144750. 1,
  144751. 3,
  144752. 0,
  144753. 4,
  144754. };
  144755. static long _vq_lengthlist__16u2_p6_1[] = {
  144756. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144757. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144758. };
  144759. static float _vq_quantthresh__16u2_p6_1[] = {
  144760. -1.5, -0.5, 0.5, 1.5,
  144761. };
  144762. static long _vq_quantmap__16u2_p6_1[] = {
  144763. 3, 1, 0, 2, 4,
  144764. };
  144765. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144766. _vq_quantthresh__16u2_p6_1,
  144767. _vq_quantmap__16u2_p6_1,
  144768. 5,
  144769. 5
  144770. };
  144771. static static_codebook _16u2_p6_1 = {
  144772. 2, 25,
  144773. _vq_lengthlist__16u2_p6_1,
  144774. 1, -533725184, 1611661312, 3, 0,
  144775. _vq_quantlist__16u2_p6_1,
  144776. NULL,
  144777. &_vq_auxt__16u2_p6_1,
  144778. NULL,
  144779. 0
  144780. };
  144781. static long _vq_quantlist__16u2_p7_0[] = {
  144782. 6,
  144783. 5,
  144784. 7,
  144785. 4,
  144786. 8,
  144787. 3,
  144788. 9,
  144789. 2,
  144790. 10,
  144791. 1,
  144792. 11,
  144793. 0,
  144794. 12,
  144795. };
  144796. static long _vq_lengthlist__16u2_p7_0[] = {
  144797. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144798. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144799. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144800. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144801. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144802. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144803. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144804. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144805. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144806. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144807. 12,13,13,13,14,14,14,15,14,
  144808. };
  144809. static float _vq_quantthresh__16u2_p7_0[] = {
  144810. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144811. 27.5, 38.5, 49.5, 60.5,
  144812. };
  144813. static long _vq_quantmap__16u2_p7_0[] = {
  144814. 11, 9, 7, 5, 3, 1, 0, 2,
  144815. 4, 6, 8, 10, 12,
  144816. };
  144817. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144818. _vq_quantthresh__16u2_p7_0,
  144819. _vq_quantmap__16u2_p7_0,
  144820. 13,
  144821. 13
  144822. };
  144823. static static_codebook _16u2_p7_0 = {
  144824. 2, 169,
  144825. _vq_lengthlist__16u2_p7_0,
  144826. 1, -523206656, 1618345984, 4, 0,
  144827. _vq_quantlist__16u2_p7_0,
  144828. NULL,
  144829. &_vq_auxt__16u2_p7_0,
  144830. NULL,
  144831. 0
  144832. };
  144833. static long _vq_quantlist__16u2_p7_1[] = {
  144834. 5,
  144835. 4,
  144836. 6,
  144837. 3,
  144838. 7,
  144839. 2,
  144840. 8,
  144841. 1,
  144842. 9,
  144843. 0,
  144844. 10,
  144845. };
  144846. static long _vq_lengthlist__16u2_p7_1[] = {
  144847. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144848. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144849. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144850. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144851. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144852. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144853. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144854. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144855. };
  144856. static float _vq_quantthresh__16u2_p7_1[] = {
  144857. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144858. 3.5, 4.5,
  144859. };
  144860. static long _vq_quantmap__16u2_p7_1[] = {
  144861. 9, 7, 5, 3, 1, 0, 2, 4,
  144862. 6, 8, 10,
  144863. };
  144864. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144865. _vq_quantthresh__16u2_p7_1,
  144866. _vq_quantmap__16u2_p7_1,
  144867. 11,
  144868. 11
  144869. };
  144870. static static_codebook _16u2_p7_1 = {
  144871. 2, 121,
  144872. _vq_lengthlist__16u2_p7_1,
  144873. 1, -531365888, 1611661312, 4, 0,
  144874. _vq_quantlist__16u2_p7_1,
  144875. NULL,
  144876. &_vq_auxt__16u2_p7_1,
  144877. NULL,
  144878. 0
  144879. };
  144880. static long _vq_quantlist__16u2_p8_0[] = {
  144881. 7,
  144882. 6,
  144883. 8,
  144884. 5,
  144885. 9,
  144886. 4,
  144887. 10,
  144888. 3,
  144889. 11,
  144890. 2,
  144891. 12,
  144892. 1,
  144893. 13,
  144894. 0,
  144895. 14,
  144896. };
  144897. static long _vq_lengthlist__16u2_p8_0[] = {
  144898. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144899. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144900. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144901. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144902. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144903. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144904. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144905. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144906. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144907. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144908. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144909. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144910. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144911. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144912. 14,
  144913. };
  144914. static float _vq_quantthresh__16u2_p8_0[] = {
  144915. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144916. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144917. };
  144918. static long _vq_quantmap__16u2_p8_0[] = {
  144919. 13, 11, 9, 7, 5, 3, 1, 0,
  144920. 2, 4, 6, 8, 10, 12, 14,
  144921. };
  144922. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144923. _vq_quantthresh__16u2_p8_0,
  144924. _vq_quantmap__16u2_p8_0,
  144925. 15,
  144926. 15
  144927. };
  144928. static static_codebook _16u2_p8_0 = {
  144929. 2, 225,
  144930. _vq_lengthlist__16u2_p8_0,
  144931. 1, -520986624, 1620377600, 4, 0,
  144932. _vq_quantlist__16u2_p8_0,
  144933. NULL,
  144934. &_vq_auxt__16u2_p8_0,
  144935. NULL,
  144936. 0
  144937. };
  144938. static long _vq_quantlist__16u2_p8_1[] = {
  144939. 10,
  144940. 9,
  144941. 11,
  144942. 8,
  144943. 12,
  144944. 7,
  144945. 13,
  144946. 6,
  144947. 14,
  144948. 5,
  144949. 15,
  144950. 4,
  144951. 16,
  144952. 3,
  144953. 17,
  144954. 2,
  144955. 18,
  144956. 1,
  144957. 19,
  144958. 0,
  144959. 20,
  144960. };
  144961. static long _vq_lengthlist__16u2_p8_1[] = {
  144962. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144963. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144964. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144965. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144966. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144967. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144968. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144969. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144970. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144971. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144972. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144973. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144974. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144975. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144976. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144977. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144978. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144979. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144980. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144981. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144982. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144983. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144984. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144985. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144986. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144987. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144988. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144989. 11,11,10,11,11,11,10,11,11,
  144990. };
  144991. static float _vq_quantthresh__16u2_p8_1[] = {
  144992. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144993. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144994. 6.5, 7.5, 8.5, 9.5,
  144995. };
  144996. static long _vq_quantmap__16u2_p8_1[] = {
  144997. 19, 17, 15, 13, 11, 9, 7, 5,
  144998. 3, 1, 0, 2, 4, 6, 8, 10,
  144999. 12, 14, 16, 18, 20,
  145000. };
  145001. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  145002. _vq_quantthresh__16u2_p8_1,
  145003. _vq_quantmap__16u2_p8_1,
  145004. 21,
  145005. 21
  145006. };
  145007. static static_codebook _16u2_p8_1 = {
  145008. 2, 441,
  145009. _vq_lengthlist__16u2_p8_1,
  145010. 1, -529268736, 1611661312, 5, 0,
  145011. _vq_quantlist__16u2_p8_1,
  145012. NULL,
  145013. &_vq_auxt__16u2_p8_1,
  145014. NULL,
  145015. 0
  145016. };
  145017. static long _vq_quantlist__16u2_p9_0[] = {
  145018. 5586,
  145019. 4655,
  145020. 6517,
  145021. 3724,
  145022. 7448,
  145023. 2793,
  145024. 8379,
  145025. 1862,
  145026. 9310,
  145027. 931,
  145028. 10241,
  145029. 0,
  145030. 11172,
  145031. 5521,
  145032. 5651,
  145033. };
  145034. static long _vq_lengthlist__16u2_p9_0[] = {
  145035. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145037. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145038. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145039. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145040. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145041. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145042. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145043. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145044. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145045. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145046. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145047. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145048. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145049. 5,
  145050. };
  145051. static float _vq_quantthresh__16u2_p9_0[] = {
  145052. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145053. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145054. };
  145055. static long _vq_quantmap__16u2_p9_0[] = {
  145056. 11, 9, 7, 5, 3, 1, 13, 0,
  145057. 14, 2, 4, 6, 8, 10, 12,
  145058. };
  145059. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145060. _vq_quantthresh__16u2_p9_0,
  145061. _vq_quantmap__16u2_p9_0,
  145062. 15,
  145063. 15
  145064. };
  145065. static static_codebook _16u2_p9_0 = {
  145066. 2, 225,
  145067. _vq_lengthlist__16u2_p9_0,
  145068. 1, -510275072, 1611661312, 14, 0,
  145069. _vq_quantlist__16u2_p9_0,
  145070. NULL,
  145071. &_vq_auxt__16u2_p9_0,
  145072. NULL,
  145073. 0
  145074. };
  145075. static long _vq_quantlist__16u2_p9_1[] = {
  145076. 392,
  145077. 343,
  145078. 441,
  145079. 294,
  145080. 490,
  145081. 245,
  145082. 539,
  145083. 196,
  145084. 588,
  145085. 147,
  145086. 637,
  145087. 98,
  145088. 686,
  145089. 49,
  145090. 735,
  145091. 0,
  145092. 784,
  145093. 388,
  145094. 396,
  145095. };
  145096. static long _vq_lengthlist__16u2_p9_1[] = {
  145097. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145098. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145099. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145100. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145101. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145102. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145103. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145104. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145105. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145106. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145107. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145108. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145109. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145110. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145111. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145117. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145118. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145119. 11,11,11,11,11,11,11, 5, 4,
  145120. };
  145121. static float _vq_quantthresh__16u2_p9_1[] = {
  145122. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145123. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145124. 318.5, 367.5,
  145125. };
  145126. static long _vq_quantmap__16u2_p9_1[] = {
  145127. 15, 13, 11, 9, 7, 5, 3, 1,
  145128. 17, 0, 18, 2, 4, 6, 8, 10,
  145129. 12, 14, 16,
  145130. };
  145131. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145132. _vq_quantthresh__16u2_p9_1,
  145133. _vq_quantmap__16u2_p9_1,
  145134. 19,
  145135. 19
  145136. };
  145137. static static_codebook _16u2_p9_1 = {
  145138. 2, 361,
  145139. _vq_lengthlist__16u2_p9_1,
  145140. 1, -518488064, 1611661312, 10, 0,
  145141. _vq_quantlist__16u2_p9_1,
  145142. NULL,
  145143. &_vq_auxt__16u2_p9_1,
  145144. NULL,
  145145. 0
  145146. };
  145147. static long _vq_quantlist__16u2_p9_2[] = {
  145148. 24,
  145149. 23,
  145150. 25,
  145151. 22,
  145152. 26,
  145153. 21,
  145154. 27,
  145155. 20,
  145156. 28,
  145157. 19,
  145158. 29,
  145159. 18,
  145160. 30,
  145161. 17,
  145162. 31,
  145163. 16,
  145164. 32,
  145165. 15,
  145166. 33,
  145167. 14,
  145168. 34,
  145169. 13,
  145170. 35,
  145171. 12,
  145172. 36,
  145173. 11,
  145174. 37,
  145175. 10,
  145176. 38,
  145177. 9,
  145178. 39,
  145179. 8,
  145180. 40,
  145181. 7,
  145182. 41,
  145183. 6,
  145184. 42,
  145185. 5,
  145186. 43,
  145187. 4,
  145188. 44,
  145189. 3,
  145190. 45,
  145191. 2,
  145192. 46,
  145193. 1,
  145194. 47,
  145195. 0,
  145196. 48,
  145197. };
  145198. static long _vq_lengthlist__16u2_p9_2[] = {
  145199. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145200. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145201. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145202. 11,
  145203. };
  145204. static float _vq_quantthresh__16u2_p9_2[] = {
  145205. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145206. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145207. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145208. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145209. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145210. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145211. };
  145212. static long _vq_quantmap__16u2_p9_2[] = {
  145213. 47, 45, 43, 41, 39, 37, 35, 33,
  145214. 31, 29, 27, 25, 23, 21, 19, 17,
  145215. 15, 13, 11, 9, 7, 5, 3, 1,
  145216. 0, 2, 4, 6, 8, 10, 12, 14,
  145217. 16, 18, 20, 22, 24, 26, 28, 30,
  145218. 32, 34, 36, 38, 40, 42, 44, 46,
  145219. 48,
  145220. };
  145221. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145222. _vq_quantthresh__16u2_p9_2,
  145223. _vq_quantmap__16u2_p9_2,
  145224. 49,
  145225. 49
  145226. };
  145227. static static_codebook _16u2_p9_2 = {
  145228. 1, 49,
  145229. _vq_lengthlist__16u2_p9_2,
  145230. 1, -526909440, 1611661312, 6, 0,
  145231. _vq_quantlist__16u2_p9_2,
  145232. NULL,
  145233. &_vq_auxt__16u2_p9_2,
  145234. NULL,
  145235. 0
  145236. };
  145237. static long _vq_quantlist__8u0__p1_0[] = {
  145238. 1,
  145239. 0,
  145240. 2,
  145241. };
  145242. static long _vq_lengthlist__8u0__p1_0[] = {
  145243. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145244. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145245. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145246. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145247. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145248. 11,
  145249. };
  145250. static float _vq_quantthresh__8u0__p1_0[] = {
  145251. -0.5, 0.5,
  145252. };
  145253. static long _vq_quantmap__8u0__p1_0[] = {
  145254. 1, 0, 2,
  145255. };
  145256. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145257. _vq_quantthresh__8u0__p1_0,
  145258. _vq_quantmap__8u0__p1_0,
  145259. 3,
  145260. 3
  145261. };
  145262. static static_codebook _8u0__p1_0 = {
  145263. 4, 81,
  145264. _vq_lengthlist__8u0__p1_0,
  145265. 1, -535822336, 1611661312, 2, 0,
  145266. _vq_quantlist__8u0__p1_0,
  145267. NULL,
  145268. &_vq_auxt__8u0__p1_0,
  145269. NULL,
  145270. 0
  145271. };
  145272. static long _vq_quantlist__8u0__p2_0[] = {
  145273. 1,
  145274. 0,
  145275. 2,
  145276. };
  145277. static long _vq_lengthlist__8u0__p2_0[] = {
  145278. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145279. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145280. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145281. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145282. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145283. 8,
  145284. };
  145285. static float _vq_quantthresh__8u0__p2_0[] = {
  145286. -0.5, 0.5,
  145287. };
  145288. static long _vq_quantmap__8u0__p2_0[] = {
  145289. 1, 0, 2,
  145290. };
  145291. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145292. _vq_quantthresh__8u0__p2_0,
  145293. _vq_quantmap__8u0__p2_0,
  145294. 3,
  145295. 3
  145296. };
  145297. static static_codebook _8u0__p2_0 = {
  145298. 4, 81,
  145299. _vq_lengthlist__8u0__p2_0,
  145300. 1, -535822336, 1611661312, 2, 0,
  145301. _vq_quantlist__8u0__p2_0,
  145302. NULL,
  145303. &_vq_auxt__8u0__p2_0,
  145304. NULL,
  145305. 0
  145306. };
  145307. static long _vq_quantlist__8u0__p3_0[] = {
  145308. 2,
  145309. 1,
  145310. 3,
  145311. 0,
  145312. 4,
  145313. };
  145314. static long _vq_lengthlist__8u0__p3_0[] = {
  145315. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145316. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145317. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145318. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145319. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145320. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145321. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145322. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145323. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145324. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145325. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145326. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145327. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145328. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145329. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145330. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145331. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145332. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145333. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145334. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145335. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145336. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145337. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145338. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145339. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145340. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145341. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145342. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145343. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145344. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145345. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145346. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145347. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145348. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145349. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145350. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145351. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145352. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145353. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145354. 16,
  145355. };
  145356. static float _vq_quantthresh__8u0__p3_0[] = {
  145357. -1.5, -0.5, 0.5, 1.5,
  145358. };
  145359. static long _vq_quantmap__8u0__p3_0[] = {
  145360. 3, 1, 0, 2, 4,
  145361. };
  145362. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145363. _vq_quantthresh__8u0__p3_0,
  145364. _vq_quantmap__8u0__p3_0,
  145365. 5,
  145366. 5
  145367. };
  145368. static static_codebook _8u0__p3_0 = {
  145369. 4, 625,
  145370. _vq_lengthlist__8u0__p3_0,
  145371. 1, -533725184, 1611661312, 3, 0,
  145372. _vq_quantlist__8u0__p3_0,
  145373. NULL,
  145374. &_vq_auxt__8u0__p3_0,
  145375. NULL,
  145376. 0
  145377. };
  145378. static long _vq_quantlist__8u0__p4_0[] = {
  145379. 2,
  145380. 1,
  145381. 3,
  145382. 0,
  145383. 4,
  145384. };
  145385. static long _vq_lengthlist__8u0__p4_0[] = {
  145386. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145387. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145388. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145389. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145390. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145391. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145392. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145393. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145394. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145395. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145396. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145397. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145398. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145399. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145400. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145401. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145402. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145403. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145404. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145405. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145406. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145407. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145408. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145409. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145410. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145411. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145412. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145413. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145414. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145415. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145416. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145417. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145418. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145419. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145420. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145421. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145422. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145423. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145424. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145425. 12,
  145426. };
  145427. static float _vq_quantthresh__8u0__p4_0[] = {
  145428. -1.5, -0.5, 0.5, 1.5,
  145429. };
  145430. static long _vq_quantmap__8u0__p4_0[] = {
  145431. 3, 1, 0, 2, 4,
  145432. };
  145433. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145434. _vq_quantthresh__8u0__p4_0,
  145435. _vq_quantmap__8u0__p4_0,
  145436. 5,
  145437. 5
  145438. };
  145439. static static_codebook _8u0__p4_0 = {
  145440. 4, 625,
  145441. _vq_lengthlist__8u0__p4_0,
  145442. 1, -533725184, 1611661312, 3, 0,
  145443. _vq_quantlist__8u0__p4_0,
  145444. NULL,
  145445. &_vq_auxt__8u0__p4_0,
  145446. NULL,
  145447. 0
  145448. };
  145449. static long _vq_quantlist__8u0__p5_0[] = {
  145450. 4,
  145451. 3,
  145452. 5,
  145453. 2,
  145454. 6,
  145455. 1,
  145456. 7,
  145457. 0,
  145458. 8,
  145459. };
  145460. static long _vq_lengthlist__8u0__p5_0[] = {
  145461. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145462. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145463. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145464. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145465. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145466. 12,
  145467. };
  145468. static float _vq_quantthresh__8u0__p5_0[] = {
  145469. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145470. };
  145471. static long _vq_quantmap__8u0__p5_0[] = {
  145472. 7, 5, 3, 1, 0, 2, 4, 6,
  145473. 8,
  145474. };
  145475. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145476. _vq_quantthresh__8u0__p5_0,
  145477. _vq_quantmap__8u0__p5_0,
  145478. 9,
  145479. 9
  145480. };
  145481. static static_codebook _8u0__p5_0 = {
  145482. 2, 81,
  145483. _vq_lengthlist__8u0__p5_0,
  145484. 1, -531628032, 1611661312, 4, 0,
  145485. _vq_quantlist__8u0__p5_0,
  145486. NULL,
  145487. &_vq_auxt__8u0__p5_0,
  145488. NULL,
  145489. 0
  145490. };
  145491. static long _vq_quantlist__8u0__p6_0[] = {
  145492. 6,
  145493. 5,
  145494. 7,
  145495. 4,
  145496. 8,
  145497. 3,
  145498. 9,
  145499. 2,
  145500. 10,
  145501. 1,
  145502. 11,
  145503. 0,
  145504. 12,
  145505. };
  145506. static long _vq_lengthlist__8u0__p6_0[] = {
  145507. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145508. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145509. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145510. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145511. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145512. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145513. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145514. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145515. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145516. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145517. 16, 0,15, 0,17, 0, 0, 0, 0,
  145518. };
  145519. static float _vq_quantthresh__8u0__p6_0[] = {
  145520. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145521. 12.5, 17.5, 22.5, 27.5,
  145522. };
  145523. static long _vq_quantmap__8u0__p6_0[] = {
  145524. 11, 9, 7, 5, 3, 1, 0, 2,
  145525. 4, 6, 8, 10, 12,
  145526. };
  145527. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145528. _vq_quantthresh__8u0__p6_0,
  145529. _vq_quantmap__8u0__p6_0,
  145530. 13,
  145531. 13
  145532. };
  145533. static static_codebook _8u0__p6_0 = {
  145534. 2, 169,
  145535. _vq_lengthlist__8u0__p6_0,
  145536. 1, -526516224, 1616117760, 4, 0,
  145537. _vq_quantlist__8u0__p6_0,
  145538. NULL,
  145539. &_vq_auxt__8u0__p6_0,
  145540. NULL,
  145541. 0
  145542. };
  145543. static long _vq_quantlist__8u0__p6_1[] = {
  145544. 2,
  145545. 1,
  145546. 3,
  145547. 0,
  145548. 4,
  145549. };
  145550. static long _vq_lengthlist__8u0__p6_1[] = {
  145551. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145552. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145553. };
  145554. static float _vq_quantthresh__8u0__p6_1[] = {
  145555. -1.5, -0.5, 0.5, 1.5,
  145556. };
  145557. static long _vq_quantmap__8u0__p6_1[] = {
  145558. 3, 1, 0, 2, 4,
  145559. };
  145560. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145561. _vq_quantthresh__8u0__p6_1,
  145562. _vq_quantmap__8u0__p6_1,
  145563. 5,
  145564. 5
  145565. };
  145566. static static_codebook _8u0__p6_1 = {
  145567. 2, 25,
  145568. _vq_lengthlist__8u0__p6_1,
  145569. 1, -533725184, 1611661312, 3, 0,
  145570. _vq_quantlist__8u0__p6_1,
  145571. NULL,
  145572. &_vq_auxt__8u0__p6_1,
  145573. NULL,
  145574. 0
  145575. };
  145576. static long _vq_quantlist__8u0__p7_0[] = {
  145577. 1,
  145578. 0,
  145579. 2,
  145580. };
  145581. static long _vq_lengthlist__8u0__p7_0[] = {
  145582. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145583. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145584. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145585. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145586. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145587. 7,
  145588. };
  145589. static float _vq_quantthresh__8u0__p7_0[] = {
  145590. -157.5, 157.5,
  145591. };
  145592. static long _vq_quantmap__8u0__p7_0[] = {
  145593. 1, 0, 2,
  145594. };
  145595. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145596. _vq_quantthresh__8u0__p7_0,
  145597. _vq_quantmap__8u0__p7_0,
  145598. 3,
  145599. 3
  145600. };
  145601. static static_codebook _8u0__p7_0 = {
  145602. 4, 81,
  145603. _vq_lengthlist__8u0__p7_0,
  145604. 1, -518803456, 1628680192, 2, 0,
  145605. _vq_quantlist__8u0__p7_0,
  145606. NULL,
  145607. &_vq_auxt__8u0__p7_0,
  145608. NULL,
  145609. 0
  145610. };
  145611. static long _vq_quantlist__8u0__p7_1[] = {
  145612. 7,
  145613. 6,
  145614. 8,
  145615. 5,
  145616. 9,
  145617. 4,
  145618. 10,
  145619. 3,
  145620. 11,
  145621. 2,
  145622. 12,
  145623. 1,
  145624. 13,
  145625. 0,
  145626. 14,
  145627. };
  145628. static long _vq_lengthlist__8u0__p7_1[] = {
  145629. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145630. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145631. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145632. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145633. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145634. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145641. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145642. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145643. 10,
  145644. };
  145645. static float _vq_quantthresh__8u0__p7_1[] = {
  145646. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145647. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145648. };
  145649. static long _vq_quantmap__8u0__p7_1[] = {
  145650. 13, 11, 9, 7, 5, 3, 1, 0,
  145651. 2, 4, 6, 8, 10, 12, 14,
  145652. };
  145653. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145654. _vq_quantthresh__8u0__p7_1,
  145655. _vq_quantmap__8u0__p7_1,
  145656. 15,
  145657. 15
  145658. };
  145659. static static_codebook _8u0__p7_1 = {
  145660. 2, 225,
  145661. _vq_lengthlist__8u0__p7_1,
  145662. 1, -520986624, 1620377600, 4, 0,
  145663. _vq_quantlist__8u0__p7_1,
  145664. NULL,
  145665. &_vq_auxt__8u0__p7_1,
  145666. NULL,
  145667. 0
  145668. };
  145669. static long _vq_quantlist__8u0__p7_2[] = {
  145670. 10,
  145671. 9,
  145672. 11,
  145673. 8,
  145674. 12,
  145675. 7,
  145676. 13,
  145677. 6,
  145678. 14,
  145679. 5,
  145680. 15,
  145681. 4,
  145682. 16,
  145683. 3,
  145684. 17,
  145685. 2,
  145686. 18,
  145687. 1,
  145688. 19,
  145689. 0,
  145690. 20,
  145691. };
  145692. static long _vq_lengthlist__8u0__p7_2[] = {
  145693. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145694. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145695. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145696. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145697. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145698. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145699. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145700. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145701. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145702. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145703. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145704. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145705. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145706. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145707. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145708. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145709. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145710. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145711. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145712. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145713. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145714. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145715. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145716. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145717. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145718. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145719. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145720. 11,12,11,11,11,10,10,11,11,
  145721. };
  145722. static float _vq_quantthresh__8u0__p7_2[] = {
  145723. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145724. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145725. 6.5, 7.5, 8.5, 9.5,
  145726. };
  145727. static long _vq_quantmap__8u0__p7_2[] = {
  145728. 19, 17, 15, 13, 11, 9, 7, 5,
  145729. 3, 1, 0, 2, 4, 6, 8, 10,
  145730. 12, 14, 16, 18, 20,
  145731. };
  145732. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145733. _vq_quantthresh__8u0__p7_2,
  145734. _vq_quantmap__8u0__p7_2,
  145735. 21,
  145736. 21
  145737. };
  145738. static static_codebook _8u0__p7_2 = {
  145739. 2, 441,
  145740. _vq_lengthlist__8u0__p7_2,
  145741. 1, -529268736, 1611661312, 5, 0,
  145742. _vq_quantlist__8u0__p7_2,
  145743. NULL,
  145744. &_vq_auxt__8u0__p7_2,
  145745. NULL,
  145746. 0
  145747. };
  145748. static long _huff_lengthlist__8u0__single[] = {
  145749. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145750. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145751. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145752. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145753. };
  145754. static static_codebook _huff_book__8u0__single = {
  145755. 2, 64,
  145756. _huff_lengthlist__8u0__single,
  145757. 0, 0, 0, 0, 0,
  145758. NULL,
  145759. NULL,
  145760. NULL,
  145761. NULL,
  145762. 0
  145763. };
  145764. static long _vq_quantlist__8u1__p1_0[] = {
  145765. 1,
  145766. 0,
  145767. 2,
  145768. };
  145769. static long _vq_lengthlist__8u1__p1_0[] = {
  145770. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145771. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145772. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145773. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145774. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145775. 10,
  145776. };
  145777. static float _vq_quantthresh__8u1__p1_0[] = {
  145778. -0.5, 0.5,
  145779. };
  145780. static long _vq_quantmap__8u1__p1_0[] = {
  145781. 1, 0, 2,
  145782. };
  145783. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145784. _vq_quantthresh__8u1__p1_0,
  145785. _vq_quantmap__8u1__p1_0,
  145786. 3,
  145787. 3
  145788. };
  145789. static static_codebook _8u1__p1_0 = {
  145790. 4, 81,
  145791. _vq_lengthlist__8u1__p1_0,
  145792. 1, -535822336, 1611661312, 2, 0,
  145793. _vq_quantlist__8u1__p1_0,
  145794. NULL,
  145795. &_vq_auxt__8u1__p1_0,
  145796. NULL,
  145797. 0
  145798. };
  145799. static long _vq_quantlist__8u1__p2_0[] = {
  145800. 1,
  145801. 0,
  145802. 2,
  145803. };
  145804. static long _vq_lengthlist__8u1__p2_0[] = {
  145805. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145806. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145807. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145808. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145809. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145810. 7,
  145811. };
  145812. static float _vq_quantthresh__8u1__p2_0[] = {
  145813. -0.5, 0.5,
  145814. };
  145815. static long _vq_quantmap__8u1__p2_0[] = {
  145816. 1, 0, 2,
  145817. };
  145818. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145819. _vq_quantthresh__8u1__p2_0,
  145820. _vq_quantmap__8u1__p2_0,
  145821. 3,
  145822. 3
  145823. };
  145824. static static_codebook _8u1__p2_0 = {
  145825. 4, 81,
  145826. _vq_lengthlist__8u1__p2_0,
  145827. 1, -535822336, 1611661312, 2, 0,
  145828. _vq_quantlist__8u1__p2_0,
  145829. NULL,
  145830. &_vq_auxt__8u1__p2_0,
  145831. NULL,
  145832. 0
  145833. };
  145834. static long _vq_quantlist__8u1__p3_0[] = {
  145835. 2,
  145836. 1,
  145837. 3,
  145838. 0,
  145839. 4,
  145840. };
  145841. static long _vq_lengthlist__8u1__p3_0[] = {
  145842. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145843. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145844. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145845. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145846. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145847. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145848. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145849. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145850. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145851. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145852. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145853. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145854. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145855. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145856. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145857. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145858. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145859. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145860. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145861. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145862. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145863. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145864. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145865. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145866. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145867. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145868. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145869. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145870. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145871. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145872. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145873. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145874. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145875. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145876. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145877. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145878. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145879. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145880. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145881. 16,
  145882. };
  145883. static float _vq_quantthresh__8u1__p3_0[] = {
  145884. -1.5, -0.5, 0.5, 1.5,
  145885. };
  145886. static long _vq_quantmap__8u1__p3_0[] = {
  145887. 3, 1, 0, 2, 4,
  145888. };
  145889. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145890. _vq_quantthresh__8u1__p3_0,
  145891. _vq_quantmap__8u1__p3_0,
  145892. 5,
  145893. 5
  145894. };
  145895. static static_codebook _8u1__p3_0 = {
  145896. 4, 625,
  145897. _vq_lengthlist__8u1__p3_0,
  145898. 1, -533725184, 1611661312, 3, 0,
  145899. _vq_quantlist__8u1__p3_0,
  145900. NULL,
  145901. &_vq_auxt__8u1__p3_0,
  145902. NULL,
  145903. 0
  145904. };
  145905. static long _vq_quantlist__8u1__p4_0[] = {
  145906. 2,
  145907. 1,
  145908. 3,
  145909. 0,
  145910. 4,
  145911. };
  145912. static long _vq_lengthlist__8u1__p4_0[] = {
  145913. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145914. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145915. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145916. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145917. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145918. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145919. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145920. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145921. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145922. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145923. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145924. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145925. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145926. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145927. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145928. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145929. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145930. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145931. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145932. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145933. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145934. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145935. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145936. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145937. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145938. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145939. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145940. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145941. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145942. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145943. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145944. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145945. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145946. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145947. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145948. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145949. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145950. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145951. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145952. 10,
  145953. };
  145954. static float _vq_quantthresh__8u1__p4_0[] = {
  145955. -1.5, -0.5, 0.5, 1.5,
  145956. };
  145957. static long _vq_quantmap__8u1__p4_0[] = {
  145958. 3, 1, 0, 2, 4,
  145959. };
  145960. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145961. _vq_quantthresh__8u1__p4_0,
  145962. _vq_quantmap__8u1__p4_0,
  145963. 5,
  145964. 5
  145965. };
  145966. static static_codebook _8u1__p4_0 = {
  145967. 4, 625,
  145968. _vq_lengthlist__8u1__p4_0,
  145969. 1, -533725184, 1611661312, 3, 0,
  145970. _vq_quantlist__8u1__p4_0,
  145971. NULL,
  145972. &_vq_auxt__8u1__p4_0,
  145973. NULL,
  145974. 0
  145975. };
  145976. static long _vq_quantlist__8u1__p5_0[] = {
  145977. 4,
  145978. 3,
  145979. 5,
  145980. 2,
  145981. 6,
  145982. 1,
  145983. 7,
  145984. 0,
  145985. 8,
  145986. };
  145987. static long _vq_lengthlist__8u1__p5_0[] = {
  145988. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145989. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145990. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145991. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145992. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145993. 13,
  145994. };
  145995. static float _vq_quantthresh__8u1__p5_0[] = {
  145996. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145997. };
  145998. static long _vq_quantmap__8u1__p5_0[] = {
  145999. 7, 5, 3, 1, 0, 2, 4, 6,
  146000. 8,
  146001. };
  146002. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  146003. _vq_quantthresh__8u1__p5_0,
  146004. _vq_quantmap__8u1__p5_0,
  146005. 9,
  146006. 9
  146007. };
  146008. static static_codebook _8u1__p5_0 = {
  146009. 2, 81,
  146010. _vq_lengthlist__8u1__p5_0,
  146011. 1, -531628032, 1611661312, 4, 0,
  146012. _vq_quantlist__8u1__p5_0,
  146013. NULL,
  146014. &_vq_auxt__8u1__p5_0,
  146015. NULL,
  146016. 0
  146017. };
  146018. static long _vq_quantlist__8u1__p6_0[] = {
  146019. 4,
  146020. 3,
  146021. 5,
  146022. 2,
  146023. 6,
  146024. 1,
  146025. 7,
  146026. 0,
  146027. 8,
  146028. };
  146029. static long _vq_lengthlist__8u1__p6_0[] = {
  146030. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146031. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146032. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146033. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146034. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146035. 10,
  146036. };
  146037. static float _vq_quantthresh__8u1__p6_0[] = {
  146038. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146039. };
  146040. static long _vq_quantmap__8u1__p6_0[] = {
  146041. 7, 5, 3, 1, 0, 2, 4, 6,
  146042. 8,
  146043. };
  146044. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146045. _vq_quantthresh__8u1__p6_0,
  146046. _vq_quantmap__8u1__p6_0,
  146047. 9,
  146048. 9
  146049. };
  146050. static static_codebook _8u1__p6_0 = {
  146051. 2, 81,
  146052. _vq_lengthlist__8u1__p6_0,
  146053. 1, -531628032, 1611661312, 4, 0,
  146054. _vq_quantlist__8u1__p6_0,
  146055. NULL,
  146056. &_vq_auxt__8u1__p6_0,
  146057. NULL,
  146058. 0
  146059. };
  146060. static long _vq_quantlist__8u1__p7_0[] = {
  146061. 1,
  146062. 0,
  146063. 2,
  146064. };
  146065. static long _vq_lengthlist__8u1__p7_0[] = {
  146066. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146067. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146068. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146069. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146070. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146071. 11,
  146072. };
  146073. static float _vq_quantthresh__8u1__p7_0[] = {
  146074. -5.5, 5.5,
  146075. };
  146076. static long _vq_quantmap__8u1__p7_0[] = {
  146077. 1, 0, 2,
  146078. };
  146079. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146080. _vq_quantthresh__8u1__p7_0,
  146081. _vq_quantmap__8u1__p7_0,
  146082. 3,
  146083. 3
  146084. };
  146085. static static_codebook _8u1__p7_0 = {
  146086. 4, 81,
  146087. _vq_lengthlist__8u1__p7_0,
  146088. 1, -529137664, 1618345984, 2, 0,
  146089. _vq_quantlist__8u1__p7_0,
  146090. NULL,
  146091. &_vq_auxt__8u1__p7_0,
  146092. NULL,
  146093. 0
  146094. };
  146095. static long _vq_quantlist__8u1__p7_1[] = {
  146096. 5,
  146097. 4,
  146098. 6,
  146099. 3,
  146100. 7,
  146101. 2,
  146102. 8,
  146103. 1,
  146104. 9,
  146105. 0,
  146106. 10,
  146107. };
  146108. static long _vq_lengthlist__8u1__p7_1[] = {
  146109. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146110. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146111. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146112. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146113. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146114. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146115. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146116. 9, 9, 9, 9, 9,10,10,10,10,
  146117. };
  146118. static float _vq_quantthresh__8u1__p7_1[] = {
  146119. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146120. 3.5, 4.5,
  146121. };
  146122. static long _vq_quantmap__8u1__p7_1[] = {
  146123. 9, 7, 5, 3, 1, 0, 2, 4,
  146124. 6, 8, 10,
  146125. };
  146126. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146127. _vq_quantthresh__8u1__p7_1,
  146128. _vq_quantmap__8u1__p7_1,
  146129. 11,
  146130. 11
  146131. };
  146132. static static_codebook _8u1__p7_1 = {
  146133. 2, 121,
  146134. _vq_lengthlist__8u1__p7_1,
  146135. 1, -531365888, 1611661312, 4, 0,
  146136. _vq_quantlist__8u1__p7_1,
  146137. NULL,
  146138. &_vq_auxt__8u1__p7_1,
  146139. NULL,
  146140. 0
  146141. };
  146142. static long _vq_quantlist__8u1__p8_0[] = {
  146143. 5,
  146144. 4,
  146145. 6,
  146146. 3,
  146147. 7,
  146148. 2,
  146149. 8,
  146150. 1,
  146151. 9,
  146152. 0,
  146153. 10,
  146154. };
  146155. static long _vq_lengthlist__8u1__p8_0[] = {
  146156. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146157. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146158. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146159. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146160. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146161. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146162. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146163. 12,13,13,14,14,15,15,15,15,
  146164. };
  146165. static float _vq_quantthresh__8u1__p8_0[] = {
  146166. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146167. 38.5, 49.5,
  146168. };
  146169. static long _vq_quantmap__8u1__p8_0[] = {
  146170. 9, 7, 5, 3, 1, 0, 2, 4,
  146171. 6, 8, 10,
  146172. };
  146173. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146174. _vq_quantthresh__8u1__p8_0,
  146175. _vq_quantmap__8u1__p8_0,
  146176. 11,
  146177. 11
  146178. };
  146179. static static_codebook _8u1__p8_0 = {
  146180. 2, 121,
  146181. _vq_lengthlist__8u1__p8_0,
  146182. 1, -524582912, 1618345984, 4, 0,
  146183. _vq_quantlist__8u1__p8_0,
  146184. NULL,
  146185. &_vq_auxt__8u1__p8_0,
  146186. NULL,
  146187. 0
  146188. };
  146189. static long _vq_quantlist__8u1__p8_1[] = {
  146190. 5,
  146191. 4,
  146192. 6,
  146193. 3,
  146194. 7,
  146195. 2,
  146196. 8,
  146197. 1,
  146198. 9,
  146199. 0,
  146200. 10,
  146201. };
  146202. static long _vq_lengthlist__8u1__p8_1[] = {
  146203. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146204. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146205. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146206. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146207. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146208. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146209. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146210. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146211. };
  146212. static float _vq_quantthresh__8u1__p8_1[] = {
  146213. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146214. 3.5, 4.5,
  146215. };
  146216. static long _vq_quantmap__8u1__p8_1[] = {
  146217. 9, 7, 5, 3, 1, 0, 2, 4,
  146218. 6, 8, 10,
  146219. };
  146220. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146221. _vq_quantthresh__8u1__p8_1,
  146222. _vq_quantmap__8u1__p8_1,
  146223. 11,
  146224. 11
  146225. };
  146226. static static_codebook _8u1__p8_1 = {
  146227. 2, 121,
  146228. _vq_lengthlist__8u1__p8_1,
  146229. 1, -531365888, 1611661312, 4, 0,
  146230. _vq_quantlist__8u1__p8_1,
  146231. NULL,
  146232. &_vq_auxt__8u1__p8_1,
  146233. NULL,
  146234. 0
  146235. };
  146236. static long _vq_quantlist__8u1__p9_0[] = {
  146237. 7,
  146238. 6,
  146239. 8,
  146240. 5,
  146241. 9,
  146242. 4,
  146243. 10,
  146244. 3,
  146245. 11,
  146246. 2,
  146247. 12,
  146248. 1,
  146249. 13,
  146250. 0,
  146251. 14,
  146252. };
  146253. static long _vq_lengthlist__8u1__p9_0[] = {
  146254. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146255. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146256. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146266. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146267. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146268. 10,
  146269. };
  146270. static float _vq_quantthresh__8u1__p9_0[] = {
  146271. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146272. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146273. };
  146274. static long _vq_quantmap__8u1__p9_0[] = {
  146275. 13, 11, 9, 7, 5, 3, 1, 0,
  146276. 2, 4, 6, 8, 10, 12, 14,
  146277. };
  146278. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146279. _vq_quantthresh__8u1__p9_0,
  146280. _vq_quantmap__8u1__p9_0,
  146281. 15,
  146282. 15
  146283. };
  146284. static static_codebook _8u1__p9_0 = {
  146285. 2, 225,
  146286. _vq_lengthlist__8u1__p9_0,
  146287. 1, -514071552, 1627381760, 4, 0,
  146288. _vq_quantlist__8u1__p9_0,
  146289. NULL,
  146290. &_vq_auxt__8u1__p9_0,
  146291. NULL,
  146292. 0
  146293. };
  146294. static long _vq_quantlist__8u1__p9_1[] = {
  146295. 7,
  146296. 6,
  146297. 8,
  146298. 5,
  146299. 9,
  146300. 4,
  146301. 10,
  146302. 3,
  146303. 11,
  146304. 2,
  146305. 12,
  146306. 1,
  146307. 13,
  146308. 0,
  146309. 14,
  146310. };
  146311. static long _vq_lengthlist__8u1__p9_1[] = {
  146312. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146313. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146314. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146315. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146316. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146317. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146318. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146319. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146320. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146321. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146322. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146323. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146324. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146325. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146326. 13,
  146327. };
  146328. static float _vq_quantthresh__8u1__p9_1[] = {
  146329. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146330. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146331. };
  146332. static long _vq_quantmap__8u1__p9_1[] = {
  146333. 13, 11, 9, 7, 5, 3, 1, 0,
  146334. 2, 4, 6, 8, 10, 12, 14,
  146335. };
  146336. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146337. _vq_quantthresh__8u1__p9_1,
  146338. _vq_quantmap__8u1__p9_1,
  146339. 15,
  146340. 15
  146341. };
  146342. static static_codebook _8u1__p9_1 = {
  146343. 2, 225,
  146344. _vq_lengthlist__8u1__p9_1,
  146345. 1, -522338304, 1620115456, 4, 0,
  146346. _vq_quantlist__8u1__p9_1,
  146347. NULL,
  146348. &_vq_auxt__8u1__p9_1,
  146349. NULL,
  146350. 0
  146351. };
  146352. static long _vq_quantlist__8u1__p9_2[] = {
  146353. 8,
  146354. 7,
  146355. 9,
  146356. 6,
  146357. 10,
  146358. 5,
  146359. 11,
  146360. 4,
  146361. 12,
  146362. 3,
  146363. 13,
  146364. 2,
  146365. 14,
  146366. 1,
  146367. 15,
  146368. 0,
  146369. 16,
  146370. };
  146371. static long _vq_lengthlist__8u1__p9_2[] = {
  146372. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146373. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146374. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146375. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146376. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146377. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146378. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146379. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146380. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146381. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146382. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146383. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146384. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146385. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146386. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146387. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146388. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146389. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146390. 10,
  146391. };
  146392. static float _vq_quantthresh__8u1__p9_2[] = {
  146393. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146394. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146395. };
  146396. static long _vq_quantmap__8u1__p9_2[] = {
  146397. 15, 13, 11, 9, 7, 5, 3, 1,
  146398. 0, 2, 4, 6, 8, 10, 12, 14,
  146399. 16,
  146400. };
  146401. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146402. _vq_quantthresh__8u1__p9_2,
  146403. _vq_quantmap__8u1__p9_2,
  146404. 17,
  146405. 17
  146406. };
  146407. static static_codebook _8u1__p9_2 = {
  146408. 2, 289,
  146409. _vq_lengthlist__8u1__p9_2,
  146410. 1, -529530880, 1611661312, 5, 0,
  146411. _vq_quantlist__8u1__p9_2,
  146412. NULL,
  146413. &_vq_auxt__8u1__p9_2,
  146414. NULL,
  146415. 0
  146416. };
  146417. static long _huff_lengthlist__8u1__single[] = {
  146418. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146419. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146420. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146421. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146422. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146423. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146424. 13, 8, 8,15,
  146425. };
  146426. static static_codebook _huff_book__8u1__single = {
  146427. 2, 100,
  146428. _huff_lengthlist__8u1__single,
  146429. 0, 0, 0, 0, 0,
  146430. NULL,
  146431. NULL,
  146432. NULL,
  146433. NULL,
  146434. 0
  146435. };
  146436. static long _huff_lengthlist__44u0__long[] = {
  146437. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146438. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146439. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146440. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146441. };
  146442. static static_codebook _huff_book__44u0__long = {
  146443. 2, 64,
  146444. _huff_lengthlist__44u0__long,
  146445. 0, 0, 0, 0, 0,
  146446. NULL,
  146447. NULL,
  146448. NULL,
  146449. NULL,
  146450. 0
  146451. };
  146452. static long _vq_quantlist__44u0__p1_0[] = {
  146453. 1,
  146454. 0,
  146455. 2,
  146456. };
  146457. static long _vq_lengthlist__44u0__p1_0[] = {
  146458. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146459. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146460. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146461. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146462. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146463. 13,
  146464. };
  146465. static float _vq_quantthresh__44u0__p1_0[] = {
  146466. -0.5, 0.5,
  146467. };
  146468. static long _vq_quantmap__44u0__p1_0[] = {
  146469. 1, 0, 2,
  146470. };
  146471. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146472. _vq_quantthresh__44u0__p1_0,
  146473. _vq_quantmap__44u0__p1_0,
  146474. 3,
  146475. 3
  146476. };
  146477. static static_codebook _44u0__p1_0 = {
  146478. 4, 81,
  146479. _vq_lengthlist__44u0__p1_0,
  146480. 1, -535822336, 1611661312, 2, 0,
  146481. _vq_quantlist__44u0__p1_0,
  146482. NULL,
  146483. &_vq_auxt__44u0__p1_0,
  146484. NULL,
  146485. 0
  146486. };
  146487. static long _vq_quantlist__44u0__p2_0[] = {
  146488. 1,
  146489. 0,
  146490. 2,
  146491. };
  146492. static long _vq_lengthlist__44u0__p2_0[] = {
  146493. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146494. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146495. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146496. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146497. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146498. 9,
  146499. };
  146500. static float _vq_quantthresh__44u0__p2_0[] = {
  146501. -0.5, 0.5,
  146502. };
  146503. static long _vq_quantmap__44u0__p2_0[] = {
  146504. 1, 0, 2,
  146505. };
  146506. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146507. _vq_quantthresh__44u0__p2_0,
  146508. _vq_quantmap__44u0__p2_0,
  146509. 3,
  146510. 3
  146511. };
  146512. static static_codebook _44u0__p2_0 = {
  146513. 4, 81,
  146514. _vq_lengthlist__44u0__p2_0,
  146515. 1, -535822336, 1611661312, 2, 0,
  146516. _vq_quantlist__44u0__p2_0,
  146517. NULL,
  146518. &_vq_auxt__44u0__p2_0,
  146519. NULL,
  146520. 0
  146521. };
  146522. static long _vq_quantlist__44u0__p3_0[] = {
  146523. 2,
  146524. 1,
  146525. 3,
  146526. 0,
  146527. 4,
  146528. };
  146529. static long _vq_lengthlist__44u0__p3_0[] = {
  146530. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146531. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146532. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146533. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146534. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146535. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146536. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146537. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146538. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146539. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146540. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146541. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146542. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146543. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146544. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146545. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146546. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146547. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146548. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146549. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146550. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146551. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146552. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146553. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146554. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146555. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146556. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146557. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146558. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146559. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146560. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146561. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146562. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146563. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146564. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146565. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146566. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146567. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146568. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146569. 19,
  146570. };
  146571. static float _vq_quantthresh__44u0__p3_0[] = {
  146572. -1.5, -0.5, 0.5, 1.5,
  146573. };
  146574. static long _vq_quantmap__44u0__p3_0[] = {
  146575. 3, 1, 0, 2, 4,
  146576. };
  146577. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146578. _vq_quantthresh__44u0__p3_0,
  146579. _vq_quantmap__44u0__p3_0,
  146580. 5,
  146581. 5
  146582. };
  146583. static static_codebook _44u0__p3_0 = {
  146584. 4, 625,
  146585. _vq_lengthlist__44u0__p3_0,
  146586. 1, -533725184, 1611661312, 3, 0,
  146587. _vq_quantlist__44u0__p3_0,
  146588. NULL,
  146589. &_vq_auxt__44u0__p3_0,
  146590. NULL,
  146591. 0
  146592. };
  146593. static long _vq_quantlist__44u0__p4_0[] = {
  146594. 2,
  146595. 1,
  146596. 3,
  146597. 0,
  146598. 4,
  146599. };
  146600. static long _vq_lengthlist__44u0__p4_0[] = {
  146601. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146602. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146603. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146604. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146605. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146606. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146607. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146608. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146609. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146610. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146611. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146612. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146613. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146614. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146615. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146616. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146617. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146618. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146619. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146620. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146621. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146622. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146623. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146624. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146625. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146626. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146627. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146628. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146629. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146630. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146631. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146632. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146633. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146634. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146635. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146636. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146637. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146638. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146639. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146640. 12,
  146641. };
  146642. static float _vq_quantthresh__44u0__p4_0[] = {
  146643. -1.5, -0.5, 0.5, 1.5,
  146644. };
  146645. static long _vq_quantmap__44u0__p4_0[] = {
  146646. 3, 1, 0, 2, 4,
  146647. };
  146648. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146649. _vq_quantthresh__44u0__p4_0,
  146650. _vq_quantmap__44u0__p4_0,
  146651. 5,
  146652. 5
  146653. };
  146654. static static_codebook _44u0__p4_0 = {
  146655. 4, 625,
  146656. _vq_lengthlist__44u0__p4_0,
  146657. 1, -533725184, 1611661312, 3, 0,
  146658. _vq_quantlist__44u0__p4_0,
  146659. NULL,
  146660. &_vq_auxt__44u0__p4_0,
  146661. NULL,
  146662. 0
  146663. };
  146664. static long _vq_quantlist__44u0__p5_0[] = {
  146665. 4,
  146666. 3,
  146667. 5,
  146668. 2,
  146669. 6,
  146670. 1,
  146671. 7,
  146672. 0,
  146673. 8,
  146674. };
  146675. static long _vq_lengthlist__44u0__p5_0[] = {
  146676. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146677. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146678. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146679. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146680. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146681. 12,
  146682. };
  146683. static float _vq_quantthresh__44u0__p5_0[] = {
  146684. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146685. };
  146686. static long _vq_quantmap__44u0__p5_0[] = {
  146687. 7, 5, 3, 1, 0, 2, 4, 6,
  146688. 8,
  146689. };
  146690. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146691. _vq_quantthresh__44u0__p5_0,
  146692. _vq_quantmap__44u0__p5_0,
  146693. 9,
  146694. 9
  146695. };
  146696. static static_codebook _44u0__p5_0 = {
  146697. 2, 81,
  146698. _vq_lengthlist__44u0__p5_0,
  146699. 1, -531628032, 1611661312, 4, 0,
  146700. _vq_quantlist__44u0__p5_0,
  146701. NULL,
  146702. &_vq_auxt__44u0__p5_0,
  146703. NULL,
  146704. 0
  146705. };
  146706. static long _vq_quantlist__44u0__p6_0[] = {
  146707. 6,
  146708. 5,
  146709. 7,
  146710. 4,
  146711. 8,
  146712. 3,
  146713. 9,
  146714. 2,
  146715. 10,
  146716. 1,
  146717. 11,
  146718. 0,
  146719. 12,
  146720. };
  146721. static long _vq_lengthlist__44u0__p6_0[] = {
  146722. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146723. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146724. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146725. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146726. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146727. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146728. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146729. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146730. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146731. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146732. 15,17,16,17,18,17,17,18, 0,
  146733. };
  146734. static float _vq_quantthresh__44u0__p6_0[] = {
  146735. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146736. 12.5, 17.5, 22.5, 27.5,
  146737. };
  146738. static long _vq_quantmap__44u0__p6_0[] = {
  146739. 11, 9, 7, 5, 3, 1, 0, 2,
  146740. 4, 6, 8, 10, 12,
  146741. };
  146742. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146743. _vq_quantthresh__44u0__p6_0,
  146744. _vq_quantmap__44u0__p6_0,
  146745. 13,
  146746. 13
  146747. };
  146748. static static_codebook _44u0__p6_0 = {
  146749. 2, 169,
  146750. _vq_lengthlist__44u0__p6_0,
  146751. 1, -526516224, 1616117760, 4, 0,
  146752. _vq_quantlist__44u0__p6_0,
  146753. NULL,
  146754. &_vq_auxt__44u0__p6_0,
  146755. NULL,
  146756. 0
  146757. };
  146758. static long _vq_quantlist__44u0__p6_1[] = {
  146759. 2,
  146760. 1,
  146761. 3,
  146762. 0,
  146763. 4,
  146764. };
  146765. static long _vq_lengthlist__44u0__p6_1[] = {
  146766. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146767. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146768. };
  146769. static float _vq_quantthresh__44u0__p6_1[] = {
  146770. -1.5, -0.5, 0.5, 1.5,
  146771. };
  146772. static long _vq_quantmap__44u0__p6_1[] = {
  146773. 3, 1, 0, 2, 4,
  146774. };
  146775. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146776. _vq_quantthresh__44u0__p6_1,
  146777. _vq_quantmap__44u0__p6_1,
  146778. 5,
  146779. 5
  146780. };
  146781. static static_codebook _44u0__p6_1 = {
  146782. 2, 25,
  146783. _vq_lengthlist__44u0__p6_1,
  146784. 1, -533725184, 1611661312, 3, 0,
  146785. _vq_quantlist__44u0__p6_1,
  146786. NULL,
  146787. &_vq_auxt__44u0__p6_1,
  146788. NULL,
  146789. 0
  146790. };
  146791. static long _vq_quantlist__44u0__p7_0[] = {
  146792. 2,
  146793. 1,
  146794. 3,
  146795. 0,
  146796. 4,
  146797. };
  146798. static long _vq_lengthlist__44u0__p7_0[] = {
  146799. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146802. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146806. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146810. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146829. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146830. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146831. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146832. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146833. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146835. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146836. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146837. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146838. 10,
  146839. };
  146840. static float _vq_quantthresh__44u0__p7_0[] = {
  146841. -253.5, -84.5, 84.5, 253.5,
  146842. };
  146843. static long _vq_quantmap__44u0__p7_0[] = {
  146844. 3, 1, 0, 2, 4,
  146845. };
  146846. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146847. _vq_quantthresh__44u0__p7_0,
  146848. _vq_quantmap__44u0__p7_0,
  146849. 5,
  146850. 5
  146851. };
  146852. static static_codebook _44u0__p7_0 = {
  146853. 4, 625,
  146854. _vq_lengthlist__44u0__p7_0,
  146855. 1, -518709248, 1626677248, 3, 0,
  146856. _vq_quantlist__44u0__p7_0,
  146857. NULL,
  146858. &_vq_auxt__44u0__p7_0,
  146859. NULL,
  146860. 0
  146861. };
  146862. static long _vq_quantlist__44u0__p7_1[] = {
  146863. 6,
  146864. 5,
  146865. 7,
  146866. 4,
  146867. 8,
  146868. 3,
  146869. 9,
  146870. 2,
  146871. 10,
  146872. 1,
  146873. 11,
  146874. 0,
  146875. 12,
  146876. };
  146877. static long _vq_lengthlist__44u0__p7_1[] = {
  146878. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146879. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146880. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146881. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146882. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146883. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146884. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146885. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146886. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146887. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146888. 15,15,15,15,15,15,15,15,15,
  146889. };
  146890. static float _vq_quantthresh__44u0__p7_1[] = {
  146891. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146892. 32.5, 45.5, 58.5, 71.5,
  146893. };
  146894. static long _vq_quantmap__44u0__p7_1[] = {
  146895. 11, 9, 7, 5, 3, 1, 0, 2,
  146896. 4, 6, 8, 10, 12,
  146897. };
  146898. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146899. _vq_quantthresh__44u0__p7_1,
  146900. _vq_quantmap__44u0__p7_1,
  146901. 13,
  146902. 13
  146903. };
  146904. static static_codebook _44u0__p7_1 = {
  146905. 2, 169,
  146906. _vq_lengthlist__44u0__p7_1,
  146907. 1, -523010048, 1618608128, 4, 0,
  146908. _vq_quantlist__44u0__p7_1,
  146909. NULL,
  146910. &_vq_auxt__44u0__p7_1,
  146911. NULL,
  146912. 0
  146913. };
  146914. static long _vq_quantlist__44u0__p7_2[] = {
  146915. 6,
  146916. 5,
  146917. 7,
  146918. 4,
  146919. 8,
  146920. 3,
  146921. 9,
  146922. 2,
  146923. 10,
  146924. 1,
  146925. 11,
  146926. 0,
  146927. 12,
  146928. };
  146929. static long _vq_lengthlist__44u0__p7_2[] = {
  146930. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146931. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146932. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146933. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146934. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146935. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146936. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146937. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146938. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146939. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146940. 9, 9, 9,10, 9, 9,10,10, 9,
  146941. };
  146942. static float _vq_quantthresh__44u0__p7_2[] = {
  146943. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146944. 2.5, 3.5, 4.5, 5.5,
  146945. };
  146946. static long _vq_quantmap__44u0__p7_2[] = {
  146947. 11, 9, 7, 5, 3, 1, 0, 2,
  146948. 4, 6, 8, 10, 12,
  146949. };
  146950. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146951. _vq_quantthresh__44u0__p7_2,
  146952. _vq_quantmap__44u0__p7_2,
  146953. 13,
  146954. 13
  146955. };
  146956. static static_codebook _44u0__p7_2 = {
  146957. 2, 169,
  146958. _vq_lengthlist__44u0__p7_2,
  146959. 1, -531103744, 1611661312, 4, 0,
  146960. _vq_quantlist__44u0__p7_2,
  146961. NULL,
  146962. &_vq_auxt__44u0__p7_2,
  146963. NULL,
  146964. 0
  146965. };
  146966. static long _huff_lengthlist__44u0__short[] = {
  146967. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146968. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146969. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146970. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146971. };
  146972. static static_codebook _huff_book__44u0__short = {
  146973. 2, 64,
  146974. _huff_lengthlist__44u0__short,
  146975. 0, 0, 0, 0, 0,
  146976. NULL,
  146977. NULL,
  146978. NULL,
  146979. NULL,
  146980. 0
  146981. };
  146982. static long _huff_lengthlist__44u1__long[] = {
  146983. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146984. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146985. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146986. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146987. };
  146988. static static_codebook _huff_book__44u1__long = {
  146989. 2, 64,
  146990. _huff_lengthlist__44u1__long,
  146991. 0, 0, 0, 0, 0,
  146992. NULL,
  146993. NULL,
  146994. NULL,
  146995. NULL,
  146996. 0
  146997. };
  146998. static long _vq_quantlist__44u1__p1_0[] = {
  146999. 1,
  147000. 0,
  147001. 2,
  147002. };
  147003. static long _vq_lengthlist__44u1__p1_0[] = {
  147004. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147005. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147006. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  147007. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  147008. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  147009. 13,
  147010. };
  147011. static float _vq_quantthresh__44u1__p1_0[] = {
  147012. -0.5, 0.5,
  147013. };
  147014. static long _vq_quantmap__44u1__p1_0[] = {
  147015. 1, 0, 2,
  147016. };
  147017. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  147018. _vq_quantthresh__44u1__p1_0,
  147019. _vq_quantmap__44u1__p1_0,
  147020. 3,
  147021. 3
  147022. };
  147023. static static_codebook _44u1__p1_0 = {
  147024. 4, 81,
  147025. _vq_lengthlist__44u1__p1_0,
  147026. 1, -535822336, 1611661312, 2, 0,
  147027. _vq_quantlist__44u1__p1_0,
  147028. NULL,
  147029. &_vq_auxt__44u1__p1_0,
  147030. NULL,
  147031. 0
  147032. };
  147033. static long _vq_quantlist__44u1__p2_0[] = {
  147034. 1,
  147035. 0,
  147036. 2,
  147037. };
  147038. static long _vq_lengthlist__44u1__p2_0[] = {
  147039. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147040. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147041. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147042. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147043. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147044. 9,
  147045. };
  147046. static float _vq_quantthresh__44u1__p2_0[] = {
  147047. -0.5, 0.5,
  147048. };
  147049. static long _vq_quantmap__44u1__p2_0[] = {
  147050. 1, 0, 2,
  147051. };
  147052. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147053. _vq_quantthresh__44u1__p2_0,
  147054. _vq_quantmap__44u1__p2_0,
  147055. 3,
  147056. 3
  147057. };
  147058. static static_codebook _44u1__p2_0 = {
  147059. 4, 81,
  147060. _vq_lengthlist__44u1__p2_0,
  147061. 1, -535822336, 1611661312, 2, 0,
  147062. _vq_quantlist__44u1__p2_0,
  147063. NULL,
  147064. &_vq_auxt__44u1__p2_0,
  147065. NULL,
  147066. 0
  147067. };
  147068. static long _vq_quantlist__44u1__p3_0[] = {
  147069. 2,
  147070. 1,
  147071. 3,
  147072. 0,
  147073. 4,
  147074. };
  147075. static long _vq_lengthlist__44u1__p3_0[] = {
  147076. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147077. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147078. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147079. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147080. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147081. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147082. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147083. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147084. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147085. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147086. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147087. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147088. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147089. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147090. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147091. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147092. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147093. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147094. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147095. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147096. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147097. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147098. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147099. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147100. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147101. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147102. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147103. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147104. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147105. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147106. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147107. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147108. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147109. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147110. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147111. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147112. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147113. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147114. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147115. 19,
  147116. };
  147117. static float _vq_quantthresh__44u1__p3_0[] = {
  147118. -1.5, -0.5, 0.5, 1.5,
  147119. };
  147120. static long _vq_quantmap__44u1__p3_0[] = {
  147121. 3, 1, 0, 2, 4,
  147122. };
  147123. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147124. _vq_quantthresh__44u1__p3_0,
  147125. _vq_quantmap__44u1__p3_0,
  147126. 5,
  147127. 5
  147128. };
  147129. static static_codebook _44u1__p3_0 = {
  147130. 4, 625,
  147131. _vq_lengthlist__44u1__p3_0,
  147132. 1, -533725184, 1611661312, 3, 0,
  147133. _vq_quantlist__44u1__p3_0,
  147134. NULL,
  147135. &_vq_auxt__44u1__p3_0,
  147136. NULL,
  147137. 0
  147138. };
  147139. static long _vq_quantlist__44u1__p4_0[] = {
  147140. 2,
  147141. 1,
  147142. 3,
  147143. 0,
  147144. 4,
  147145. };
  147146. static long _vq_lengthlist__44u1__p4_0[] = {
  147147. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147148. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147149. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147150. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147151. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147152. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147153. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147154. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147155. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147156. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147157. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147158. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147159. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147160. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147161. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147162. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147163. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147164. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147165. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147166. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147167. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147168. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147169. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147170. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147171. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147172. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147173. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147174. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147175. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147176. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147177. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147178. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147179. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147180. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147181. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147182. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147183. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147184. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147185. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147186. 12,
  147187. };
  147188. static float _vq_quantthresh__44u1__p4_0[] = {
  147189. -1.5, -0.5, 0.5, 1.5,
  147190. };
  147191. static long _vq_quantmap__44u1__p4_0[] = {
  147192. 3, 1, 0, 2, 4,
  147193. };
  147194. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147195. _vq_quantthresh__44u1__p4_0,
  147196. _vq_quantmap__44u1__p4_0,
  147197. 5,
  147198. 5
  147199. };
  147200. static static_codebook _44u1__p4_0 = {
  147201. 4, 625,
  147202. _vq_lengthlist__44u1__p4_0,
  147203. 1, -533725184, 1611661312, 3, 0,
  147204. _vq_quantlist__44u1__p4_0,
  147205. NULL,
  147206. &_vq_auxt__44u1__p4_0,
  147207. NULL,
  147208. 0
  147209. };
  147210. static long _vq_quantlist__44u1__p5_0[] = {
  147211. 4,
  147212. 3,
  147213. 5,
  147214. 2,
  147215. 6,
  147216. 1,
  147217. 7,
  147218. 0,
  147219. 8,
  147220. };
  147221. static long _vq_lengthlist__44u1__p5_0[] = {
  147222. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147223. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147224. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147225. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147226. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147227. 12,
  147228. };
  147229. static float _vq_quantthresh__44u1__p5_0[] = {
  147230. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147231. };
  147232. static long _vq_quantmap__44u1__p5_0[] = {
  147233. 7, 5, 3, 1, 0, 2, 4, 6,
  147234. 8,
  147235. };
  147236. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147237. _vq_quantthresh__44u1__p5_0,
  147238. _vq_quantmap__44u1__p5_0,
  147239. 9,
  147240. 9
  147241. };
  147242. static static_codebook _44u1__p5_0 = {
  147243. 2, 81,
  147244. _vq_lengthlist__44u1__p5_0,
  147245. 1, -531628032, 1611661312, 4, 0,
  147246. _vq_quantlist__44u1__p5_0,
  147247. NULL,
  147248. &_vq_auxt__44u1__p5_0,
  147249. NULL,
  147250. 0
  147251. };
  147252. static long _vq_quantlist__44u1__p6_0[] = {
  147253. 6,
  147254. 5,
  147255. 7,
  147256. 4,
  147257. 8,
  147258. 3,
  147259. 9,
  147260. 2,
  147261. 10,
  147262. 1,
  147263. 11,
  147264. 0,
  147265. 12,
  147266. };
  147267. static long _vq_lengthlist__44u1__p6_0[] = {
  147268. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147269. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147270. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147271. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147272. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147273. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147274. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147275. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147276. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147277. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147278. 15,17,16,17,18,17,17,18, 0,
  147279. };
  147280. static float _vq_quantthresh__44u1__p6_0[] = {
  147281. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147282. 12.5, 17.5, 22.5, 27.5,
  147283. };
  147284. static long _vq_quantmap__44u1__p6_0[] = {
  147285. 11, 9, 7, 5, 3, 1, 0, 2,
  147286. 4, 6, 8, 10, 12,
  147287. };
  147288. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147289. _vq_quantthresh__44u1__p6_0,
  147290. _vq_quantmap__44u1__p6_0,
  147291. 13,
  147292. 13
  147293. };
  147294. static static_codebook _44u1__p6_0 = {
  147295. 2, 169,
  147296. _vq_lengthlist__44u1__p6_0,
  147297. 1, -526516224, 1616117760, 4, 0,
  147298. _vq_quantlist__44u1__p6_0,
  147299. NULL,
  147300. &_vq_auxt__44u1__p6_0,
  147301. NULL,
  147302. 0
  147303. };
  147304. static long _vq_quantlist__44u1__p6_1[] = {
  147305. 2,
  147306. 1,
  147307. 3,
  147308. 0,
  147309. 4,
  147310. };
  147311. static long _vq_lengthlist__44u1__p6_1[] = {
  147312. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147313. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147314. };
  147315. static float _vq_quantthresh__44u1__p6_1[] = {
  147316. -1.5, -0.5, 0.5, 1.5,
  147317. };
  147318. static long _vq_quantmap__44u1__p6_1[] = {
  147319. 3, 1, 0, 2, 4,
  147320. };
  147321. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147322. _vq_quantthresh__44u1__p6_1,
  147323. _vq_quantmap__44u1__p6_1,
  147324. 5,
  147325. 5
  147326. };
  147327. static static_codebook _44u1__p6_1 = {
  147328. 2, 25,
  147329. _vq_lengthlist__44u1__p6_1,
  147330. 1, -533725184, 1611661312, 3, 0,
  147331. _vq_quantlist__44u1__p6_1,
  147332. NULL,
  147333. &_vq_auxt__44u1__p6_1,
  147334. NULL,
  147335. 0
  147336. };
  147337. static long _vq_quantlist__44u1__p7_0[] = {
  147338. 3,
  147339. 2,
  147340. 4,
  147341. 1,
  147342. 5,
  147343. 0,
  147344. 6,
  147345. };
  147346. static long _vq_lengthlist__44u1__p7_0[] = {
  147347. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147348. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147349. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147350. 8,
  147351. };
  147352. static float _vq_quantthresh__44u1__p7_0[] = {
  147353. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147354. };
  147355. static long _vq_quantmap__44u1__p7_0[] = {
  147356. 5, 3, 1, 0, 2, 4, 6,
  147357. };
  147358. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147359. _vq_quantthresh__44u1__p7_0,
  147360. _vq_quantmap__44u1__p7_0,
  147361. 7,
  147362. 7
  147363. };
  147364. static static_codebook _44u1__p7_0 = {
  147365. 2, 49,
  147366. _vq_lengthlist__44u1__p7_0,
  147367. 1, -518017024, 1626677248, 3, 0,
  147368. _vq_quantlist__44u1__p7_0,
  147369. NULL,
  147370. &_vq_auxt__44u1__p7_0,
  147371. NULL,
  147372. 0
  147373. };
  147374. static long _vq_quantlist__44u1__p7_1[] = {
  147375. 6,
  147376. 5,
  147377. 7,
  147378. 4,
  147379. 8,
  147380. 3,
  147381. 9,
  147382. 2,
  147383. 10,
  147384. 1,
  147385. 11,
  147386. 0,
  147387. 12,
  147388. };
  147389. static long _vq_lengthlist__44u1__p7_1[] = {
  147390. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147391. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147392. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147393. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147394. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147395. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147396. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147397. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147398. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147399. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147400. 15,15,15,15,15,15,15,15,15,
  147401. };
  147402. static float _vq_quantthresh__44u1__p7_1[] = {
  147403. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147404. 32.5, 45.5, 58.5, 71.5,
  147405. };
  147406. static long _vq_quantmap__44u1__p7_1[] = {
  147407. 11, 9, 7, 5, 3, 1, 0, 2,
  147408. 4, 6, 8, 10, 12,
  147409. };
  147410. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147411. _vq_quantthresh__44u1__p7_1,
  147412. _vq_quantmap__44u1__p7_1,
  147413. 13,
  147414. 13
  147415. };
  147416. static static_codebook _44u1__p7_1 = {
  147417. 2, 169,
  147418. _vq_lengthlist__44u1__p7_1,
  147419. 1, -523010048, 1618608128, 4, 0,
  147420. _vq_quantlist__44u1__p7_1,
  147421. NULL,
  147422. &_vq_auxt__44u1__p7_1,
  147423. NULL,
  147424. 0
  147425. };
  147426. static long _vq_quantlist__44u1__p7_2[] = {
  147427. 6,
  147428. 5,
  147429. 7,
  147430. 4,
  147431. 8,
  147432. 3,
  147433. 9,
  147434. 2,
  147435. 10,
  147436. 1,
  147437. 11,
  147438. 0,
  147439. 12,
  147440. };
  147441. static long _vq_lengthlist__44u1__p7_2[] = {
  147442. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147443. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147444. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147445. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147446. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147447. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147448. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147449. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147450. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147451. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147452. 9, 9, 9,10, 9, 9,10,10, 9,
  147453. };
  147454. static float _vq_quantthresh__44u1__p7_2[] = {
  147455. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147456. 2.5, 3.5, 4.5, 5.5,
  147457. };
  147458. static long _vq_quantmap__44u1__p7_2[] = {
  147459. 11, 9, 7, 5, 3, 1, 0, 2,
  147460. 4, 6, 8, 10, 12,
  147461. };
  147462. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147463. _vq_quantthresh__44u1__p7_2,
  147464. _vq_quantmap__44u1__p7_2,
  147465. 13,
  147466. 13
  147467. };
  147468. static static_codebook _44u1__p7_2 = {
  147469. 2, 169,
  147470. _vq_lengthlist__44u1__p7_2,
  147471. 1, -531103744, 1611661312, 4, 0,
  147472. _vq_quantlist__44u1__p7_2,
  147473. NULL,
  147474. &_vq_auxt__44u1__p7_2,
  147475. NULL,
  147476. 0
  147477. };
  147478. static long _huff_lengthlist__44u1__short[] = {
  147479. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147480. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147481. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147482. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147483. };
  147484. static static_codebook _huff_book__44u1__short = {
  147485. 2, 64,
  147486. _huff_lengthlist__44u1__short,
  147487. 0, 0, 0, 0, 0,
  147488. NULL,
  147489. NULL,
  147490. NULL,
  147491. NULL,
  147492. 0
  147493. };
  147494. static long _huff_lengthlist__44u2__long[] = {
  147495. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147496. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147497. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147498. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147499. };
  147500. static static_codebook _huff_book__44u2__long = {
  147501. 2, 64,
  147502. _huff_lengthlist__44u2__long,
  147503. 0, 0, 0, 0, 0,
  147504. NULL,
  147505. NULL,
  147506. NULL,
  147507. NULL,
  147508. 0
  147509. };
  147510. static long _vq_quantlist__44u2__p1_0[] = {
  147511. 1,
  147512. 0,
  147513. 2,
  147514. };
  147515. static long _vq_lengthlist__44u2__p1_0[] = {
  147516. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147517. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147518. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147519. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147520. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147521. 13,
  147522. };
  147523. static float _vq_quantthresh__44u2__p1_0[] = {
  147524. -0.5, 0.5,
  147525. };
  147526. static long _vq_quantmap__44u2__p1_0[] = {
  147527. 1, 0, 2,
  147528. };
  147529. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147530. _vq_quantthresh__44u2__p1_0,
  147531. _vq_quantmap__44u2__p1_0,
  147532. 3,
  147533. 3
  147534. };
  147535. static static_codebook _44u2__p1_0 = {
  147536. 4, 81,
  147537. _vq_lengthlist__44u2__p1_0,
  147538. 1, -535822336, 1611661312, 2, 0,
  147539. _vq_quantlist__44u2__p1_0,
  147540. NULL,
  147541. &_vq_auxt__44u2__p1_0,
  147542. NULL,
  147543. 0
  147544. };
  147545. static long _vq_quantlist__44u2__p2_0[] = {
  147546. 1,
  147547. 0,
  147548. 2,
  147549. };
  147550. static long _vq_lengthlist__44u2__p2_0[] = {
  147551. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147552. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147553. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147554. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147555. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147556. 9,
  147557. };
  147558. static float _vq_quantthresh__44u2__p2_0[] = {
  147559. -0.5, 0.5,
  147560. };
  147561. static long _vq_quantmap__44u2__p2_0[] = {
  147562. 1, 0, 2,
  147563. };
  147564. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147565. _vq_quantthresh__44u2__p2_0,
  147566. _vq_quantmap__44u2__p2_0,
  147567. 3,
  147568. 3
  147569. };
  147570. static static_codebook _44u2__p2_0 = {
  147571. 4, 81,
  147572. _vq_lengthlist__44u2__p2_0,
  147573. 1, -535822336, 1611661312, 2, 0,
  147574. _vq_quantlist__44u2__p2_0,
  147575. NULL,
  147576. &_vq_auxt__44u2__p2_0,
  147577. NULL,
  147578. 0
  147579. };
  147580. static long _vq_quantlist__44u2__p3_0[] = {
  147581. 2,
  147582. 1,
  147583. 3,
  147584. 0,
  147585. 4,
  147586. };
  147587. static long _vq_lengthlist__44u2__p3_0[] = {
  147588. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147589. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147590. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147591. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147592. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147593. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147594. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147595. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147596. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147597. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147598. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147599. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147600. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147601. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147602. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147603. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147604. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147605. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147606. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147607. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147608. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147609. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147610. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147611. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147612. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147613. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147614. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147615. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147616. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147617. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147618. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147619. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147620. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147621. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147622. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147623. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147624. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147625. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147626. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147627. 0,
  147628. };
  147629. static float _vq_quantthresh__44u2__p3_0[] = {
  147630. -1.5, -0.5, 0.5, 1.5,
  147631. };
  147632. static long _vq_quantmap__44u2__p3_0[] = {
  147633. 3, 1, 0, 2, 4,
  147634. };
  147635. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147636. _vq_quantthresh__44u2__p3_0,
  147637. _vq_quantmap__44u2__p3_0,
  147638. 5,
  147639. 5
  147640. };
  147641. static static_codebook _44u2__p3_0 = {
  147642. 4, 625,
  147643. _vq_lengthlist__44u2__p3_0,
  147644. 1, -533725184, 1611661312, 3, 0,
  147645. _vq_quantlist__44u2__p3_0,
  147646. NULL,
  147647. &_vq_auxt__44u2__p3_0,
  147648. NULL,
  147649. 0
  147650. };
  147651. static long _vq_quantlist__44u2__p4_0[] = {
  147652. 2,
  147653. 1,
  147654. 3,
  147655. 0,
  147656. 4,
  147657. };
  147658. static long _vq_lengthlist__44u2__p4_0[] = {
  147659. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147660. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147661. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147662. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147663. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147664. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147665. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147666. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147667. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147668. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147669. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147670. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147671. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147672. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147673. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147674. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147675. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147676. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147677. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147678. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147679. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147680. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147681. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147682. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147683. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147684. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147685. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147686. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147687. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147688. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147689. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147690. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147691. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147692. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147693. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147694. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147695. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147696. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147697. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147698. 13,
  147699. };
  147700. static float _vq_quantthresh__44u2__p4_0[] = {
  147701. -1.5, -0.5, 0.5, 1.5,
  147702. };
  147703. static long _vq_quantmap__44u2__p4_0[] = {
  147704. 3, 1, 0, 2, 4,
  147705. };
  147706. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147707. _vq_quantthresh__44u2__p4_0,
  147708. _vq_quantmap__44u2__p4_0,
  147709. 5,
  147710. 5
  147711. };
  147712. static static_codebook _44u2__p4_0 = {
  147713. 4, 625,
  147714. _vq_lengthlist__44u2__p4_0,
  147715. 1, -533725184, 1611661312, 3, 0,
  147716. _vq_quantlist__44u2__p4_0,
  147717. NULL,
  147718. &_vq_auxt__44u2__p4_0,
  147719. NULL,
  147720. 0
  147721. };
  147722. static long _vq_quantlist__44u2__p5_0[] = {
  147723. 4,
  147724. 3,
  147725. 5,
  147726. 2,
  147727. 6,
  147728. 1,
  147729. 7,
  147730. 0,
  147731. 8,
  147732. };
  147733. static long _vq_lengthlist__44u2__p5_0[] = {
  147734. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147735. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147736. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147737. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147738. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147739. 13,
  147740. };
  147741. static float _vq_quantthresh__44u2__p5_0[] = {
  147742. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147743. };
  147744. static long _vq_quantmap__44u2__p5_0[] = {
  147745. 7, 5, 3, 1, 0, 2, 4, 6,
  147746. 8,
  147747. };
  147748. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147749. _vq_quantthresh__44u2__p5_0,
  147750. _vq_quantmap__44u2__p5_0,
  147751. 9,
  147752. 9
  147753. };
  147754. static static_codebook _44u2__p5_0 = {
  147755. 2, 81,
  147756. _vq_lengthlist__44u2__p5_0,
  147757. 1, -531628032, 1611661312, 4, 0,
  147758. _vq_quantlist__44u2__p5_0,
  147759. NULL,
  147760. &_vq_auxt__44u2__p5_0,
  147761. NULL,
  147762. 0
  147763. };
  147764. static long _vq_quantlist__44u2__p6_0[] = {
  147765. 6,
  147766. 5,
  147767. 7,
  147768. 4,
  147769. 8,
  147770. 3,
  147771. 9,
  147772. 2,
  147773. 10,
  147774. 1,
  147775. 11,
  147776. 0,
  147777. 12,
  147778. };
  147779. static long _vq_lengthlist__44u2__p6_0[] = {
  147780. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147781. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147782. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147783. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147784. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147785. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147786. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147787. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147788. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147789. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147790. 15,17,17,16,18,17,18, 0, 0,
  147791. };
  147792. static float _vq_quantthresh__44u2__p6_0[] = {
  147793. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147794. 12.5, 17.5, 22.5, 27.5,
  147795. };
  147796. static long _vq_quantmap__44u2__p6_0[] = {
  147797. 11, 9, 7, 5, 3, 1, 0, 2,
  147798. 4, 6, 8, 10, 12,
  147799. };
  147800. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147801. _vq_quantthresh__44u2__p6_0,
  147802. _vq_quantmap__44u2__p6_0,
  147803. 13,
  147804. 13
  147805. };
  147806. static static_codebook _44u2__p6_0 = {
  147807. 2, 169,
  147808. _vq_lengthlist__44u2__p6_0,
  147809. 1, -526516224, 1616117760, 4, 0,
  147810. _vq_quantlist__44u2__p6_0,
  147811. NULL,
  147812. &_vq_auxt__44u2__p6_0,
  147813. NULL,
  147814. 0
  147815. };
  147816. static long _vq_quantlist__44u2__p6_1[] = {
  147817. 2,
  147818. 1,
  147819. 3,
  147820. 0,
  147821. 4,
  147822. };
  147823. static long _vq_lengthlist__44u2__p6_1[] = {
  147824. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147825. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147826. };
  147827. static float _vq_quantthresh__44u2__p6_1[] = {
  147828. -1.5, -0.5, 0.5, 1.5,
  147829. };
  147830. static long _vq_quantmap__44u2__p6_1[] = {
  147831. 3, 1, 0, 2, 4,
  147832. };
  147833. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147834. _vq_quantthresh__44u2__p6_1,
  147835. _vq_quantmap__44u2__p6_1,
  147836. 5,
  147837. 5
  147838. };
  147839. static static_codebook _44u2__p6_1 = {
  147840. 2, 25,
  147841. _vq_lengthlist__44u2__p6_1,
  147842. 1, -533725184, 1611661312, 3, 0,
  147843. _vq_quantlist__44u2__p6_1,
  147844. NULL,
  147845. &_vq_auxt__44u2__p6_1,
  147846. NULL,
  147847. 0
  147848. };
  147849. static long _vq_quantlist__44u2__p7_0[] = {
  147850. 4,
  147851. 3,
  147852. 5,
  147853. 2,
  147854. 6,
  147855. 1,
  147856. 7,
  147857. 0,
  147858. 8,
  147859. };
  147860. static long _vq_lengthlist__44u2__p7_0[] = {
  147861. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147862. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147866. 11,
  147867. };
  147868. static float _vq_quantthresh__44u2__p7_0[] = {
  147869. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147870. };
  147871. static long _vq_quantmap__44u2__p7_0[] = {
  147872. 7, 5, 3, 1, 0, 2, 4, 6,
  147873. 8,
  147874. };
  147875. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147876. _vq_quantthresh__44u2__p7_0,
  147877. _vq_quantmap__44u2__p7_0,
  147878. 9,
  147879. 9
  147880. };
  147881. static static_codebook _44u2__p7_0 = {
  147882. 2, 81,
  147883. _vq_lengthlist__44u2__p7_0,
  147884. 1, -516612096, 1626677248, 4, 0,
  147885. _vq_quantlist__44u2__p7_0,
  147886. NULL,
  147887. &_vq_auxt__44u2__p7_0,
  147888. NULL,
  147889. 0
  147890. };
  147891. static long _vq_quantlist__44u2__p7_1[] = {
  147892. 6,
  147893. 5,
  147894. 7,
  147895. 4,
  147896. 8,
  147897. 3,
  147898. 9,
  147899. 2,
  147900. 10,
  147901. 1,
  147902. 11,
  147903. 0,
  147904. 12,
  147905. };
  147906. static long _vq_lengthlist__44u2__p7_1[] = {
  147907. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147908. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147909. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147910. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147911. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147912. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147913. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147914. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147915. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147916. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147917. 14,14,14,17,15,17,17,17,17,
  147918. };
  147919. static float _vq_quantthresh__44u2__p7_1[] = {
  147920. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147921. 32.5, 45.5, 58.5, 71.5,
  147922. };
  147923. static long _vq_quantmap__44u2__p7_1[] = {
  147924. 11, 9, 7, 5, 3, 1, 0, 2,
  147925. 4, 6, 8, 10, 12,
  147926. };
  147927. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147928. _vq_quantthresh__44u2__p7_1,
  147929. _vq_quantmap__44u2__p7_1,
  147930. 13,
  147931. 13
  147932. };
  147933. static static_codebook _44u2__p7_1 = {
  147934. 2, 169,
  147935. _vq_lengthlist__44u2__p7_1,
  147936. 1, -523010048, 1618608128, 4, 0,
  147937. _vq_quantlist__44u2__p7_1,
  147938. NULL,
  147939. &_vq_auxt__44u2__p7_1,
  147940. NULL,
  147941. 0
  147942. };
  147943. static long _vq_quantlist__44u2__p7_2[] = {
  147944. 6,
  147945. 5,
  147946. 7,
  147947. 4,
  147948. 8,
  147949. 3,
  147950. 9,
  147951. 2,
  147952. 10,
  147953. 1,
  147954. 11,
  147955. 0,
  147956. 12,
  147957. };
  147958. static long _vq_lengthlist__44u2__p7_2[] = {
  147959. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147960. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147961. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147962. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147963. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147964. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147965. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147966. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147967. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147968. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147969. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147970. };
  147971. static float _vq_quantthresh__44u2__p7_2[] = {
  147972. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147973. 2.5, 3.5, 4.5, 5.5,
  147974. };
  147975. static long _vq_quantmap__44u2__p7_2[] = {
  147976. 11, 9, 7, 5, 3, 1, 0, 2,
  147977. 4, 6, 8, 10, 12,
  147978. };
  147979. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147980. _vq_quantthresh__44u2__p7_2,
  147981. _vq_quantmap__44u2__p7_2,
  147982. 13,
  147983. 13
  147984. };
  147985. static static_codebook _44u2__p7_2 = {
  147986. 2, 169,
  147987. _vq_lengthlist__44u2__p7_2,
  147988. 1, -531103744, 1611661312, 4, 0,
  147989. _vq_quantlist__44u2__p7_2,
  147990. NULL,
  147991. &_vq_auxt__44u2__p7_2,
  147992. NULL,
  147993. 0
  147994. };
  147995. static long _huff_lengthlist__44u2__short[] = {
  147996. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147997. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147998. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147999. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  148000. };
  148001. static static_codebook _huff_book__44u2__short = {
  148002. 2, 64,
  148003. _huff_lengthlist__44u2__short,
  148004. 0, 0, 0, 0, 0,
  148005. NULL,
  148006. NULL,
  148007. NULL,
  148008. NULL,
  148009. 0
  148010. };
  148011. static long _huff_lengthlist__44u3__long[] = {
  148012. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  148013. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  148014. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  148015. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  148016. };
  148017. static static_codebook _huff_book__44u3__long = {
  148018. 2, 64,
  148019. _huff_lengthlist__44u3__long,
  148020. 0, 0, 0, 0, 0,
  148021. NULL,
  148022. NULL,
  148023. NULL,
  148024. NULL,
  148025. 0
  148026. };
  148027. static long _vq_quantlist__44u3__p1_0[] = {
  148028. 1,
  148029. 0,
  148030. 2,
  148031. };
  148032. static long _vq_lengthlist__44u3__p1_0[] = {
  148033. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148034. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148035. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148036. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148037. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148038. 13,
  148039. };
  148040. static float _vq_quantthresh__44u3__p1_0[] = {
  148041. -0.5, 0.5,
  148042. };
  148043. static long _vq_quantmap__44u3__p1_0[] = {
  148044. 1, 0, 2,
  148045. };
  148046. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148047. _vq_quantthresh__44u3__p1_0,
  148048. _vq_quantmap__44u3__p1_0,
  148049. 3,
  148050. 3
  148051. };
  148052. static static_codebook _44u3__p1_0 = {
  148053. 4, 81,
  148054. _vq_lengthlist__44u3__p1_0,
  148055. 1, -535822336, 1611661312, 2, 0,
  148056. _vq_quantlist__44u3__p1_0,
  148057. NULL,
  148058. &_vq_auxt__44u3__p1_0,
  148059. NULL,
  148060. 0
  148061. };
  148062. static long _vq_quantlist__44u3__p2_0[] = {
  148063. 1,
  148064. 0,
  148065. 2,
  148066. };
  148067. static long _vq_lengthlist__44u3__p2_0[] = {
  148068. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148069. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148070. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148071. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148072. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148073. 9,
  148074. };
  148075. static float _vq_quantthresh__44u3__p2_0[] = {
  148076. -0.5, 0.5,
  148077. };
  148078. static long _vq_quantmap__44u3__p2_0[] = {
  148079. 1, 0, 2,
  148080. };
  148081. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148082. _vq_quantthresh__44u3__p2_0,
  148083. _vq_quantmap__44u3__p2_0,
  148084. 3,
  148085. 3
  148086. };
  148087. static static_codebook _44u3__p2_0 = {
  148088. 4, 81,
  148089. _vq_lengthlist__44u3__p2_0,
  148090. 1, -535822336, 1611661312, 2, 0,
  148091. _vq_quantlist__44u3__p2_0,
  148092. NULL,
  148093. &_vq_auxt__44u3__p2_0,
  148094. NULL,
  148095. 0
  148096. };
  148097. static long _vq_quantlist__44u3__p3_0[] = {
  148098. 2,
  148099. 1,
  148100. 3,
  148101. 0,
  148102. 4,
  148103. };
  148104. static long _vq_lengthlist__44u3__p3_0[] = {
  148105. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148106. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148107. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148108. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148109. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148110. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148111. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148112. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148113. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148114. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148115. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148116. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148117. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148118. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148119. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148120. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148121. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148122. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148123. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148124. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148125. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148126. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148127. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148128. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148129. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148130. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148131. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148132. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148133. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148134. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148135. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148136. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148137. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148138. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148139. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148140. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148141. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148142. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148143. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148144. 0,
  148145. };
  148146. static float _vq_quantthresh__44u3__p3_0[] = {
  148147. -1.5, -0.5, 0.5, 1.5,
  148148. };
  148149. static long _vq_quantmap__44u3__p3_0[] = {
  148150. 3, 1, 0, 2, 4,
  148151. };
  148152. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148153. _vq_quantthresh__44u3__p3_0,
  148154. _vq_quantmap__44u3__p3_0,
  148155. 5,
  148156. 5
  148157. };
  148158. static static_codebook _44u3__p3_0 = {
  148159. 4, 625,
  148160. _vq_lengthlist__44u3__p3_0,
  148161. 1, -533725184, 1611661312, 3, 0,
  148162. _vq_quantlist__44u3__p3_0,
  148163. NULL,
  148164. &_vq_auxt__44u3__p3_0,
  148165. NULL,
  148166. 0
  148167. };
  148168. static long _vq_quantlist__44u3__p4_0[] = {
  148169. 2,
  148170. 1,
  148171. 3,
  148172. 0,
  148173. 4,
  148174. };
  148175. static long _vq_lengthlist__44u3__p4_0[] = {
  148176. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148177. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148178. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148179. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148180. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148181. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148182. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148183. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148184. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148185. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148186. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148187. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148188. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148189. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148190. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148191. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148192. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148193. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148194. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148195. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148196. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148197. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148198. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148199. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148200. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148201. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148202. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148203. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148204. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148205. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148206. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148207. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148208. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148209. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148210. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148211. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148212. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148213. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148214. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148215. 13,
  148216. };
  148217. static float _vq_quantthresh__44u3__p4_0[] = {
  148218. -1.5, -0.5, 0.5, 1.5,
  148219. };
  148220. static long _vq_quantmap__44u3__p4_0[] = {
  148221. 3, 1, 0, 2, 4,
  148222. };
  148223. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148224. _vq_quantthresh__44u3__p4_0,
  148225. _vq_quantmap__44u3__p4_0,
  148226. 5,
  148227. 5
  148228. };
  148229. static static_codebook _44u3__p4_0 = {
  148230. 4, 625,
  148231. _vq_lengthlist__44u3__p4_0,
  148232. 1, -533725184, 1611661312, 3, 0,
  148233. _vq_quantlist__44u3__p4_0,
  148234. NULL,
  148235. &_vq_auxt__44u3__p4_0,
  148236. NULL,
  148237. 0
  148238. };
  148239. static long _vq_quantlist__44u3__p5_0[] = {
  148240. 4,
  148241. 3,
  148242. 5,
  148243. 2,
  148244. 6,
  148245. 1,
  148246. 7,
  148247. 0,
  148248. 8,
  148249. };
  148250. static long _vq_lengthlist__44u3__p5_0[] = {
  148251. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148252. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148253. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148254. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148255. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148256. 12,
  148257. };
  148258. static float _vq_quantthresh__44u3__p5_0[] = {
  148259. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148260. };
  148261. static long _vq_quantmap__44u3__p5_0[] = {
  148262. 7, 5, 3, 1, 0, 2, 4, 6,
  148263. 8,
  148264. };
  148265. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148266. _vq_quantthresh__44u3__p5_0,
  148267. _vq_quantmap__44u3__p5_0,
  148268. 9,
  148269. 9
  148270. };
  148271. static static_codebook _44u3__p5_0 = {
  148272. 2, 81,
  148273. _vq_lengthlist__44u3__p5_0,
  148274. 1, -531628032, 1611661312, 4, 0,
  148275. _vq_quantlist__44u3__p5_0,
  148276. NULL,
  148277. &_vq_auxt__44u3__p5_0,
  148278. NULL,
  148279. 0
  148280. };
  148281. static long _vq_quantlist__44u3__p6_0[] = {
  148282. 6,
  148283. 5,
  148284. 7,
  148285. 4,
  148286. 8,
  148287. 3,
  148288. 9,
  148289. 2,
  148290. 10,
  148291. 1,
  148292. 11,
  148293. 0,
  148294. 12,
  148295. };
  148296. static long _vq_lengthlist__44u3__p6_0[] = {
  148297. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148298. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148299. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148300. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148301. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148302. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148303. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148304. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148305. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148306. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148307. 15,16,16,16,17,18,16,20,18,
  148308. };
  148309. static float _vq_quantthresh__44u3__p6_0[] = {
  148310. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148311. 12.5, 17.5, 22.5, 27.5,
  148312. };
  148313. static long _vq_quantmap__44u3__p6_0[] = {
  148314. 11, 9, 7, 5, 3, 1, 0, 2,
  148315. 4, 6, 8, 10, 12,
  148316. };
  148317. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148318. _vq_quantthresh__44u3__p6_0,
  148319. _vq_quantmap__44u3__p6_0,
  148320. 13,
  148321. 13
  148322. };
  148323. static static_codebook _44u3__p6_0 = {
  148324. 2, 169,
  148325. _vq_lengthlist__44u3__p6_0,
  148326. 1, -526516224, 1616117760, 4, 0,
  148327. _vq_quantlist__44u3__p6_0,
  148328. NULL,
  148329. &_vq_auxt__44u3__p6_0,
  148330. NULL,
  148331. 0
  148332. };
  148333. static long _vq_quantlist__44u3__p6_1[] = {
  148334. 2,
  148335. 1,
  148336. 3,
  148337. 0,
  148338. 4,
  148339. };
  148340. static long _vq_lengthlist__44u3__p6_1[] = {
  148341. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148342. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148343. };
  148344. static float _vq_quantthresh__44u3__p6_1[] = {
  148345. -1.5, -0.5, 0.5, 1.5,
  148346. };
  148347. static long _vq_quantmap__44u3__p6_1[] = {
  148348. 3, 1, 0, 2, 4,
  148349. };
  148350. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148351. _vq_quantthresh__44u3__p6_1,
  148352. _vq_quantmap__44u3__p6_1,
  148353. 5,
  148354. 5
  148355. };
  148356. static static_codebook _44u3__p6_1 = {
  148357. 2, 25,
  148358. _vq_lengthlist__44u3__p6_1,
  148359. 1, -533725184, 1611661312, 3, 0,
  148360. _vq_quantlist__44u3__p6_1,
  148361. NULL,
  148362. &_vq_auxt__44u3__p6_1,
  148363. NULL,
  148364. 0
  148365. };
  148366. static long _vq_quantlist__44u3__p7_0[] = {
  148367. 4,
  148368. 3,
  148369. 5,
  148370. 2,
  148371. 6,
  148372. 1,
  148373. 7,
  148374. 0,
  148375. 8,
  148376. };
  148377. static long _vq_lengthlist__44u3__p7_0[] = {
  148378. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148379. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148380. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148381. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148382. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148383. 9,
  148384. };
  148385. static float _vq_quantthresh__44u3__p7_0[] = {
  148386. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148387. };
  148388. static long _vq_quantmap__44u3__p7_0[] = {
  148389. 7, 5, 3, 1, 0, 2, 4, 6,
  148390. 8,
  148391. };
  148392. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148393. _vq_quantthresh__44u3__p7_0,
  148394. _vq_quantmap__44u3__p7_0,
  148395. 9,
  148396. 9
  148397. };
  148398. static static_codebook _44u3__p7_0 = {
  148399. 2, 81,
  148400. _vq_lengthlist__44u3__p7_0,
  148401. 1, -515907584, 1627381760, 4, 0,
  148402. _vq_quantlist__44u3__p7_0,
  148403. NULL,
  148404. &_vq_auxt__44u3__p7_0,
  148405. NULL,
  148406. 0
  148407. };
  148408. static long _vq_quantlist__44u3__p7_1[] = {
  148409. 7,
  148410. 6,
  148411. 8,
  148412. 5,
  148413. 9,
  148414. 4,
  148415. 10,
  148416. 3,
  148417. 11,
  148418. 2,
  148419. 12,
  148420. 1,
  148421. 13,
  148422. 0,
  148423. 14,
  148424. };
  148425. static long _vq_lengthlist__44u3__p7_1[] = {
  148426. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148427. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148428. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148429. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148430. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148431. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148432. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148433. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148434. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148435. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148436. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148437. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148438. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148439. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148440. 17,
  148441. };
  148442. static float _vq_quantthresh__44u3__p7_1[] = {
  148443. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148444. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148445. };
  148446. static long _vq_quantmap__44u3__p7_1[] = {
  148447. 13, 11, 9, 7, 5, 3, 1, 0,
  148448. 2, 4, 6, 8, 10, 12, 14,
  148449. };
  148450. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148451. _vq_quantthresh__44u3__p7_1,
  148452. _vq_quantmap__44u3__p7_1,
  148453. 15,
  148454. 15
  148455. };
  148456. static static_codebook _44u3__p7_1 = {
  148457. 2, 225,
  148458. _vq_lengthlist__44u3__p7_1,
  148459. 1, -522338304, 1620115456, 4, 0,
  148460. _vq_quantlist__44u3__p7_1,
  148461. NULL,
  148462. &_vq_auxt__44u3__p7_1,
  148463. NULL,
  148464. 0
  148465. };
  148466. static long _vq_quantlist__44u3__p7_2[] = {
  148467. 8,
  148468. 7,
  148469. 9,
  148470. 6,
  148471. 10,
  148472. 5,
  148473. 11,
  148474. 4,
  148475. 12,
  148476. 3,
  148477. 13,
  148478. 2,
  148479. 14,
  148480. 1,
  148481. 15,
  148482. 0,
  148483. 16,
  148484. };
  148485. static long _vq_lengthlist__44u3__p7_2[] = {
  148486. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148487. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148488. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148489. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148490. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148491. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148492. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148493. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148494. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148495. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148496. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148497. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148498. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148499. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148500. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148501. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148502. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148503. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148504. 11,
  148505. };
  148506. static float _vq_quantthresh__44u3__p7_2[] = {
  148507. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148508. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148509. };
  148510. static long _vq_quantmap__44u3__p7_2[] = {
  148511. 15, 13, 11, 9, 7, 5, 3, 1,
  148512. 0, 2, 4, 6, 8, 10, 12, 14,
  148513. 16,
  148514. };
  148515. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148516. _vq_quantthresh__44u3__p7_2,
  148517. _vq_quantmap__44u3__p7_2,
  148518. 17,
  148519. 17
  148520. };
  148521. static static_codebook _44u3__p7_2 = {
  148522. 2, 289,
  148523. _vq_lengthlist__44u3__p7_2,
  148524. 1, -529530880, 1611661312, 5, 0,
  148525. _vq_quantlist__44u3__p7_2,
  148526. NULL,
  148527. &_vq_auxt__44u3__p7_2,
  148528. NULL,
  148529. 0
  148530. };
  148531. static long _huff_lengthlist__44u3__short[] = {
  148532. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148533. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148534. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148535. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148536. };
  148537. static static_codebook _huff_book__44u3__short = {
  148538. 2, 64,
  148539. _huff_lengthlist__44u3__short,
  148540. 0, 0, 0, 0, 0,
  148541. NULL,
  148542. NULL,
  148543. NULL,
  148544. NULL,
  148545. 0
  148546. };
  148547. static long _huff_lengthlist__44u4__long[] = {
  148548. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148549. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148550. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148551. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148552. };
  148553. static static_codebook _huff_book__44u4__long = {
  148554. 2, 64,
  148555. _huff_lengthlist__44u4__long,
  148556. 0, 0, 0, 0, 0,
  148557. NULL,
  148558. NULL,
  148559. NULL,
  148560. NULL,
  148561. 0
  148562. };
  148563. static long _vq_quantlist__44u4__p1_0[] = {
  148564. 1,
  148565. 0,
  148566. 2,
  148567. };
  148568. static long _vq_lengthlist__44u4__p1_0[] = {
  148569. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148570. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148571. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148572. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148573. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148574. 13,
  148575. };
  148576. static float _vq_quantthresh__44u4__p1_0[] = {
  148577. -0.5, 0.5,
  148578. };
  148579. static long _vq_quantmap__44u4__p1_0[] = {
  148580. 1, 0, 2,
  148581. };
  148582. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148583. _vq_quantthresh__44u4__p1_0,
  148584. _vq_quantmap__44u4__p1_0,
  148585. 3,
  148586. 3
  148587. };
  148588. static static_codebook _44u4__p1_0 = {
  148589. 4, 81,
  148590. _vq_lengthlist__44u4__p1_0,
  148591. 1, -535822336, 1611661312, 2, 0,
  148592. _vq_quantlist__44u4__p1_0,
  148593. NULL,
  148594. &_vq_auxt__44u4__p1_0,
  148595. NULL,
  148596. 0
  148597. };
  148598. static long _vq_quantlist__44u4__p2_0[] = {
  148599. 1,
  148600. 0,
  148601. 2,
  148602. };
  148603. static long _vq_lengthlist__44u4__p2_0[] = {
  148604. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148605. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148606. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148607. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148608. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148609. 9,
  148610. };
  148611. static float _vq_quantthresh__44u4__p2_0[] = {
  148612. -0.5, 0.5,
  148613. };
  148614. static long _vq_quantmap__44u4__p2_0[] = {
  148615. 1, 0, 2,
  148616. };
  148617. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148618. _vq_quantthresh__44u4__p2_0,
  148619. _vq_quantmap__44u4__p2_0,
  148620. 3,
  148621. 3
  148622. };
  148623. static static_codebook _44u4__p2_0 = {
  148624. 4, 81,
  148625. _vq_lengthlist__44u4__p2_0,
  148626. 1, -535822336, 1611661312, 2, 0,
  148627. _vq_quantlist__44u4__p2_0,
  148628. NULL,
  148629. &_vq_auxt__44u4__p2_0,
  148630. NULL,
  148631. 0
  148632. };
  148633. static long _vq_quantlist__44u4__p3_0[] = {
  148634. 2,
  148635. 1,
  148636. 3,
  148637. 0,
  148638. 4,
  148639. };
  148640. static long _vq_lengthlist__44u4__p3_0[] = {
  148641. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148642. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148643. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148644. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148645. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148646. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148647. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148648. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148649. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148650. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148651. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148652. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148653. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148654. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148655. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148656. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148657. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148658. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148659. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148660. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148661. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148662. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148663. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148664. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148665. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148666. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148667. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148668. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148669. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148670. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148671. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148672. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148673. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148674. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148675. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148676. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148677. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148678. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148679. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148680. 0,
  148681. };
  148682. static float _vq_quantthresh__44u4__p3_0[] = {
  148683. -1.5, -0.5, 0.5, 1.5,
  148684. };
  148685. static long _vq_quantmap__44u4__p3_0[] = {
  148686. 3, 1, 0, 2, 4,
  148687. };
  148688. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148689. _vq_quantthresh__44u4__p3_0,
  148690. _vq_quantmap__44u4__p3_0,
  148691. 5,
  148692. 5
  148693. };
  148694. static static_codebook _44u4__p3_0 = {
  148695. 4, 625,
  148696. _vq_lengthlist__44u4__p3_0,
  148697. 1, -533725184, 1611661312, 3, 0,
  148698. _vq_quantlist__44u4__p3_0,
  148699. NULL,
  148700. &_vq_auxt__44u4__p3_0,
  148701. NULL,
  148702. 0
  148703. };
  148704. static long _vq_quantlist__44u4__p4_0[] = {
  148705. 2,
  148706. 1,
  148707. 3,
  148708. 0,
  148709. 4,
  148710. };
  148711. static long _vq_lengthlist__44u4__p4_0[] = {
  148712. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148713. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148714. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148715. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148716. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148717. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148718. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148719. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148720. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148721. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148722. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148723. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148724. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148725. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148726. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148727. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148728. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148729. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148730. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148731. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148732. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148733. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148734. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148735. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148736. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148737. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148738. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148739. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148740. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148741. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148742. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148743. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148744. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148745. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148746. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148747. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148748. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148749. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148750. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148751. 13,
  148752. };
  148753. static float _vq_quantthresh__44u4__p4_0[] = {
  148754. -1.5, -0.5, 0.5, 1.5,
  148755. };
  148756. static long _vq_quantmap__44u4__p4_0[] = {
  148757. 3, 1, 0, 2, 4,
  148758. };
  148759. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148760. _vq_quantthresh__44u4__p4_0,
  148761. _vq_quantmap__44u4__p4_0,
  148762. 5,
  148763. 5
  148764. };
  148765. static static_codebook _44u4__p4_0 = {
  148766. 4, 625,
  148767. _vq_lengthlist__44u4__p4_0,
  148768. 1, -533725184, 1611661312, 3, 0,
  148769. _vq_quantlist__44u4__p4_0,
  148770. NULL,
  148771. &_vq_auxt__44u4__p4_0,
  148772. NULL,
  148773. 0
  148774. };
  148775. static long _vq_quantlist__44u4__p5_0[] = {
  148776. 4,
  148777. 3,
  148778. 5,
  148779. 2,
  148780. 6,
  148781. 1,
  148782. 7,
  148783. 0,
  148784. 8,
  148785. };
  148786. static long _vq_lengthlist__44u4__p5_0[] = {
  148787. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148788. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148789. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148790. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148791. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148792. 12,
  148793. };
  148794. static float _vq_quantthresh__44u4__p5_0[] = {
  148795. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148796. };
  148797. static long _vq_quantmap__44u4__p5_0[] = {
  148798. 7, 5, 3, 1, 0, 2, 4, 6,
  148799. 8,
  148800. };
  148801. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148802. _vq_quantthresh__44u4__p5_0,
  148803. _vq_quantmap__44u4__p5_0,
  148804. 9,
  148805. 9
  148806. };
  148807. static static_codebook _44u4__p5_0 = {
  148808. 2, 81,
  148809. _vq_lengthlist__44u4__p5_0,
  148810. 1, -531628032, 1611661312, 4, 0,
  148811. _vq_quantlist__44u4__p5_0,
  148812. NULL,
  148813. &_vq_auxt__44u4__p5_0,
  148814. NULL,
  148815. 0
  148816. };
  148817. static long _vq_quantlist__44u4__p6_0[] = {
  148818. 6,
  148819. 5,
  148820. 7,
  148821. 4,
  148822. 8,
  148823. 3,
  148824. 9,
  148825. 2,
  148826. 10,
  148827. 1,
  148828. 11,
  148829. 0,
  148830. 12,
  148831. };
  148832. static long _vq_lengthlist__44u4__p6_0[] = {
  148833. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148834. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148835. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148836. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148837. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148838. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148839. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148840. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148841. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148842. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148843. 16,16,16,17,17,18,17,20,21,
  148844. };
  148845. static float _vq_quantthresh__44u4__p6_0[] = {
  148846. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148847. 12.5, 17.5, 22.5, 27.5,
  148848. };
  148849. static long _vq_quantmap__44u4__p6_0[] = {
  148850. 11, 9, 7, 5, 3, 1, 0, 2,
  148851. 4, 6, 8, 10, 12,
  148852. };
  148853. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148854. _vq_quantthresh__44u4__p6_0,
  148855. _vq_quantmap__44u4__p6_0,
  148856. 13,
  148857. 13
  148858. };
  148859. static static_codebook _44u4__p6_0 = {
  148860. 2, 169,
  148861. _vq_lengthlist__44u4__p6_0,
  148862. 1, -526516224, 1616117760, 4, 0,
  148863. _vq_quantlist__44u4__p6_0,
  148864. NULL,
  148865. &_vq_auxt__44u4__p6_0,
  148866. NULL,
  148867. 0
  148868. };
  148869. static long _vq_quantlist__44u4__p6_1[] = {
  148870. 2,
  148871. 1,
  148872. 3,
  148873. 0,
  148874. 4,
  148875. };
  148876. static long _vq_lengthlist__44u4__p6_1[] = {
  148877. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148878. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148879. };
  148880. static float _vq_quantthresh__44u4__p6_1[] = {
  148881. -1.5, -0.5, 0.5, 1.5,
  148882. };
  148883. static long _vq_quantmap__44u4__p6_1[] = {
  148884. 3, 1, 0, 2, 4,
  148885. };
  148886. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148887. _vq_quantthresh__44u4__p6_1,
  148888. _vq_quantmap__44u4__p6_1,
  148889. 5,
  148890. 5
  148891. };
  148892. static static_codebook _44u4__p6_1 = {
  148893. 2, 25,
  148894. _vq_lengthlist__44u4__p6_1,
  148895. 1, -533725184, 1611661312, 3, 0,
  148896. _vq_quantlist__44u4__p6_1,
  148897. NULL,
  148898. &_vq_auxt__44u4__p6_1,
  148899. NULL,
  148900. 0
  148901. };
  148902. static long _vq_quantlist__44u4__p7_0[] = {
  148903. 6,
  148904. 5,
  148905. 7,
  148906. 4,
  148907. 8,
  148908. 3,
  148909. 9,
  148910. 2,
  148911. 10,
  148912. 1,
  148913. 11,
  148914. 0,
  148915. 12,
  148916. };
  148917. static long _vq_lengthlist__44u4__p7_0[] = {
  148918. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148919. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148920. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148921. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148922. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148923. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148928. 11,11,11,11,11,11,11,11,11,
  148929. };
  148930. static float _vq_quantthresh__44u4__p7_0[] = {
  148931. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148932. 637.5, 892.5, 1147.5, 1402.5,
  148933. };
  148934. static long _vq_quantmap__44u4__p7_0[] = {
  148935. 11, 9, 7, 5, 3, 1, 0, 2,
  148936. 4, 6, 8, 10, 12,
  148937. };
  148938. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148939. _vq_quantthresh__44u4__p7_0,
  148940. _vq_quantmap__44u4__p7_0,
  148941. 13,
  148942. 13
  148943. };
  148944. static static_codebook _44u4__p7_0 = {
  148945. 2, 169,
  148946. _vq_lengthlist__44u4__p7_0,
  148947. 1, -514332672, 1627381760, 4, 0,
  148948. _vq_quantlist__44u4__p7_0,
  148949. NULL,
  148950. &_vq_auxt__44u4__p7_0,
  148951. NULL,
  148952. 0
  148953. };
  148954. static long _vq_quantlist__44u4__p7_1[] = {
  148955. 7,
  148956. 6,
  148957. 8,
  148958. 5,
  148959. 9,
  148960. 4,
  148961. 10,
  148962. 3,
  148963. 11,
  148964. 2,
  148965. 12,
  148966. 1,
  148967. 13,
  148968. 0,
  148969. 14,
  148970. };
  148971. static long _vq_lengthlist__44u4__p7_1[] = {
  148972. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148973. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148974. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148975. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148976. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148977. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148978. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148979. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148980. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148981. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148982. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148983. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148984. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148985. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148986. 16,
  148987. };
  148988. static float _vq_quantthresh__44u4__p7_1[] = {
  148989. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148990. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148991. };
  148992. static long _vq_quantmap__44u4__p7_1[] = {
  148993. 13, 11, 9, 7, 5, 3, 1, 0,
  148994. 2, 4, 6, 8, 10, 12, 14,
  148995. };
  148996. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148997. _vq_quantthresh__44u4__p7_1,
  148998. _vq_quantmap__44u4__p7_1,
  148999. 15,
  149000. 15
  149001. };
  149002. static static_codebook _44u4__p7_1 = {
  149003. 2, 225,
  149004. _vq_lengthlist__44u4__p7_1,
  149005. 1, -522338304, 1620115456, 4, 0,
  149006. _vq_quantlist__44u4__p7_1,
  149007. NULL,
  149008. &_vq_auxt__44u4__p7_1,
  149009. NULL,
  149010. 0
  149011. };
  149012. static long _vq_quantlist__44u4__p7_2[] = {
  149013. 8,
  149014. 7,
  149015. 9,
  149016. 6,
  149017. 10,
  149018. 5,
  149019. 11,
  149020. 4,
  149021. 12,
  149022. 3,
  149023. 13,
  149024. 2,
  149025. 14,
  149026. 1,
  149027. 15,
  149028. 0,
  149029. 16,
  149030. };
  149031. static long _vq_lengthlist__44u4__p7_2[] = {
  149032. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149033. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149034. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149035. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149036. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149037. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149038. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149039. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149040. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149041. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149042. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149043. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149044. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149045. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149046. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149047. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149048. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149049. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149050. 10,
  149051. };
  149052. static float _vq_quantthresh__44u4__p7_2[] = {
  149053. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149054. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149055. };
  149056. static long _vq_quantmap__44u4__p7_2[] = {
  149057. 15, 13, 11, 9, 7, 5, 3, 1,
  149058. 0, 2, 4, 6, 8, 10, 12, 14,
  149059. 16,
  149060. };
  149061. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149062. _vq_quantthresh__44u4__p7_2,
  149063. _vq_quantmap__44u4__p7_2,
  149064. 17,
  149065. 17
  149066. };
  149067. static static_codebook _44u4__p7_2 = {
  149068. 2, 289,
  149069. _vq_lengthlist__44u4__p7_2,
  149070. 1, -529530880, 1611661312, 5, 0,
  149071. _vq_quantlist__44u4__p7_2,
  149072. NULL,
  149073. &_vq_auxt__44u4__p7_2,
  149074. NULL,
  149075. 0
  149076. };
  149077. static long _huff_lengthlist__44u4__short[] = {
  149078. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149079. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149080. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149081. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149082. };
  149083. static static_codebook _huff_book__44u4__short = {
  149084. 2, 64,
  149085. _huff_lengthlist__44u4__short,
  149086. 0, 0, 0, 0, 0,
  149087. NULL,
  149088. NULL,
  149089. NULL,
  149090. NULL,
  149091. 0
  149092. };
  149093. static long _huff_lengthlist__44u5__long[] = {
  149094. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149095. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149096. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149097. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149098. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149099. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149100. 14, 8, 7, 8,
  149101. };
  149102. static static_codebook _huff_book__44u5__long = {
  149103. 2, 100,
  149104. _huff_lengthlist__44u5__long,
  149105. 0, 0, 0, 0, 0,
  149106. NULL,
  149107. NULL,
  149108. NULL,
  149109. NULL,
  149110. 0
  149111. };
  149112. static long _vq_quantlist__44u5__p1_0[] = {
  149113. 1,
  149114. 0,
  149115. 2,
  149116. };
  149117. static long _vq_lengthlist__44u5__p1_0[] = {
  149118. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149119. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149120. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149121. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149122. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149123. 12,
  149124. };
  149125. static float _vq_quantthresh__44u5__p1_0[] = {
  149126. -0.5, 0.5,
  149127. };
  149128. static long _vq_quantmap__44u5__p1_0[] = {
  149129. 1, 0, 2,
  149130. };
  149131. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149132. _vq_quantthresh__44u5__p1_0,
  149133. _vq_quantmap__44u5__p1_0,
  149134. 3,
  149135. 3
  149136. };
  149137. static static_codebook _44u5__p1_0 = {
  149138. 4, 81,
  149139. _vq_lengthlist__44u5__p1_0,
  149140. 1, -535822336, 1611661312, 2, 0,
  149141. _vq_quantlist__44u5__p1_0,
  149142. NULL,
  149143. &_vq_auxt__44u5__p1_0,
  149144. NULL,
  149145. 0
  149146. };
  149147. static long _vq_quantlist__44u5__p2_0[] = {
  149148. 1,
  149149. 0,
  149150. 2,
  149151. };
  149152. static long _vq_lengthlist__44u5__p2_0[] = {
  149153. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149154. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149155. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149156. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149157. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149158. 9,
  149159. };
  149160. static float _vq_quantthresh__44u5__p2_0[] = {
  149161. -0.5, 0.5,
  149162. };
  149163. static long _vq_quantmap__44u5__p2_0[] = {
  149164. 1, 0, 2,
  149165. };
  149166. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149167. _vq_quantthresh__44u5__p2_0,
  149168. _vq_quantmap__44u5__p2_0,
  149169. 3,
  149170. 3
  149171. };
  149172. static static_codebook _44u5__p2_0 = {
  149173. 4, 81,
  149174. _vq_lengthlist__44u5__p2_0,
  149175. 1, -535822336, 1611661312, 2, 0,
  149176. _vq_quantlist__44u5__p2_0,
  149177. NULL,
  149178. &_vq_auxt__44u5__p2_0,
  149179. NULL,
  149180. 0
  149181. };
  149182. static long _vq_quantlist__44u5__p3_0[] = {
  149183. 2,
  149184. 1,
  149185. 3,
  149186. 0,
  149187. 4,
  149188. };
  149189. static long _vq_lengthlist__44u5__p3_0[] = {
  149190. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149191. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149192. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149193. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149194. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149195. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149196. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149197. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149198. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149199. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149200. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149201. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149202. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149203. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149204. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149205. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149206. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149207. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149208. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149209. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149210. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149211. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149212. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149213. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149214. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149215. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149216. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149217. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149218. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149219. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149220. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149221. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149222. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149223. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149224. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149225. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149226. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149227. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149228. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149229. 0,
  149230. };
  149231. static float _vq_quantthresh__44u5__p3_0[] = {
  149232. -1.5, -0.5, 0.5, 1.5,
  149233. };
  149234. static long _vq_quantmap__44u5__p3_0[] = {
  149235. 3, 1, 0, 2, 4,
  149236. };
  149237. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149238. _vq_quantthresh__44u5__p3_0,
  149239. _vq_quantmap__44u5__p3_0,
  149240. 5,
  149241. 5
  149242. };
  149243. static static_codebook _44u5__p3_0 = {
  149244. 4, 625,
  149245. _vq_lengthlist__44u5__p3_0,
  149246. 1, -533725184, 1611661312, 3, 0,
  149247. _vq_quantlist__44u5__p3_0,
  149248. NULL,
  149249. &_vq_auxt__44u5__p3_0,
  149250. NULL,
  149251. 0
  149252. };
  149253. static long _vq_quantlist__44u5__p4_0[] = {
  149254. 2,
  149255. 1,
  149256. 3,
  149257. 0,
  149258. 4,
  149259. };
  149260. static long _vq_lengthlist__44u5__p4_0[] = {
  149261. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149262. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149263. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149264. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149265. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149266. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149267. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149268. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149269. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149270. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149271. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149272. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149273. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149274. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149275. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149276. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149277. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149278. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149279. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149280. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149281. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149282. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149283. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149284. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149285. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149286. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149287. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149288. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149289. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149290. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149291. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149292. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149293. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149294. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149295. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149296. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149297. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149298. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149299. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149300. 12,
  149301. };
  149302. static float _vq_quantthresh__44u5__p4_0[] = {
  149303. -1.5, -0.5, 0.5, 1.5,
  149304. };
  149305. static long _vq_quantmap__44u5__p4_0[] = {
  149306. 3, 1, 0, 2, 4,
  149307. };
  149308. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149309. _vq_quantthresh__44u5__p4_0,
  149310. _vq_quantmap__44u5__p4_0,
  149311. 5,
  149312. 5
  149313. };
  149314. static static_codebook _44u5__p4_0 = {
  149315. 4, 625,
  149316. _vq_lengthlist__44u5__p4_0,
  149317. 1, -533725184, 1611661312, 3, 0,
  149318. _vq_quantlist__44u5__p4_0,
  149319. NULL,
  149320. &_vq_auxt__44u5__p4_0,
  149321. NULL,
  149322. 0
  149323. };
  149324. static long _vq_quantlist__44u5__p5_0[] = {
  149325. 4,
  149326. 3,
  149327. 5,
  149328. 2,
  149329. 6,
  149330. 1,
  149331. 7,
  149332. 0,
  149333. 8,
  149334. };
  149335. static long _vq_lengthlist__44u5__p5_0[] = {
  149336. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149337. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149338. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149339. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149340. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149341. 14,
  149342. };
  149343. static float _vq_quantthresh__44u5__p5_0[] = {
  149344. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149345. };
  149346. static long _vq_quantmap__44u5__p5_0[] = {
  149347. 7, 5, 3, 1, 0, 2, 4, 6,
  149348. 8,
  149349. };
  149350. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149351. _vq_quantthresh__44u5__p5_0,
  149352. _vq_quantmap__44u5__p5_0,
  149353. 9,
  149354. 9
  149355. };
  149356. static static_codebook _44u5__p5_0 = {
  149357. 2, 81,
  149358. _vq_lengthlist__44u5__p5_0,
  149359. 1, -531628032, 1611661312, 4, 0,
  149360. _vq_quantlist__44u5__p5_0,
  149361. NULL,
  149362. &_vq_auxt__44u5__p5_0,
  149363. NULL,
  149364. 0
  149365. };
  149366. static long _vq_quantlist__44u5__p6_0[] = {
  149367. 4,
  149368. 3,
  149369. 5,
  149370. 2,
  149371. 6,
  149372. 1,
  149373. 7,
  149374. 0,
  149375. 8,
  149376. };
  149377. static long _vq_lengthlist__44u5__p6_0[] = {
  149378. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149379. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149380. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149381. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149382. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149383. 11,
  149384. };
  149385. static float _vq_quantthresh__44u5__p6_0[] = {
  149386. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149387. };
  149388. static long _vq_quantmap__44u5__p6_0[] = {
  149389. 7, 5, 3, 1, 0, 2, 4, 6,
  149390. 8,
  149391. };
  149392. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149393. _vq_quantthresh__44u5__p6_0,
  149394. _vq_quantmap__44u5__p6_0,
  149395. 9,
  149396. 9
  149397. };
  149398. static static_codebook _44u5__p6_0 = {
  149399. 2, 81,
  149400. _vq_lengthlist__44u5__p6_0,
  149401. 1, -531628032, 1611661312, 4, 0,
  149402. _vq_quantlist__44u5__p6_0,
  149403. NULL,
  149404. &_vq_auxt__44u5__p6_0,
  149405. NULL,
  149406. 0
  149407. };
  149408. static long _vq_quantlist__44u5__p7_0[] = {
  149409. 1,
  149410. 0,
  149411. 2,
  149412. };
  149413. static long _vq_lengthlist__44u5__p7_0[] = {
  149414. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149415. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149416. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149417. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149418. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149419. 12,
  149420. };
  149421. static float _vq_quantthresh__44u5__p7_0[] = {
  149422. -5.5, 5.5,
  149423. };
  149424. static long _vq_quantmap__44u5__p7_0[] = {
  149425. 1, 0, 2,
  149426. };
  149427. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149428. _vq_quantthresh__44u5__p7_0,
  149429. _vq_quantmap__44u5__p7_0,
  149430. 3,
  149431. 3
  149432. };
  149433. static static_codebook _44u5__p7_0 = {
  149434. 4, 81,
  149435. _vq_lengthlist__44u5__p7_0,
  149436. 1, -529137664, 1618345984, 2, 0,
  149437. _vq_quantlist__44u5__p7_0,
  149438. NULL,
  149439. &_vq_auxt__44u5__p7_0,
  149440. NULL,
  149441. 0
  149442. };
  149443. static long _vq_quantlist__44u5__p7_1[] = {
  149444. 5,
  149445. 4,
  149446. 6,
  149447. 3,
  149448. 7,
  149449. 2,
  149450. 8,
  149451. 1,
  149452. 9,
  149453. 0,
  149454. 10,
  149455. };
  149456. static long _vq_lengthlist__44u5__p7_1[] = {
  149457. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149458. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149459. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149460. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149461. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149462. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149463. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149464. 9, 9, 9, 9, 9,10,10,10,10,
  149465. };
  149466. static float _vq_quantthresh__44u5__p7_1[] = {
  149467. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149468. 3.5, 4.5,
  149469. };
  149470. static long _vq_quantmap__44u5__p7_1[] = {
  149471. 9, 7, 5, 3, 1, 0, 2, 4,
  149472. 6, 8, 10,
  149473. };
  149474. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149475. _vq_quantthresh__44u5__p7_1,
  149476. _vq_quantmap__44u5__p7_1,
  149477. 11,
  149478. 11
  149479. };
  149480. static static_codebook _44u5__p7_1 = {
  149481. 2, 121,
  149482. _vq_lengthlist__44u5__p7_1,
  149483. 1, -531365888, 1611661312, 4, 0,
  149484. _vq_quantlist__44u5__p7_1,
  149485. NULL,
  149486. &_vq_auxt__44u5__p7_1,
  149487. NULL,
  149488. 0
  149489. };
  149490. static long _vq_quantlist__44u5__p8_0[] = {
  149491. 5,
  149492. 4,
  149493. 6,
  149494. 3,
  149495. 7,
  149496. 2,
  149497. 8,
  149498. 1,
  149499. 9,
  149500. 0,
  149501. 10,
  149502. };
  149503. static long _vq_lengthlist__44u5__p8_0[] = {
  149504. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149505. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149506. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149507. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149508. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149509. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149510. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149511. 12,13,13,14,14,14,14,15,15,
  149512. };
  149513. static float _vq_quantthresh__44u5__p8_0[] = {
  149514. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149515. 38.5, 49.5,
  149516. };
  149517. static long _vq_quantmap__44u5__p8_0[] = {
  149518. 9, 7, 5, 3, 1, 0, 2, 4,
  149519. 6, 8, 10,
  149520. };
  149521. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149522. _vq_quantthresh__44u5__p8_0,
  149523. _vq_quantmap__44u5__p8_0,
  149524. 11,
  149525. 11
  149526. };
  149527. static static_codebook _44u5__p8_0 = {
  149528. 2, 121,
  149529. _vq_lengthlist__44u5__p8_0,
  149530. 1, -524582912, 1618345984, 4, 0,
  149531. _vq_quantlist__44u5__p8_0,
  149532. NULL,
  149533. &_vq_auxt__44u5__p8_0,
  149534. NULL,
  149535. 0
  149536. };
  149537. static long _vq_quantlist__44u5__p8_1[] = {
  149538. 5,
  149539. 4,
  149540. 6,
  149541. 3,
  149542. 7,
  149543. 2,
  149544. 8,
  149545. 1,
  149546. 9,
  149547. 0,
  149548. 10,
  149549. };
  149550. static long _vq_lengthlist__44u5__p8_1[] = {
  149551. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149552. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149553. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149554. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149555. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149556. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149557. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149558. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149559. };
  149560. static float _vq_quantthresh__44u5__p8_1[] = {
  149561. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149562. 3.5, 4.5,
  149563. };
  149564. static long _vq_quantmap__44u5__p8_1[] = {
  149565. 9, 7, 5, 3, 1, 0, 2, 4,
  149566. 6, 8, 10,
  149567. };
  149568. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149569. _vq_quantthresh__44u5__p8_1,
  149570. _vq_quantmap__44u5__p8_1,
  149571. 11,
  149572. 11
  149573. };
  149574. static static_codebook _44u5__p8_1 = {
  149575. 2, 121,
  149576. _vq_lengthlist__44u5__p8_1,
  149577. 1, -531365888, 1611661312, 4, 0,
  149578. _vq_quantlist__44u5__p8_1,
  149579. NULL,
  149580. &_vq_auxt__44u5__p8_1,
  149581. NULL,
  149582. 0
  149583. };
  149584. static long _vq_quantlist__44u5__p9_0[] = {
  149585. 6,
  149586. 5,
  149587. 7,
  149588. 4,
  149589. 8,
  149590. 3,
  149591. 9,
  149592. 2,
  149593. 10,
  149594. 1,
  149595. 11,
  149596. 0,
  149597. 12,
  149598. };
  149599. static long _vq_lengthlist__44u5__p9_0[] = {
  149600. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149601. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149602. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149603. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149604. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149605. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149606. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149607. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149608. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149609. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149610. 12,12,12,12,12,12,12,12,12,
  149611. };
  149612. static float _vq_quantthresh__44u5__p9_0[] = {
  149613. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149614. 637.5, 892.5, 1147.5, 1402.5,
  149615. };
  149616. static long _vq_quantmap__44u5__p9_0[] = {
  149617. 11, 9, 7, 5, 3, 1, 0, 2,
  149618. 4, 6, 8, 10, 12,
  149619. };
  149620. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149621. _vq_quantthresh__44u5__p9_0,
  149622. _vq_quantmap__44u5__p9_0,
  149623. 13,
  149624. 13
  149625. };
  149626. static static_codebook _44u5__p9_0 = {
  149627. 2, 169,
  149628. _vq_lengthlist__44u5__p9_0,
  149629. 1, -514332672, 1627381760, 4, 0,
  149630. _vq_quantlist__44u5__p9_0,
  149631. NULL,
  149632. &_vq_auxt__44u5__p9_0,
  149633. NULL,
  149634. 0
  149635. };
  149636. static long _vq_quantlist__44u5__p9_1[] = {
  149637. 7,
  149638. 6,
  149639. 8,
  149640. 5,
  149641. 9,
  149642. 4,
  149643. 10,
  149644. 3,
  149645. 11,
  149646. 2,
  149647. 12,
  149648. 1,
  149649. 13,
  149650. 0,
  149651. 14,
  149652. };
  149653. static long _vq_lengthlist__44u5__p9_1[] = {
  149654. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149655. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149656. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149657. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149658. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149659. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149660. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149661. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149662. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149663. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149664. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149665. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149666. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149667. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149668. 14,
  149669. };
  149670. static float _vq_quantthresh__44u5__p9_1[] = {
  149671. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149672. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149673. };
  149674. static long _vq_quantmap__44u5__p9_1[] = {
  149675. 13, 11, 9, 7, 5, 3, 1, 0,
  149676. 2, 4, 6, 8, 10, 12, 14,
  149677. };
  149678. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149679. _vq_quantthresh__44u5__p9_1,
  149680. _vq_quantmap__44u5__p9_1,
  149681. 15,
  149682. 15
  149683. };
  149684. static static_codebook _44u5__p9_1 = {
  149685. 2, 225,
  149686. _vq_lengthlist__44u5__p9_1,
  149687. 1, -522338304, 1620115456, 4, 0,
  149688. _vq_quantlist__44u5__p9_1,
  149689. NULL,
  149690. &_vq_auxt__44u5__p9_1,
  149691. NULL,
  149692. 0
  149693. };
  149694. static long _vq_quantlist__44u5__p9_2[] = {
  149695. 8,
  149696. 7,
  149697. 9,
  149698. 6,
  149699. 10,
  149700. 5,
  149701. 11,
  149702. 4,
  149703. 12,
  149704. 3,
  149705. 13,
  149706. 2,
  149707. 14,
  149708. 1,
  149709. 15,
  149710. 0,
  149711. 16,
  149712. };
  149713. static long _vq_lengthlist__44u5__p9_2[] = {
  149714. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149715. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149716. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149717. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149718. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149719. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149720. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149721. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149722. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149723. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149724. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149725. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149726. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149727. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149728. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149729. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149730. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149731. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149732. 10,
  149733. };
  149734. static float _vq_quantthresh__44u5__p9_2[] = {
  149735. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149736. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149737. };
  149738. static long _vq_quantmap__44u5__p9_2[] = {
  149739. 15, 13, 11, 9, 7, 5, 3, 1,
  149740. 0, 2, 4, 6, 8, 10, 12, 14,
  149741. 16,
  149742. };
  149743. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149744. _vq_quantthresh__44u5__p9_2,
  149745. _vq_quantmap__44u5__p9_2,
  149746. 17,
  149747. 17
  149748. };
  149749. static static_codebook _44u5__p9_2 = {
  149750. 2, 289,
  149751. _vq_lengthlist__44u5__p9_2,
  149752. 1, -529530880, 1611661312, 5, 0,
  149753. _vq_quantlist__44u5__p9_2,
  149754. NULL,
  149755. &_vq_auxt__44u5__p9_2,
  149756. NULL,
  149757. 0
  149758. };
  149759. static long _huff_lengthlist__44u5__short[] = {
  149760. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149761. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149762. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149763. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149764. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149765. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149766. 6, 8,15,17,
  149767. };
  149768. static static_codebook _huff_book__44u5__short = {
  149769. 2, 100,
  149770. _huff_lengthlist__44u5__short,
  149771. 0, 0, 0, 0, 0,
  149772. NULL,
  149773. NULL,
  149774. NULL,
  149775. NULL,
  149776. 0
  149777. };
  149778. static long _huff_lengthlist__44u6__long[] = {
  149779. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149780. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149781. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149782. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149783. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149784. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149785. 13, 8, 7, 7,
  149786. };
  149787. static static_codebook _huff_book__44u6__long = {
  149788. 2, 100,
  149789. _huff_lengthlist__44u6__long,
  149790. 0, 0, 0, 0, 0,
  149791. NULL,
  149792. NULL,
  149793. NULL,
  149794. NULL,
  149795. 0
  149796. };
  149797. static long _vq_quantlist__44u6__p1_0[] = {
  149798. 1,
  149799. 0,
  149800. 2,
  149801. };
  149802. static long _vq_lengthlist__44u6__p1_0[] = {
  149803. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149804. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149805. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149806. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149807. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149808. 12,
  149809. };
  149810. static float _vq_quantthresh__44u6__p1_0[] = {
  149811. -0.5, 0.5,
  149812. };
  149813. static long _vq_quantmap__44u6__p1_0[] = {
  149814. 1, 0, 2,
  149815. };
  149816. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149817. _vq_quantthresh__44u6__p1_0,
  149818. _vq_quantmap__44u6__p1_0,
  149819. 3,
  149820. 3
  149821. };
  149822. static static_codebook _44u6__p1_0 = {
  149823. 4, 81,
  149824. _vq_lengthlist__44u6__p1_0,
  149825. 1, -535822336, 1611661312, 2, 0,
  149826. _vq_quantlist__44u6__p1_0,
  149827. NULL,
  149828. &_vq_auxt__44u6__p1_0,
  149829. NULL,
  149830. 0
  149831. };
  149832. static long _vq_quantlist__44u6__p2_0[] = {
  149833. 1,
  149834. 0,
  149835. 2,
  149836. };
  149837. static long _vq_lengthlist__44u6__p2_0[] = {
  149838. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149839. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149840. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149841. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149842. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149843. 9,
  149844. };
  149845. static float _vq_quantthresh__44u6__p2_0[] = {
  149846. -0.5, 0.5,
  149847. };
  149848. static long _vq_quantmap__44u6__p2_0[] = {
  149849. 1, 0, 2,
  149850. };
  149851. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149852. _vq_quantthresh__44u6__p2_0,
  149853. _vq_quantmap__44u6__p2_0,
  149854. 3,
  149855. 3
  149856. };
  149857. static static_codebook _44u6__p2_0 = {
  149858. 4, 81,
  149859. _vq_lengthlist__44u6__p2_0,
  149860. 1, -535822336, 1611661312, 2, 0,
  149861. _vq_quantlist__44u6__p2_0,
  149862. NULL,
  149863. &_vq_auxt__44u6__p2_0,
  149864. NULL,
  149865. 0
  149866. };
  149867. static long _vq_quantlist__44u6__p3_0[] = {
  149868. 2,
  149869. 1,
  149870. 3,
  149871. 0,
  149872. 4,
  149873. };
  149874. static long _vq_lengthlist__44u6__p3_0[] = {
  149875. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149876. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149877. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149878. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149879. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149880. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149881. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149882. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149883. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149884. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149885. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149886. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149887. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149888. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149889. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149890. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149891. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149892. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149893. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149894. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149895. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149896. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149897. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149898. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149899. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149900. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149901. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149902. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149903. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149904. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149905. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149906. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149907. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149908. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149909. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149910. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149911. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149912. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149913. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149914. 19,
  149915. };
  149916. static float _vq_quantthresh__44u6__p3_0[] = {
  149917. -1.5, -0.5, 0.5, 1.5,
  149918. };
  149919. static long _vq_quantmap__44u6__p3_0[] = {
  149920. 3, 1, 0, 2, 4,
  149921. };
  149922. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149923. _vq_quantthresh__44u6__p3_0,
  149924. _vq_quantmap__44u6__p3_0,
  149925. 5,
  149926. 5
  149927. };
  149928. static static_codebook _44u6__p3_0 = {
  149929. 4, 625,
  149930. _vq_lengthlist__44u6__p3_0,
  149931. 1, -533725184, 1611661312, 3, 0,
  149932. _vq_quantlist__44u6__p3_0,
  149933. NULL,
  149934. &_vq_auxt__44u6__p3_0,
  149935. NULL,
  149936. 0
  149937. };
  149938. static long _vq_quantlist__44u6__p4_0[] = {
  149939. 2,
  149940. 1,
  149941. 3,
  149942. 0,
  149943. 4,
  149944. };
  149945. static long _vq_lengthlist__44u6__p4_0[] = {
  149946. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149947. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149948. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149949. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149950. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149951. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149952. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149953. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149954. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149955. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149956. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149957. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149958. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149959. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149960. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149961. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149962. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149963. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149964. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149965. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149966. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149967. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149968. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149969. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149970. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149971. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149972. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149973. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149974. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149975. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149976. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149977. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149978. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149979. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149980. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149981. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149982. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149983. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149984. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149985. 13,
  149986. };
  149987. static float _vq_quantthresh__44u6__p4_0[] = {
  149988. -1.5, -0.5, 0.5, 1.5,
  149989. };
  149990. static long _vq_quantmap__44u6__p4_0[] = {
  149991. 3, 1, 0, 2, 4,
  149992. };
  149993. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149994. _vq_quantthresh__44u6__p4_0,
  149995. _vq_quantmap__44u6__p4_0,
  149996. 5,
  149997. 5
  149998. };
  149999. static static_codebook _44u6__p4_0 = {
  150000. 4, 625,
  150001. _vq_lengthlist__44u6__p4_0,
  150002. 1, -533725184, 1611661312, 3, 0,
  150003. _vq_quantlist__44u6__p4_0,
  150004. NULL,
  150005. &_vq_auxt__44u6__p4_0,
  150006. NULL,
  150007. 0
  150008. };
  150009. static long _vq_quantlist__44u6__p5_0[] = {
  150010. 4,
  150011. 3,
  150012. 5,
  150013. 2,
  150014. 6,
  150015. 1,
  150016. 7,
  150017. 0,
  150018. 8,
  150019. };
  150020. static long _vq_lengthlist__44u6__p5_0[] = {
  150021. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150022. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  150023. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  150024. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  150025. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  150026. 14,
  150027. };
  150028. static float _vq_quantthresh__44u6__p5_0[] = {
  150029. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150030. };
  150031. static long _vq_quantmap__44u6__p5_0[] = {
  150032. 7, 5, 3, 1, 0, 2, 4, 6,
  150033. 8,
  150034. };
  150035. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150036. _vq_quantthresh__44u6__p5_0,
  150037. _vq_quantmap__44u6__p5_0,
  150038. 9,
  150039. 9
  150040. };
  150041. static static_codebook _44u6__p5_0 = {
  150042. 2, 81,
  150043. _vq_lengthlist__44u6__p5_0,
  150044. 1, -531628032, 1611661312, 4, 0,
  150045. _vq_quantlist__44u6__p5_0,
  150046. NULL,
  150047. &_vq_auxt__44u6__p5_0,
  150048. NULL,
  150049. 0
  150050. };
  150051. static long _vq_quantlist__44u6__p6_0[] = {
  150052. 4,
  150053. 3,
  150054. 5,
  150055. 2,
  150056. 6,
  150057. 1,
  150058. 7,
  150059. 0,
  150060. 8,
  150061. };
  150062. static long _vq_lengthlist__44u6__p6_0[] = {
  150063. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150064. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150065. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150066. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150067. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150068. 12,
  150069. };
  150070. static float _vq_quantthresh__44u6__p6_0[] = {
  150071. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150072. };
  150073. static long _vq_quantmap__44u6__p6_0[] = {
  150074. 7, 5, 3, 1, 0, 2, 4, 6,
  150075. 8,
  150076. };
  150077. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150078. _vq_quantthresh__44u6__p6_0,
  150079. _vq_quantmap__44u6__p6_0,
  150080. 9,
  150081. 9
  150082. };
  150083. static static_codebook _44u6__p6_0 = {
  150084. 2, 81,
  150085. _vq_lengthlist__44u6__p6_0,
  150086. 1, -531628032, 1611661312, 4, 0,
  150087. _vq_quantlist__44u6__p6_0,
  150088. NULL,
  150089. &_vq_auxt__44u6__p6_0,
  150090. NULL,
  150091. 0
  150092. };
  150093. static long _vq_quantlist__44u6__p7_0[] = {
  150094. 1,
  150095. 0,
  150096. 2,
  150097. };
  150098. static long _vq_lengthlist__44u6__p7_0[] = {
  150099. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150100. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150101. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150102. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150103. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150104. 10,
  150105. };
  150106. static float _vq_quantthresh__44u6__p7_0[] = {
  150107. -5.5, 5.5,
  150108. };
  150109. static long _vq_quantmap__44u6__p7_0[] = {
  150110. 1, 0, 2,
  150111. };
  150112. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150113. _vq_quantthresh__44u6__p7_0,
  150114. _vq_quantmap__44u6__p7_0,
  150115. 3,
  150116. 3
  150117. };
  150118. static static_codebook _44u6__p7_0 = {
  150119. 4, 81,
  150120. _vq_lengthlist__44u6__p7_0,
  150121. 1, -529137664, 1618345984, 2, 0,
  150122. _vq_quantlist__44u6__p7_0,
  150123. NULL,
  150124. &_vq_auxt__44u6__p7_0,
  150125. NULL,
  150126. 0
  150127. };
  150128. static long _vq_quantlist__44u6__p7_1[] = {
  150129. 5,
  150130. 4,
  150131. 6,
  150132. 3,
  150133. 7,
  150134. 2,
  150135. 8,
  150136. 1,
  150137. 9,
  150138. 0,
  150139. 10,
  150140. };
  150141. static long _vq_lengthlist__44u6__p7_1[] = {
  150142. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150143. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150144. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150145. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150146. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150147. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150148. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150149. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150150. };
  150151. static float _vq_quantthresh__44u6__p7_1[] = {
  150152. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150153. 3.5, 4.5,
  150154. };
  150155. static long _vq_quantmap__44u6__p7_1[] = {
  150156. 9, 7, 5, 3, 1, 0, 2, 4,
  150157. 6, 8, 10,
  150158. };
  150159. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150160. _vq_quantthresh__44u6__p7_1,
  150161. _vq_quantmap__44u6__p7_1,
  150162. 11,
  150163. 11
  150164. };
  150165. static static_codebook _44u6__p7_1 = {
  150166. 2, 121,
  150167. _vq_lengthlist__44u6__p7_1,
  150168. 1, -531365888, 1611661312, 4, 0,
  150169. _vq_quantlist__44u6__p7_1,
  150170. NULL,
  150171. &_vq_auxt__44u6__p7_1,
  150172. NULL,
  150173. 0
  150174. };
  150175. static long _vq_quantlist__44u6__p8_0[] = {
  150176. 5,
  150177. 4,
  150178. 6,
  150179. 3,
  150180. 7,
  150181. 2,
  150182. 8,
  150183. 1,
  150184. 9,
  150185. 0,
  150186. 10,
  150187. };
  150188. static long _vq_lengthlist__44u6__p8_0[] = {
  150189. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150190. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150191. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150192. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150193. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150194. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150195. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150196. 12,13,13,14,14,14,15,15,15,
  150197. };
  150198. static float _vq_quantthresh__44u6__p8_0[] = {
  150199. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150200. 38.5, 49.5,
  150201. };
  150202. static long _vq_quantmap__44u6__p8_0[] = {
  150203. 9, 7, 5, 3, 1, 0, 2, 4,
  150204. 6, 8, 10,
  150205. };
  150206. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150207. _vq_quantthresh__44u6__p8_0,
  150208. _vq_quantmap__44u6__p8_0,
  150209. 11,
  150210. 11
  150211. };
  150212. static static_codebook _44u6__p8_0 = {
  150213. 2, 121,
  150214. _vq_lengthlist__44u6__p8_0,
  150215. 1, -524582912, 1618345984, 4, 0,
  150216. _vq_quantlist__44u6__p8_0,
  150217. NULL,
  150218. &_vq_auxt__44u6__p8_0,
  150219. NULL,
  150220. 0
  150221. };
  150222. static long _vq_quantlist__44u6__p8_1[] = {
  150223. 5,
  150224. 4,
  150225. 6,
  150226. 3,
  150227. 7,
  150228. 2,
  150229. 8,
  150230. 1,
  150231. 9,
  150232. 0,
  150233. 10,
  150234. };
  150235. static long _vq_lengthlist__44u6__p8_1[] = {
  150236. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150237. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150238. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150239. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150240. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150241. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150242. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150243. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150244. };
  150245. static float _vq_quantthresh__44u6__p8_1[] = {
  150246. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150247. 3.5, 4.5,
  150248. };
  150249. static long _vq_quantmap__44u6__p8_1[] = {
  150250. 9, 7, 5, 3, 1, 0, 2, 4,
  150251. 6, 8, 10,
  150252. };
  150253. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150254. _vq_quantthresh__44u6__p8_1,
  150255. _vq_quantmap__44u6__p8_1,
  150256. 11,
  150257. 11
  150258. };
  150259. static static_codebook _44u6__p8_1 = {
  150260. 2, 121,
  150261. _vq_lengthlist__44u6__p8_1,
  150262. 1, -531365888, 1611661312, 4, 0,
  150263. _vq_quantlist__44u6__p8_1,
  150264. NULL,
  150265. &_vq_auxt__44u6__p8_1,
  150266. NULL,
  150267. 0
  150268. };
  150269. static long _vq_quantlist__44u6__p9_0[] = {
  150270. 7,
  150271. 6,
  150272. 8,
  150273. 5,
  150274. 9,
  150275. 4,
  150276. 10,
  150277. 3,
  150278. 11,
  150279. 2,
  150280. 12,
  150281. 1,
  150282. 13,
  150283. 0,
  150284. 14,
  150285. };
  150286. static long _vq_lengthlist__44u6__p9_0[] = {
  150287. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150288. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150289. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150290. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150291. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150292. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150293. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150294. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150295. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150296. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150297. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150298. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150299. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150300. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150301. 14,
  150302. };
  150303. static float _vq_quantthresh__44u6__p9_0[] = {
  150304. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150305. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150306. };
  150307. static long _vq_quantmap__44u6__p9_0[] = {
  150308. 13, 11, 9, 7, 5, 3, 1, 0,
  150309. 2, 4, 6, 8, 10, 12, 14,
  150310. };
  150311. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150312. _vq_quantthresh__44u6__p9_0,
  150313. _vq_quantmap__44u6__p9_0,
  150314. 15,
  150315. 15
  150316. };
  150317. static static_codebook _44u6__p9_0 = {
  150318. 2, 225,
  150319. _vq_lengthlist__44u6__p9_0,
  150320. 1, -514071552, 1627381760, 4, 0,
  150321. _vq_quantlist__44u6__p9_0,
  150322. NULL,
  150323. &_vq_auxt__44u6__p9_0,
  150324. NULL,
  150325. 0
  150326. };
  150327. static long _vq_quantlist__44u6__p9_1[] = {
  150328. 7,
  150329. 6,
  150330. 8,
  150331. 5,
  150332. 9,
  150333. 4,
  150334. 10,
  150335. 3,
  150336. 11,
  150337. 2,
  150338. 12,
  150339. 1,
  150340. 13,
  150341. 0,
  150342. 14,
  150343. };
  150344. static long _vq_lengthlist__44u6__p9_1[] = {
  150345. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150346. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150347. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150348. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150349. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150350. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150351. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150352. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150353. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150354. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150355. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150356. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150357. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150358. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150359. 13,
  150360. };
  150361. static float _vq_quantthresh__44u6__p9_1[] = {
  150362. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150363. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150364. };
  150365. static long _vq_quantmap__44u6__p9_1[] = {
  150366. 13, 11, 9, 7, 5, 3, 1, 0,
  150367. 2, 4, 6, 8, 10, 12, 14,
  150368. };
  150369. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150370. _vq_quantthresh__44u6__p9_1,
  150371. _vq_quantmap__44u6__p9_1,
  150372. 15,
  150373. 15
  150374. };
  150375. static static_codebook _44u6__p9_1 = {
  150376. 2, 225,
  150377. _vq_lengthlist__44u6__p9_1,
  150378. 1, -522338304, 1620115456, 4, 0,
  150379. _vq_quantlist__44u6__p9_1,
  150380. NULL,
  150381. &_vq_auxt__44u6__p9_1,
  150382. NULL,
  150383. 0
  150384. };
  150385. static long _vq_quantlist__44u6__p9_2[] = {
  150386. 8,
  150387. 7,
  150388. 9,
  150389. 6,
  150390. 10,
  150391. 5,
  150392. 11,
  150393. 4,
  150394. 12,
  150395. 3,
  150396. 13,
  150397. 2,
  150398. 14,
  150399. 1,
  150400. 15,
  150401. 0,
  150402. 16,
  150403. };
  150404. static long _vq_lengthlist__44u6__p9_2[] = {
  150405. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150406. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150407. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150408. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150409. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150410. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150411. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150412. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150413. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150414. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150415. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150416. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150417. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150418. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150419. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150420. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150421. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150422. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150423. 10,
  150424. };
  150425. static float _vq_quantthresh__44u6__p9_2[] = {
  150426. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150427. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150428. };
  150429. static long _vq_quantmap__44u6__p9_2[] = {
  150430. 15, 13, 11, 9, 7, 5, 3, 1,
  150431. 0, 2, 4, 6, 8, 10, 12, 14,
  150432. 16,
  150433. };
  150434. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150435. _vq_quantthresh__44u6__p9_2,
  150436. _vq_quantmap__44u6__p9_2,
  150437. 17,
  150438. 17
  150439. };
  150440. static static_codebook _44u6__p9_2 = {
  150441. 2, 289,
  150442. _vq_lengthlist__44u6__p9_2,
  150443. 1, -529530880, 1611661312, 5, 0,
  150444. _vq_quantlist__44u6__p9_2,
  150445. NULL,
  150446. &_vq_auxt__44u6__p9_2,
  150447. NULL,
  150448. 0
  150449. };
  150450. static long _huff_lengthlist__44u6__short[] = {
  150451. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150452. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150453. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150454. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150455. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150456. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150457. 7, 6, 9,16,
  150458. };
  150459. static static_codebook _huff_book__44u6__short = {
  150460. 2, 100,
  150461. _huff_lengthlist__44u6__short,
  150462. 0, 0, 0, 0, 0,
  150463. NULL,
  150464. NULL,
  150465. NULL,
  150466. NULL,
  150467. 0
  150468. };
  150469. static long _huff_lengthlist__44u7__long[] = {
  150470. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150471. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150472. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150473. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150474. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150475. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150476. 12, 8, 6, 7,
  150477. };
  150478. static static_codebook _huff_book__44u7__long = {
  150479. 2, 100,
  150480. _huff_lengthlist__44u7__long,
  150481. 0, 0, 0, 0, 0,
  150482. NULL,
  150483. NULL,
  150484. NULL,
  150485. NULL,
  150486. 0
  150487. };
  150488. static long _vq_quantlist__44u7__p1_0[] = {
  150489. 1,
  150490. 0,
  150491. 2,
  150492. };
  150493. static long _vq_lengthlist__44u7__p1_0[] = {
  150494. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150495. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150496. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150497. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150498. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150499. 12,
  150500. };
  150501. static float _vq_quantthresh__44u7__p1_0[] = {
  150502. -0.5, 0.5,
  150503. };
  150504. static long _vq_quantmap__44u7__p1_0[] = {
  150505. 1, 0, 2,
  150506. };
  150507. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150508. _vq_quantthresh__44u7__p1_0,
  150509. _vq_quantmap__44u7__p1_0,
  150510. 3,
  150511. 3
  150512. };
  150513. static static_codebook _44u7__p1_0 = {
  150514. 4, 81,
  150515. _vq_lengthlist__44u7__p1_0,
  150516. 1, -535822336, 1611661312, 2, 0,
  150517. _vq_quantlist__44u7__p1_0,
  150518. NULL,
  150519. &_vq_auxt__44u7__p1_0,
  150520. NULL,
  150521. 0
  150522. };
  150523. static long _vq_quantlist__44u7__p2_0[] = {
  150524. 1,
  150525. 0,
  150526. 2,
  150527. };
  150528. static long _vq_lengthlist__44u7__p2_0[] = {
  150529. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150530. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150531. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150532. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150533. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150534. 9,
  150535. };
  150536. static float _vq_quantthresh__44u7__p2_0[] = {
  150537. -0.5, 0.5,
  150538. };
  150539. static long _vq_quantmap__44u7__p2_0[] = {
  150540. 1, 0, 2,
  150541. };
  150542. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150543. _vq_quantthresh__44u7__p2_0,
  150544. _vq_quantmap__44u7__p2_0,
  150545. 3,
  150546. 3
  150547. };
  150548. static static_codebook _44u7__p2_0 = {
  150549. 4, 81,
  150550. _vq_lengthlist__44u7__p2_0,
  150551. 1, -535822336, 1611661312, 2, 0,
  150552. _vq_quantlist__44u7__p2_0,
  150553. NULL,
  150554. &_vq_auxt__44u7__p2_0,
  150555. NULL,
  150556. 0
  150557. };
  150558. static long _vq_quantlist__44u7__p3_0[] = {
  150559. 2,
  150560. 1,
  150561. 3,
  150562. 0,
  150563. 4,
  150564. };
  150565. static long _vq_lengthlist__44u7__p3_0[] = {
  150566. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150567. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150568. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150569. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150570. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150571. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150572. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150573. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150574. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150575. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150576. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150577. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150578. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150579. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150580. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150581. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150582. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150583. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150584. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150585. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150586. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150587. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150588. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150589. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150590. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150591. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150592. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150593. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150594. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150595. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150596. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150597. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150598. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150599. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150600. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150601. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150602. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150603. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150604. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150605. 0,
  150606. };
  150607. static float _vq_quantthresh__44u7__p3_0[] = {
  150608. -1.5, -0.5, 0.5, 1.5,
  150609. };
  150610. static long _vq_quantmap__44u7__p3_0[] = {
  150611. 3, 1, 0, 2, 4,
  150612. };
  150613. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150614. _vq_quantthresh__44u7__p3_0,
  150615. _vq_quantmap__44u7__p3_0,
  150616. 5,
  150617. 5
  150618. };
  150619. static static_codebook _44u7__p3_0 = {
  150620. 4, 625,
  150621. _vq_lengthlist__44u7__p3_0,
  150622. 1, -533725184, 1611661312, 3, 0,
  150623. _vq_quantlist__44u7__p3_0,
  150624. NULL,
  150625. &_vq_auxt__44u7__p3_0,
  150626. NULL,
  150627. 0
  150628. };
  150629. static long _vq_quantlist__44u7__p4_0[] = {
  150630. 2,
  150631. 1,
  150632. 3,
  150633. 0,
  150634. 4,
  150635. };
  150636. static long _vq_lengthlist__44u7__p4_0[] = {
  150637. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150638. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150639. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150640. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150641. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150642. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150643. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150644. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150645. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150646. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150647. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150648. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150649. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150650. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150651. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150652. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150653. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150654. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150655. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150656. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150657. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150658. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150659. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150660. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150661. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150662. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150663. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150664. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150665. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150666. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150667. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150668. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150669. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150670. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150671. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150672. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150673. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150674. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150675. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150676. 14,
  150677. };
  150678. static float _vq_quantthresh__44u7__p4_0[] = {
  150679. -1.5, -0.5, 0.5, 1.5,
  150680. };
  150681. static long _vq_quantmap__44u7__p4_0[] = {
  150682. 3, 1, 0, 2, 4,
  150683. };
  150684. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150685. _vq_quantthresh__44u7__p4_0,
  150686. _vq_quantmap__44u7__p4_0,
  150687. 5,
  150688. 5
  150689. };
  150690. static static_codebook _44u7__p4_0 = {
  150691. 4, 625,
  150692. _vq_lengthlist__44u7__p4_0,
  150693. 1, -533725184, 1611661312, 3, 0,
  150694. _vq_quantlist__44u7__p4_0,
  150695. NULL,
  150696. &_vq_auxt__44u7__p4_0,
  150697. NULL,
  150698. 0
  150699. };
  150700. static long _vq_quantlist__44u7__p5_0[] = {
  150701. 4,
  150702. 3,
  150703. 5,
  150704. 2,
  150705. 6,
  150706. 1,
  150707. 7,
  150708. 0,
  150709. 8,
  150710. };
  150711. static long _vq_lengthlist__44u7__p5_0[] = {
  150712. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150713. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150714. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150715. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150716. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150717. 14,
  150718. };
  150719. static float _vq_quantthresh__44u7__p5_0[] = {
  150720. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150721. };
  150722. static long _vq_quantmap__44u7__p5_0[] = {
  150723. 7, 5, 3, 1, 0, 2, 4, 6,
  150724. 8,
  150725. };
  150726. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150727. _vq_quantthresh__44u7__p5_0,
  150728. _vq_quantmap__44u7__p5_0,
  150729. 9,
  150730. 9
  150731. };
  150732. static static_codebook _44u7__p5_0 = {
  150733. 2, 81,
  150734. _vq_lengthlist__44u7__p5_0,
  150735. 1, -531628032, 1611661312, 4, 0,
  150736. _vq_quantlist__44u7__p5_0,
  150737. NULL,
  150738. &_vq_auxt__44u7__p5_0,
  150739. NULL,
  150740. 0
  150741. };
  150742. static long _vq_quantlist__44u7__p6_0[] = {
  150743. 4,
  150744. 3,
  150745. 5,
  150746. 2,
  150747. 6,
  150748. 1,
  150749. 7,
  150750. 0,
  150751. 8,
  150752. };
  150753. static long _vq_lengthlist__44u7__p6_0[] = {
  150754. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150755. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150756. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150757. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150758. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150759. 12,
  150760. };
  150761. static float _vq_quantthresh__44u7__p6_0[] = {
  150762. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150763. };
  150764. static long _vq_quantmap__44u7__p6_0[] = {
  150765. 7, 5, 3, 1, 0, 2, 4, 6,
  150766. 8,
  150767. };
  150768. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150769. _vq_quantthresh__44u7__p6_0,
  150770. _vq_quantmap__44u7__p6_0,
  150771. 9,
  150772. 9
  150773. };
  150774. static static_codebook _44u7__p6_0 = {
  150775. 2, 81,
  150776. _vq_lengthlist__44u7__p6_0,
  150777. 1, -531628032, 1611661312, 4, 0,
  150778. _vq_quantlist__44u7__p6_0,
  150779. NULL,
  150780. &_vq_auxt__44u7__p6_0,
  150781. NULL,
  150782. 0
  150783. };
  150784. static long _vq_quantlist__44u7__p7_0[] = {
  150785. 1,
  150786. 0,
  150787. 2,
  150788. };
  150789. static long _vq_lengthlist__44u7__p7_0[] = {
  150790. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150791. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150792. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150793. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150794. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150795. 10,
  150796. };
  150797. static float _vq_quantthresh__44u7__p7_0[] = {
  150798. -5.5, 5.5,
  150799. };
  150800. static long _vq_quantmap__44u7__p7_0[] = {
  150801. 1, 0, 2,
  150802. };
  150803. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150804. _vq_quantthresh__44u7__p7_0,
  150805. _vq_quantmap__44u7__p7_0,
  150806. 3,
  150807. 3
  150808. };
  150809. static static_codebook _44u7__p7_0 = {
  150810. 4, 81,
  150811. _vq_lengthlist__44u7__p7_0,
  150812. 1, -529137664, 1618345984, 2, 0,
  150813. _vq_quantlist__44u7__p7_0,
  150814. NULL,
  150815. &_vq_auxt__44u7__p7_0,
  150816. NULL,
  150817. 0
  150818. };
  150819. static long _vq_quantlist__44u7__p7_1[] = {
  150820. 5,
  150821. 4,
  150822. 6,
  150823. 3,
  150824. 7,
  150825. 2,
  150826. 8,
  150827. 1,
  150828. 9,
  150829. 0,
  150830. 10,
  150831. };
  150832. static long _vq_lengthlist__44u7__p7_1[] = {
  150833. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150834. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150835. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150836. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150837. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150838. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150839. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150840. 8, 9, 9, 9, 9, 9,10,10,10,
  150841. };
  150842. static float _vq_quantthresh__44u7__p7_1[] = {
  150843. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150844. 3.5, 4.5,
  150845. };
  150846. static long _vq_quantmap__44u7__p7_1[] = {
  150847. 9, 7, 5, 3, 1, 0, 2, 4,
  150848. 6, 8, 10,
  150849. };
  150850. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150851. _vq_quantthresh__44u7__p7_1,
  150852. _vq_quantmap__44u7__p7_1,
  150853. 11,
  150854. 11
  150855. };
  150856. static static_codebook _44u7__p7_1 = {
  150857. 2, 121,
  150858. _vq_lengthlist__44u7__p7_1,
  150859. 1, -531365888, 1611661312, 4, 0,
  150860. _vq_quantlist__44u7__p7_1,
  150861. NULL,
  150862. &_vq_auxt__44u7__p7_1,
  150863. NULL,
  150864. 0
  150865. };
  150866. static long _vq_quantlist__44u7__p8_0[] = {
  150867. 5,
  150868. 4,
  150869. 6,
  150870. 3,
  150871. 7,
  150872. 2,
  150873. 8,
  150874. 1,
  150875. 9,
  150876. 0,
  150877. 10,
  150878. };
  150879. static long _vq_lengthlist__44u7__p8_0[] = {
  150880. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150881. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150882. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150883. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150884. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150885. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150886. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150887. 12,13,13,14,14,15,15,15,16,
  150888. };
  150889. static float _vq_quantthresh__44u7__p8_0[] = {
  150890. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150891. 38.5, 49.5,
  150892. };
  150893. static long _vq_quantmap__44u7__p8_0[] = {
  150894. 9, 7, 5, 3, 1, 0, 2, 4,
  150895. 6, 8, 10,
  150896. };
  150897. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150898. _vq_quantthresh__44u7__p8_0,
  150899. _vq_quantmap__44u7__p8_0,
  150900. 11,
  150901. 11
  150902. };
  150903. static static_codebook _44u7__p8_0 = {
  150904. 2, 121,
  150905. _vq_lengthlist__44u7__p8_0,
  150906. 1, -524582912, 1618345984, 4, 0,
  150907. _vq_quantlist__44u7__p8_0,
  150908. NULL,
  150909. &_vq_auxt__44u7__p8_0,
  150910. NULL,
  150911. 0
  150912. };
  150913. static long _vq_quantlist__44u7__p8_1[] = {
  150914. 5,
  150915. 4,
  150916. 6,
  150917. 3,
  150918. 7,
  150919. 2,
  150920. 8,
  150921. 1,
  150922. 9,
  150923. 0,
  150924. 10,
  150925. };
  150926. static long _vq_lengthlist__44u7__p8_1[] = {
  150927. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150928. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150929. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150930. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150931. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150932. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150933. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150934. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150935. };
  150936. static float _vq_quantthresh__44u7__p8_1[] = {
  150937. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150938. 3.5, 4.5,
  150939. };
  150940. static long _vq_quantmap__44u7__p8_1[] = {
  150941. 9, 7, 5, 3, 1, 0, 2, 4,
  150942. 6, 8, 10,
  150943. };
  150944. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150945. _vq_quantthresh__44u7__p8_1,
  150946. _vq_quantmap__44u7__p8_1,
  150947. 11,
  150948. 11
  150949. };
  150950. static static_codebook _44u7__p8_1 = {
  150951. 2, 121,
  150952. _vq_lengthlist__44u7__p8_1,
  150953. 1, -531365888, 1611661312, 4, 0,
  150954. _vq_quantlist__44u7__p8_1,
  150955. NULL,
  150956. &_vq_auxt__44u7__p8_1,
  150957. NULL,
  150958. 0
  150959. };
  150960. static long _vq_quantlist__44u7__p9_0[] = {
  150961. 5,
  150962. 4,
  150963. 6,
  150964. 3,
  150965. 7,
  150966. 2,
  150967. 8,
  150968. 1,
  150969. 9,
  150970. 0,
  150971. 10,
  150972. };
  150973. static long _vq_lengthlist__44u7__p9_0[] = {
  150974. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150975. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150976. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150977. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150978. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150979. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150980. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150981. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150982. };
  150983. static float _vq_quantthresh__44u7__p9_0[] = {
  150984. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150985. 2229.5, 2866.5,
  150986. };
  150987. static long _vq_quantmap__44u7__p9_0[] = {
  150988. 9, 7, 5, 3, 1, 0, 2, 4,
  150989. 6, 8, 10,
  150990. };
  150991. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150992. _vq_quantthresh__44u7__p9_0,
  150993. _vq_quantmap__44u7__p9_0,
  150994. 11,
  150995. 11
  150996. };
  150997. static static_codebook _44u7__p9_0 = {
  150998. 2, 121,
  150999. _vq_lengthlist__44u7__p9_0,
  151000. 1, -512171520, 1630791680, 4, 0,
  151001. _vq_quantlist__44u7__p9_0,
  151002. NULL,
  151003. &_vq_auxt__44u7__p9_0,
  151004. NULL,
  151005. 0
  151006. };
  151007. static long _vq_quantlist__44u7__p9_1[] = {
  151008. 6,
  151009. 5,
  151010. 7,
  151011. 4,
  151012. 8,
  151013. 3,
  151014. 9,
  151015. 2,
  151016. 10,
  151017. 1,
  151018. 11,
  151019. 0,
  151020. 12,
  151021. };
  151022. static long _vq_lengthlist__44u7__p9_1[] = {
  151023. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  151024. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  151025. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  151026. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  151027. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  151028. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  151029. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151030. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151031. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151032. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151033. 15,15,15,15,17,17,16,17,16,
  151034. };
  151035. static float _vq_quantthresh__44u7__p9_1[] = {
  151036. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151037. 122.5, 171.5, 220.5, 269.5,
  151038. };
  151039. static long _vq_quantmap__44u7__p9_1[] = {
  151040. 11, 9, 7, 5, 3, 1, 0, 2,
  151041. 4, 6, 8, 10, 12,
  151042. };
  151043. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151044. _vq_quantthresh__44u7__p9_1,
  151045. _vq_quantmap__44u7__p9_1,
  151046. 13,
  151047. 13
  151048. };
  151049. static static_codebook _44u7__p9_1 = {
  151050. 2, 169,
  151051. _vq_lengthlist__44u7__p9_1,
  151052. 1, -518889472, 1622704128, 4, 0,
  151053. _vq_quantlist__44u7__p9_1,
  151054. NULL,
  151055. &_vq_auxt__44u7__p9_1,
  151056. NULL,
  151057. 0
  151058. };
  151059. static long _vq_quantlist__44u7__p9_2[] = {
  151060. 24,
  151061. 23,
  151062. 25,
  151063. 22,
  151064. 26,
  151065. 21,
  151066. 27,
  151067. 20,
  151068. 28,
  151069. 19,
  151070. 29,
  151071. 18,
  151072. 30,
  151073. 17,
  151074. 31,
  151075. 16,
  151076. 32,
  151077. 15,
  151078. 33,
  151079. 14,
  151080. 34,
  151081. 13,
  151082. 35,
  151083. 12,
  151084. 36,
  151085. 11,
  151086. 37,
  151087. 10,
  151088. 38,
  151089. 9,
  151090. 39,
  151091. 8,
  151092. 40,
  151093. 7,
  151094. 41,
  151095. 6,
  151096. 42,
  151097. 5,
  151098. 43,
  151099. 4,
  151100. 44,
  151101. 3,
  151102. 45,
  151103. 2,
  151104. 46,
  151105. 1,
  151106. 47,
  151107. 0,
  151108. 48,
  151109. };
  151110. static long _vq_lengthlist__44u7__p9_2[] = {
  151111. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151112. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151113. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151114. 8,
  151115. };
  151116. static float _vq_quantthresh__44u7__p9_2[] = {
  151117. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151118. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151119. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151120. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151121. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151122. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151123. };
  151124. static long _vq_quantmap__44u7__p9_2[] = {
  151125. 47, 45, 43, 41, 39, 37, 35, 33,
  151126. 31, 29, 27, 25, 23, 21, 19, 17,
  151127. 15, 13, 11, 9, 7, 5, 3, 1,
  151128. 0, 2, 4, 6, 8, 10, 12, 14,
  151129. 16, 18, 20, 22, 24, 26, 28, 30,
  151130. 32, 34, 36, 38, 40, 42, 44, 46,
  151131. 48,
  151132. };
  151133. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151134. _vq_quantthresh__44u7__p9_2,
  151135. _vq_quantmap__44u7__p9_2,
  151136. 49,
  151137. 49
  151138. };
  151139. static static_codebook _44u7__p9_2 = {
  151140. 1, 49,
  151141. _vq_lengthlist__44u7__p9_2,
  151142. 1, -526909440, 1611661312, 6, 0,
  151143. _vq_quantlist__44u7__p9_2,
  151144. NULL,
  151145. &_vq_auxt__44u7__p9_2,
  151146. NULL,
  151147. 0
  151148. };
  151149. static long _huff_lengthlist__44u7__short[] = {
  151150. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151151. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151152. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151153. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151154. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151155. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151156. 6, 8, 5, 9,
  151157. };
  151158. static static_codebook _huff_book__44u7__short = {
  151159. 2, 100,
  151160. _huff_lengthlist__44u7__short,
  151161. 0, 0, 0, 0, 0,
  151162. NULL,
  151163. NULL,
  151164. NULL,
  151165. NULL,
  151166. 0
  151167. };
  151168. static long _huff_lengthlist__44u8__long[] = {
  151169. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151170. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151171. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151172. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151173. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151174. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151175. 10, 8, 8, 9,
  151176. };
  151177. static static_codebook _huff_book__44u8__long = {
  151178. 2, 100,
  151179. _huff_lengthlist__44u8__long,
  151180. 0, 0, 0, 0, 0,
  151181. NULL,
  151182. NULL,
  151183. NULL,
  151184. NULL,
  151185. 0
  151186. };
  151187. static long _huff_lengthlist__44u8__short[] = {
  151188. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151189. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151190. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151191. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151192. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151193. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151194. 10,10,15,17,
  151195. };
  151196. static static_codebook _huff_book__44u8__short = {
  151197. 2, 100,
  151198. _huff_lengthlist__44u8__short,
  151199. 0, 0, 0, 0, 0,
  151200. NULL,
  151201. NULL,
  151202. NULL,
  151203. NULL,
  151204. 0
  151205. };
  151206. static long _vq_quantlist__44u8_p1_0[] = {
  151207. 1,
  151208. 0,
  151209. 2,
  151210. };
  151211. static long _vq_lengthlist__44u8_p1_0[] = {
  151212. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151213. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151214. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151215. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151216. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151217. 10,
  151218. };
  151219. static float _vq_quantthresh__44u8_p1_0[] = {
  151220. -0.5, 0.5,
  151221. };
  151222. static long _vq_quantmap__44u8_p1_0[] = {
  151223. 1, 0, 2,
  151224. };
  151225. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151226. _vq_quantthresh__44u8_p1_0,
  151227. _vq_quantmap__44u8_p1_0,
  151228. 3,
  151229. 3
  151230. };
  151231. static static_codebook _44u8_p1_0 = {
  151232. 4, 81,
  151233. _vq_lengthlist__44u8_p1_0,
  151234. 1, -535822336, 1611661312, 2, 0,
  151235. _vq_quantlist__44u8_p1_0,
  151236. NULL,
  151237. &_vq_auxt__44u8_p1_0,
  151238. NULL,
  151239. 0
  151240. };
  151241. static long _vq_quantlist__44u8_p2_0[] = {
  151242. 2,
  151243. 1,
  151244. 3,
  151245. 0,
  151246. 4,
  151247. };
  151248. static long _vq_lengthlist__44u8_p2_0[] = {
  151249. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151250. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151251. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151252. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151253. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151254. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151255. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151256. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151257. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151258. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151259. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151260. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151261. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151262. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151263. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151264. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151265. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151266. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151267. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151268. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151269. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151270. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151271. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151272. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151273. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151274. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151275. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151276. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151277. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151278. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151279. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151280. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151281. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151282. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151283. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151284. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151285. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151286. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151287. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151288. 14,
  151289. };
  151290. static float _vq_quantthresh__44u8_p2_0[] = {
  151291. -1.5, -0.5, 0.5, 1.5,
  151292. };
  151293. static long _vq_quantmap__44u8_p2_0[] = {
  151294. 3, 1, 0, 2, 4,
  151295. };
  151296. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151297. _vq_quantthresh__44u8_p2_0,
  151298. _vq_quantmap__44u8_p2_0,
  151299. 5,
  151300. 5
  151301. };
  151302. static static_codebook _44u8_p2_0 = {
  151303. 4, 625,
  151304. _vq_lengthlist__44u8_p2_0,
  151305. 1, -533725184, 1611661312, 3, 0,
  151306. _vq_quantlist__44u8_p2_0,
  151307. NULL,
  151308. &_vq_auxt__44u8_p2_0,
  151309. NULL,
  151310. 0
  151311. };
  151312. static long _vq_quantlist__44u8_p3_0[] = {
  151313. 4,
  151314. 3,
  151315. 5,
  151316. 2,
  151317. 6,
  151318. 1,
  151319. 7,
  151320. 0,
  151321. 8,
  151322. };
  151323. static long _vq_lengthlist__44u8_p3_0[] = {
  151324. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151325. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151326. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151327. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151328. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151329. 12,
  151330. };
  151331. static float _vq_quantthresh__44u8_p3_0[] = {
  151332. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151333. };
  151334. static long _vq_quantmap__44u8_p3_0[] = {
  151335. 7, 5, 3, 1, 0, 2, 4, 6,
  151336. 8,
  151337. };
  151338. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151339. _vq_quantthresh__44u8_p3_0,
  151340. _vq_quantmap__44u8_p3_0,
  151341. 9,
  151342. 9
  151343. };
  151344. static static_codebook _44u8_p3_0 = {
  151345. 2, 81,
  151346. _vq_lengthlist__44u8_p3_0,
  151347. 1, -531628032, 1611661312, 4, 0,
  151348. _vq_quantlist__44u8_p3_0,
  151349. NULL,
  151350. &_vq_auxt__44u8_p3_0,
  151351. NULL,
  151352. 0
  151353. };
  151354. static long _vq_quantlist__44u8_p4_0[] = {
  151355. 8,
  151356. 7,
  151357. 9,
  151358. 6,
  151359. 10,
  151360. 5,
  151361. 11,
  151362. 4,
  151363. 12,
  151364. 3,
  151365. 13,
  151366. 2,
  151367. 14,
  151368. 1,
  151369. 15,
  151370. 0,
  151371. 16,
  151372. };
  151373. static long _vq_lengthlist__44u8_p4_0[] = {
  151374. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151375. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151376. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151377. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151378. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151379. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151380. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151381. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151382. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151383. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151384. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151385. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151386. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151387. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151388. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151389. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151390. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151391. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151392. 14,
  151393. };
  151394. static float _vq_quantthresh__44u8_p4_0[] = {
  151395. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151396. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151397. };
  151398. static long _vq_quantmap__44u8_p4_0[] = {
  151399. 15, 13, 11, 9, 7, 5, 3, 1,
  151400. 0, 2, 4, 6, 8, 10, 12, 14,
  151401. 16,
  151402. };
  151403. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151404. _vq_quantthresh__44u8_p4_0,
  151405. _vq_quantmap__44u8_p4_0,
  151406. 17,
  151407. 17
  151408. };
  151409. static static_codebook _44u8_p4_0 = {
  151410. 2, 289,
  151411. _vq_lengthlist__44u8_p4_0,
  151412. 1, -529530880, 1611661312, 5, 0,
  151413. _vq_quantlist__44u8_p4_0,
  151414. NULL,
  151415. &_vq_auxt__44u8_p4_0,
  151416. NULL,
  151417. 0
  151418. };
  151419. static long _vq_quantlist__44u8_p5_0[] = {
  151420. 1,
  151421. 0,
  151422. 2,
  151423. };
  151424. static long _vq_lengthlist__44u8_p5_0[] = {
  151425. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151426. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151427. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151428. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151429. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151430. 10,
  151431. };
  151432. static float _vq_quantthresh__44u8_p5_0[] = {
  151433. -5.5, 5.5,
  151434. };
  151435. static long _vq_quantmap__44u8_p5_0[] = {
  151436. 1, 0, 2,
  151437. };
  151438. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151439. _vq_quantthresh__44u8_p5_0,
  151440. _vq_quantmap__44u8_p5_0,
  151441. 3,
  151442. 3
  151443. };
  151444. static static_codebook _44u8_p5_0 = {
  151445. 4, 81,
  151446. _vq_lengthlist__44u8_p5_0,
  151447. 1, -529137664, 1618345984, 2, 0,
  151448. _vq_quantlist__44u8_p5_0,
  151449. NULL,
  151450. &_vq_auxt__44u8_p5_0,
  151451. NULL,
  151452. 0
  151453. };
  151454. static long _vq_quantlist__44u8_p5_1[] = {
  151455. 5,
  151456. 4,
  151457. 6,
  151458. 3,
  151459. 7,
  151460. 2,
  151461. 8,
  151462. 1,
  151463. 9,
  151464. 0,
  151465. 10,
  151466. };
  151467. static long _vq_lengthlist__44u8_p5_1[] = {
  151468. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151469. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151470. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151471. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151472. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151473. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151474. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151475. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151476. };
  151477. static float _vq_quantthresh__44u8_p5_1[] = {
  151478. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151479. 3.5, 4.5,
  151480. };
  151481. static long _vq_quantmap__44u8_p5_1[] = {
  151482. 9, 7, 5, 3, 1, 0, 2, 4,
  151483. 6, 8, 10,
  151484. };
  151485. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151486. _vq_quantthresh__44u8_p5_1,
  151487. _vq_quantmap__44u8_p5_1,
  151488. 11,
  151489. 11
  151490. };
  151491. static static_codebook _44u8_p5_1 = {
  151492. 2, 121,
  151493. _vq_lengthlist__44u8_p5_1,
  151494. 1, -531365888, 1611661312, 4, 0,
  151495. _vq_quantlist__44u8_p5_1,
  151496. NULL,
  151497. &_vq_auxt__44u8_p5_1,
  151498. NULL,
  151499. 0
  151500. };
  151501. static long _vq_quantlist__44u8_p6_0[] = {
  151502. 6,
  151503. 5,
  151504. 7,
  151505. 4,
  151506. 8,
  151507. 3,
  151508. 9,
  151509. 2,
  151510. 10,
  151511. 1,
  151512. 11,
  151513. 0,
  151514. 12,
  151515. };
  151516. static long _vq_lengthlist__44u8_p6_0[] = {
  151517. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151518. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151519. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151520. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151521. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151522. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151523. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151524. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151525. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151526. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151527. 11,11,11,11,11,12,11,12,12,
  151528. };
  151529. static float _vq_quantthresh__44u8_p6_0[] = {
  151530. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151531. 12.5, 17.5, 22.5, 27.5,
  151532. };
  151533. static long _vq_quantmap__44u8_p6_0[] = {
  151534. 11, 9, 7, 5, 3, 1, 0, 2,
  151535. 4, 6, 8, 10, 12,
  151536. };
  151537. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151538. _vq_quantthresh__44u8_p6_0,
  151539. _vq_quantmap__44u8_p6_0,
  151540. 13,
  151541. 13
  151542. };
  151543. static static_codebook _44u8_p6_0 = {
  151544. 2, 169,
  151545. _vq_lengthlist__44u8_p6_0,
  151546. 1, -526516224, 1616117760, 4, 0,
  151547. _vq_quantlist__44u8_p6_0,
  151548. NULL,
  151549. &_vq_auxt__44u8_p6_0,
  151550. NULL,
  151551. 0
  151552. };
  151553. static long _vq_quantlist__44u8_p6_1[] = {
  151554. 2,
  151555. 1,
  151556. 3,
  151557. 0,
  151558. 4,
  151559. };
  151560. static long _vq_lengthlist__44u8_p6_1[] = {
  151561. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151562. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151563. };
  151564. static float _vq_quantthresh__44u8_p6_1[] = {
  151565. -1.5, -0.5, 0.5, 1.5,
  151566. };
  151567. static long _vq_quantmap__44u8_p6_1[] = {
  151568. 3, 1, 0, 2, 4,
  151569. };
  151570. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151571. _vq_quantthresh__44u8_p6_1,
  151572. _vq_quantmap__44u8_p6_1,
  151573. 5,
  151574. 5
  151575. };
  151576. static static_codebook _44u8_p6_1 = {
  151577. 2, 25,
  151578. _vq_lengthlist__44u8_p6_1,
  151579. 1, -533725184, 1611661312, 3, 0,
  151580. _vq_quantlist__44u8_p6_1,
  151581. NULL,
  151582. &_vq_auxt__44u8_p6_1,
  151583. NULL,
  151584. 0
  151585. };
  151586. static long _vq_quantlist__44u8_p7_0[] = {
  151587. 6,
  151588. 5,
  151589. 7,
  151590. 4,
  151591. 8,
  151592. 3,
  151593. 9,
  151594. 2,
  151595. 10,
  151596. 1,
  151597. 11,
  151598. 0,
  151599. 12,
  151600. };
  151601. static long _vq_lengthlist__44u8_p7_0[] = {
  151602. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151603. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151604. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151605. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151606. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151607. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151608. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151609. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151610. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151611. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151612. 13,13,14,14,14,15,15,15,16,
  151613. };
  151614. static float _vq_quantthresh__44u8_p7_0[] = {
  151615. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151616. 27.5, 38.5, 49.5, 60.5,
  151617. };
  151618. static long _vq_quantmap__44u8_p7_0[] = {
  151619. 11, 9, 7, 5, 3, 1, 0, 2,
  151620. 4, 6, 8, 10, 12,
  151621. };
  151622. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151623. _vq_quantthresh__44u8_p7_0,
  151624. _vq_quantmap__44u8_p7_0,
  151625. 13,
  151626. 13
  151627. };
  151628. static static_codebook _44u8_p7_0 = {
  151629. 2, 169,
  151630. _vq_lengthlist__44u8_p7_0,
  151631. 1, -523206656, 1618345984, 4, 0,
  151632. _vq_quantlist__44u8_p7_0,
  151633. NULL,
  151634. &_vq_auxt__44u8_p7_0,
  151635. NULL,
  151636. 0
  151637. };
  151638. static long _vq_quantlist__44u8_p7_1[] = {
  151639. 5,
  151640. 4,
  151641. 6,
  151642. 3,
  151643. 7,
  151644. 2,
  151645. 8,
  151646. 1,
  151647. 9,
  151648. 0,
  151649. 10,
  151650. };
  151651. static long _vq_lengthlist__44u8_p7_1[] = {
  151652. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151653. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151654. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151655. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151656. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151657. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151658. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151659. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151660. };
  151661. static float _vq_quantthresh__44u8_p7_1[] = {
  151662. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151663. 3.5, 4.5,
  151664. };
  151665. static long _vq_quantmap__44u8_p7_1[] = {
  151666. 9, 7, 5, 3, 1, 0, 2, 4,
  151667. 6, 8, 10,
  151668. };
  151669. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151670. _vq_quantthresh__44u8_p7_1,
  151671. _vq_quantmap__44u8_p7_1,
  151672. 11,
  151673. 11
  151674. };
  151675. static static_codebook _44u8_p7_1 = {
  151676. 2, 121,
  151677. _vq_lengthlist__44u8_p7_1,
  151678. 1, -531365888, 1611661312, 4, 0,
  151679. _vq_quantlist__44u8_p7_1,
  151680. NULL,
  151681. &_vq_auxt__44u8_p7_1,
  151682. NULL,
  151683. 0
  151684. };
  151685. static long _vq_quantlist__44u8_p8_0[] = {
  151686. 7,
  151687. 6,
  151688. 8,
  151689. 5,
  151690. 9,
  151691. 4,
  151692. 10,
  151693. 3,
  151694. 11,
  151695. 2,
  151696. 12,
  151697. 1,
  151698. 13,
  151699. 0,
  151700. 14,
  151701. };
  151702. static long _vq_lengthlist__44u8_p8_0[] = {
  151703. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151704. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151705. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151706. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151707. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151708. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151709. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151710. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151711. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151712. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151713. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151714. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151715. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151716. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151717. 17,
  151718. };
  151719. static float _vq_quantthresh__44u8_p8_0[] = {
  151720. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151721. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151722. };
  151723. static long _vq_quantmap__44u8_p8_0[] = {
  151724. 13, 11, 9, 7, 5, 3, 1, 0,
  151725. 2, 4, 6, 8, 10, 12, 14,
  151726. };
  151727. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151728. _vq_quantthresh__44u8_p8_0,
  151729. _vq_quantmap__44u8_p8_0,
  151730. 15,
  151731. 15
  151732. };
  151733. static static_codebook _44u8_p8_0 = {
  151734. 2, 225,
  151735. _vq_lengthlist__44u8_p8_0,
  151736. 1, -520986624, 1620377600, 4, 0,
  151737. _vq_quantlist__44u8_p8_0,
  151738. NULL,
  151739. &_vq_auxt__44u8_p8_0,
  151740. NULL,
  151741. 0
  151742. };
  151743. static long _vq_quantlist__44u8_p8_1[] = {
  151744. 10,
  151745. 9,
  151746. 11,
  151747. 8,
  151748. 12,
  151749. 7,
  151750. 13,
  151751. 6,
  151752. 14,
  151753. 5,
  151754. 15,
  151755. 4,
  151756. 16,
  151757. 3,
  151758. 17,
  151759. 2,
  151760. 18,
  151761. 1,
  151762. 19,
  151763. 0,
  151764. 20,
  151765. };
  151766. static long _vq_lengthlist__44u8_p8_1[] = {
  151767. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151768. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151769. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151770. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151771. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151772. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151773. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151774. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151775. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151776. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151777. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151778. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151779. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151780. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151781. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151782. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151783. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151784. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151785. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151786. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151787. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151788. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151789. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151790. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151791. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151792. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151793. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151794. 10,10,10,10,10,10,10,10,10,
  151795. };
  151796. static float _vq_quantthresh__44u8_p8_1[] = {
  151797. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151798. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151799. 6.5, 7.5, 8.5, 9.5,
  151800. };
  151801. static long _vq_quantmap__44u8_p8_1[] = {
  151802. 19, 17, 15, 13, 11, 9, 7, 5,
  151803. 3, 1, 0, 2, 4, 6, 8, 10,
  151804. 12, 14, 16, 18, 20,
  151805. };
  151806. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151807. _vq_quantthresh__44u8_p8_1,
  151808. _vq_quantmap__44u8_p8_1,
  151809. 21,
  151810. 21
  151811. };
  151812. static static_codebook _44u8_p8_1 = {
  151813. 2, 441,
  151814. _vq_lengthlist__44u8_p8_1,
  151815. 1, -529268736, 1611661312, 5, 0,
  151816. _vq_quantlist__44u8_p8_1,
  151817. NULL,
  151818. &_vq_auxt__44u8_p8_1,
  151819. NULL,
  151820. 0
  151821. };
  151822. static long _vq_quantlist__44u8_p9_0[] = {
  151823. 4,
  151824. 3,
  151825. 5,
  151826. 2,
  151827. 6,
  151828. 1,
  151829. 7,
  151830. 0,
  151831. 8,
  151832. };
  151833. static long _vq_lengthlist__44u8_p9_0[] = {
  151834. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151835. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151836. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151837. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151838. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151839. 8,
  151840. };
  151841. static float _vq_quantthresh__44u8_p9_0[] = {
  151842. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151843. };
  151844. static long _vq_quantmap__44u8_p9_0[] = {
  151845. 7, 5, 3, 1, 0, 2, 4, 6,
  151846. 8,
  151847. };
  151848. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151849. _vq_quantthresh__44u8_p9_0,
  151850. _vq_quantmap__44u8_p9_0,
  151851. 9,
  151852. 9
  151853. };
  151854. static static_codebook _44u8_p9_0 = {
  151855. 2, 81,
  151856. _vq_lengthlist__44u8_p9_0,
  151857. 1, -511895552, 1631393792, 4, 0,
  151858. _vq_quantlist__44u8_p9_0,
  151859. NULL,
  151860. &_vq_auxt__44u8_p9_0,
  151861. NULL,
  151862. 0
  151863. };
  151864. static long _vq_quantlist__44u8_p9_1[] = {
  151865. 9,
  151866. 8,
  151867. 10,
  151868. 7,
  151869. 11,
  151870. 6,
  151871. 12,
  151872. 5,
  151873. 13,
  151874. 4,
  151875. 14,
  151876. 3,
  151877. 15,
  151878. 2,
  151879. 16,
  151880. 1,
  151881. 17,
  151882. 0,
  151883. 18,
  151884. };
  151885. static long _vq_lengthlist__44u8_p9_1[] = {
  151886. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151887. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151888. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151889. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151890. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151891. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151892. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151893. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151894. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151895. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151896. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151897. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151898. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151899. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151900. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151901. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151902. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151903. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151904. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151905. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151906. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151907. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151908. 16,15,16,16,16,16,16,16,16,
  151909. };
  151910. static float _vq_quantthresh__44u8_p9_1[] = {
  151911. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151912. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151913. 367.5, 416.5,
  151914. };
  151915. static long _vq_quantmap__44u8_p9_1[] = {
  151916. 17, 15, 13, 11, 9, 7, 5, 3,
  151917. 1, 0, 2, 4, 6, 8, 10, 12,
  151918. 14, 16, 18,
  151919. };
  151920. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151921. _vq_quantthresh__44u8_p9_1,
  151922. _vq_quantmap__44u8_p9_1,
  151923. 19,
  151924. 19
  151925. };
  151926. static static_codebook _44u8_p9_1 = {
  151927. 2, 361,
  151928. _vq_lengthlist__44u8_p9_1,
  151929. 1, -518287360, 1622704128, 5, 0,
  151930. _vq_quantlist__44u8_p9_1,
  151931. NULL,
  151932. &_vq_auxt__44u8_p9_1,
  151933. NULL,
  151934. 0
  151935. };
  151936. static long _vq_quantlist__44u8_p9_2[] = {
  151937. 24,
  151938. 23,
  151939. 25,
  151940. 22,
  151941. 26,
  151942. 21,
  151943. 27,
  151944. 20,
  151945. 28,
  151946. 19,
  151947. 29,
  151948. 18,
  151949. 30,
  151950. 17,
  151951. 31,
  151952. 16,
  151953. 32,
  151954. 15,
  151955. 33,
  151956. 14,
  151957. 34,
  151958. 13,
  151959. 35,
  151960. 12,
  151961. 36,
  151962. 11,
  151963. 37,
  151964. 10,
  151965. 38,
  151966. 9,
  151967. 39,
  151968. 8,
  151969. 40,
  151970. 7,
  151971. 41,
  151972. 6,
  151973. 42,
  151974. 5,
  151975. 43,
  151976. 4,
  151977. 44,
  151978. 3,
  151979. 45,
  151980. 2,
  151981. 46,
  151982. 1,
  151983. 47,
  151984. 0,
  151985. 48,
  151986. };
  151987. static long _vq_lengthlist__44u8_p9_2[] = {
  151988. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151989. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151990. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151991. 7,
  151992. };
  151993. static float _vq_quantthresh__44u8_p9_2[] = {
  151994. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151995. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151996. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151997. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151998. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151999. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152000. };
  152001. static long _vq_quantmap__44u8_p9_2[] = {
  152002. 47, 45, 43, 41, 39, 37, 35, 33,
  152003. 31, 29, 27, 25, 23, 21, 19, 17,
  152004. 15, 13, 11, 9, 7, 5, 3, 1,
  152005. 0, 2, 4, 6, 8, 10, 12, 14,
  152006. 16, 18, 20, 22, 24, 26, 28, 30,
  152007. 32, 34, 36, 38, 40, 42, 44, 46,
  152008. 48,
  152009. };
  152010. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  152011. _vq_quantthresh__44u8_p9_2,
  152012. _vq_quantmap__44u8_p9_2,
  152013. 49,
  152014. 49
  152015. };
  152016. static static_codebook _44u8_p9_2 = {
  152017. 1, 49,
  152018. _vq_lengthlist__44u8_p9_2,
  152019. 1, -526909440, 1611661312, 6, 0,
  152020. _vq_quantlist__44u8_p9_2,
  152021. NULL,
  152022. &_vq_auxt__44u8_p9_2,
  152023. NULL,
  152024. 0
  152025. };
  152026. static long _huff_lengthlist__44u9__long[] = {
  152027. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  152028. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  152029. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152030. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152031. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152032. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152033. 10, 8, 8, 9,
  152034. };
  152035. static static_codebook _huff_book__44u9__long = {
  152036. 2, 100,
  152037. _huff_lengthlist__44u9__long,
  152038. 0, 0, 0, 0, 0,
  152039. NULL,
  152040. NULL,
  152041. NULL,
  152042. NULL,
  152043. 0
  152044. };
  152045. static long _huff_lengthlist__44u9__short[] = {
  152046. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152047. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152048. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152049. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152050. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152051. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152052. 9, 9,12,15,
  152053. };
  152054. static static_codebook _huff_book__44u9__short = {
  152055. 2, 100,
  152056. _huff_lengthlist__44u9__short,
  152057. 0, 0, 0, 0, 0,
  152058. NULL,
  152059. NULL,
  152060. NULL,
  152061. NULL,
  152062. 0
  152063. };
  152064. static long _vq_quantlist__44u9_p1_0[] = {
  152065. 1,
  152066. 0,
  152067. 2,
  152068. };
  152069. static long _vq_lengthlist__44u9_p1_0[] = {
  152070. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152071. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152072. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152073. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152074. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152075. 10,
  152076. };
  152077. static float _vq_quantthresh__44u9_p1_0[] = {
  152078. -0.5, 0.5,
  152079. };
  152080. static long _vq_quantmap__44u9_p1_0[] = {
  152081. 1, 0, 2,
  152082. };
  152083. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152084. _vq_quantthresh__44u9_p1_0,
  152085. _vq_quantmap__44u9_p1_0,
  152086. 3,
  152087. 3
  152088. };
  152089. static static_codebook _44u9_p1_0 = {
  152090. 4, 81,
  152091. _vq_lengthlist__44u9_p1_0,
  152092. 1, -535822336, 1611661312, 2, 0,
  152093. _vq_quantlist__44u9_p1_0,
  152094. NULL,
  152095. &_vq_auxt__44u9_p1_0,
  152096. NULL,
  152097. 0
  152098. };
  152099. static long _vq_quantlist__44u9_p2_0[] = {
  152100. 2,
  152101. 1,
  152102. 3,
  152103. 0,
  152104. 4,
  152105. };
  152106. static long _vq_lengthlist__44u9_p2_0[] = {
  152107. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152108. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152109. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152110. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152111. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152112. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152113. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152114. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152115. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152116. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152117. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152118. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152119. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152120. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152121. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152122. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152123. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152124. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152125. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152126. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152127. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152128. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152129. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152130. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152131. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152132. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152133. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152134. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152135. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152136. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152137. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152138. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152139. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152140. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152141. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152142. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152143. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152144. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152145. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152146. 14,
  152147. };
  152148. static float _vq_quantthresh__44u9_p2_0[] = {
  152149. -1.5, -0.5, 0.5, 1.5,
  152150. };
  152151. static long _vq_quantmap__44u9_p2_0[] = {
  152152. 3, 1, 0, 2, 4,
  152153. };
  152154. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152155. _vq_quantthresh__44u9_p2_0,
  152156. _vq_quantmap__44u9_p2_0,
  152157. 5,
  152158. 5
  152159. };
  152160. static static_codebook _44u9_p2_0 = {
  152161. 4, 625,
  152162. _vq_lengthlist__44u9_p2_0,
  152163. 1, -533725184, 1611661312, 3, 0,
  152164. _vq_quantlist__44u9_p2_0,
  152165. NULL,
  152166. &_vq_auxt__44u9_p2_0,
  152167. NULL,
  152168. 0
  152169. };
  152170. static long _vq_quantlist__44u9_p3_0[] = {
  152171. 4,
  152172. 3,
  152173. 5,
  152174. 2,
  152175. 6,
  152176. 1,
  152177. 7,
  152178. 0,
  152179. 8,
  152180. };
  152181. static long _vq_lengthlist__44u9_p3_0[] = {
  152182. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152183. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152184. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152185. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152186. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152187. 11,
  152188. };
  152189. static float _vq_quantthresh__44u9_p3_0[] = {
  152190. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152191. };
  152192. static long _vq_quantmap__44u9_p3_0[] = {
  152193. 7, 5, 3, 1, 0, 2, 4, 6,
  152194. 8,
  152195. };
  152196. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152197. _vq_quantthresh__44u9_p3_0,
  152198. _vq_quantmap__44u9_p3_0,
  152199. 9,
  152200. 9
  152201. };
  152202. static static_codebook _44u9_p3_0 = {
  152203. 2, 81,
  152204. _vq_lengthlist__44u9_p3_0,
  152205. 1, -531628032, 1611661312, 4, 0,
  152206. _vq_quantlist__44u9_p3_0,
  152207. NULL,
  152208. &_vq_auxt__44u9_p3_0,
  152209. NULL,
  152210. 0
  152211. };
  152212. static long _vq_quantlist__44u9_p4_0[] = {
  152213. 8,
  152214. 7,
  152215. 9,
  152216. 6,
  152217. 10,
  152218. 5,
  152219. 11,
  152220. 4,
  152221. 12,
  152222. 3,
  152223. 13,
  152224. 2,
  152225. 14,
  152226. 1,
  152227. 15,
  152228. 0,
  152229. 16,
  152230. };
  152231. static long _vq_lengthlist__44u9_p4_0[] = {
  152232. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152233. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152234. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152235. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152236. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152237. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152238. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152239. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152240. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152241. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152242. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152243. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152244. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152245. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152246. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152247. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152248. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152249. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152250. 14,
  152251. };
  152252. static float _vq_quantthresh__44u9_p4_0[] = {
  152253. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152254. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152255. };
  152256. static long _vq_quantmap__44u9_p4_0[] = {
  152257. 15, 13, 11, 9, 7, 5, 3, 1,
  152258. 0, 2, 4, 6, 8, 10, 12, 14,
  152259. 16,
  152260. };
  152261. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152262. _vq_quantthresh__44u9_p4_0,
  152263. _vq_quantmap__44u9_p4_0,
  152264. 17,
  152265. 17
  152266. };
  152267. static static_codebook _44u9_p4_0 = {
  152268. 2, 289,
  152269. _vq_lengthlist__44u9_p4_0,
  152270. 1, -529530880, 1611661312, 5, 0,
  152271. _vq_quantlist__44u9_p4_0,
  152272. NULL,
  152273. &_vq_auxt__44u9_p4_0,
  152274. NULL,
  152275. 0
  152276. };
  152277. static long _vq_quantlist__44u9_p5_0[] = {
  152278. 1,
  152279. 0,
  152280. 2,
  152281. };
  152282. static long _vq_lengthlist__44u9_p5_0[] = {
  152283. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152284. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152285. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152286. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152287. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152288. 10,
  152289. };
  152290. static float _vq_quantthresh__44u9_p5_0[] = {
  152291. -5.5, 5.5,
  152292. };
  152293. static long _vq_quantmap__44u9_p5_0[] = {
  152294. 1, 0, 2,
  152295. };
  152296. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152297. _vq_quantthresh__44u9_p5_0,
  152298. _vq_quantmap__44u9_p5_0,
  152299. 3,
  152300. 3
  152301. };
  152302. static static_codebook _44u9_p5_0 = {
  152303. 4, 81,
  152304. _vq_lengthlist__44u9_p5_0,
  152305. 1, -529137664, 1618345984, 2, 0,
  152306. _vq_quantlist__44u9_p5_0,
  152307. NULL,
  152308. &_vq_auxt__44u9_p5_0,
  152309. NULL,
  152310. 0
  152311. };
  152312. static long _vq_quantlist__44u9_p5_1[] = {
  152313. 5,
  152314. 4,
  152315. 6,
  152316. 3,
  152317. 7,
  152318. 2,
  152319. 8,
  152320. 1,
  152321. 9,
  152322. 0,
  152323. 10,
  152324. };
  152325. static long _vq_lengthlist__44u9_p5_1[] = {
  152326. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152327. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152328. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152329. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152330. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152331. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152332. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152333. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152334. };
  152335. static float _vq_quantthresh__44u9_p5_1[] = {
  152336. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152337. 3.5, 4.5,
  152338. };
  152339. static long _vq_quantmap__44u9_p5_1[] = {
  152340. 9, 7, 5, 3, 1, 0, 2, 4,
  152341. 6, 8, 10,
  152342. };
  152343. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152344. _vq_quantthresh__44u9_p5_1,
  152345. _vq_quantmap__44u9_p5_1,
  152346. 11,
  152347. 11
  152348. };
  152349. static static_codebook _44u9_p5_1 = {
  152350. 2, 121,
  152351. _vq_lengthlist__44u9_p5_1,
  152352. 1, -531365888, 1611661312, 4, 0,
  152353. _vq_quantlist__44u9_p5_1,
  152354. NULL,
  152355. &_vq_auxt__44u9_p5_1,
  152356. NULL,
  152357. 0
  152358. };
  152359. static long _vq_quantlist__44u9_p6_0[] = {
  152360. 6,
  152361. 5,
  152362. 7,
  152363. 4,
  152364. 8,
  152365. 3,
  152366. 9,
  152367. 2,
  152368. 10,
  152369. 1,
  152370. 11,
  152371. 0,
  152372. 12,
  152373. };
  152374. static long _vq_lengthlist__44u9_p6_0[] = {
  152375. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152376. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152377. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152378. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152379. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152380. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152381. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152382. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152383. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152384. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152385. 10,11,11,11,11,12,11,12,12,
  152386. };
  152387. static float _vq_quantthresh__44u9_p6_0[] = {
  152388. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152389. 12.5, 17.5, 22.5, 27.5,
  152390. };
  152391. static long _vq_quantmap__44u9_p6_0[] = {
  152392. 11, 9, 7, 5, 3, 1, 0, 2,
  152393. 4, 6, 8, 10, 12,
  152394. };
  152395. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152396. _vq_quantthresh__44u9_p6_0,
  152397. _vq_quantmap__44u9_p6_0,
  152398. 13,
  152399. 13
  152400. };
  152401. static static_codebook _44u9_p6_0 = {
  152402. 2, 169,
  152403. _vq_lengthlist__44u9_p6_0,
  152404. 1, -526516224, 1616117760, 4, 0,
  152405. _vq_quantlist__44u9_p6_0,
  152406. NULL,
  152407. &_vq_auxt__44u9_p6_0,
  152408. NULL,
  152409. 0
  152410. };
  152411. static long _vq_quantlist__44u9_p6_1[] = {
  152412. 2,
  152413. 1,
  152414. 3,
  152415. 0,
  152416. 4,
  152417. };
  152418. static long _vq_lengthlist__44u9_p6_1[] = {
  152419. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152420. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152421. };
  152422. static float _vq_quantthresh__44u9_p6_1[] = {
  152423. -1.5, -0.5, 0.5, 1.5,
  152424. };
  152425. static long _vq_quantmap__44u9_p6_1[] = {
  152426. 3, 1, 0, 2, 4,
  152427. };
  152428. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152429. _vq_quantthresh__44u9_p6_1,
  152430. _vq_quantmap__44u9_p6_1,
  152431. 5,
  152432. 5
  152433. };
  152434. static static_codebook _44u9_p6_1 = {
  152435. 2, 25,
  152436. _vq_lengthlist__44u9_p6_1,
  152437. 1, -533725184, 1611661312, 3, 0,
  152438. _vq_quantlist__44u9_p6_1,
  152439. NULL,
  152440. &_vq_auxt__44u9_p6_1,
  152441. NULL,
  152442. 0
  152443. };
  152444. static long _vq_quantlist__44u9_p7_0[] = {
  152445. 6,
  152446. 5,
  152447. 7,
  152448. 4,
  152449. 8,
  152450. 3,
  152451. 9,
  152452. 2,
  152453. 10,
  152454. 1,
  152455. 11,
  152456. 0,
  152457. 12,
  152458. };
  152459. static long _vq_lengthlist__44u9_p7_0[] = {
  152460. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152461. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152462. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152463. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152464. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152465. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152466. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152467. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152468. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152469. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152470. 12,13,13,14,14,14,15,15,15,
  152471. };
  152472. static float _vq_quantthresh__44u9_p7_0[] = {
  152473. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152474. 27.5, 38.5, 49.5, 60.5,
  152475. };
  152476. static long _vq_quantmap__44u9_p7_0[] = {
  152477. 11, 9, 7, 5, 3, 1, 0, 2,
  152478. 4, 6, 8, 10, 12,
  152479. };
  152480. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152481. _vq_quantthresh__44u9_p7_0,
  152482. _vq_quantmap__44u9_p7_0,
  152483. 13,
  152484. 13
  152485. };
  152486. static static_codebook _44u9_p7_0 = {
  152487. 2, 169,
  152488. _vq_lengthlist__44u9_p7_0,
  152489. 1, -523206656, 1618345984, 4, 0,
  152490. _vq_quantlist__44u9_p7_0,
  152491. NULL,
  152492. &_vq_auxt__44u9_p7_0,
  152493. NULL,
  152494. 0
  152495. };
  152496. static long _vq_quantlist__44u9_p7_1[] = {
  152497. 5,
  152498. 4,
  152499. 6,
  152500. 3,
  152501. 7,
  152502. 2,
  152503. 8,
  152504. 1,
  152505. 9,
  152506. 0,
  152507. 10,
  152508. };
  152509. static long _vq_lengthlist__44u9_p7_1[] = {
  152510. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152511. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152512. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152513. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152514. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152515. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152516. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152517. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152518. };
  152519. static float _vq_quantthresh__44u9_p7_1[] = {
  152520. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152521. 3.5, 4.5,
  152522. };
  152523. static long _vq_quantmap__44u9_p7_1[] = {
  152524. 9, 7, 5, 3, 1, 0, 2, 4,
  152525. 6, 8, 10,
  152526. };
  152527. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152528. _vq_quantthresh__44u9_p7_1,
  152529. _vq_quantmap__44u9_p7_1,
  152530. 11,
  152531. 11
  152532. };
  152533. static static_codebook _44u9_p7_1 = {
  152534. 2, 121,
  152535. _vq_lengthlist__44u9_p7_1,
  152536. 1, -531365888, 1611661312, 4, 0,
  152537. _vq_quantlist__44u9_p7_1,
  152538. NULL,
  152539. &_vq_auxt__44u9_p7_1,
  152540. NULL,
  152541. 0
  152542. };
  152543. static long _vq_quantlist__44u9_p8_0[] = {
  152544. 7,
  152545. 6,
  152546. 8,
  152547. 5,
  152548. 9,
  152549. 4,
  152550. 10,
  152551. 3,
  152552. 11,
  152553. 2,
  152554. 12,
  152555. 1,
  152556. 13,
  152557. 0,
  152558. 14,
  152559. };
  152560. static long _vq_lengthlist__44u9_p8_0[] = {
  152561. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152562. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152563. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152564. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152565. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152566. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152567. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152568. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152569. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152570. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152571. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152572. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152573. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152574. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152575. 15,
  152576. };
  152577. static float _vq_quantthresh__44u9_p8_0[] = {
  152578. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152579. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152580. };
  152581. static long _vq_quantmap__44u9_p8_0[] = {
  152582. 13, 11, 9, 7, 5, 3, 1, 0,
  152583. 2, 4, 6, 8, 10, 12, 14,
  152584. };
  152585. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152586. _vq_quantthresh__44u9_p8_0,
  152587. _vq_quantmap__44u9_p8_0,
  152588. 15,
  152589. 15
  152590. };
  152591. static static_codebook _44u9_p8_0 = {
  152592. 2, 225,
  152593. _vq_lengthlist__44u9_p8_0,
  152594. 1, -520986624, 1620377600, 4, 0,
  152595. _vq_quantlist__44u9_p8_0,
  152596. NULL,
  152597. &_vq_auxt__44u9_p8_0,
  152598. NULL,
  152599. 0
  152600. };
  152601. static long _vq_quantlist__44u9_p8_1[] = {
  152602. 10,
  152603. 9,
  152604. 11,
  152605. 8,
  152606. 12,
  152607. 7,
  152608. 13,
  152609. 6,
  152610. 14,
  152611. 5,
  152612. 15,
  152613. 4,
  152614. 16,
  152615. 3,
  152616. 17,
  152617. 2,
  152618. 18,
  152619. 1,
  152620. 19,
  152621. 0,
  152622. 20,
  152623. };
  152624. static long _vq_lengthlist__44u9_p8_1[] = {
  152625. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152626. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152627. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152628. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152629. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152630. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152631. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152632. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152633. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152634. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152635. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152636. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152637. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152638. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152639. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152640. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152641. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152642. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152643. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152644. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152645. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152646. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152647. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152648. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152650. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152651. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152652. 10,10,10,10,10,10,10,10,10,
  152653. };
  152654. static float _vq_quantthresh__44u9_p8_1[] = {
  152655. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152656. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152657. 6.5, 7.5, 8.5, 9.5,
  152658. };
  152659. static long _vq_quantmap__44u9_p8_1[] = {
  152660. 19, 17, 15, 13, 11, 9, 7, 5,
  152661. 3, 1, 0, 2, 4, 6, 8, 10,
  152662. 12, 14, 16, 18, 20,
  152663. };
  152664. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152665. _vq_quantthresh__44u9_p8_1,
  152666. _vq_quantmap__44u9_p8_1,
  152667. 21,
  152668. 21
  152669. };
  152670. static static_codebook _44u9_p8_1 = {
  152671. 2, 441,
  152672. _vq_lengthlist__44u9_p8_1,
  152673. 1, -529268736, 1611661312, 5, 0,
  152674. _vq_quantlist__44u9_p8_1,
  152675. NULL,
  152676. &_vq_auxt__44u9_p8_1,
  152677. NULL,
  152678. 0
  152679. };
  152680. static long _vq_quantlist__44u9_p9_0[] = {
  152681. 7,
  152682. 6,
  152683. 8,
  152684. 5,
  152685. 9,
  152686. 4,
  152687. 10,
  152688. 3,
  152689. 11,
  152690. 2,
  152691. 12,
  152692. 1,
  152693. 13,
  152694. 0,
  152695. 14,
  152696. };
  152697. static long _vq_lengthlist__44u9_p9_0[] = {
  152698. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152699. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152700. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152711. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152712. 10,
  152713. };
  152714. static float _vq_quantthresh__44u9_p9_0[] = {
  152715. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152716. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152717. };
  152718. static long _vq_quantmap__44u9_p9_0[] = {
  152719. 13, 11, 9, 7, 5, 3, 1, 0,
  152720. 2, 4, 6, 8, 10, 12, 14,
  152721. };
  152722. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152723. _vq_quantthresh__44u9_p9_0,
  152724. _vq_quantmap__44u9_p9_0,
  152725. 15,
  152726. 15
  152727. };
  152728. static static_codebook _44u9_p9_0 = {
  152729. 2, 225,
  152730. _vq_lengthlist__44u9_p9_0,
  152731. 1, -510036736, 1631393792, 4, 0,
  152732. _vq_quantlist__44u9_p9_0,
  152733. NULL,
  152734. &_vq_auxt__44u9_p9_0,
  152735. NULL,
  152736. 0
  152737. };
  152738. static long _vq_quantlist__44u9_p9_1[] = {
  152739. 9,
  152740. 8,
  152741. 10,
  152742. 7,
  152743. 11,
  152744. 6,
  152745. 12,
  152746. 5,
  152747. 13,
  152748. 4,
  152749. 14,
  152750. 3,
  152751. 15,
  152752. 2,
  152753. 16,
  152754. 1,
  152755. 17,
  152756. 0,
  152757. 18,
  152758. };
  152759. static long _vq_lengthlist__44u9_p9_1[] = {
  152760. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152761. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152762. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152763. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152764. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152765. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152766. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152767. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152768. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152769. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152770. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152771. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152772. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152773. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152774. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152775. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152776. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152777. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152778. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152779. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152780. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152781. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152782. 17,17,15,17,15,17,16,16,17,
  152783. };
  152784. static float _vq_quantthresh__44u9_p9_1[] = {
  152785. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152786. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152787. 367.5, 416.5,
  152788. };
  152789. static long _vq_quantmap__44u9_p9_1[] = {
  152790. 17, 15, 13, 11, 9, 7, 5, 3,
  152791. 1, 0, 2, 4, 6, 8, 10, 12,
  152792. 14, 16, 18,
  152793. };
  152794. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152795. _vq_quantthresh__44u9_p9_1,
  152796. _vq_quantmap__44u9_p9_1,
  152797. 19,
  152798. 19
  152799. };
  152800. static static_codebook _44u9_p9_1 = {
  152801. 2, 361,
  152802. _vq_lengthlist__44u9_p9_1,
  152803. 1, -518287360, 1622704128, 5, 0,
  152804. _vq_quantlist__44u9_p9_1,
  152805. NULL,
  152806. &_vq_auxt__44u9_p9_1,
  152807. NULL,
  152808. 0
  152809. };
  152810. static long _vq_quantlist__44u9_p9_2[] = {
  152811. 24,
  152812. 23,
  152813. 25,
  152814. 22,
  152815. 26,
  152816. 21,
  152817. 27,
  152818. 20,
  152819. 28,
  152820. 19,
  152821. 29,
  152822. 18,
  152823. 30,
  152824. 17,
  152825. 31,
  152826. 16,
  152827. 32,
  152828. 15,
  152829. 33,
  152830. 14,
  152831. 34,
  152832. 13,
  152833. 35,
  152834. 12,
  152835. 36,
  152836. 11,
  152837. 37,
  152838. 10,
  152839. 38,
  152840. 9,
  152841. 39,
  152842. 8,
  152843. 40,
  152844. 7,
  152845. 41,
  152846. 6,
  152847. 42,
  152848. 5,
  152849. 43,
  152850. 4,
  152851. 44,
  152852. 3,
  152853. 45,
  152854. 2,
  152855. 46,
  152856. 1,
  152857. 47,
  152858. 0,
  152859. 48,
  152860. };
  152861. static long _vq_lengthlist__44u9_p9_2[] = {
  152862. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152863. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152864. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152865. 7,
  152866. };
  152867. static float _vq_quantthresh__44u9_p9_2[] = {
  152868. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152869. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152870. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152871. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152872. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152873. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152874. };
  152875. static long _vq_quantmap__44u9_p9_2[] = {
  152876. 47, 45, 43, 41, 39, 37, 35, 33,
  152877. 31, 29, 27, 25, 23, 21, 19, 17,
  152878. 15, 13, 11, 9, 7, 5, 3, 1,
  152879. 0, 2, 4, 6, 8, 10, 12, 14,
  152880. 16, 18, 20, 22, 24, 26, 28, 30,
  152881. 32, 34, 36, 38, 40, 42, 44, 46,
  152882. 48,
  152883. };
  152884. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152885. _vq_quantthresh__44u9_p9_2,
  152886. _vq_quantmap__44u9_p9_2,
  152887. 49,
  152888. 49
  152889. };
  152890. static static_codebook _44u9_p9_2 = {
  152891. 1, 49,
  152892. _vq_lengthlist__44u9_p9_2,
  152893. 1, -526909440, 1611661312, 6, 0,
  152894. _vq_quantlist__44u9_p9_2,
  152895. NULL,
  152896. &_vq_auxt__44u9_p9_2,
  152897. NULL,
  152898. 0
  152899. };
  152900. static long _huff_lengthlist__44un1__long[] = {
  152901. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152902. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152903. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152904. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152905. };
  152906. static static_codebook _huff_book__44un1__long = {
  152907. 2, 64,
  152908. _huff_lengthlist__44un1__long,
  152909. 0, 0, 0, 0, 0,
  152910. NULL,
  152911. NULL,
  152912. NULL,
  152913. NULL,
  152914. 0
  152915. };
  152916. static long _vq_quantlist__44un1__p1_0[] = {
  152917. 1,
  152918. 0,
  152919. 2,
  152920. };
  152921. static long _vq_lengthlist__44un1__p1_0[] = {
  152922. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152923. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152924. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152925. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152926. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152927. 12,
  152928. };
  152929. static float _vq_quantthresh__44un1__p1_0[] = {
  152930. -0.5, 0.5,
  152931. };
  152932. static long _vq_quantmap__44un1__p1_0[] = {
  152933. 1, 0, 2,
  152934. };
  152935. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152936. _vq_quantthresh__44un1__p1_0,
  152937. _vq_quantmap__44un1__p1_0,
  152938. 3,
  152939. 3
  152940. };
  152941. static static_codebook _44un1__p1_0 = {
  152942. 4, 81,
  152943. _vq_lengthlist__44un1__p1_0,
  152944. 1, -535822336, 1611661312, 2, 0,
  152945. _vq_quantlist__44un1__p1_0,
  152946. NULL,
  152947. &_vq_auxt__44un1__p1_0,
  152948. NULL,
  152949. 0
  152950. };
  152951. static long _vq_quantlist__44un1__p2_0[] = {
  152952. 1,
  152953. 0,
  152954. 2,
  152955. };
  152956. static long _vq_lengthlist__44un1__p2_0[] = {
  152957. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152958. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152959. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152960. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152961. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152962. 8,
  152963. };
  152964. static float _vq_quantthresh__44un1__p2_0[] = {
  152965. -0.5, 0.5,
  152966. };
  152967. static long _vq_quantmap__44un1__p2_0[] = {
  152968. 1, 0, 2,
  152969. };
  152970. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152971. _vq_quantthresh__44un1__p2_0,
  152972. _vq_quantmap__44un1__p2_0,
  152973. 3,
  152974. 3
  152975. };
  152976. static static_codebook _44un1__p2_0 = {
  152977. 4, 81,
  152978. _vq_lengthlist__44un1__p2_0,
  152979. 1, -535822336, 1611661312, 2, 0,
  152980. _vq_quantlist__44un1__p2_0,
  152981. NULL,
  152982. &_vq_auxt__44un1__p2_0,
  152983. NULL,
  152984. 0
  152985. };
  152986. static long _vq_quantlist__44un1__p3_0[] = {
  152987. 2,
  152988. 1,
  152989. 3,
  152990. 0,
  152991. 4,
  152992. };
  152993. static long _vq_lengthlist__44un1__p3_0[] = {
  152994. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152995. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152996. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152997. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152998. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152999. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  153000. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  153001. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  153002. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  153003. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  153004. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  153005. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  153006. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  153007. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  153008. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  153009. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  153010. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  153011. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  153012. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  153013. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  153014. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  153015. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  153016. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  153017. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  153018. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  153019. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  153020. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  153021. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  153022. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  153023. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  153024. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  153025. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  153026. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  153027. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  153028. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  153029. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153030. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153031. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153032. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153033. 17,
  153034. };
  153035. static float _vq_quantthresh__44un1__p3_0[] = {
  153036. -1.5, -0.5, 0.5, 1.5,
  153037. };
  153038. static long _vq_quantmap__44un1__p3_0[] = {
  153039. 3, 1, 0, 2, 4,
  153040. };
  153041. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153042. _vq_quantthresh__44un1__p3_0,
  153043. _vq_quantmap__44un1__p3_0,
  153044. 5,
  153045. 5
  153046. };
  153047. static static_codebook _44un1__p3_0 = {
  153048. 4, 625,
  153049. _vq_lengthlist__44un1__p3_0,
  153050. 1, -533725184, 1611661312, 3, 0,
  153051. _vq_quantlist__44un1__p3_0,
  153052. NULL,
  153053. &_vq_auxt__44un1__p3_0,
  153054. NULL,
  153055. 0
  153056. };
  153057. static long _vq_quantlist__44un1__p4_0[] = {
  153058. 2,
  153059. 1,
  153060. 3,
  153061. 0,
  153062. 4,
  153063. };
  153064. static long _vq_lengthlist__44un1__p4_0[] = {
  153065. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153066. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153067. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153068. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153069. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153070. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153071. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153072. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153073. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153074. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153075. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153076. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153077. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153078. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153079. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153080. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153081. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153082. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153083. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153084. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153085. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153086. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153087. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153088. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153089. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153090. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153091. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153092. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153093. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153094. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153095. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153096. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153097. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153098. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153099. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153100. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153101. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153102. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153103. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153104. 12,
  153105. };
  153106. static float _vq_quantthresh__44un1__p4_0[] = {
  153107. -1.5, -0.5, 0.5, 1.5,
  153108. };
  153109. static long _vq_quantmap__44un1__p4_0[] = {
  153110. 3, 1, 0, 2, 4,
  153111. };
  153112. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153113. _vq_quantthresh__44un1__p4_0,
  153114. _vq_quantmap__44un1__p4_0,
  153115. 5,
  153116. 5
  153117. };
  153118. static static_codebook _44un1__p4_0 = {
  153119. 4, 625,
  153120. _vq_lengthlist__44un1__p4_0,
  153121. 1, -533725184, 1611661312, 3, 0,
  153122. _vq_quantlist__44un1__p4_0,
  153123. NULL,
  153124. &_vq_auxt__44un1__p4_0,
  153125. NULL,
  153126. 0
  153127. };
  153128. static long _vq_quantlist__44un1__p5_0[] = {
  153129. 4,
  153130. 3,
  153131. 5,
  153132. 2,
  153133. 6,
  153134. 1,
  153135. 7,
  153136. 0,
  153137. 8,
  153138. };
  153139. static long _vq_lengthlist__44un1__p5_0[] = {
  153140. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153141. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153142. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153143. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153144. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153145. 12,
  153146. };
  153147. static float _vq_quantthresh__44un1__p5_0[] = {
  153148. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153149. };
  153150. static long _vq_quantmap__44un1__p5_0[] = {
  153151. 7, 5, 3, 1, 0, 2, 4, 6,
  153152. 8,
  153153. };
  153154. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153155. _vq_quantthresh__44un1__p5_0,
  153156. _vq_quantmap__44un1__p5_0,
  153157. 9,
  153158. 9
  153159. };
  153160. static static_codebook _44un1__p5_0 = {
  153161. 2, 81,
  153162. _vq_lengthlist__44un1__p5_0,
  153163. 1, -531628032, 1611661312, 4, 0,
  153164. _vq_quantlist__44un1__p5_0,
  153165. NULL,
  153166. &_vq_auxt__44un1__p5_0,
  153167. NULL,
  153168. 0
  153169. };
  153170. static long _vq_quantlist__44un1__p6_0[] = {
  153171. 6,
  153172. 5,
  153173. 7,
  153174. 4,
  153175. 8,
  153176. 3,
  153177. 9,
  153178. 2,
  153179. 10,
  153180. 1,
  153181. 11,
  153182. 0,
  153183. 12,
  153184. };
  153185. static long _vq_lengthlist__44un1__p6_0[] = {
  153186. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153187. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153188. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153189. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153190. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153191. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153192. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153193. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153194. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153195. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153196. 16, 0,15,18,18, 0,16, 0, 0,
  153197. };
  153198. static float _vq_quantthresh__44un1__p6_0[] = {
  153199. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153200. 12.5, 17.5, 22.5, 27.5,
  153201. };
  153202. static long _vq_quantmap__44un1__p6_0[] = {
  153203. 11, 9, 7, 5, 3, 1, 0, 2,
  153204. 4, 6, 8, 10, 12,
  153205. };
  153206. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153207. _vq_quantthresh__44un1__p6_0,
  153208. _vq_quantmap__44un1__p6_0,
  153209. 13,
  153210. 13
  153211. };
  153212. static static_codebook _44un1__p6_0 = {
  153213. 2, 169,
  153214. _vq_lengthlist__44un1__p6_0,
  153215. 1, -526516224, 1616117760, 4, 0,
  153216. _vq_quantlist__44un1__p6_0,
  153217. NULL,
  153218. &_vq_auxt__44un1__p6_0,
  153219. NULL,
  153220. 0
  153221. };
  153222. static long _vq_quantlist__44un1__p6_1[] = {
  153223. 2,
  153224. 1,
  153225. 3,
  153226. 0,
  153227. 4,
  153228. };
  153229. static long _vq_lengthlist__44un1__p6_1[] = {
  153230. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153231. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153232. };
  153233. static float _vq_quantthresh__44un1__p6_1[] = {
  153234. -1.5, -0.5, 0.5, 1.5,
  153235. };
  153236. static long _vq_quantmap__44un1__p6_1[] = {
  153237. 3, 1, 0, 2, 4,
  153238. };
  153239. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153240. _vq_quantthresh__44un1__p6_1,
  153241. _vq_quantmap__44un1__p6_1,
  153242. 5,
  153243. 5
  153244. };
  153245. static static_codebook _44un1__p6_1 = {
  153246. 2, 25,
  153247. _vq_lengthlist__44un1__p6_1,
  153248. 1, -533725184, 1611661312, 3, 0,
  153249. _vq_quantlist__44un1__p6_1,
  153250. NULL,
  153251. &_vq_auxt__44un1__p6_1,
  153252. NULL,
  153253. 0
  153254. };
  153255. static long _vq_quantlist__44un1__p7_0[] = {
  153256. 2,
  153257. 1,
  153258. 3,
  153259. 0,
  153260. 4,
  153261. };
  153262. static long _vq_lengthlist__44un1__p7_0[] = {
  153263. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153264. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153266. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153270. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153278. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153280. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153285. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153299. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153300. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153301. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153302. 10,
  153303. };
  153304. static float _vq_quantthresh__44un1__p7_0[] = {
  153305. -253.5, -84.5, 84.5, 253.5,
  153306. };
  153307. static long _vq_quantmap__44un1__p7_0[] = {
  153308. 3, 1, 0, 2, 4,
  153309. };
  153310. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153311. _vq_quantthresh__44un1__p7_0,
  153312. _vq_quantmap__44un1__p7_0,
  153313. 5,
  153314. 5
  153315. };
  153316. static static_codebook _44un1__p7_0 = {
  153317. 4, 625,
  153318. _vq_lengthlist__44un1__p7_0,
  153319. 1, -518709248, 1626677248, 3, 0,
  153320. _vq_quantlist__44un1__p7_0,
  153321. NULL,
  153322. &_vq_auxt__44un1__p7_0,
  153323. NULL,
  153324. 0
  153325. };
  153326. static long _vq_quantlist__44un1__p7_1[] = {
  153327. 6,
  153328. 5,
  153329. 7,
  153330. 4,
  153331. 8,
  153332. 3,
  153333. 9,
  153334. 2,
  153335. 10,
  153336. 1,
  153337. 11,
  153338. 0,
  153339. 12,
  153340. };
  153341. static long _vq_lengthlist__44un1__p7_1[] = {
  153342. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153343. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153344. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153345. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153346. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153347. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153348. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153349. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153350. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153351. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153352. 12,13,13,12,13,13,14,14,14,
  153353. };
  153354. static float _vq_quantthresh__44un1__p7_1[] = {
  153355. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153356. 32.5, 45.5, 58.5, 71.5,
  153357. };
  153358. static long _vq_quantmap__44un1__p7_1[] = {
  153359. 11, 9, 7, 5, 3, 1, 0, 2,
  153360. 4, 6, 8, 10, 12,
  153361. };
  153362. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153363. _vq_quantthresh__44un1__p7_1,
  153364. _vq_quantmap__44un1__p7_1,
  153365. 13,
  153366. 13
  153367. };
  153368. static static_codebook _44un1__p7_1 = {
  153369. 2, 169,
  153370. _vq_lengthlist__44un1__p7_1,
  153371. 1, -523010048, 1618608128, 4, 0,
  153372. _vq_quantlist__44un1__p7_1,
  153373. NULL,
  153374. &_vq_auxt__44un1__p7_1,
  153375. NULL,
  153376. 0
  153377. };
  153378. static long _vq_quantlist__44un1__p7_2[] = {
  153379. 6,
  153380. 5,
  153381. 7,
  153382. 4,
  153383. 8,
  153384. 3,
  153385. 9,
  153386. 2,
  153387. 10,
  153388. 1,
  153389. 11,
  153390. 0,
  153391. 12,
  153392. };
  153393. static long _vq_lengthlist__44un1__p7_2[] = {
  153394. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153395. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153396. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153397. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153398. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153399. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153400. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153401. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153402. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153403. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153404. 9, 9, 9,10,10,10,10,10,10,
  153405. };
  153406. static float _vq_quantthresh__44un1__p7_2[] = {
  153407. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153408. 2.5, 3.5, 4.5, 5.5,
  153409. };
  153410. static long _vq_quantmap__44un1__p7_2[] = {
  153411. 11, 9, 7, 5, 3, 1, 0, 2,
  153412. 4, 6, 8, 10, 12,
  153413. };
  153414. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153415. _vq_quantthresh__44un1__p7_2,
  153416. _vq_quantmap__44un1__p7_2,
  153417. 13,
  153418. 13
  153419. };
  153420. static static_codebook _44un1__p7_2 = {
  153421. 2, 169,
  153422. _vq_lengthlist__44un1__p7_2,
  153423. 1, -531103744, 1611661312, 4, 0,
  153424. _vq_quantlist__44un1__p7_2,
  153425. NULL,
  153426. &_vq_auxt__44un1__p7_2,
  153427. NULL,
  153428. 0
  153429. };
  153430. static long _huff_lengthlist__44un1__short[] = {
  153431. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153432. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153433. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153434. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153435. };
  153436. static static_codebook _huff_book__44un1__short = {
  153437. 2, 64,
  153438. _huff_lengthlist__44un1__short,
  153439. 0, 0, 0, 0, 0,
  153440. NULL,
  153441. NULL,
  153442. NULL,
  153443. NULL,
  153444. 0
  153445. };
  153446. /*** End of inlined file: res_books_uncoupled.h ***/
  153447. /***** residue backends *********************************************/
  153448. static vorbis_info_residue0 _residue_44_low_un={
  153449. 0,-1, -1, 8,-1,
  153450. {0},
  153451. {-1},
  153452. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153453. { -1, 25, -1, 45, -1, -1, -1}
  153454. };
  153455. static vorbis_info_residue0 _residue_44_mid_un={
  153456. 0,-1, -1, 10,-1,
  153457. /* 0 1 2 3 4 5 6 7 8 9 */
  153458. {0},
  153459. {-1},
  153460. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153461. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153462. };
  153463. static vorbis_info_residue0 _residue_44_hi_un={
  153464. 0,-1, -1, 10,-1,
  153465. /* 0 1 2 3 4 5 6 7 8 9 */
  153466. {0},
  153467. {-1},
  153468. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153469. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153470. };
  153471. /* mapping conventions:
  153472. only one submap (this would change for efficient 5.1 support for example)*/
  153473. /* Four psychoacoustic profiles are used, one for each blocktype */
  153474. static vorbis_info_mapping0 _map_nominal_u[2]={
  153475. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153476. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153477. };
  153478. static static_bookblock _resbook_44u_n1={
  153479. {
  153480. {0},
  153481. {0,0,&_44un1__p1_0},
  153482. {0,0,&_44un1__p2_0},
  153483. {0,0,&_44un1__p3_0},
  153484. {0,0,&_44un1__p4_0},
  153485. {0,0,&_44un1__p5_0},
  153486. {&_44un1__p6_0,&_44un1__p6_1},
  153487. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153488. }
  153489. };
  153490. static static_bookblock _resbook_44u_0={
  153491. {
  153492. {0},
  153493. {0,0,&_44u0__p1_0},
  153494. {0,0,&_44u0__p2_0},
  153495. {0,0,&_44u0__p3_0},
  153496. {0,0,&_44u0__p4_0},
  153497. {0,0,&_44u0__p5_0},
  153498. {&_44u0__p6_0,&_44u0__p6_1},
  153499. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153500. }
  153501. };
  153502. static static_bookblock _resbook_44u_1={
  153503. {
  153504. {0},
  153505. {0,0,&_44u1__p1_0},
  153506. {0,0,&_44u1__p2_0},
  153507. {0,0,&_44u1__p3_0},
  153508. {0,0,&_44u1__p4_0},
  153509. {0,0,&_44u1__p5_0},
  153510. {&_44u1__p6_0,&_44u1__p6_1},
  153511. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153512. }
  153513. };
  153514. static static_bookblock _resbook_44u_2={
  153515. {
  153516. {0},
  153517. {0,0,&_44u2__p1_0},
  153518. {0,0,&_44u2__p2_0},
  153519. {0,0,&_44u2__p3_0},
  153520. {0,0,&_44u2__p4_0},
  153521. {0,0,&_44u2__p5_0},
  153522. {&_44u2__p6_0,&_44u2__p6_1},
  153523. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153524. }
  153525. };
  153526. static static_bookblock _resbook_44u_3={
  153527. {
  153528. {0},
  153529. {0,0,&_44u3__p1_0},
  153530. {0,0,&_44u3__p2_0},
  153531. {0,0,&_44u3__p3_0},
  153532. {0,0,&_44u3__p4_0},
  153533. {0,0,&_44u3__p5_0},
  153534. {&_44u3__p6_0,&_44u3__p6_1},
  153535. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153536. }
  153537. };
  153538. static static_bookblock _resbook_44u_4={
  153539. {
  153540. {0},
  153541. {0,0,&_44u4__p1_0},
  153542. {0,0,&_44u4__p2_0},
  153543. {0,0,&_44u4__p3_0},
  153544. {0,0,&_44u4__p4_0},
  153545. {0,0,&_44u4__p5_0},
  153546. {&_44u4__p6_0,&_44u4__p6_1},
  153547. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153548. }
  153549. };
  153550. static static_bookblock _resbook_44u_5={
  153551. {
  153552. {0},
  153553. {0,0,&_44u5__p1_0},
  153554. {0,0,&_44u5__p2_0},
  153555. {0,0,&_44u5__p3_0},
  153556. {0,0,&_44u5__p4_0},
  153557. {0,0,&_44u5__p5_0},
  153558. {0,0,&_44u5__p6_0},
  153559. {&_44u5__p7_0,&_44u5__p7_1},
  153560. {&_44u5__p8_0,&_44u5__p8_1},
  153561. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153562. }
  153563. };
  153564. static static_bookblock _resbook_44u_6={
  153565. {
  153566. {0},
  153567. {0,0,&_44u6__p1_0},
  153568. {0,0,&_44u6__p2_0},
  153569. {0,0,&_44u6__p3_0},
  153570. {0,0,&_44u6__p4_0},
  153571. {0,0,&_44u6__p5_0},
  153572. {0,0,&_44u6__p6_0},
  153573. {&_44u6__p7_0,&_44u6__p7_1},
  153574. {&_44u6__p8_0,&_44u6__p8_1},
  153575. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153576. }
  153577. };
  153578. static static_bookblock _resbook_44u_7={
  153579. {
  153580. {0},
  153581. {0,0,&_44u7__p1_0},
  153582. {0,0,&_44u7__p2_0},
  153583. {0,0,&_44u7__p3_0},
  153584. {0,0,&_44u7__p4_0},
  153585. {0,0,&_44u7__p5_0},
  153586. {0,0,&_44u7__p6_0},
  153587. {&_44u7__p7_0,&_44u7__p7_1},
  153588. {&_44u7__p8_0,&_44u7__p8_1},
  153589. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153590. }
  153591. };
  153592. static static_bookblock _resbook_44u_8={
  153593. {
  153594. {0},
  153595. {0,0,&_44u8_p1_0},
  153596. {0,0,&_44u8_p2_0},
  153597. {0,0,&_44u8_p3_0},
  153598. {0,0,&_44u8_p4_0},
  153599. {&_44u8_p5_0,&_44u8_p5_1},
  153600. {&_44u8_p6_0,&_44u8_p6_1},
  153601. {&_44u8_p7_0,&_44u8_p7_1},
  153602. {&_44u8_p8_0,&_44u8_p8_1},
  153603. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153604. }
  153605. };
  153606. static static_bookblock _resbook_44u_9={
  153607. {
  153608. {0},
  153609. {0,0,&_44u9_p1_0},
  153610. {0,0,&_44u9_p2_0},
  153611. {0,0,&_44u9_p3_0},
  153612. {0,0,&_44u9_p4_0},
  153613. {&_44u9_p5_0,&_44u9_p5_1},
  153614. {&_44u9_p6_0,&_44u9_p6_1},
  153615. {&_44u9_p7_0,&_44u9_p7_1},
  153616. {&_44u9_p8_0,&_44u9_p8_1},
  153617. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153618. }
  153619. };
  153620. static vorbis_residue_template _res_44u_n1[]={
  153621. {1,0, &_residue_44_low_un,
  153622. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153623. &_resbook_44u_n1,&_resbook_44u_n1},
  153624. {1,0, &_residue_44_low_un,
  153625. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153626. &_resbook_44u_n1,&_resbook_44u_n1}
  153627. };
  153628. static vorbis_residue_template _res_44u_0[]={
  153629. {1,0, &_residue_44_low_un,
  153630. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153631. &_resbook_44u_0,&_resbook_44u_0},
  153632. {1,0, &_residue_44_low_un,
  153633. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153634. &_resbook_44u_0,&_resbook_44u_0}
  153635. };
  153636. static vorbis_residue_template _res_44u_1[]={
  153637. {1,0, &_residue_44_low_un,
  153638. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153639. &_resbook_44u_1,&_resbook_44u_1},
  153640. {1,0, &_residue_44_low_un,
  153641. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153642. &_resbook_44u_1,&_resbook_44u_1}
  153643. };
  153644. static vorbis_residue_template _res_44u_2[]={
  153645. {1,0, &_residue_44_low_un,
  153646. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153647. &_resbook_44u_2,&_resbook_44u_2},
  153648. {1,0, &_residue_44_low_un,
  153649. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153650. &_resbook_44u_2,&_resbook_44u_2}
  153651. };
  153652. static vorbis_residue_template _res_44u_3[]={
  153653. {1,0, &_residue_44_low_un,
  153654. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153655. &_resbook_44u_3,&_resbook_44u_3},
  153656. {1,0, &_residue_44_low_un,
  153657. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153658. &_resbook_44u_3,&_resbook_44u_3}
  153659. };
  153660. static vorbis_residue_template _res_44u_4[]={
  153661. {1,0, &_residue_44_low_un,
  153662. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153663. &_resbook_44u_4,&_resbook_44u_4},
  153664. {1,0, &_residue_44_low_un,
  153665. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153666. &_resbook_44u_4,&_resbook_44u_4}
  153667. };
  153668. static vorbis_residue_template _res_44u_5[]={
  153669. {1,0, &_residue_44_mid_un,
  153670. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153671. &_resbook_44u_5,&_resbook_44u_5},
  153672. {1,0, &_residue_44_mid_un,
  153673. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153674. &_resbook_44u_5,&_resbook_44u_5}
  153675. };
  153676. static vorbis_residue_template _res_44u_6[]={
  153677. {1,0, &_residue_44_mid_un,
  153678. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153679. &_resbook_44u_6,&_resbook_44u_6},
  153680. {1,0, &_residue_44_mid_un,
  153681. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153682. &_resbook_44u_6,&_resbook_44u_6}
  153683. };
  153684. static vorbis_residue_template _res_44u_7[]={
  153685. {1,0, &_residue_44_mid_un,
  153686. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153687. &_resbook_44u_7,&_resbook_44u_7},
  153688. {1,0, &_residue_44_mid_un,
  153689. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153690. &_resbook_44u_7,&_resbook_44u_7}
  153691. };
  153692. static vorbis_residue_template _res_44u_8[]={
  153693. {1,0, &_residue_44_hi_un,
  153694. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153695. &_resbook_44u_8,&_resbook_44u_8},
  153696. {1,0, &_residue_44_hi_un,
  153697. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153698. &_resbook_44u_8,&_resbook_44u_8}
  153699. };
  153700. static vorbis_residue_template _res_44u_9[]={
  153701. {1,0, &_residue_44_hi_un,
  153702. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153703. &_resbook_44u_9,&_resbook_44u_9},
  153704. {1,0, &_residue_44_hi_un,
  153705. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153706. &_resbook_44u_9,&_resbook_44u_9}
  153707. };
  153708. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153709. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153710. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153711. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153712. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153713. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153714. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153715. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153716. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153717. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153718. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153719. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153720. };
  153721. /*** End of inlined file: residue_44u.h ***/
  153722. static double rate_mapping_44_un[12]={
  153723. 32000.,48000.,60000.,70000.,80000.,86000.,
  153724. 96000.,110000.,120000.,140000.,160000.,240001.
  153725. };
  153726. ve_setup_data_template ve_setup_44_uncoupled={
  153727. 11,
  153728. rate_mapping_44_un,
  153729. quality_mapping_44,
  153730. -1,
  153731. 40000,
  153732. 50000,
  153733. blocksize_short_44,
  153734. blocksize_long_44,
  153735. _psy_tone_masteratt_44,
  153736. _psy_tone_0dB,
  153737. _psy_tone_suppress,
  153738. _vp_tonemask_adj_otherblock,
  153739. _vp_tonemask_adj_longblock,
  153740. _vp_tonemask_adj_otherblock,
  153741. _psy_noiseguards_44,
  153742. _psy_noisebias_impulse,
  153743. _psy_noisebias_padding,
  153744. _psy_noisebias_trans,
  153745. _psy_noisebias_long,
  153746. _psy_noise_suppress,
  153747. _psy_compand_44,
  153748. _psy_compand_short_mapping,
  153749. _psy_compand_long_mapping,
  153750. {_noise_start_short_44,_noise_start_long_44},
  153751. {_noise_part_short_44,_noise_part_long_44},
  153752. _noise_thresh_44,
  153753. _psy_ath_floater,
  153754. _psy_ath_abs,
  153755. _psy_lowpass_44,
  153756. _psy_global_44,
  153757. _global_mapping_44,
  153758. NULL,
  153759. _floor_books,
  153760. _floor,
  153761. _floor_short_mapping_44,
  153762. _floor_long_mapping_44,
  153763. _mapres_template_44_uncoupled
  153764. };
  153765. /*** End of inlined file: setup_44u.h ***/
  153766. /*** Start of inlined file: setup_32.h ***/
  153767. static double rate_mapping_32[12]={
  153768. 18000.,28000.,35000.,45000.,56000.,60000.,
  153769. 75000.,90000.,100000.,115000.,150000.,190000.,
  153770. };
  153771. static double rate_mapping_32_un[12]={
  153772. 30000.,42000.,52000.,64000.,72000.,78000.,
  153773. 86000.,92000.,110000.,120000.,140000.,190000.,
  153774. };
  153775. static double _psy_lowpass_32[12]={
  153776. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153777. };
  153778. ve_setup_data_template ve_setup_32_stereo={
  153779. 11,
  153780. rate_mapping_32,
  153781. quality_mapping_44,
  153782. 2,
  153783. 26000,
  153784. 40000,
  153785. blocksize_short_44,
  153786. blocksize_long_44,
  153787. _psy_tone_masteratt_44,
  153788. _psy_tone_0dB,
  153789. _psy_tone_suppress,
  153790. _vp_tonemask_adj_otherblock,
  153791. _vp_tonemask_adj_longblock,
  153792. _vp_tonemask_adj_otherblock,
  153793. _psy_noiseguards_44,
  153794. _psy_noisebias_impulse,
  153795. _psy_noisebias_padding,
  153796. _psy_noisebias_trans,
  153797. _psy_noisebias_long,
  153798. _psy_noise_suppress,
  153799. _psy_compand_44,
  153800. _psy_compand_short_mapping,
  153801. _psy_compand_long_mapping,
  153802. {_noise_start_short_44,_noise_start_long_44},
  153803. {_noise_part_short_44,_noise_part_long_44},
  153804. _noise_thresh_44,
  153805. _psy_ath_floater,
  153806. _psy_ath_abs,
  153807. _psy_lowpass_32,
  153808. _psy_global_44,
  153809. _global_mapping_44,
  153810. _psy_stereo_modes_44,
  153811. _floor_books,
  153812. _floor,
  153813. _floor_short_mapping_44,
  153814. _floor_long_mapping_44,
  153815. _mapres_template_44_stereo
  153816. };
  153817. ve_setup_data_template ve_setup_32_uncoupled={
  153818. 11,
  153819. rate_mapping_32_un,
  153820. quality_mapping_44,
  153821. -1,
  153822. 26000,
  153823. 40000,
  153824. blocksize_short_44,
  153825. blocksize_long_44,
  153826. _psy_tone_masteratt_44,
  153827. _psy_tone_0dB,
  153828. _psy_tone_suppress,
  153829. _vp_tonemask_adj_otherblock,
  153830. _vp_tonemask_adj_longblock,
  153831. _vp_tonemask_adj_otherblock,
  153832. _psy_noiseguards_44,
  153833. _psy_noisebias_impulse,
  153834. _psy_noisebias_padding,
  153835. _psy_noisebias_trans,
  153836. _psy_noisebias_long,
  153837. _psy_noise_suppress,
  153838. _psy_compand_44,
  153839. _psy_compand_short_mapping,
  153840. _psy_compand_long_mapping,
  153841. {_noise_start_short_44,_noise_start_long_44},
  153842. {_noise_part_short_44,_noise_part_long_44},
  153843. _noise_thresh_44,
  153844. _psy_ath_floater,
  153845. _psy_ath_abs,
  153846. _psy_lowpass_32,
  153847. _psy_global_44,
  153848. _global_mapping_44,
  153849. NULL,
  153850. _floor_books,
  153851. _floor,
  153852. _floor_short_mapping_44,
  153853. _floor_long_mapping_44,
  153854. _mapres_template_44_uncoupled
  153855. };
  153856. /*** End of inlined file: setup_32.h ***/
  153857. /*** Start of inlined file: setup_8.h ***/
  153858. /*** Start of inlined file: psych_8.h ***/
  153859. static att3 _psy_tone_masteratt_8[3]={
  153860. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153861. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153862. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153863. };
  153864. static vp_adjblock _vp_tonemask_adj_8[3]={
  153865. /* adjust for mode zero */
  153866. /* 63 125 250 500 1 2 4 8 16 */
  153867. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153868. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153869. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153870. };
  153871. static noise3 _psy_noisebias_8[3]={
  153872. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153873. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153874. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153875. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153876. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153877. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153878. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153879. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153880. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153881. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153882. };
  153883. /* stereo mode by base quality level */
  153884. static adj_stereo _psy_stereo_modes_8[3]={
  153885. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153886. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153887. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153888. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153889. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153890. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153891. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153892. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153893. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153894. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153895. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153896. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153897. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153898. };
  153899. static noiseguard _psy_noiseguards_8[2]={
  153900. {10,10,-1},
  153901. {10,10,-1},
  153902. };
  153903. static compandblock _psy_compand_8[2]={
  153904. {{
  153905. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153906. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153907. 12,12,13,13,14,14,15, 15, /* 23dB */
  153908. 16,16,17,17,17,18,18, 19, /* 31dB */
  153909. 19,19,20,21,22,23,24, 25, /* 39dB */
  153910. }},
  153911. {{
  153912. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153913. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153914. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153915. 9,10,11,12,13,14,15, 16, /* 31dB */
  153916. 17,18,19,20,21,22,23, 24, /* 39dB */
  153917. }},
  153918. };
  153919. static double _psy_lowpass_8[3]={3.,4.,4.};
  153920. static int _noise_start_8[2]={
  153921. 64,64,
  153922. };
  153923. static int _noise_part_8[2]={
  153924. 8,8,
  153925. };
  153926. static int _psy_ath_floater_8[3]={
  153927. -100,-100,-105,
  153928. };
  153929. static int _psy_ath_abs_8[3]={
  153930. -130,-130,-140,
  153931. };
  153932. /*** End of inlined file: psych_8.h ***/
  153933. /*** Start of inlined file: residue_8.h ***/
  153934. /***** residue backends *********************************************/
  153935. static static_bookblock _resbook_8s_0={
  153936. {
  153937. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153938. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153939. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153940. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153941. }
  153942. };
  153943. static static_bookblock _resbook_8s_1={
  153944. {
  153945. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153946. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153947. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153948. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153949. }
  153950. };
  153951. static vorbis_residue_template _res_8s_0[]={
  153952. {2,0, &_residue_44_mid,
  153953. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153954. &_resbook_8s_0,&_resbook_8s_0},
  153955. };
  153956. static vorbis_residue_template _res_8s_1[]={
  153957. {2,0, &_residue_44_mid,
  153958. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153959. &_resbook_8s_1,&_resbook_8s_1},
  153960. };
  153961. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153962. { _map_nominal, _res_8s_0 }, /* 0 */
  153963. { _map_nominal, _res_8s_1 }, /* 1 */
  153964. };
  153965. static static_bookblock _resbook_8u_0={
  153966. {
  153967. {0},
  153968. {0,0,&_8u0__p1_0},
  153969. {0,0,&_8u0__p2_0},
  153970. {0,0,&_8u0__p3_0},
  153971. {0,0,&_8u0__p4_0},
  153972. {0,0,&_8u0__p5_0},
  153973. {&_8u0__p6_0,&_8u0__p6_1},
  153974. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153975. }
  153976. };
  153977. static static_bookblock _resbook_8u_1={
  153978. {
  153979. {0},
  153980. {0,0,&_8u1__p1_0},
  153981. {0,0,&_8u1__p2_0},
  153982. {0,0,&_8u1__p3_0},
  153983. {0,0,&_8u1__p4_0},
  153984. {0,0,&_8u1__p5_0},
  153985. {0,0,&_8u1__p6_0},
  153986. {&_8u1__p7_0,&_8u1__p7_1},
  153987. {&_8u1__p8_0,&_8u1__p8_1},
  153988. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153989. }
  153990. };
  153991. static vorbis_residue_template _res_8u_0[]={
  153992. {1,0, &_residue_44_low_un,
  153993. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153994. &_resbook_8u_0,&_resbook_8u_0},
  153995. };
  153996. static vorbis_residue_template _res_8u_1[]={
  153997. {1,0, &_residue_44_mid_un,
  153998. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153999. &_resbook_8u_1,&_resbook_8u_1},
  154000. };
  154001. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  154002. { _map_nominal_u, _res_8u_0 }, /* 0 */
  154003. { _map_nominal_u, _res_8u_1 }, /* 1 */
  154004. };
  154005. /*** End of inlined file: residue_8.h ***/
  154006. static int blocksize_8[2]={
  154007. 512,512
  154008. };
  154009. static int _floor_mapping_8[2]={
  154010. 6,6,
  154011. };
  154012. static double rate_mapping_8[3]={
  154013. 6000.,9000.,32000.,
  154014. };
  154015. static double rate_mapping_8_uncoupled[3]={
  154016. 8000.,14000.,42000.,
  154017. };
  154018. static double quality_mapping_8[3]={
  154019. -.1,.0,1.
  154020. };
  154021. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  154022. static double _global_mapping_8[3]={ 1., 2., 3. };
  154023. ve_setup_data_template ve_setup_8_stereo={
  154024. 2,
  154025. rate_mapping_8,
  154026. quality_mapping_8,
  154027. 2,
  154028. 8000,
  154029. 9000,
  154030. blocksize_8,
  154031. blocksize_8,
  154032. _psy_tone_masteratt_8,
  154033. _psy_tone_0dB,
  154034. _psy_tone_suppress,
  154035. _vp_tonemask_adj_8,
  154036. NULL,
  154037. _vp_tonemask_adj_8,
  154038. _psy_noiseguards_8,
  154039. _psy_noisebias_8,
  154040. _psy_noisebias_8,
  154041. NULL,
  154042. NULL,
  154043. _psy_noise_suppress,
  154044. _psy_compand_8,
  154045. _psy_compand_8_mapping,
  154046. NULL,
  154047. {_noise_start_8,_noise_start_8},
  154048. {_noise_part_8,_noise_part_8},
  154049. _noise_thresh_5only,
  154050. _psy_ath_floater_8,
  154051. _psy_ath_abs_8,
  154052. _psy_lowpass_8,
  154053. _psy_global_44,
  154054. _global_mapping_8,
  154055. _psy_stereo_modes_8,
  154056. _floor_books,
  154057. _floor,
  154058. _floor_mapping_8,
  154059. NULL,
  154060. _mapres_template_8_stereo
  154061. };
  154062. ve_setup_data_template ve_setup_8_uncoupled={
  154063. 2,
  154064. rate_mapping_8_uncoupled,
  154065. quality_mapping_8,
  154066. -1,
  154067. 8000,
  154068. 9000,
  154069. blocksize_8,
  154070. blocksize_8,
  154071. _psy_tone_masteratt_8,
  154072. _psy_tone_0dB,
  154073. _psy_tone_suppress,
  154074. _vp_tonemask_adj_8,
  154075. NULL,
  154076. _vp_tonemask_adj_8,
  154077. _psy_noiseguards_8,
  154078. _psy_noisebias_8,
  154079. _psy_noisebias_8,
  154080. NULL,
  154081. NULL,
  154082. _psy_noise_suppress,
  154083. _psy_compand_8,
  154084. _psy_compand_8_mapping,
  154085. NULL,
  154086. {_noise_start_8,_noise_start_8},
  154087. {_noise_part_8,_noise_part_8},
  154088. _noise_thresh_5only,
  154089. _psy_ath_floater_8,
  154090. _psy_ath_abs_8,
  154091. _psy_lowpass_8,
  154092. _psy_global_44,
  154093. _global_mapping_8,
  154094. _psy_stereo_modes_8,
  154095. _floor_books,
  154096. _floor,
  154097. _floor_mapping_8,
  154098. NULL,
  154099. _mapres_template_8_uncoupled
  154100. };
  154101. /*** End of inlined file: setup_8.h ***/
  154102. /*** Start of inlined file: setup_11.h ***/
  154103. /*** Start of inlined file: psych_11.h ***/
  154104. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154105. static att3 _psy_tone_masteratt_11[3]={
  154106. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154107. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154108. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154109. };
  154110. static vp_adjblock _vp_tonemask_adj_11[3]={
  154111. /* adjust for mode zero */
  154112. /* 63 125 250 500 1 2 4 8 16 */
  154113. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154114. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154115. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154116. };
  154117. static noise3 _psy_noisebias_11[3]={
  154118. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154119. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154120. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154121. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154122. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154123. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154124. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154125. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154126. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154127. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154128. };
  154129. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154130. /*** End of inlined file: psych_11.h ***/
  154131. static int blocksize_11[2]={
  154132. 512,512
  154133. };
  154134. static int _floor_mapping_11[2]={
  154135. 6,6,
  154136. };
  154137. static double rate_mapping_11[3]={
  154138. 8000.,13000.,44000.,
  154139. };
  154140. static double rate_mapping_11_uncoupled[3]={
  154141. 12000.,20000.,50000.,
  154142. };
  154143. static double quality_mapping_11[3]={
  154144. -.1,.0,1.
  154145. };
  154146. ve_setup_data_template ve_setup_11_stereo={
  154147. 2,
  154148. rate_mapping_11,
  154149. quality_mapping_11,
  154150. 2,
  154151. 9000,
  154152. 15000,
  154153. blocksize_11,
  154154. blocksize_11,
  154155. _psy_tone_masteratt_11,
  154156. _psy_tone_0dB,
  154157. _psy_tone_suppress,
  154158. _vp_tonemask_adj_11,
  154159. NULL,
  154160. _vp_tonemask_adj_11,
  154161. _psy_noiseguards_8,
  154162. _psy_noisebias_11,
  154163. _psy_noisebias_11,
  154164. NULL,
  154165. NULL,
  154166. _psy_noise_suppress,
  154167. _psy_compand_8,
  154168. _psy_compand_8_mapping,
  154169. NULL,
  154170. {_noise_start_8,_noise_start_8},
  154171. {_noise_part_8,_noise_part_8},
  154172. _noise_thresh_11,
  154173. _psy_ath_floater_8,
  154174. _psy_ath_abs_8,
  154175. _psy_lowpass_11,
  154176. _psy_global_44,
  154177. _global_mapping_8,
  154178. _psy_stereo_modes_8,
  154179. _floor_books,
  154180. _floor,
  154181. _floor_mapping_11,
  154182. NULL,
  154183. _mapres_template_8_stereo
  154184. };
  154185. ve_setup_data_template ve_setup_11_uncoupled={
  154186. 2,
  154187. rate_mapping_11_uncoupled,
  154188. quality_mapping_11,
  154189. -1,
  154190. 9000,
  154191. 15000,
  154192. blocksize_11,
  154193. blocksize_11,
  154194. _psy_tone_masteratt_11,
  154195. _psy_tone_0dB,
  154196. _psy_tone_suppress,
  154197. _vp_tonemask_adj_11,
  154198. NULL,
  154199. _vp_tonemask_adj_11,
  154200. _psy_noiseguards_8,
  154201. _psy_noisebias_11,
  154202. _psy_noisebias_11,
  154203. NULL,
  154204. NULL,
  154205. _psy_noise_suppress,
  154206. _psy_compand_8,
  154207. _psy_compand_8_mapping,
  154208. NULL,
  154209. {_noise_start_8,_noise_start_8},
  154210. {_noise_part_8,_noise_part_8},
  154211. _noise_thresh_11,
  154212. _psy_ath_floater_8,
  154213. _psy_ath_abs_8,
  154214. _psy_lowpass_11,
  154215. _psy_global_44,
  154216. _global_mapping_8,
  154217. _psy_stereo_modes_8,
  154218. _floor_books,
  154219. _floor,
  154220. _floor_mapping_11,
  154221. NULL,
  154222. _mapres_template_8_uncoupled
  154223. };
  154224. /*** End of inlined file: setup_11.h ***/
  154225. /*** Start of inlined file: setup_16.h ***/
  154226. /*** Start of inlined file: psych_16.h ***/
  154227. /* stereo mode by base quality level */
  154228. static adj_stereo _psy_stereo_modes_16[4]={
  154229. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154230. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154231. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154232. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154233. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154234. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154235. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154236. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154237. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154238. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154239. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154240. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154241. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154242. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154243. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154244. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154245. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154246. };
  154247. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154248. static att3 _psy_tone_masteratt_16[4]={
  154249. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154250. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154251. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154252. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154253. };
  154254. static vp_adjblock _vp_tonemask_adj_16[4]={
  154255. /* adjust for mode zero */
  154256. /* 63 125 250 500 1 2 4 8 16 */
  154257. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154258. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154259. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154260. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154261. };
  154262. static noise3 _psy_noisebias_16_short[4]={
  154263. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154264. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154265. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154266. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154267. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154268. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154269. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154270. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154271. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154272. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154273. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154274. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154275. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154276. };
  154277. static noise3 _psy_noisebias_16_impulse[4]={
  154278. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154279. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154280. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154281. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154282. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154283. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154284. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154285. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154286. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154287. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154288. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154289. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154290. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154291. };
  154292. static noise3 _psy_noisebias_16[4]={
  154293. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154294. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154295. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154296. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154297. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154298. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154299. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154300. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154301. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154302. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154303. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154304. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154305. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154306. };
  154307. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154308. static int _noise_start_16[3]={ 256,256,9999 };
  154309. static int _noise_part_16[4]={ 8,8,8,8 };
  154310. static int _psy_ath_floater_16[4]={
  154311. -100,-100,-100,-105,
  154312. };
  154313. static int _psy_ath_abs_16[4]={
  154314. -130,-130,-130,-140,
  154315. };
  154316. /*** End of inlined file: psych_16.h ***/
  154317. /*** Start of inlined file: residue_16.h ***/
  154318. /***** residue backends *********************************************/
  154319. static static_bookblock _resbook_16s_0={
  154320. {
  154321. {0},
  154322. {0,0,&_16c0_s_p1_0},
  154323. {0,0,&_16c0_s_p2_0},
  154324. {0,0,&_16c0_s_p3_0},
  154325. {0,0,&_16c0_s_p4_0},
  154326. {0,0,&_16c0_s_p5_0},
  154327. {0,0,&_16c0_s_p6_0},
  154328. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154329. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154330. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154331. }
  154332. };
  154333. static static_bookblock _resbook_16s_1={
  154334. {
  154335. {0},
  154336. {0,0,&_16c1_s_p1_0},
  154337. {0,0,&_16c1_s_p2_0},
  154338. {0,0,&_16c1_s_p3_0},
  154339. {0,0,&_16c1_s_p4_0},
  154340. {0,0,&_16c1_s_p5_0},
  154341. {0,0,&_16c1_s_p6_0},
  154342. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154343. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154344. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154345. }
  154346. };
  154347. static static_bookblock _resbook_16s_2={
  154348. {
  154349. {0},
  154350. {0,0,&_16c2_s_p1_0},
  154351. {0,0,&_16c2_s_p2_0},
  154352. {0,0,&_16c2_s_p3_0},
  154353. {0,0,&_16c2_s_p4_0},
  154354. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154355. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154356. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154357. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154358. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154359. }
  154360. };
  154361. static vorbis_residue_template _res_16s_0[]={
  154362. {2,0, &_residue_44_mid,
  154363. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154364. &_resbook_16s_0,&_resbook_16s_0},
  154365. };
  154366. static vorbis_residue_template _res_16s_1[]={
  154367. {2,0, &_residue_44_mid,
  154368. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154369. &_resbook_16s_1,&_resbook_16s_1},
  154370. {2,0, &_residue_44_mid,
  154371. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154372. &_resbook_16s_1,&_resbook_16s_1}
  154373. };
  154374. static vorbis_residue_template _res_16s_2[]={
  154375. {2,0, &_residue_44_high,
  154376. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154377. &_resbook_16s_2,&_resbook_16s_2},
  154378. {2,0, &_residue_44_high,
  154379. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154380. &_resbook_16s_2,&_resbook_16s_2}
  154381. };
  154382. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154383. { _map_nominal, _res_16s_0 }, /* 0 */
  154384. { _map_nominal, _res_16s_1 }, /* 1 */
  154385. { _map_nominal, _res_16s_2 }, /* 2 */
  154386. };
  154387. static static_bookblock _resbook_16u_0={
  154388. {
  154389. {0},
  154390. {0,0,&_16u0__p1_0},
  154391. {0,0,&_16u0__p2_0},
  154392. {0,0,&_16u0__p3_0},
  154393. {0,0,&_16u0__p4_0},
  154394. {0,0,&_16u0__p5_0},
  154395. {&_16u0__p6_0,&_16u0__p6_1},
  154396. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154397. }
  154398. };
  154399. static static_bookblock _resbook_16u_1={
  154400. {
  154401. {0},
  154402. {0,0,&_16u1__p1_0},
  154403. {0,0,&_16u1__p2_0},
  154404. {0,0,&_16u1__p3_0},
  154405. {0,0,&_16u1__p4_0},
  154406. {0,0,&_16u1__p5_0},
  154407. {0,0,&_16u1__p6_0},
  154408. {&_16u1__p7_0,&_16u1__p7_1},
  154409. {&_16u1__p8_0,&_16u1__p8_1},
  154410. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154411. }
  154412. };
  154413. static static_bookblock _resbook_16u_2={
  154414. {
  154415. {0},
  154416. {0,0,&_16u2_p1_0},
  154417. {0,0,&_16u2_p2_0},
  154418. {0,0,&_16u2_p3_0},
  154419. {0,0,&_16u2_p4_0},
  154420. {&_16u2_p5_0,&_16u2_p5_1},
  154421. {&_16u2_p6_0,&_16u2_p6_1},
  154422. {&_16u2_p7_0,&_16u2_p7_1},
  154423. {&_16u2_p8_0,&_16u2_p8_1},
  154424. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154425. }
  154426. };
  154427. static vorbis_residue_template _res_16u_0[]={
  154428. {1,0, &_residue_44_low_un,
  154429. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154430. &_resbook_16u_0,&_resbook_16u_0},
  154431. };
  154432. static vorbis_residue_template _res_16u_1[]={
  154433. {1,0, &_residue_44_mid_un,
  154434. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154435. &_resbook_16u_1,&_resbook_16u_1},
  154436. {1,0, &_residue_44_mid_un,
  154437. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154438. &_resbook_16u_1,&_resbook_16u_1}
  154439. };
  154440. static vorbis_residue_template _res_16u_2[]={
  154441. {1,0, &_residue_44_hi_un,
  154442. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154443. &_resbook_16u_2,&_resbook_16u_2},
  154444. {1,0, &_residue_44_hi_un,
  154445. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154446. &_resbook_16u_2,&_resbook_16u_2}
  154447. };
  154448. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154449. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154450. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154451. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154452. };
  154453. /*** End of inlined file: residue_16.h ***/
  154454. static int blocksize_16_short[3]={
  154455. 1024,512,512
  154456. };
  154457. static int blocksize_16_long[3]={
  154458. 1024,1024,1024
  154459. };
  154460. static int _floor_mapping_16_short[3]={
  154461. 9,3,3
  154462. };
  154463. static int _floor_mapping_16[3]={
  154464. 9,9,9
  154465. };
  154466. static double rate_mapping_16[4]={
  154467. 12000.,20000.,44000.,86000.
  154468. };
  154469. static double rate_mapping_16_uncoupled[4]={
  154470. 16000.,28000.,64000.,100000.
  154471. };
  154472. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154473. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154474. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154475. ve_setup_data_template ve_setup_16_stereo={
  154476. 3,
  154477. rate_mapping_16,
  154478. quality_mapping_16,
  154479. 2,
  154480. 15000,
  154481. 19000,
  154482. blocksize_16_short,
  154483. blocksize_16_long,
  154484. _psy_tone_masteratt_16,
  154485. _psy_tone_0dB,
  154486. _psy_tone_suppress,
  154487. _vp_tonemask_adj_16,
  154488. _vp_tonemask_adj_16,
  154489. _vp_tonemask_adj_16,
  154490. _psy_noiseguards_8,
  154491. _psy_noisebias_16_impulse,
  154492. _psy_noisebias_16_short,
  154493. _psy_noisebias_16_short,
  154494. _psy_noisebias_16,
  154495. _psy_noise_suppress,
  154496. _psy_compand_8,
  154497. _psy_compand_16_mapping,
  154498. _psy_compand_16_mapping,
  154499. {_noise_start_16,_noise_start_16},
  154500. { _noise_part_16, _noise_part_16},
  154501. _noise_thresh_16,
  154502. _psy_ath_floater_16,
  154503. _psy_ath_abs_16,
  154504. _psy_lowpass_16,
  154505. _psy_global_44,
  154506. _global_mapping_16,
  154507. _psy_stereo_modes_16,
  154508. _floor_books,
  154509. _floor,
  154510. _floor_mapping_16_short,
  154511. _floor_mapping_16,
  154512. _mapres_template_16_stereo
  154513. };
  154514. ve_setup_data_template ve_setup_16_uncoupled={
  154515. 3,
  154516. rate_mapping_16_uncoupled,
  154517. quality_mapping_16,
  154518. -1,
  154519. 15000,
  154520. 19000,
  154521. blocksize_16_short,
  154522. blocksize_16_long,
  154523. _psy_tone_masteratt_16,
  154524. _psy_tone_0dB,
  154525. _psy_tone_suppress,
  154526. _vp_tonemask_adj_16,
  154527. _vp_tonemask_adj_16,
  154528. _vp_tonemask_adj_16,
  154529. _psy_noiseguards_8,
  154530. _psy_noisebias_16_impulse,
  154531. _psy_noisebias_16_short,
  154532. _psy_noisebias_16_short,
  154533. _psy_noisebias_16,
  154534. _psy_noise_suppress,
  154535. _psy_compand_8,
  154536. _psy_compand_16_mapping,
  154537. _psy_compand_16_mapping,
  154538. {_noise_start_16,_noise_start_16},
  154539. { _noise_part_16, _noise_part_16},
  154540. _noise_thresh_16,
  154541. _psy_ath_floater_16,
  154542. _psy_ath_abs_16,
  154543. _psy_lowpass_16,
  154544. _psy_global_44,
  154545. _global_mapping_16,
  154546. _psy_stereo_modes_16,
  154547. _floor_books,
  154548. _floor,
  154549. _floor_mapping_16_short,
  154550. _floor_mapping_16,
  154551. _mapres_template_16_uncoupled
  154552. };
  154553. /*** End of inlined file: setup_16.h ***/
  154554. /*** Start of inlined file: setup_22.h ***/
  154555. static double rate_mapping_22[4]={
  154556. 15000.,20000.,44000.,86000.
  154557. };
  154558. static double rate_mapping_22_uncoupled[4]={
  154559. 16000.,28000.,50000.,90000.
  154560. };
  154561. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154562. ve_setup_data_template ve_setup_22_stereo={
  154563. 3,
  154564. rate_mapping_22,
  154565. quality_mapping_16,
  154566. 2,
  154567. 19000,
  154568. 26000,
  154569. blocksize_16_short,
  154570. blocksize_16_long,
  154571. _psy_tone_masteratt_16,
  154572. _psy_tone_0dB,
  154573. _psy_tone_suppress,
  154574. _vp_tonemask_adj_16,
  154575. _vp_tonemask_adj_16,
  154576. _vp_tonemask_adj_16,
  154577. _psy_noiseguards_8,
  154578. _psy_noisebias_16_impulse,
  154579. _psy_noisebias_16_short,
  154580. _psy_noisebias_16_short,
  154581. _psy_noisebias_16,
  154582. _psy_noise_suppress,
  154583. _psy_compand_8,
  154584. _psy_compand_8_mapping,
  154585. _psy_compand_8_mapping,
  154586. {_noise_start_16,_noise_start_16},
  154587. { _noise_part_16, _noise_part_16},
  154588. _noise_thresh_16,
  154589. _psy_ath_floater_16,
  154590. _psy_ath_abs_16,
  154591. _psy_lowpass_22,
  154592. _psy_global_44,
  154593. _global_mapping_16,
  154594. _psy_stereo_modes_16,
  154595. _floor_books,
  154596. _floor,
  154597. _floor_mapping_16_short,
  154598. _floor_mapping_16,
  154599. _mapres_template_16_stereo
  154600. };
  154601. ve_setup_data_template ve_setup_22_uncoupled={
  154602. 3,
  154603. rate_mapping_22_uncoupled,
  154604. quality_mapping_16,
  154605. -1,
  154606. 19000,
  154607. 26000,
  154608. blocksize_16_short,
  154609. blocksize_16_long,
  154610. _psy_tone_masteratt_16,
  154611. _psy_tone_0dB,
  154612. _psy_tone_suppress,
  154613. _vp_tonemask_adj_16,
  154614. _vp_tonemask_adj_16,
  154615. _vp_tonemask_adj_16,
  154616. _psy_noiseguards_8,
  154617. _psy_noisebias_16_impulse,
  154618. _psy_noisebias_16_short,
  154619. _psy_noisebias_16_short,
  154620. _psy_noisebias_16,
  154621. _psy_noise_suppress,
  154622. _psy_compand_8,
  154623. _psy_compand_8_mapping,
  154624. _psy_compand_8_mapping,
  154625. {_noise_start_16,_noise_start_16},
  154626. { _noise_part_16, _noise_part_16},
  154627. _noise_thresh_16,
  154628. _psy_ath_floater_16,
  154629. _psy_ath_abs_16,
  154630. _psy_lowpass_22,
  154631. _psy_global_44,
  154632. _global_mapping_16,
  154633. _psy_stereo_modes_16,
  154634. _floor_books,
  154635. _floor,
  154636. _floor_mapping_16_short,
  154637. _floor_mapping_16,
  154638. _mapres_template_16_uncoupled
  154639. };
  154640. /*** End of inlined file: setup_22.h ***/
  154641. /*** Start of inlined file: setup_X.h ***/
  154642. static double rate_mapping_X[12]={
  154643. -1.,-1.,-1.,-1.,-1.,-1.,
  154644. -1.,-1.,-1.,-1.,-1.,-1.
  154645. };
  154646. ve_setup_data_template ve_setup_X_stereo={
  154647. 11,
  154648. rate_mapping_X,
  154649. quality_mapping_44,
  154650. 2,
  154651. 50000,
  154652. 200000,
  154653. blocksize_short_44,
  154654. blocksize_long_44,
  154655. _psy_tone_masteratt_44,
  154656. _psy_tone_0dB,
  154657. _psy_tone_suppress,
  154658. _vp_tonemask_adj_otherblock,
  154659. _vp_tonemask_adj_longblock,
  154660. _vp_tonemask_adj_otherblock,
  154661. _psy_noiseguards_44,
  154662. _psy_noisebias_impulse,
  154663. _psy_noisebias_padding,
  154664. _psy_noisebias_trans,
  154665. _psy_noisebias_long,
  154666. _psy_noise_suppress,
  154667. _psy_compand_44,
  154668. _psy_compand_short_mapping,
  154669. _psy_compand_long_mapping,
  154670. {_noise_start_short_44,_noise_start_long_44},
  154671. {_noise_part_short_44,_noise_part_long_44},
  154672. _noise_thresh_44,
  154673. _psy_ath_floater,
  154674. _psy_ath_abs,
  154675. _psy_lowpass_44,
  154676. _psy_global_44,
  154677. _global_mapping_44,
  154678. _psy_stereo_modes_44,
  154679. _floor_books,
  154680. _floor,
  154681. _floor_short_mapping_44,
  154682. _floor_long_mapping_44,
  154683. _mapres_template_44_stereo
  154684. };
  154685. ve_setup_data_template ve_setup_X_uncoupled={
  154686. 11,
  154687. rate_mapping_X,
  154688. quality_mapping_44,
  154689. -1,
  154690. 50000,
  154691. 200000,
  154692. blocksize_short_44,
  154693. blocksize_long_44,
  154694. _psy_tone_masteratt_44,
  154695. _psy_tone_0dB,
  154696. _psy_tone_suppress,
  154697. _vp_tonemask_adj_otherblock,
  154698. _vp_tonemask_adj_longblock,
  154699. _vp_tonemask_adj_otherblock,
  154700. _psy_noiseguards_44,
  154701. _psy_noisebias_impulse,
  154702. _psy_noisebias_padding,
  154703. _psy_noisebias_trans,
  154704. _psy_noisebias_long,
  154705. _psy_noise_suppress,
  154706. _psy_compand_44,
  154707. _psy_compand_short_mapping,
  154708. _psy_compand_long_mapping,
  154709. {_noise_start_short_44,_noise_start_long_44},
  154710. {_noise_part_short_44,_noise_part_long_44},
  154711. _noise_thresh_44,
  154712. _psy_ath_floater,
  154713. _psy_ath_abs,
  154714. _psy_lowpass_44,
  154715. _psy_global_44,
  154716. _global_mapping_44,
  154717. NULL,
  154718. _floor_books,
  154719. _floor,
  154720. _floor_short_mapping_44,
  154721. _floor_long_mapping_44,
  154722. _mapres_template_44_uncoupled
  154723. };
  154724. ve_setup_data_template ve_setup_XX_stereo={
  154725. 2,
  154726. rate_mapping_X,
  154727. quality_mapping_8,
  154728. 2,
  154729. 0,
  154730. 8000,
  154731. blocksize_8,
  154732. blocksize_8,
  154733. _psy_tone_masteratt_8,
  154734. _psy_tone_0dB,
  154735. _psy_tone_suppress,
  154736. _vp_tonemask_adj_8,
  154737. NULL,
  154738. _vp_tonemask_adj_8,
  154739. _psy_noiseguards_8,
  154740. _psy_noisebias_8,
  154741. _psy_noisebias_8,
  154742. NULL,
  154743. NULL,
  154744. _psy_noise_suppress,
  154745. _psy_compand_8,
  154746. _psy_compand_8_mapping,
  154747. NULL,
  154748. {_noise_start_8,_noise_start_8},
  154749. {_noise_part_8,_noise_part_8},
  154750. _noise_thresh_5only,
  154751. _psy_ath_floater_8,
  154752. _psy_ath_abs_8,
  154753. _psy_lowpass_8,
  154754. _psy_global_44,
  154755. _global_mapping_8,
  154756. _psy_stereo_modes_8,
  154757. _floor_books,
  154758. _floor,
  154759. _floor_mapping_8,
  154760. NULL,
  154761. _mapres_template_8_stereo
  154762. };
  154763. ve_setup_data_template ve_setup_XX_uncoupled={
  154764. 2,
  154765. rate_mapping_X,
  154766. quality_mapping_8,
  154767. -1,
  154768. 0,
  154769. 8000,
  154770. blocksize_8,
  154771. blocksize_8,
  154772. _psy_tone_masteratt_8,
  154773. _psy_tone_0dB,
  154774. _psy_tone_suppress,
  154775. _vp_tonemask_adj_8,
  154776. NULL,
  154777. _vp_tonemask_adj_8,
  154778. _psy_noiseguards_8,
  154779. _psy_noisebias_8,
  154780. _psy_noisebias_8,
  154781. NULL,
  154782. NULL,
  154783. _psy_noise_suppress,
  154784. _psy_compand_8,
  154785. _psy_compand_8_mapping,
  154786. NULL,
  154787. {_noise_start_8,_noise_start_8},
  154788. {_noise_part_8,_noise_part_8},
  154789. _noise_thresh_5only,
  154790. _psy_ath_floater_8,
  154791. _psy_ath_abs_8,
  154792. _psy_lowpass_8,
  154793. _psy_global_44,
  154794. _global_mapping_8,
  154795. _psy_stereo_modes_8,
  154796. _floor_books,
  154797. _floor,
  154798. _floor_mapping_8,
  154799. NULL,
  154800. _mapres_template_8_uncoupled
  154801. };
  154802. /*** End of inlined file: setup_X.h ***/
  154803. static ve_setup_data_template *setup_list[]={
  154804. &ve_setup_44_stereo,
  154805. &ve_setup_44_uncoupled,
  154806. &ve_setup_32_stereo,
  154807. &ve_setup_32_uncoupled,
  154808. &ve_setup_22_stereo,
  154809. &ve_setup_22_uncoupled,
  154810. &ve_setup_16_stereo,
  154811. &ve_setup_16_uncoupled,
  154812. &ve_setup_11_stereo,
  154813. &ve_setup_11_uncoupled,
  154814. &ve_setup_8_stereo,
  154815. &ve_setup_8_uncoupled,
  154816. &ve_setup_X_stereo,
  154817. &ve_setup_X_uncoupled,
  154818. &ve_setup_XX_stereo,
  154819. &ve_setup_XX_uncoupled,
  154820. 0
  154821. };
  154822. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154823. if(vi && vi->codec_setup){
  154824. vi->version=0;
  154825. vi->channels=ch;
  154826. vi->rate=rate;
  154827. return(0);
  154828. }
  154829. return(OV_EINVAL);
  154830. }
  154831. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154832. static_codebook ***books,
  154833. vorbis_info_floor1 *in,
  154834. int *x){
  154835. int i,k,is=s;
  154836. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154837. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154838. memcpy(f,in+x[is],sizeof(*f));
  154839. /* fill in the lowpass field, even if it's temporary */
  154840. f->n=ci->blocksizes[block]>>1;
  154841. /* books */
  154842. {
  154843. int partitions=f->partitions;
  154844. int maxclass=-1;
  154845. int maxbook=-1;
  154846. for(i=0;i<partitions;i++)
  154847. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154848. for(i=0;i<=maxclass;i++){
  154849. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154850. f->class_book[i]+=ci->books;
  154851. for(k=0;k<(1<<f->class_subs[i]);k++){
  154852. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154853. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154854. }
  154855. }
  154856. for(i=0;i<=maxbook;i++)
  154857. ci->book_param[ci->books++]=books[x[is]][i];
  154858. }
  154859. /* for now, we're only using floor 1 */
  154860. ci->floor_type[ci->floors]=1;
  154861. ci->floor_param[ci->floors]=f;
  154862. ci->floors++;
  154863. return;
  154864. }
  154865. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154866. vorbis_info_psy_global *in,
  154867. double *x){
  154868. int i,is=s;
  154869. double ds=s-is;
  154870. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154871. vorbis_info_psy_global *g=&ci->psy_g_param;
  154872. memcpy(g,in+(int)x[is],sizeof(*g));
  154873. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154874. is=(int)ds;
  154875. ds-=is;
  154876. if(ds==0 && is>0){
  154877. is--;
  154878. ds=1.;
  154879. }
  154880. /* interpolate the trigger threshholds */
  154881. for(i=0;i<4;i++){
  154882. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154883. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154884. }
  154885. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154886. return;
  154887. }
  154888. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154889. highlevel_encode_setup *hi,
  154890. adj_stereo *p){
  154891. float s=hi->stereo_point_setting;
  154892. int i,is=s;
  154893. double ds=s-is;
  154894. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154895. vorbis_info_psy_global *g=&ci->psy_g_param;
  154896. if(p){
  154897. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154898. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154899. if(hi->managed){
  154900. /* interpolate the kHz threshholds */
  154901. for(i=0;i<PACKETBLOBS;i++){
  154902. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154903. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154904. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154905. g->coupling_pkHz[i]=kHz;
  154906. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154907. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154908. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154909. }
  154910. }else{
  154911. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154912. for(i=0;i<PACKETBLOBS;i++){
  154913. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154914. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154915. g->coupling_pkHz[i]=kHz;
  154916. }
  154917. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154918. for(i=0;i<PACKETBLOBS;i++){
  154919. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154920. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154921. }
  154922. }
  154923. }else{
  154924. for(i=0;i<PACKETBLOBS;i++){
  154925. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154926. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154927. }
  154928. }
  154929. return;
  154930. }
  154931. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154932. int *nn_start,
  154933. int *nn_partition,
  154934. double *nn_thresh,
  154935. int block){
  154936. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154937. vorbis_info_psy *p=ci->psy_param[block];
  154938. highlevel_encode_setup *hi=&ci->hi;
  154939. int is=s;
  154940. if(block>=ci->psys)
  154941. ci->psys=block+1;
  154942. if(!p){
  154943. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154944. ci->psy_param[block]=p;
  154945. }
  154946. memcpy(p,&_psy_info_template,sizeof(*p));
  154947. p->blockflag=block>>1;
  154948. if(hi->noise_normalize_p){
  154949. p->normal_channel_p=1;
  154950. p->normal_point_p=1;
  154951. p->normal_start=nn_start[is];
  154952. p->normal_partition=nn_partition[is];
  154953. p->normal_thresh=nn_thresh[is];
  154954. }
  154955. return;
  154956. }
  154957. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154958. att3 *att,
  154959. int *max,
  154960. vp_adjblock *in){
  154961. int i,is=s;
  154962. double ds=s-is;
  154963. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154964. vorbis_info_psy *p=ci->psy_param[block];
  154965. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154966. filling the values in here */
  154967. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154968. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154969. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154970. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154971. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154972. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154973. for(i=0;i<P_BANDS;i++)
  154974. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154975. return;
  154976. }
  154977. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154978. compandblock *in, double *x){
  154979. int i,is=s;
  154980. double ds=s-is;
  154981. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154982. vorbis_info_psy *p=ci->psy_param[block];
  154983. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154984. is=(int)ds;
  154985. ds-=is;
  154986. if(ds==0 && is>0){
  154987. is--;
  154988. ds=1.;
  154989. }
  154990. /* interpolate the compander settings */
  154991. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154992. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154993. return;
  154994. }
  154995. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154996. int *suppress){
  154997. int is=s;
  154998. double ds=s-is;
  154999. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155000. vorbis_info_psy *p=ci->psy_param[block];
  155001. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155002. return;
  155003. }
  155004. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  155005. int *suppress,
  155006. noise3 *in,
  155007. noiseguard *guard,
  155008. double userbias){
  155009. int i,is=s,j;
  155010. double ds=s-is;
  155011. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155012. vorbis_info_psy *p=ci->psy_param[block];
  155013. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155014. p->noisewindowlomin=guard[block].lo;
  155015. p->noisewindowhimin=guard[block].hi;
  155016. p->noisewindowfixed=guard[block].fixed;
  155017. for(j=0;j<P_NOISECURVES;j++)
  155018. for(i=0;i<P_BANDS;i++)
  155019. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  155020. /* impulse blocks may take a user specified bias to boost the
  155021. nominal/high noise encoding depth */
  155022. for(j=0;j<P_NOISECURVES;j++){
  155023. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  155024. for(i=0;i<P_BANDS;i++){
  155025. p->noiseoff[j][i]+=userbias;
  155026. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  155027. }
  155028. }
  155029. return;
  155030. }
  155031. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155032. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155033. vorbis_info_psy *p=ci->psy_param[block];
  155034. p->ath_adjatt=ci->hi.ath_floating_dB;
  155035. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155036. return;
  155037. }
  155038. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155039. int i;
  155040. for(i=0;i<ci->books;i++)
  155041. if(ci->book_param[i]==book)return(i);
  155042. return(ci->books++);
  155043. }
  155044. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155045. int *shortb,int *longb){
  155046. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155047. int is=s;
  155048. int blockshort=shortb[is];
  155049. int blocklong=longb[is];
  155050. ci->blocksizes[0]=blockshort;
  155051. ci->blocksizes[1]=blocklong;
  155052. }
  155053. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155054. int number, int block,
  155055. vorbis_residue_template *res){
  155056. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155057. int i,n;
  155058. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155059. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155060. memcpy(r,res->res,sizeof(*r));
  155061. if(ci->residues<=number)ci->residues=number+1;
  155062. switch(ci->blocksizes[block]){
  155063. case 64:case 128:case 256:
  155064. r->grouping=16;
  155065. break;
  155066. default:
  155067. r->grouping=32;
  155068. break;
  155069. }
  155070. ci->residue_type[number]=res->res_type;
  155071. /* to be adjusted by lowpass/pointlimit later */
  155072. n=r->end=ci->blocksizes[block]>>1;
  155073. if(res->res_type==2)
  155074. n=r->end*=vi->channels;
  155075. /* fill in all the books */
  155076. {
  155077. int booklist=0,k;
  155078. if(ci->hi.managed){
  155079. for(i=0;i<r->partitions;i++)
  155080. for(k=0;k<3;k++)
  155081. if(res->books_base_managed->books[i][k])
  155082. r->secondstages[i]|=(1<<k);
  155083. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155084. ci->book_param[r->groupbook]=res->book_aux_managed;
  155085. for(i=0;i<r->partitions;i++){
  155086. for(k=0;k<3;k++){
  155087. if(res->books_base_managed->books[i][k]){
  155088. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155089. r->booklist[booklist++]=bookid;
  155090. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155091. }
  155092. }
  155093. }
  155094. }else{
  155095. for(i=0;i<r->partitions;i++)
  155096. for(k=0;k<3;k++)
  155097. if(res->books_base->books[i][k])
  155098. r->secondstages[i]|=(1<<k);
  155099. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155100. ci->book_param[r->groupbook]=res->book_aux;
  155101. for(i=0;i<r->partitions;i++){
  155102. for(k=0;k<3;k++){
  155103. if(res->books_base->books[i][k]){
  155104. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155105. r->booklist[booklist++]=bookid;
  155106. ci->book_param[bookid]=res->books_base->books[i][k];
  155107. }
  155108. }
  155109. }
  155110. }
  155111. }
  155112. /* lowpass setup/pointlimit */
  155113. {
  155114. double freq=ci->hi.lowpass_kHz*1000.;
  155115. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155116. double nyq=vi->rate/2.;
  155117. long blocksize=ci->blocksizes[block]>>1;
  155118. /* lowpass needs to be set in the floor and the residue. */
  155119. if(freq>nyq)freq=nyq;
  155120. /* in the floor, the granularity can be very fine; it doesn't alter
  155121. the encoding structure, only the samples used to fit the floor
  155122. approximation */
  155123. f->n=freq/nyq*blocksize;
  155124. /* this res may by limited by the maximum pointlimit of the mode,
  155125. not the lowpass. the floor is always lowpass limited. */
  155126. if(res->limit_type){
  155127. if(ci->hi.managed)
  155128. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155129. else
  155130. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155131. if(freq>nyq)freq=nyq;
  155132. }
  155133. /* in the residue, we're constrained, physically, by partition
  155134. boundaries. We still lowpass 'wherever', but we have to round up
  155135. here to next boundary, or the vorbis spec will round it *down* to
  155136. previous boundary in encode/decode */
  155137. if(ci->residue_type[block]==2)
  155138. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155139. r->grouping;
  155140. else
  155141. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155142. r->grouping;
  155143. }
  155144. }
  155145. /* we assume two maps in this encoder */
  155146. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155147. vorbis_mapping_template *maps){
  155148. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155149. int i,j,is=s,modes=2;
  155150. vorbis_info_mapping0 *map=maps[is].map;
  155151. vorbis_info_mode *mode=_mode_template;
  155152. vorbis_residue_template *res=maps[is].res;
  155153. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155154. for(i=0;i<modes;i++){
  155155. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155156. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155157. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155158. if(i>=ci->modes)ci->modes=i+1;
  155159. ci->map_type[i]=0;
  155160. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155161. if(i>=ci->maps)ci->maps=i+1;
  155162. for(j=0;j<map[i].submaps;j++)
  155163. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155164. ,res+map[i].residuesubmap[j]);
  155165. }
  155166. }
  155167. static double setting_to_approx_bitrate(vorbis_info *vi){
  155168. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155169. highlevel_encode_setup *hi=&ci->hi;
  155170. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155171. int is=hi->base_setting;
  155172. double ds=hi->base_setting-is;
  155173. int ch=vi->channels;
  155174. double *r=setup->rate_mapping;
  155175. if(r==NULL)
  155176. return(-1);
  155177. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155178. }
  155179. static void get_setup_template(vorbis_info *vi,
  155180. long ch,long srate,
  155181. double req,int q_or_bitrate){
  155182. int i=0,j;
  155183. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155184. highlevel_encode_setup *hi=&ci->hi;
  155185. if(q_or_bitrate)req/=ch;
  155186. while(setup_list[i]){
  155187. if(setup_list[i]->coupling_restriction==-1 ||
  155188. setup_list[i]->coupling_restriction==ch){
  155189. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155190. srate<=setup_list[i]->samplerate_max_restriction){
  155191. int mappings=setup_list[i]->mappings;
  155192. double *map=(q_or_bitrate?
  155193. setup_list[i]->rate_mapping:
  155194. setup_list[i]->quality_mapping);
  155195. /* the template matches. Does the requested quality mode
  155196. fall within this template's modes? */
  155197. if(req<map[0]){++i;continue;}
  155198. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155199. for(j=0;j<mappings;j++)
  155200. if(req>=map[j] && req<map[j+1])break;
  155201. /* an all-points match */
  155202. hi->setup=setup_list[i];
  155203. if(j==mappings)
  155204. hi->base_setting=j-.001;
  155205. else{
  155206. float low=map[j];
  155207. float high=map[j+1];
  155208. float del=(req-low)/(high-low);
  155209. hi->base_setting=j+del;
  155210. }
  155211. return;
  155212. }
  155213. }
  155214. i++;
  155215. }
  155216. hi->setup=NULL;
  155217. }
  155218. /* encoders will need to use vorbis_info_init beforehand and call
  155219. vorbis_info clear when all done */
  155220. /* two interfaces; this, more detailed one, and later a convenience
  155221. layer on top */
  155222. /* the final setup call */
  155223. int vorbis_encode_setup_init(vorbis_info *vi){
  155224. int i0=0,singleblock=0;
  155225. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155226. ve_setup_data_template *setup=NULL;
  155227. highlevel_encode_setup *hi=&ci->hi;
  155228. if(ci==NULL)return(OV_EINVAL);
  155229. if(!hi->impulse_block_p)i0=1;
  155230. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155231. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155232. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155233. /* again, bound this to avoid the app shooting itself int he foot
  155234. too badly */
  155235. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155236. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155237. /* get the appropriate setup template; matches the fetch in previous
  155238. stages */
  155239. setup=(ve_setup_data_template *)hi->setup;
  155240. if(setup==NULL)return(OV_EINVAL);
  155241. hi->set_in_stone=1;
  155242. /* choose block sizes from configured sizes as well as paying
  155243. attention to long_block_p and short_block_p. If the configured
  155244. short and long blocks are the same length, we set long_block_p
  155245. and unset short_block_p */
  155246. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155247. setup->blocksize_short,
  155248. setup->blocksize_long);
  155249. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155250. /* floor setup; choose proper floor params. Allocated on the floor
  155251. stack in order; if we alloc only long floor, it's 0 */
  155252. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155253. setup->floor_books,
  155254. setup->floor_params,
  155255. setup->floor_short_mapping);
  155256. if(!singleblock)
  155257. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155258. setup->floor_books,
  155259. setup->floor_params,
  155260. setup->floor_long_mapping);
  155261. /* setup of [mostly] short block detection and stereo*/
  155262. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155263. setup->global_params,
  155264. setup->global_mapping);
  155265. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155266. /* basic psych setup and noise normalization */
  155267. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155268. setup->psy_noise_normal_start[0],
  155269. setup->psy_noise_normal_partition[0],
  155270. setup->psy_noise_normal_thresh,
  155271. 0);
  155272. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155273. setup->psy_noise_normal_start[0],
  155274. setup->psy_noise_normal_partition[0],
  155275. setup->psy_noise_normal_thresh,
  155276. 1);
  155277. if(!singleblock){
  155278. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155279. setup->psy_noise_normal_start[1],
  155280. setup->psy_noise_normal_partition[1],
  155281. setup->psy_noise_normal_thresh,
  155282. 2);
  155283. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155284. setup->psy_noise_normal_start[1],
  155285. setup->psy_noise_normal_partition[1],
  155286. setup->psy_noise_normal_thresh,
  155287. 3);
  155288. }
  155289. /* tone masking setup */
  155290. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155291. setup->psy_tone_masteratt,
  155292. setup->psy_tone_0dB,
  155293. setup->psy_tone_adj_impulse);
  155294. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155295. setup->psy_tone_masteratt,
  155296. setup->psy_tone_0dB,
  155297. setup->psy_tone_adj_other);
  155298. if(!singleblock){
  155299. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155300. setup->psy_tone_masteratt,
  155301. setup->psy_tone_0dB,
  155302. setup->psy_tone_adj_other);
  155303. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155304. setup->psy_tone_masteratt,
  155305. setup->psy_tone_0dB,
  155306. setup->psy_tone_adj_long);
  155307. }
  155308. /* noise companding setup */
  155309. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155310. setup->psy_noise_compand,
  155311. setup->psy_noise_compand_short_mapping);
  155312. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155313. setup->psy_noise_compand,
  155314. setup->psy_noise_compand_short_mapping);
  155315. if(!singleblock){
  155316. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155317. setup->psy_noise_compand,
  155318. setup->psy_noise_compand_long_mapping);
  155319. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155320. setup->psy_noise_compand,
  155321. setup->psy_noise_compand_long_mapping);
  155322. }
  155323. /* peak guarding setup */
  155324. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155325. setup->psy_tone_dBsuppress);
  155326. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155327. setup->psy_tone_dBsuppress);
  155328. if(!singleblock){
  155329. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155330. setup->psy_tone_dBsuppress);
  155331. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155332. setup->psy_tone_dBsuppress);
  155333. }
  155334. /* noise bias setup */
  155335. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155336. setup->psy_noise_dBsuppress,
  155337. setup->psy_noise_bias_impulse,
  155338. setup->psy_noiseguards,
  155339. (i0==0?hi->impulse_noisetune:0.));
  155340. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155341. setup->psy_noise_dBsuppress,
  155342. setup->psy_noise_bias_padding,
  155343. setup->psy_noiseguards,0.);
  155344. if(!singleblock){
  155345. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155346. setup->psy_noise_dBsuppress,
  155347. setup->psy_noise_bias_trans,
  155348. setup->psy_noiseguards,0.);
  155349. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155350. setup->psy_noise_dBsuppress,
  155351. setup->psy_noise_bias_long,
  155352. setup->psy_noiseguards,0.);
  155353. }
  155354. vorbis_encode_ath_setup(vi,0);
  155355. vorbis_encode_ath_setup(vi,1);
  155356. if(!singleblock){
  155357. vorbis_encode_ath_setup(vi,2);
  155358. vorbis_encode_ath_setup(vi,3);
  155359. }
  155360. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155361. /* set bitrate readonlies and management */
  155362. if(hi->bitrate_av>0)
  155363. vi->bitrate_nominal=hi->bitrate_av;
  155364. else{
  155365. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155366. }
  155367. vi->bitrate_lower=hi->bitrate_min;
  155368. vi->bitrate_upper=hi->bitrate_max;
  155369. if(hi->bitrate_av)
  155370. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155371. else
  155372. vi->bitrate_window=0.;
  155373. if(hi->managed){
  155374. ci->bi.avg_rate=hi->bitrate_av;
  155375. ci->bi.min_rate=hi->bitrate_min;
  155376. ci->bi.max_rate=hi->bitrate_max;
  155377. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155378. ci->bi.reservoir_bias=
  155379. hi->bitrate_reservoir_bias;
  155380. ci->bi.slew_damp=hi->bitrate_av_damp;
  155381. }
  155382. return(0);
  155383. }
  155384. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155385. long channels,
  155386. long rate){
  155387. int ret=0,i,is;
  155388. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155389. highlevel_encode_setup *hi=&ci->hi;
  155390. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155391. double ds;
  155392. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155393. if(ret)return(ret);
  155394. is=hi->base_setting;
  155395. ds=hi->base_setting-is;
  155396. hi->short_setting=hi->base_setting;
  155397. hi->long_setting=hi->base_setting;
  155398. hi->managed=0;
  155399. hi->impulse_block_p=1;
  155400. hi->noise_normalize_p=1;
  155401. hi->stereo_point_setting=hi->base_setting;
  155402. hi->lowpass_kHz=
  155403. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155404. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155405. setup->psy_ath_float[is+1]*ds;
  155406. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155407. setup->psy_ath_abs[is+1]*ds;
  155408. hi->amplitude_track_dBpersec=-6.;
  155409. hi->trigger_setting=hi->base_setting;
  155410. for(i=0;i<4;i++){
  155411. hi->block[i].tone_mask_setting=hi->base_setting;
  155412. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155413. hi->block[i].noise_bias_setting=hi->base_setting;
  155414. hi->block[i].noise_compand_setting=hi->base_setting;
  155415. }
  155416. return(ret);
  155417. }
  155418. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155419. long channels,
  155420. long rate,
  155421. float quality){
  155422. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155423. highlevel_encode_setup *hi=&ci->hi;
  155424. quality+=.0000001;
  155425. if(quality>=1.)quality=.9999;
  155426. get_setup_template(vi,channels,rate,quality,0);
  155427. if(!hi->setup)return OV_EIMPL;
  155428. return vorbis_encode_setup_setting(vi,channels,rate);
  155429. }
  155430. int vorbis_encode_init_vbr(vorbis_info *vi,
  155431. long channels,
  155432. long rate,
  155433. float base_quality /* 0. to 1. */
  155434. ){
  155435. int ret=0;
  155436. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155437. if(ret){
  155438. vorbis_info_clear(vi);
  155439. return ret;
  155440. }
  155441. ret=vorbis_encode_setup_init(vi);
  155442. if(ret)
  155443. vorbis_info_clear(vi);
  155444. return(ret);
  155445. }
  155446. int vorbis_encode_setup_managed(vorbis_info *vi,
  155447. long channels,
  155448. long rate,
  155449. long max_bitrate,
  155450. long nominal_bitrate,
  155451. long min_bitrate){
  155452. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155453. highlevel_encode_setup *hi=&ci->hi;
  155454. double tnominal=nominal_bitrate;
  155455. int ret=0;
  155456. if(nominal_bitrate<=0.){
  155457. if(max_bitrate>0.){
  155458. if(min_bitrate>0.)
  155459. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155460. else
  155461. nominal_bitrate=max_bitrate*.875;
  155462. }else{
  155463. if(min_bitrate>0.){
  155464. nominal_bitrate=min_bitrate;
  155465. }else{
  155466. return(OV_EINVAL);
  155467. }
  155468. }
  155469. }
  155470. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155471. if(!hi->setup)return OV_EIMPL;
  155472. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155473. if(ret){
  155474. vorbis_info_clear(vi);
  155475. return ret;
  155476. }
  155477. /* initialize management with sane defaults */
  155478. hi->managed=1;
  155479. hi->bitrate_min=min_bitrate;
  155480. hi->bitrate_max=max_bitrate;
  155481. hi->bitrate_av=tnominal;
  155482. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155483. hi->bitrate_reservoir=nominal_bitrate*2;
  155484. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155485. return(ret);
  155486. }
  155487. int vorbis_encode_init(vorbis_info *vi,
  155488. long channels,
  155489. long rate,
  155490. long max_bitrate,
  155491. long nominal_bitrate,
  155492. long min_bitrate){
  155493. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155494. max_bitrate,
  155495. nominal_bitrate,
  155496. min_bitrate);
  155497. if(ret){
  155498. vorbis_info_clear(vi);
  155499. return(ret);
  155500. }
  155501. ret=vorbis_encode_setup_init(vi);
  155502. if(ret)
  155503. vorbis_info_clear(vi);
  155504. return(ret);
  155505. }
  155506. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155507. if(vi){
  155508. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155509. highlevel_encode_setup *hi=&ci->hi;
  155510. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155511. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155512. switch(number){
  155513. /* now deprecated *****************/
  155514. case OV_ECTL_RATEMANAGE_GET:
  155515. {
  155516. struct ovectl_ratemanage_arg *ai=
  155517. (struct ovectl_ratemanage_arg *)arg;
  155518. ai->management_active=hi->managed;
  155519. ai->bitrate_hard_window=ai->bitrate_av_window=
  155520. (double)hi->bitrate_reservoir/vi->rate;
  155521. ai->bitrate_av_window_center=1.;
  155522. ai->bitrate_hard_min=hi->bitrate_min;
  155523. ai->bitrate_hard_max=hi->bitrate_max;
  155524. ai->bitrate_av_lo=hi->bitrate_av;
  155525. ai->bitrate_av_hi=hi->bitrate_av;
  155526. }
  155527. return(0);
  155528. /* now deprecated *****************/
  155529. case OV_ECTL_RATEMANAGE_SET:
  155530. {
  155531. struct ovectl_ratemanage_arg *ai=
  155532. (struct ovectl_ratemanage_arg *)arg;
  155533. if(ai==NULL){
  155534. hi->managed=0;
  155535. }else{
  155536. hi->managed=ai->management_active;
  155537. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155538. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155539. }
  155540. }
  155541. return 0;
  155542. /* now deprecated *****************/
  155543. case OV_ECTL_RATEMANAGE_AVG:
  155544. {
  155545. struct ovectl_ratemanage_arg *ai=
  155546. (struct ovectl_ratemanage_arg *)arg;
  155547. if(ai==NULL){
  155548. hi->bitrate_av=0;
  155549. }else{
  155550. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155551. }
  155552. }
  155553. return(0);
  155554. /* now deprecated *****************/
  155555. case OV_ECTL_RATEMANAGE_HARD:
  155556. {
  155557. struct ovectl_ratemanage_arg *ai=
  155558. (struct ovectl_ratemanage_arg *)arg;
  155559. if(ai==NULL){
  155560. hi->bitrate_min=0;
  155561. hi->bitrate_max=0;
  155562. }else{
  155563. hi->bitrate_min=ai->bitrate_hard_min;
  155564. hi->bitrate_max=ai->bitrate_hard_max;
  155565. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155566. (hi->bitrate_max+hi->bitrate_min)*.5;
  155567. }
  155568. if(hi->bitrate_reservoir<128.)
  155569. hi->bitrate_reservoir=128.;
  155570. }
  155571. return(0);
  155572. /* replacement ratemanage interface */
  155573. case OV_ECTL_RATEMANAGE2_GET:
  155574. {
  155575. struct ovectl_ratemanage2_arg *ai=
  155576. (struct ovectl_ratemanage2_arg *)arg;
  155577. if(ai==NULL)return OV_EINVAL;
  155578. ai->management_active=hi->managed;
  155579. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155580. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155581. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155582. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155583. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155584. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155585. }
  155586. return (0);
  155587. case OV_ECTL_RATEMANAGE2_SET:
  155588. {
  155589. struct ovectl_ratemanage2_arg *ai=
  155590. (struct ovectl_ratemanage2_arg *)arg;
  155591. if(ai==NULL){
  155592. hi->managed=0;
  155593. }else{
  155594. /* sanity check; only catch invariant violations */
  155595. if(ai->bitrate_limit_min_kbps>0 &&
  155596. ai->bitrate_average_kbps>0 &&
  155597. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155598. return OV_EINVAL;
  155599. if(ai->bitrate_limit_max_kbps>0 &&
  155600. ai->bitrate_average_kbps>0 &&
  155601. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155602. return OV_EINVAL;
  155603. if(ai->bitrate_limit_min_kbps>0 &&
  155604. ai->bitrate_limit_max_kbps>0 &&
  155605. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155606. return OV_EINVAL;
  155607. if(ai->bitrate_average_damping <= 0.)
  155608. return OV_EINVAL;
  155609. if(ai->bitrate_limit_reservoir_bits < 0)
  155610. return OV_EINVAL;
  155611. if(ai->bitrate_limit_reservoir_bias < 0.)
  155612. return OV_EINVAL;
  155613. if(ai->bitrate_limit_reservoir_bias > 1.)
  155614. return OV_EINVAL;
  155615. hi->managed=ai->management_active;
  155616. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155617. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155618. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155619. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155620. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155621. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155622. }
  155623. }
  155624. return 0;
  155625. case OV_ECTL_LOWPASS_GET:
  155626. {
  155627. double *farg=(double *)arg;
  155628. *farg=hi->lowpass_kHz;
  155629. }
  155630. return(0);
  155631. case OV_ECTL_LOWPASS_SET:
  155632. {
  155633. double *farg=(double *)arg;
  155634. hi->lowpass_kHz=*farg;
  155635. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155636. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155637. }
  155638. return(0);
  155639. case OV_ECTL_IBLOCK_GET:
  155640. {
  155641. double *farg=(double *)arg;
  155642. *farg=hi->impulse_noisetune;
  155643. }
  155644. return(0);
  155645. case OV_ECTL_IBLOCK_SET:
  155646. {
  155647. double *farg=(double *)arg;
  155648. hi->impulse_noisetune=*farg;
  155649. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155650. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155651. }
  155652. return(0);
  155653. }
  155654. return(OV_EIMPL);
  155655. }
  155656. return(OV_EINVAL);
  155657. }
  155658. #endif
  155659. /*** End of inlined file: vorbisenc.c ***/
  155660. /*** Start of inlined file: vorbisfile.c ***/
  155661. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155662. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155663. // tasks..
  155664. #if JUCE_MSVC
  155665. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155666. #endif
  155667. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155668. #if JUCE_USE_OGGVORBIS
  155669. #include <stdlib.h>
  155670. #include <stdio.h>
  155671. #include <errno.h>
  155672. #include <string.h>
  155673. #include <math.h>
  155674. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155675. one logical bitstream arranged end to end (the only form of Ogg
  155676. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155677. multiplexing] is not allowed in Vorbis) */
  155678. /* A Vorbis file can be played beginning to end (streamed) without
  155679. worrying ahead of time about chaining (see decoder_example.c). If
  155680. we have the whole file, however, and want random access
  155681. (seeking/scrubbing) or desire to know the total length/time of a
  155682. file, we need to account for the possibility of chaining. */
  155683. /* We can handle things a number of ways; we can determine the entire
  155684. bitstream structure right off the bat, or find pieces on demand.
  155685. This example determines and caches structure for the entire
  155686. bitstream, but builds a virtual decoder on the fly when moving
  155687. between links in the chain. */
  155688. /* There are also different ways to implement seeking. Enough
  155689. information exists in an Ogg bitstream to seek to
  155690. sample-granularity positions in the output. Or, one can seek by
  155691. picking some portion of the stream roughly in the desired area if
  155692. we only want coarse navigation through the stream. */
  155693. /*************************************************************************
  155694. * Many, many internal helpers. The intention is not to be confusing;
  155695. * rampant duplication and monolithic function implementation would be
  155696. * harder to understand anyway. The high level functions are last. Begin
  155697. * grokking near the end of the file */
  155698. /* read a little more data from the file/pipe into the ogg_sync framer
  155699. */
  155700. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155701. over 8k gets what they deserve */
  155702. static long _get_data(OggVorbis_File *vf){
  155703. errno=0;
  155704. if(vf->datasource){
  155705. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155706. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155707. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155708. if(bytes==0 && errno)return(-1);
  155709. return(bytes);
  155710. }else
  155711. return(0);
  155712. }
  155713. /* save a tiny smidge of verbosity to make the code more readable */
  155714. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155715. if(vf->datasource){
  155716. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155717. vf->offset=offset;
  155718. ogg_sync_reset(&vf->oy);
  155719. }else{
  155720. /* shouldn't happen unless someone writes a broken callback */
  155721. return;
  155722. }
  155723. }
  155724. /* The read/seek functions track absolute position within the stream */
  155725. /* from the head of the stream, get the next page. boundary specifies
  155726. if the function is allowed to fetch more data from the stream (and
  155727. how much) or only use internally buffered data.
  155728. boundary: -1) unbounded search
  155729. 0) read no additional data; use cached only
  155730. n) search for a new page beginning for n bytes
  155731. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155732. n) found a page at absolute offset n */
  155733. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155734. ogg_int64_t boundary){
  155735. if(boundary>0)boundary+=vf->offset;
  155736. while(1){
  155737. long more;
  155738. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155739. more=ogg_sync_pageseek(&vf->oy,og);
  155740. if(more<0){
  155741. /* skipped n bytes */
  155742. vf->offset-=more;
  155743. }else{
  155744. if(more==0){
  155745. /* send more paramedics */
  155746. if(!boundary)return(OV_FALSE);
  155747. {
  155748. long ret=_get_data(vf);
  155749. if(ret==0)return(OV_EOF);
  155750. if(ret<0)return(OV_EREAD);
  155751. }
  155752. }else{
  155753. /* got a page. Return the offset at the page beginning,
  155754. advance the internal offset past the page end */
  155755. ogg_int64_t ret=vf->offset;
  155756. vf->offset+=more;
  155757. return(ret);
  155758. }
  155759. }
  155760. }
  155761. }
  155762. /* find the latest page beginning before the current stream cursor
  155763. position. Much dirtier than the above as Ogg doesn't have any
  155764. backward search linkage. no 'readp' as it will certainly have to
  155765. read. */
  155766. /* returns offset or OV_EREAD, OV_FAULT */
  155767. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155768. ogg_int64_t begin=vf->offset;
  155769. ogg_int64_t end=begin;
  155770. ogg_int64_t ret;
  155771. ogg_int64_t offset=-1;
  155772. while(offset==-1){
  155773. begin-=CHUNKSIZE;
  155774. if(begin<0)
  155775. begin=0;
  155776. _seek_helper(vf,begin);
  155777. while(vf->offset<end){
  155778. ret=_get_next_page(vf,og,end-vf->offset);
  155779. if(ret==OV_EREAD)return(OV_EREAD);
  155780. if(ret<0){
  155781. break;
  155782. }else{
  155783. offset=ret;
  155784. }
  155785. }
  155786. }
  155787. /* we have the offset. Actually snork and hold the page now */
  155788. _seek_helper(vf,offset);
  155789. ret=_get_next_page(vf,og,CHUNKSIZE);
  155790. if(ret<0)
  155791. /* this shouldn't be possible */
  155792. return(OV_EFAULT);
  155793. return(offset);
  155794. }
  155795. /* finds each bitstream link one at a time using a bisection search
  155796. (has to begin by knowing the offset of the lb's initial page).
  155797. Recurses for each link so it can alloc the link storage after
  155798. finding them all, then unroll and fill the cache at the same time */
  155799. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155800. ogg_int64_t begin,
  155801. ogg_int64_t searched,
  155802. ogg_int64_t end,
  155803. long currentno,
  155804. long m){
  155805. ogg_int64_t endsearched=end;
  155806. ogg_int64_t next=end;
  155807. ogg_page og;
  155808. ogg_int64_t ret;
  155809. /* the below guards against garbage seperating the last and
  155810. first pages of two links. */
  155811. while(searched<endsearched){
  155812. ogg_int64_t bisect;
  155813. if(endsearched-searched<CHUNKSIZE){
  155814. bisect=searched;
  155815. }else{
  155816. bisect=(searched+endsearched)/2;
  155817. }
  155818. _seek_helper(vf,bisect);
  155819. ret=_get_next_page(vf,&og,-1);
  155820. if(ret==OV_EREAD)return(OV_EREAD);
  155821. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155822. endsearched=bisect;
  155823. if(ret>=0)next=ret;
  155824. }else{
  155825. searched=ret+og.header_len+og.body_len;
  155826. }
  155827. }
  155828. _seek_helper(vf,next);
  155829. ret=_get_next_page(vf,&og,-1);
  155830. if(ret==OV_EREAD)return(OV_EREAD);
  155831. if(searched>=end || ret<0){
  155832. vf->links=m+1;
  155833. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155834. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155835. vf->offsets[m+1]=searched;
  155836. }else{
  155837. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155838. end,ogg_page_serialno(&og),m+1);
  155839. if(ret==OV_EREAD)return(OV_EREAD);
  155840. }
  155841. vf->offsets[m]=begin;
  155842. vf->serialnos[m]=currentno;
  155843. return(0);
  155844. }
  155845. /* uses the local ogg_stream storage in vf; this is important for
  155846. non-streaming input sources */
  155847. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155848. long *serialno,ogg_page *og_ptr){
  155849. ogg_page og;
  155850. ogg_packet op;
  155851. int i,ret;
  155852. if(!og_ptr){
  155853. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155854. if(llret==OV_EREAD)return(OV_EREAD);
  155855. if(llret<0)return OV_ENOTVORBIS;
  155856. og_ptr=&og;
  155857. }
  155858. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155859. if(serialno)*serialno=vf->os.serialno;
  155860. vf->ready_state=STREAMSET;
  155861. /* extract the initial header from the first page and verify that the
  155862. Ogg bitstream is in fact Vorbis data */
  155863. vorbis_info_init(vi);
  155864. vorbis_comment_init(vc);
  155865. i=0;
  155866. while(i<3){
  155867. ogg_stream_pagein(&vf->os,og_ptr);
  155868. while(i<3){
  155869. int result=ogg_stream_packetout(&vf->os,&op);
  155870. if(result==0)break;
  155871. if(result==-1){
  155872. ret=OV_EBADHEADER;
  155873. goto bail_header;
  155874. }
  155875. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155876. goto bail_header;
  155877. }
  155878. i++;
  155879. }
  155880. if(i<3)
  155881. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155882. ret=OV_EBADHEADER;
  155883. goto bail_header;
  155884. }
  155885. }
  155886. return 0;
  155887. bail_header:
  155888. vorbis_info_clear(vi);
  155889. vorbis_comment_clear(vc);
  155890. vf->ready_state=OPENED;
  155891. return ret;
  155892. }
  155893. /* last step of the OggVorbis_File initialization; get all the
  155894. vorbis_info structs and PCM positions. Only called by the seekable
  155895. initialization (local stream storage is hacked slightly; pay
  155896. attention to how that's done) */
  155897. /* this is void and does not propogate errors up because we want to be
  155898. able to open and use damaged bitstreams as well as we can. Just
  155899. watch out for missing information for links in the OggVorbis_File
  155900. struct */
  155901. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155902. ogg_page og;
  155903. int i;
  155904. ogg_int64_t ret;
  155905. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155906. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155907. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155908. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155909. for(i=0;i<vf->links;i++){
  155910. if(i==0){
  155911. /* we already grabbed the initial header earlier. Just set the offset */
  155912. vf->dataoffsets[i]=dataoffset;
  155913. _seek_helper(vf,dataoffset);
  155914. }else{
  155915. /* seek to the location of the initial header */
  155916. _seek_helper(vf,vf->offsets[i]);
  155917. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155918. vf->dataoffsets[i]=-1;
  155919. }else{
  155920. vf->dataoffsets[i]=vf->offset;
  155921. }
  155922. }
  155923. /* fetch beginning PCM offset */
  155924. if(vf->dataoffsets[i]!=-1){
  155925. ogg_int64_t accumulated=0;
  155926. long lastblock=-1;
  155927. int result;
  155928. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155929. while(1){
  155930. ogg_packet op;
  155931. ret=_get_next_page(vf,&og,-1);
  155932. if(ret<0)
  155933. /* this should not be possible unless the file is
  155934. truncated/mangled */
  155935. break;
  155936. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155937. break;
  155938. /* count blocksizes of all frames in the page */
  155939. ogg_stream_pagein(&vf->os,&og);
  155940. while((result=ogg_stream_packetout(&vf->os,&op))){
  155941. if(result>0){ /* ignore holes */
  155942. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155943. if(lastblock!=-1)
  155944. accumulated+=(lastblock+thisblock)>>2;
  155945. lastblock=thisblock;
  155946. }
  155947. }
  155948. if(ogg_page_granulepos(&og)!=-1){
  155949. /* pcm offset of last packet on the first audio page */
  155950. accumulated= ogg_page_granulepos(&og)-accumulated;
  155951. break;
  155952. }
  155953. }
  155954. /* less than zero? This is a stream with samples trimmed off
  155955. the beginning, a normal occurrence; set the offset to zero */
  155956. if(accumulated<0)accumulated=0;
  155957. vf->pcmlengths[i*2]=accumulated;
  155958. }
  155959. /* get the PCM length of this link. To do this,
  155960. get the last page of the stream */
  155961. {
  155962. ogg_int64_t end=vf->offsets[i+1];
  155963. _seek_helper(vf,end);
  155964. while(1){
  155965. ret=_get_prev_page(vf,&og);
  155966. if(ret<0){
  155967. /* this should not be possible */
  155968. vorbis_info_clear(vf->vi+i);
  155969. vorbis_comment_clear(vf->vc+i);
  155970. break;
  155971. }
  155972. if(ogg_page_granulepos(&og)!=-1){
  155973. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155974. break;
  155975. }
  155976. vf->offset=ret;
  155977. }
  155978. }
  155979. }
  155980. }
  155981. static int _make_decode_ready(OggVorbis_File *vf){
  155982. if(vf->ready_state>STREAMSET)return 0;
  155983. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155984. if(vf->seekable){
  155985. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155986. return OV_EBADLINK;
  155987. }else{
  155988. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155989. return OV_EBADLINK;
  155990. }
  155991. vorbis_block_init(&vf->vd,&vf->vb);
  155992. vf->ready_state=INITSET;
  155993. vf->bittrack=0.f;
  155994. vf->samptrack=0.f;
  155995. return 0;
  155996. }
  155997. static int _open_seekable2(OggVorbis_File *vf){
  155998. long serialno=vf->current_serialno;
  155999. ogg_int64_t dataoffset=vf->offset, end;
  156000. ogg_page og;
  156001. /* we're partially open and have a first link header state in
  156002. storage in vf */
  156003. /* we can seek, so set out learning all about this file */
  156004. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  156005. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  156006. /* We get the offset for the last page of the physical bitstream.
  156007. Most OggVorbis files will contain a single logical bitstream */
  156008. end=_get_prev_page(vf,&og);
  156009. if(end<0)return(end);
  156010. /* more than one logical bitstream? */
  156011. if(ogg_page_serialno(&og)!=serialno){
  156012. /* Chained bitstream. Bisect-search each logical bitstream
  156013. section. Do so based on serial number only */
  156014. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  156015. }else{
  156016. /* Only one logical bitstream */
  156017. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  156018. }
  156019. /* the initial header memory is referenced by vf after; don't free it */
  156020. _prefetch_all_headers(vf,dataoffset);
  156021. return(ov_raw_seek(vf,0));
  156022. }
  156023. /* clear out the current logical bitstream decoder */
  156024. static void _decode_clear(OggVorbis_File *vf){
  156025. vorbis_dsp_clear(&vf->vd);
  156026. vorbis_block_clear(&vf->vb);
  156027. vf->ready_state=OPENED;
  156028. }
  156029. /* fetch and process a packet. Handles the case where we're at a
  156030. bitstream boundary and dumps the decoding machine. If the decoding
  156031. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156032. date (seek and read both use this. seek uses a special hack with
  156033. readp).
  156034. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156035. 0) need more data (only if readp==0)
  156036. 1) got a packet
  156037. */
  156038. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156039. ogg_packet *op_in,
  156040. int readp,
  156041. int spanp){
  156042. ogg_page og;
  156043. /* handle one packet. Try to fetch it from current stream state */
  156044. /* extract packets from page */
  156045. while(1){
  156046. /* process a packet if we can. If the machine isn't loaded,
  156047. neither is a page */
  156048. if(vf->ready_state==INITSET){
  156049. while(1) {
  156050. ogg_packet op;
  156051. ogg_packet *op_ptr=(op_in?op_in:&op);
  156052. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156053. ogg_int64_t granulepos;
  156054. op_in=NULL;
  156055. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156056. if(result>0){
  156057. /* got a packet. process it */
  156058. granulepos=op_ptr->granulepos;
  156059. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156060. header handling. The
  156061. header packets aren't
  156062. audio, so if/when we
  156063. submit them,
  156064. vorbis_synthesis will
  156065. reject them */
  156066. /* suck in the synthesis data and track bitrate */
  156067. {
  156068. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156069. /* for proper use of libvorbis within libvorbisfile,
  156070. oldsamples will always be zero. */
  156071. if(oldsamples)return(OV_EFAULT);
  156072. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156073. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156074. vf->bittrack+=op_ptr->bytes*8;
  156075. }
  156076. /* update the pcm offset. */
  156077. if(granulepos!=-1 && !op_ptr->e_o_s){
  156078. int link=(vf->seekable?vf->current_link:0);
  156079. int i,samples;
  156080. /* this packet has a pcm_offset on it (the last packet
  156081. completed on a page carries the offset) After processing
  156082. (above), we know the pcm position of the *last* sample
  156083. ready to be returned. Find the offset of the *first*
  156084. As an aside, this trick is inaccurate if we begin
  156085. reading anew right at the last page; the end-of-stream
  156086. granulepos declares the last frame in the stream, and the
  156087. last packet of the last page may be a partial frame.
  156088. So, we need a previous granulepos from an in-sequence page
  156089. to have a reference point. Thus the !op_ptr->e_o_s clause
  156090. above */
  156091. if(vf->seekable && link>0)
  156092. granulepos-=vf->pcmlengths[link*2];
  156093. if(granulepos<0)granulepos=0; /* actually, this
  156094. shouldn't be possible
  156095. here unless the stream
  156096. is very broken */
  156097. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156098. granulepos-=samples;
  156099. for(i=0;i<link;i++)
  156100. granulepos+=vf->pcmlengths[i*2+1];
  156101. vf->pcm_offset=granulepos;
  156102. }
  156103. return(1);
  156104. }
  156105. }
  156106. else
  156107. break;
  156108. }
  156109. }
  156110. if(vf->ready_state>=OPENED){
  156111. ogg_int64_t ret;
  156112. if(!readp)return(0);
  156113. if((ret=_get_next_page(vf,&og,-1))<0){
  156114. return(OV_EOF); /* eof.
  156115. leave unitialized */
  156116. }
  156117. /* bitrate tracking; add the header's bytes here, the body bytes
  156118. are done by packet above */
  156119. vf->bittrack+=og.header_len*8;
  156120. /* has our decoding just traversed a bitstream boundary? */
  156121. if(vf->ready_state==INITSET){
  156122. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156123. if(!spanp)
  156124. return(OV_EOF);
  156125. _decode_clear(vf);
  156126. if(!vf->seekable){
  156127. vorbis_info_clear(vf->vi);
  156128. vorbis_comment_clear(vf->vc);
  156129. }
  156130. }
  156131. }
  156132. }
  156133. /* Do we need to load a new machine before submitting the page? */
  156134. /* This is different in the seekable and non-seekable cases.
  156135. In the seekable case, we already have all the header
  156136. information loaded and cached; we just initialize the machine
  156137. with it and continue on our merry way.
  156138. In the non-seekable (streaming) case, we'll only be at a
  156139. boundary if we just left the previous logical bitstream and
  156140. we're now nominally at the header of the next bitstream
  156141. */
  156142. if(vf->ready_state!=INITSET){
  156143. int link;
  156144. if(vf->ready_state<STREAMSET){
  156145. if(vf->seekable){
  156146. vf->current_serialno=ogg_page_serialno(&og);
  156147. /* match the serialno to bitstream section. We use this rather than
  156148. offset positions to avoid problems near logical bitstream
  156149. boundaries */
  156150. for(link=0;link<vf->links;link++)
  156151. if(vf->serialnos[link]==vf->current_serialno)break;
  156152. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156153. stream. error out,
  156154. leave machine
  156155. uninitialized */
  156156. vf->current_link=link;
  156157. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156158. vf->ready_state=STREAMSET;
  156159. }else{
  156160. /* we're streaming */
  156161. /* fetch the three header packets, build the info struct */
  156162. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156163. if(ret)return(ret);
  156164. vf->current_link++;
  156165. link=0;
  156166. }
  156167. }
  156168. {
  156169. int ret=_make_decode_ready(vf);
  156170. if(ret<0)return ret;
  156171. }
  156172. }
  156173. ogg_stream_pagein(&vf->os,&og);
  156174. }
  156175. }
  156176. /* if, eg, 64 bit stdio is configured by default, this will build with
  156177. fseek64 */
  156178. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156179. if(f==NULL)return(-1);
  156180. return fseek(f,off,whence);
  156181. }
  156182. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156183. long ibytes, ov_callbacks callbacks){
  156184. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156185. int ret;
  156186. memset(vf,0,sizeof(*vf));
  156187. vf->datasource=f;
  156188. vf->callbacks = callbacks;
  156189. /* init the framing state */
  156190. ogg_sync_init(&vf->oy);
  156191. /* perhaps some data was previously read into a buffer for testing
  156192. against other stream types. Allow initialization from this
  156193. previously read data (as we may be reading from a non-seekable
  156194. stream) */
  156195. if(initial){
  156196. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156197. memcpy(buffer,initial,ibytes);
  156198. ogg_sync_wrote(&vf->oy,ibytes);
  156199. }
  156200. /* can we seek? Stevens suggests the seek test was portable */
  156201. if(offsettest!=-1)vf->seekable=1;
  156202. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156203. entry for partial open */
  156204. vf->links=1;
  156205. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156206. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156207. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156208. /* Try to fetch the headers, maintaining all the storage */
  156209. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156210. vf->datasource=NULL;
  156211. ov_clear(vf);
  156212. }else
  156213. vf->ready_state=PARTOPEN;
  156214. return(ret);
  156215. }
  156216. static int _ov_open2(OggVorbis_File *vf){
  156217. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156218. vf->ready_state=OPENED;
  156219. if(vf->seekable){
  156220. int ret=_open_seekable2(vf);
  156221. if(ret){
  156222. vf->datasource=NULL;
  156223. ov_clear(vf);
  156224. }
  156225. return(ret);
  156226. }else
  156227. vf->ready_state=STREAMSET;
  156228. return 0;
  156229. }
  156230. /* clear out the OggVorbis_File struct */
  156231. int ov_clear(OggVorbis_File *vf){
  156232. if(vf){
  156233. vorbis_block_clear(&vf->vb);
  156234. vorbis_dsp_clear(&vf->vd);
  156235. ogg_stream_clear(&vf->os);
  156236. if(vf->vi && vf->links){
  156237. int i;
  156238. for(i=0;i<vf->links;i++){
  156239. vorbis_info_clear(vf->vi+i);
  156240. vorbis_comment_clear(vf->vc+i);
  156241. }
  156242. _ogg_free(vf->vi);
  156243. _ogg_free(vf->vc);
  156244. }
  156245. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156246. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156247. if(vf->serialnos)_ogg_free(vf->serialnos);
  156248. if(vf->offsets)_ogg_free(vf->offsets);
  156249. ogg_sync_clear(&vf->oy);
  156250. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156251. memset(vf,0,sizeof(*vf));
  156252. }
  156253. #ifdef DEBUG_LEAKS
  156254. _VDBG_dump();
  156255. #endif
  156256. return(0);
  156257. }
  156258. /* inspects the OggVorbis file and finds/documents all the logical
  156259. bitstreams contained in it. Tries to be tolerant of logical
  156260. bitstream sections that are truncated/woogie.
  156261. return: -1) error
  156262. 0) OK
  156263. */
  156264. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156265. ov_callbacks callbacks){
  156266. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156267. if(ret)return ret;
  156268. return _ov_open2(vf);
  156269. }
  156270. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156271. ov_callbacks callbacks = {
  156272. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156273. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156274. (int (*)(void *)) fclose,
  156275. (long (*)(void *)) ftell
  156276. };
  156277. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156278. }
  156279. /* cheap hack for game usage where downsampling is desirable; there's
  156280. no need for SRC as we can just do it cheaply in libvorbis. */
  156281. int ov_halfrate(OggVorbis_File *vf,int flag){
  156282. int i;
  156283. if(vf->vi==NULL)return OV_EINVAL;
  156284. if(!vf->seekable)return OV_EINVAL;
  156285. if(vf->ready_state>=STREAMSET)
  156286. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156287. will be able to swap this on the fly, but
  156288. for now dumping the decode machine is needed
  156289. to reinit the MDCT lookups. 1.1 libvorbis
  156290. is planned to be able to switch on the fly */
  156291. for(i=0;i<vf->links;i++){
  156292. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156293. ov_halfrate(vf,0);
  156294. return OV_EINVAL;
  156295. }
  156296. }
  156297. return 0;
  156298. }
  156299. int ov_halfrate_p(OggVorbis_File *vf){
  156300. if(vf->vi==NULL)return OV_EINVAL;
  156301. return vorbis_synthesis_halfrate_p(vf->vi);
  156302. }
  156303. /* Only partially open the vorbis file; test for Vorbisness, and load
  156304. the headers for the first chain. Do not seek (although test for
  156305. seekability). Use ov_test_open to finish opening the file, else
  156306. ov_clear to close/free it. Same return codes as open. */
  156307. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156308. ov_callbacks callbacks)
  156309. {
  156310. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156311. }
  156312. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156313. ov_callbacks callbacks = {
  156314. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156315. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156316. (int (*)(void *)) fclose,
  156317. (long (*)(void *)) ftell
  156318. };
  156319. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156320. }
  156321. int ov_test_open(OggVorbis_File *vf){
  156322. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156323. return _ov_open2(vf);
  156324. }
  156325. /* How many logical bitstreams in this physical bitstream? */
  156326. long ov_streams(OggVorbis_File *vf){
  156327. return vf->links;
  156328. }
  156329. /* Is the FILE * associated with vf seekable? */
  156330. long ov_seekable(OggVorbis_File *vf){
  156331. return vf->seekable;
  156332. }
  156333. /* returns the bitrate for a given logical bitstream or the entire
  156334. physical bitstream. If the file is open for random access, it will
  156335. find the *actual* average bitrate. If the file is streaming, it
  156336. returns the nominal bitrate (if set) else the average of the
  156337. upper/lower bounds (if set) else -1 (unset).
  156338. If you want the actual bitrate field settings, get them from the
  156339. vorbis_info structs */
  156340. long ov_bitrate(OggVorbis_File *vf,int i){
  156341. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156342. if(i>=vf->links)return(OV_EINVAL);
  156343. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156344. if(i<0){
  156345. ogg_int64_t bits=0;
  156346. int i;
  156347. float br;
  156348. for(i=0;i<vf->links;i++)
  156349. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156350. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156351. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156352. * so this is slightly transformed to make it work.
  156353. */
  156354. br = bits/ov_time_total(vf,-1);
  156355. return(rint(br));
  156356. }else{
  156357. if(vf->seekable){
  156358. /* return the actual bitrate */
  156359. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156360. }else{
  156361. /* return nominal if set */
  156362. if(vf->vi[i].bitrate_nominal>0){
  156363. return vf->vi[i].bitrate_nominal;
  156364. }else{
  156365. if(vf->vi[i].bitrate_upper>0){
  156366. if(vf->vi[i].bitrate_lower>0){
  156367. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156368. }else{
  156369. return vf->vi[i].bitrate_upper;
  156370. }
  156371. }
  156372. return(OV_FALSE);
  156373. }
  156374. }
  156375. }
  156376. }
  156377. /* returns the actual bitrate since last call. returns -1 if no
  156378. additional data to offer since last call (or at beginning of stream),
  156379. EINVAL if stream is only partially open
  156380. */
  156381. long ov_bitrate_instant(OggVorbis_File *vf){
  156382. int link=(vf->seekable?vf->current_link:0);
  156383. long ret;
  156384. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156385. if(vf->samptrack==0)return(OV_FALSE);
  156386. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156387. vf->bittrack=0.f;
  156388. vf->samptrack=0.f;
  156389. return(ret);
  156390. }
  156391. /* Guess */
  156392. long ov_serialnumber(OggVorbis_File *vf,int i){
  156393. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156394. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156395. if(i<0){
  156396. return(vf->current_serialno);
  156397. }else{
  156398. return(vf->serialnos[i]);
  156399. }
  156400. }
  156401. /* returns: total raw (compressed) length of content if i==-1
  156402. raw (compressed) length of that logical bitstream for i==0 to n
  156403. OV_EINVAL if the stream is not seekable (we can't know the length)
  156404. or if stream is only partially open
  156405. */
  156406. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156407. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156408. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156409. if(i<0){
  156410. ogg_int64_t acc=0;
  156411. int i;
  156412. for(i=0;i<vf->links;i++)
  156413. acc+=ov_raw_total(vf,i);
  156414. return(acc);
  156415. }else{
  156416. return(vf->offsets[i+1]-vf->offsets[i]);
  156417. }
  156418. }
  156419. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156420. (samples) of that logical bitstream for i==0 to n
  156421. OV_EINVAL if the stream is not seekable (we can't know the
  156422. length) or only partially open
  156423. */
  156424. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156425. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156426. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156427. if(i<0){
  156428. ogg_int64_t acc=0;
  156429. int i;
  156430. for(i=0;i<vf->links;i++)
  156431. acc+=ov_pcm_total(vf,i);
  156432. return(acc);
  156433. }else{
  156434. return(vf->pcmlengths[i*2+1]);
  156435. }
  156436. }
  156437. /* returns: total seconds of content if i==-1
  156438. seconds in that logical bitstream for i==0 to n
  156439. OV_EINVAL if the stream is not seekable (we can't know the
  156440. length) or only partially open
  156441. */
  156442. double ov_time_total(OggVorbis_File *vf,int i){
  156443. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156444. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156445. if(i<0){
  156446. double acc=0;
  156447. int i;
  156448. for(i=0;i<vf->links;i++)
  156449. acc+=ov_time_total(vf,i);
  156450. return(acc);
  156451. }else{
  156452. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156453. }
  156454. }
  156455. /* seek to an offset relative to the *compressed* data. This also
  156456. scans packets to update the PCM cursor. It will cross a logical
  156457. bitstream boundary, but only if it can't get any packets out of the
  156458. tail of the bitstream we seek to (so no surprises).
  156459. returns zero on success, nonzero on failure */
  156460. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156461. ogg_stream_state work_os;
  156462. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156463. if(!vf->seekable)
  156464. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156465. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156466. /* don't yet clear out decoding machine (if it's initialized), in
  156467. the case we're in the same link. Restart the decode lapping, and
  156468. let _fetch_and_process_packet deal with a potential bitstream
  156469. boundary */
  156470. vf->pcm_offset=-1;
  156471. ogg_stream_reset_serialno(&vf->os,
  156472. vf->current_serialno); /* must set serialno */
  156473. vorbis_synthesis_restart(&vf->vd);
  156474. _seek_helper(vf,pos);
  156475. /* we need to make sure the pcm_offset is set, but we don't want to
  156476. advance the raw cursor past good packets just to get to the first
  156477. with a granulepos. That's not equivalent behavior to beginning
  156478. decoding as immediately after the seek position as possible.
  156479. So, a hack. We use two stream states; a local scratch state and
  156480. the shared vf->os stream state. We use the local state to
  156481. scan, and the shared state as a buffer for later decode.
  156482. Unfortuantely, on the last page we still advance to last packet
  156483. because the granulepos on the last page is not necessarily on a
  156484. packet boundary, and we need to make sure the granpos is
  156485. correct.
  156486. */
  156487. {
  156488. ogg_page og;
  156489. ogg_packet op;
  156490. int lastblock=0;
  156491. int accblock=0;
  156492. int thisblock;
  156493. int eosflag;
  156494. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156495. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156496. return from not necessarily
  156497. starting from the beginning */
  156498. while(1){
  156499. if(vf->ready_state>=STREAMSET){
  156500. /* snarf/scan a packet if we can */
  156501. int result=ogg_stream_packetout(&work_os,&op);
  156502. if(result>0){
  156503. if(vf->vi[vf->current_link].codec_setup){
  156504. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156505. if(thisblock<0){
  156506. ogg_stream_packetout(&vf->os,NULL);
  156507. thisblock=0;
  156508. }else{
  156509. if(eosflag)
  156510. ogg_stream_packetout(&vf->os,NULL);
  156511. else
  156512. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156513. }
  156514. if(op.granulepos!=-1){
  156515. int i,link=vf->current_link;
  156516. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156517. if(granulepos<0)granulepos=0;
  156518. for(i=0;i<link;i++)
  156519. granulepos+=vf->pcmlengths[i*2+1];
  156520. vf->pcm_offset=granulepos-accblock;
  156521. break;
  156522. }
  156523. lastblock=thisblock;
  156524. continue;
  156525. }else
  156526. ogg_stream_packetout(&vf->os,NULL);
  156527. }
  156528. }
  156529. if(!lastblock){
  156530. if(_get_next_page(vf,&og,-1)<0){
  156531. vf->pcm_offset=ov_pcm_total(vf,-1);
  156532. break;
  156533. }
  156534. }else{
  156535. /* huh? Bogus stream with packets but no granulepos */
  156536. vf->pcm_offset=-1;
  156537. break;
  156538. }
  156539. /* has our decoding just traversed a bitstream boundary? */
  156540. if(vf->ready_state>=STREAMSET)
  156541. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156542. _decode_clear(vf); /* clear out stream state */
  156543. ogg_stream_clear(&work_os);
  156544. }
  156545. if(vf->ready_state<STREAMSET){
  156546. int link;
  156547. vf->current_serialno=ogg_page_serialno(&og);
  156548. for(link=0;link<vf->links;link++)
  156549. if(vf->serialnos[link]==vf->current_serialno)break;
  156550. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156551. error out, leave
  156552. machine uninitialized */
  156553. vf->current_link=link;
  156554. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156555. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156556. vf->ready_state=STREAMSET;
  156557. }
  156558. ogg_stream_pagein(&vf->os,&og);
  156559. ogg_stream_pagein(&work_os,&og);
  156560. eosflag=ogg_page_eos(&og);
  156561. }
  156562. }
  156563. ogg_stream_clear(&work_os);
  156564. vf->bittrack=0.f;
  156565. vf->samptrack=0.f;
  156566. return(0);
  156567. seek_error:
  156568. /* dump the machine so we're in a known state */
  156569. vf->pcm_offset=-1;
  156570. ogg_stream_clear(&work_os);
  156571. _decode_clear(vf);
  156572. return OV_EBADLINK;
  156573. }
  156574. /* Page granularity seek (faster than sample granularity because we
  156575. don't do the last bit of decode to find a specific sample).
  156576. Seek to the last [granule marked] page preceeding the specified pos
  156577. location, such that decoding past the returned point will quickly
  156578. arrive at the requested position. */
  156579. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156580. int link=-1;
  156581. ogg_int64_t result=0;
  156582. ogg_int64_t total=ov_pcm_total(vf,-1);
  156583. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156584. if(!vf->seekable)return(OV_ENOSEEK);
  156585. if(pos<0 || pos>total)return(OV_EINVAL);
  156586. /* which bitstream section does this pcm offset occur in? */
  156587. for(link=vf->links-1;link>=0;link--){
  156588. total-=vf->pcmlengths[link*2+1];
  156589. if(pos>=total)break;
  156590. }
  156591. /* search within the logical bitstream for the page with the highest
  156592. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156593. missing pages or incorrect frame number information in the
  156594. bitstream could make our task impossible. Account for that (it
  156595. would be an error condition) */
  156596. /* new search algorithm by HB (Nicholas Vinen) */
  156597. {
  156598. ogg_int64_t end=vf->offsets[link+1];
  156599. ogg_int64_t begin=vf->offsets[link];
  156600. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156601. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156602. ogg_int64_t target=pos-total+begintime;
  156603. ogg_int64_t best=begin;
  156604. ogg_page og;
  156605. while(begin<end){
  156606. ogg_int64_t bisect;
  156607. if(end-begin<CHUNKSIZE){
  156608. bisect=begin;
  156609. }else{
  156610. /* take a (pretty decent) guess. */
  156611. bisect=begin +
  156612. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156613. if(bisect<=begin)
  156614. bisect=begin+1;
  156615. }
  156616. _seek_helper(vf,bisect);
  156617. while(begin<end){
  156618. result=_get_next_page(vf,&og,end-vf->offset);
  156619. if(result==OV_EREAD) goto seek_error;
  156620. if(result<0){
  156621. if(bisect<=begin+1)
  156622. end=begin; /* found it */
  156623. else{
  156624. if(bisect==0) goto seek_error;
  156625. bisect-=CHUNKSIZE;
  156626. if(bisect<=begin)bisect=begin+1;
  156627. _seek_helper(vf,bisect);
  156628. }
  156629. }else{
  156630. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156631. if(granulepos==-1)continue;
  156632. if(granulepos<target){
  156633. best=result; /* raw offset of packet with granulepos */
  156634. begin=vf->offset; /* raw offset of next page */
  156635. begintime=granulepos;
  156636. if(target-begintime>44100)break;
  156637. bisect=begin; /* *not* begin + 1 */
  156638. }else{
  156639. if(bisect<=begin+1)
  156640. end=begin; /* found it */
  156641. else{
  156642. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156643. end=result;
  156644. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156645. if(bisect<=begin)bisect=begin+1;
  156646. _seek_helper(vf,bisect);
  156647. }else{
  156648. end=result;
  156649. endtime=granulepos;
  156650. break;
  156651. }
  156652. }
  156653. }
  156654. }
  156655. }
  156656. }
  156657. /* found our page. seek to it, update pcm offset. Easier case than
  156658. raw_seek, don't keep packets preceeding granulepos. */
  156659. {
  156660. ogg_page og;
  156661. ogg_packet op;
  156662. /* seek */
  156663. _seek_helper(vf,best);
  156664. vf->pcm_offset=-1;
  156665. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156666. if(link!=vf->current_link){
  156667. /* Different link; dump entire decode machine */
  156668. _decode_clear(vf);
  156669. vf->current_link=link;
  156670. vf->current_serialno=ogg_page_serialno(&og);
  156671. vf->ready_state=STREAMSET;
  156672. }else{
  156673. vorbis_synthesis_restart(&vf->vd);
  156674. }
  156675. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156676. ogg_stream_pagein(&vf->os,&og);
  156677. /* pull out all but last packet; the one with granulepos */
  156678. while(1){
  156679. result=ogg_stream_packetpeek(&vf->os,&op);
  156680. if(result==0){
  156681. /* !!! the packet finishing this page originated on a
  156682. preceeding page. Keep fetching previous pages until we
  156683. get one with a granulepos or without the 'continued' flag
  156684. set. Then just use raw_seek for simplicity. */
  156685. _seek_helper(vf,best);
  156686. while(1){
  156687. result=_get_prev_page(vf,&og);
  156688. if(result<0) goto seek_error;
  156689. if(ogg_page_granulepos(&og)>-1 ||
  156690. !ogg_page_continued(&og)){
  156691. return ov_raw_seek(vf,result);
  156692. }
  156693. vf->offset=result;
  156694. }
  156695. }
  156696. if(result<0){
  156697. result = OV_EBADPACKET;
  156698. goto seek_error;
  156699. }
  156700. if(op.granulepos!=-1){
  156701. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156702. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156703. vf->pcm_offset+=total;
  156704. break;
  156705. }else
  156706. result=ogg_stream_packetout(&vf->os,NULL);
  156707. }
  156708. }
  156709. }
  156710. /* verify result */
  156711. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156712. result=OV_EFAULT;
  156713. goto seek_error;
  156714. }
  156715. vf->bittrack=0.f;
  156716. vf->samptrack=0.f;
  156717. return(0);
  156718. seek_error:
  156719. /* dump machine so we're in a known state */
  156720. vf->pcm_offset=-1;
  156721. _decode_clear(vf);
  156722. return (int)result;
  156723. }
  156724. /* seek to a sample offset relative to the decompressed pcm stream
  156725. returns zero on success, nonzero on failure */
  156726. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156727. int thisblock,lastblock=0;
  156728. int ret=ov_pcm_seek_page(vf,pos);
  156729. if(ret<0)return(ret);
  156730. if((ret=_make_decode_ready(vf)))return ret;
  156731. /* discard leading packets we don't need for the lapping of the
  156732. position we want; don't decode them */
  156733. while(1){
  156734. ogg_packet op;
  156735. ogg_page og;
  156736. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156737. if(ret>0){
  156738. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156739. if(thisblock<0){
  156740. ogg_stream_packetout(&vf->os,NULL);
  156741. continue; /* non audio packet */
  156742. }
  156743. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156744. if(vf->pcm_offset+((thisblock+
  156745. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156746. /* remove the packet from packet queue and track its granulepos */
  156747. ogg_stream_packetout(&vf->os,NULL);
  156748. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156749. only tracking, no
  156750. pcm_decode */
  156751. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156752. /* end of logical stream case is hard, especially with exact
  156753. length positioning. */
  156754. if(op.granulepos>-1){
  156755. int i;
  156756. /* always believe the stream markers */
  156757. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156758. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156759. for(i=0;i<vf->current_link;i++)
  156760. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156761. }
  156762. lastblock=thisblock;
  156763. }else{
  156764. if(ret<0 && ret!=OV_HOLE)break;
  156765. /* suck in a new page */
  156766. if(_get_next_page(vf,&og,-1)<0)break;
  156767. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156768. if(vf->ready_state<STREAMSET){
  156769. int link;
  156770. vf->current_serialno=ogg_page_serialno(&og);
  156771. for(link=0;link<vf->links;link++)
  156772. if(vf->serialnos[link]==vf->current_serialno)break;
  156773. if(link==vf->links)return(OV_EBADLINK);
  156774. vf->current_link=link;
  156775. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156776. vf->ready_state=STREAMSET;
  156777. ret=_make_decode_ready(vf);
  156778. if(ret)return ret;
  156779. lastblock=0;
  156780. }
  156781. ogg_stream_pagein(&vf->os,&og);
  156782. }
  156783. }
  156784. vf->bittrack=0.f;
  156785. vf->samptrack=0.f;
  156786. /* discard samples until we reach the desired position. Crossing a
  156787. logical bitstream boundary with abandon is OK. */
  156788. while(vf->pcm_offset<pos){
  156789. ogg_int64_t target=pos-vf->pcm_offset;
  156790. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156791. if(samples>target)samples=target;
  156792. vorbis_synthesis_read(&vf->vd,samples);
  156793. vf->pcm_offset+=samples;
  156794. if(samples<target)
  156795. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156796. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156797. }
  156798. return 0;
  156799. }
  156800. /* seek to a playback time relative to the decompressed pcm stream
  156801. returns zero on success, nonzero on failure */
  156802. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156803. /* translate time to PCM position and call ov_pcm_seek */
  156804. int link=-1;
  156805. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156806. double time_total=ov_time_total(vf,-1);
  156807. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156808. if(!vf->seekable)return(OV_ENOSEEK);
  156809. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156810. /* which bitstream section does this time offset occur in? */
  156811. for(link=vf->links-1;link>=0;link--){
  156812. pcm_total-=vf->pcmlengths[link*2+1];
  156813. time_total-=ov_time_total(vf,link);
  156814. if(seconds>=time_total)break;
  156815. }
  156816. /* enough information to convert time offset to pcm offset */
  156817. {
  156818. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156819. return(ov_pcm_seek(vf,target));
  156820. }
  156821. }
  156822. /* page-granularity version of ov_time_seek
  156823. returns zero on success, nonzero on failure */
  156824. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156825. /* translate time to PCM position and call ov_pcm_seek */
  156826. int link=-1;
  156827. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156828. double time_total=ov_time_total(vf,-1);
  156829. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156830. if(!vf->seekable)return(OV_ENOSEEK);
  156831. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156832. /* which bitstream section does this time offset occur in? */
  156833. for(link=vf->links-1;link>=0;link--){
  156834. pcm_total-=vf->pcmlengths[link*2+1];
  156835. time_total-=ov_time_total(vf,link);
  156836. if(seconds>=time_total)break;
  156837. }
  156838. /* enough information to convert time offset to pcm offset */
  156839. {
  156840. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156841. return(ov_pcm_seek_page(vf,target));
  156842. }
  156843. }
  156844. /* tell the current stream offset cursor. Note that seek followed by
  156845. tell will likely not give the set offset due to caching */
  156846. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156847. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156848. return(vf->offset);
  156849. }
  156850. /* return PCM offset (sample) of next PCM sample to be read */
  156851. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156852. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156853. return(vf->pcm_offset);
  156854. }
  156855. /* return time offset (seconds) of next PCM sample to be read */
  156856. double ov_time_tell(OggVorbis_File *vf){
  156857. int link=0;
  156858. ogg_int64_t pcm_total=0;
  156859. double time_total=0.f;
  156860. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156861. if(vf->seekable){
  156862. pcm_total=ov_pcm_total(vf,-1);
  156863. time_total=ov_time_total(vf,-1);
  156864. /* which bitstream section does this time offset occur in? */
  156865. for(link=vf->links-1;link>=0;link--){
  156866. pcm_total-=vf->pcmlengths[link*2+1];
  156867. time_total-=ov_time_total(vf,link);
  156868. if(vf->pcm_offset>=pcm_total)break;
  156869. }
  156870. }
  156871. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156872. }
  156873. /* link: -1) return the vorbis_info struct for the bitstream section
  156874. currently being decoded
  156875. 0-n) to request information for a specific bitstream section
  156876. In the case of a non-seekable bitstream, any call returns the
  156877. current bitstream. NULL in the case that the machine is not
  156878. initialized */
  156879. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156880. if(vf->seekable){
  156881. if(link<0)
  156882. if(vf->ready_state>=STREAMSET)
  156883. return vf->vi+vf->current_link;
  156884. else
  156885. return vf->vi;
  156886. else
  156887. if(link>=vf->links)
  156888. return NULL;
  156889. else
  156890. return vf->vi+link;
  156891. }else{
  156892. return vf->vi;
  156893. }
  156894. }
  156895. /* grr, strong typing, grr, no templates/inheritence, grr */
  156896. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156897. if(vf->seekable){
  156898. if(link<0)
  156899. if(vf->ready_state>=STREAMSET)
  156900. return vf->vc+vf->current_link;
  156901. else
  156902. return vf->vc;
  156903. else
  156904. if(link>=vf->links)
  156905. return NULL;
  156906. else
  156907. return vf->vc+link;
  156908. }else{
  156909. return vf->vc;
  156910. }
  156911. }
  156912. static int host_is_big_endian() {
  156913. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156914. unsigned char *bytewise = (unsigned char *)&pattern;
  156915. if (bytewise[0] == 0xfe) return 1;
  156916. return 0;
  156917. }
  156918. /* up to this point, everything could more or less hide the multiple
  156919. logical bitstream nature of chaining from the toplevel application
  156920. if the toplevel application didn't particularly care. However, at
  156921. the point that we actually read audio back, the multiple-section
  156922. nature must surface: Multiple bitstream sections do not necessarily
  156923. have to have the same number of channels or sampling rate.
  156924. ov_read returns the sequential logical bitstream number currently
  156925. being decoded along with the PCM data in order that the toplevel
  156926. application can take action on channel/sample rate changes. This
  156927. number will be incremented even for streamed (non-seekable) streams
  156928. (for seekable streams, it represents the actual logical bitstream
  156929. index within the physical bitstream. Note that the accessor
  156930. functions above are aware of this dichotomy).
  156931. input values: buffer) a buffer to hold packed PCM data for return
  156932. length) the byte length requested to be placed into buffer
  156933. bigendianp) should the data be packed LSB first (0) or
  156934. MSB first (1)
  156935. word) word size for output. currently 1 (byte) or
  156936. 2 (16 bit short)
  156937. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156938. 0) EOF
  156939. n) number of bytes of PCM actually returned. The
  156940. below works on a packet-by-packet basis, so the
  156941. return length is not related to the 'length' passed
  156942. in, just guaranteed to fit.
  156943. *section) set to the logical bitstream number */
  156944. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156945. int bigendianp,int word,int sgned,int *bitstream){
  156946. int i,j;
  156947. int host_endian = host_is_big_endian();
  156948. float **pcm;
  156949. long samples;
  156950. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156951. while(1){
  156952. if(vf->ready_state==INITSET){
  156953. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156954. if(samples)break;
  156955. }
  156956. /* suck in another packet */
  156957. {
  156958. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156959. if(ret==OV_EOF)
  156960. return(0);
  156961. if(ret<=0)
  156962. return(ret);
  156963. }
  156964. }
  156965. if(samples>0){
  156966. /* yay! proceed to pack data into the byte buffer */
  156967. long channels=ov_info(vf,-1)->channels;
  156968. long bytespersample=word * channels;
  156969. vorbis_fpu_control fpu;
  156970. (void) fpu; // (to avoid a warning about it being unused)
  156971. if(samples>length/bytespersample)samples=length/bytespersample;
  156972. if(samples <= 0)
  156973. return OV_EINVAL;
  156974. /* a tight loop to pack each size */
  156975. {
  156976. int val;
  156977. if(word==1){
  156978. int off=(sgned?0:128);
  156979. vorbis_fpu_setround(&fpu);
  156980. for(j=0;j<samples;j++)
  156981. for(i=0;i<channels;i++){
  156982. val=vorbis_ftoi(pcm[i][j]*128.f);
  156983. if(val>127)val=127;
  156984. else if(val<-128)val=-128;
  156985. *buffer++=val+off;
  156986. }
  156987. vorbis_fpu_restore(fpu);
  156988. }else{
  156989. int off=(sgned?0:32768);
  156990. if(host_endian==bigendianp){
  156991. if(sgned){
  156992. vorbis_fpu_setround(&fpu);
  156993. for(i=0;i<channels;i++) { /* It's faster in this order */
  156994. float *src=pcm[i];
  156995. short *dest=((short *)buffer)+i;
  156996. for(j=0;j<samples;j++) {
  156997. val=vorbis_ftoi(src[j]*32768.f);
  156998. if(val>32767)val=32767;
  156999. else if(val<-32768)val=-32768;
  157000. *dest=val;
  157001. dest+=channels;
  157002. }
  157003. }
  157004. vorbis_fpu_restore(fpu);
  157005. }else{
  157006. vorbis_fpu_setround(&fpu);
  157007. for(i=0;i<channels;i++) {
  157008. float *src=pcm[i];
  157009. short *dest=((short *)buffer)+i;
  157010. for(j=0;j<samples;j++) {
  157011. val=vorbis_ftoi(src[j]*32768.f);
  157012. if(val>32767)val=32767;
  157013. else if(val<-32768)val=-32768;
  157014. *dest=val+off;
  157015. dest+=channels;
  157016. }
  157017. }
  157018. vorbis_fpu_restore(fpu);
  157019. }
  157020. }else if(bigendianp){
  157021. vorbis_fpu_setround(&fpu);
  157022. for(j=0;j<samples;j++)
  157023. for(i=0;i<channels;i++){
  157024. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157025. if(val>32767)val=32767;
  157026. else if(val<-32768)val=-32768;
  157027. val+=off;
  157028. *buffer++=(val>>8);
  157029. *buffer++=(val&0xff);
  157030. }
  157031. vorbis_fpu_restore(fpu);
  157032. }else{
  157033. int val;
  157034. vorbis_fpu_setround(&fpu);
  157035. for(j=0;j<samples;j++)
  157036. for(i=0;i<channels;i++){
  157037. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157038. if(val>32767)val=32767;
  157039. else if(val<-32768)val=-32768;
  157040. val+=off;
  157041. *buffer++=(val&0xff);
  157042. *buffer++=(val>>8);
  157043. }
  157044. vorbis_fpu_restore(fpu);
  157045. }
  157046. }
  157047. }
  157048. vorbis_synthesis_read(&vf->vd,samples);
  157049. vf->pcm_offset+=samples;
  157050. if(bitstream)*bitstream=vf->current_link;
  157051. return(samples*bytespersample);
  157052. }else{
  157053. return(samples);
  157054. }
  157055. }
  157056. /* input values: pcm_channels) a float vector per channel of output
  157057. length) the sample length being read by the app
  157058. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157059. 0) EOF
  157060. n) number of samples of PCM actually returned. The
  157061. below works on a packet-by-packet basis, so the
  157062. return length is not related to the 'length' passed
  157063. in, just guaranteed to fit.
  157064. *section) set to the logical bitstream number */
  157065. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157066. int *bitstream){
  157067. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157068. while(1){
  157069. if(vf->ready_state==INITSET){
  157070. float **pcm;
  157071. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157072. if(samples){
  157073. if(pcm_channels)*pcm_channels=pcm;
  157074. if(samples>length)samples=length;
  157075. vorbis_synthesis_read(&vf->vd,samples);
  157076. vf->pcm_offset+=samples;
  157077. if(bitstream)*bitstream=vf->current_link;
  157078. return samples;
  157079. }
  157080. }
  157081. /* suck in another packet */
  157082. {
  157083. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157084. if(ret==OV_EOF)return(0);
  157085. if(ret<=0)return(ret);
  157086. }
  157087. }
  157088. }
  157089. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157090. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157091. ogg_int64_t off);
  157092. static void _ov_splice(float **pcm,float **lappcm,
  157093. int n1, int n2,
  157094. int ch1, int ch2,
  157095. float *w1, float *w2){
  157096. int i,j;
  157097. float *w=w1;
  157098. int n=n1;
  157099. if(n1>n2){
  157100. n=n2;
  157101. w=w2;
  157102. }
  157103. /* splice */
  157104. for(j=0;j<ch1 && j<ch2;j++){
  157105. float *s=lappcm[j];
  157106. float *d=pcm[j];
  157107. for(i=0;i<n;i++){
  157108. float wd=w[i]*w[i];
  157109. float ws=1.-wd;
  157110. d[i]=d[i]*wd + s[i]*ws;
  157111. }
  157112. }
  157113. /* window from zero */
  157114. for(;j<ch2;j++){
  157115. float *d=pcm[j];
  157116. for(i=0;i<n;i++){
  157117. float wd=w[i]*w[i];
  157118. d[i]=d[i]*wd;
  157119. }
  157120. }
  157121. }
  157122. /* make sure vf is INITSET */
  157123. static int _ov_initset(OggVorbis_File *vf){
  157124. while(1){
  157125. if(vf->ready_state==INITSET)break;
  157126. /* suck in another packet */
  157127. {
  157128. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157129. if(ret<0 && ret!=OV_HOLE)return(ret);
  157130. }
  157131. }
  157132. return 0;
  157133. }
  157134. /* make sure vf is INITSET and that we have a primed buffer; if
  157135. we're crosslapping at a stream section boundary, this also makes
  157136. sure we're sanity checking against the right stream information */
  157137. static int _ov_initprime(OggVorbis_File *vf){
  157138. vorbis_dsp_state *vd=&vf->vd;
  157139. while(1){
  157140. if(vf->ready_state==INITSET)
  157141. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157142. /* suck in another packet */
  157143. {
  157144. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157145. if(ret<0 && ret!=OV_HOLE)return(ret);
  157146. }
  157147. }
  157148. return 0;
  157149. }
  157150. /* grab enough data for lapping from vf; this may be in the form of
  157151. unreturned, already-decoded pcm, remaining PCM we will need to
  157152. decode, or synthetic postextrapolation from last packets. */
  157153. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157154. float **lappcm,int lapsize){
  157155. int lapcount=0,i;
  157156. float **pcm;
  157157. /* try first to decode the lapping data */
  157158. while(lapcount<lapsize){
  157159. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157160. if(samples){
  157161. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157162. for(i=0;i<vi->channels;i++)
  157163. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157164. lapcount+=samples;
  157165. vorbis_synthesis_read(vd,samples);
  157166. }else{
  157167. /* suck in another packet */
  157168. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157169. if(ret==OV_EOF)break;
  157170. }
  157171. }
  157172. if(lapcount<lapsize){
  157173. /* failed to get lapping data from normal decode; pry it from the
  157174. postextrapolation buffering, or the second half of the MDCT
  157175. from the last packet */
  157176. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157177. if(samples==0){
  157178. for(i=0;i<vi->channels;i++)
  157179. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157180. lapcount=lapsize;
  157181. }else{
  157182. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157183. for(i=0;i<vi->channels;i++)
  157184. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157185. lapcount+=samples;
  157186. }
  157187. }
  157188. }
  157189. /* this sets up crosslapping of a sample by using trailing data from
  157190. sample 1 and lapping it into the windowing buffer of sample 2 */
  157191. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157192. vorbis_info *vi1,*vi2;
  157193. float **lappcm;
  157194. float **pcm;
  157195. float *w1,*w2;
  157196. int n1,n2,i,ret,hs1,hs2;
  157197. if(vf1==vf2)return(0); /* degenerate case */
  157198. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157199. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157200. /* the relevant overlap buffers must be pre-checked and pre-primed
  157201. before looking at settings in the event that priming would cross
  157202. a bitstream boundary. So, do it now */
  157203. ret=_ov_initset(vf1);
  157204. if(ret)return(ret);
  157205. ret=_ov_initprime(vf2);
  157206. if(ret)return(ret);
  157207. vi1=ov_info(vf1,-1);
  157208. vi2=ov_info(vf2,-1);
  157209. hs1=ov_halfrate_p(vf1);
  157210. hs2=ov_halfrate_p(vf2);
  157211. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157212. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157213. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157214. w1=vorbis_window(&vf1->vd,0);
  157215. w2=vorbis_window(&vf2->vd,0);
  157216. for(i=0;i<vi1->channels;i++)
  157217. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157218. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157219. /* have a lapping buffer from vf1; now to splice it into the lapping
  157220. buffer of vf2 */
  157221. /* consolidate and expose the buffer. */
  157222. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157223. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157224. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157225. /* splice */
  157226. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157227. /* done */
  157228. return(0);
  157229. }
  157230. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157231. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157232. vorbis_info *vi;
  157233. float **lappcm;
  157234. float **pcm;
  157235. float *w1,*w2;
  157236. int n1,n2,ch1,ch2,hs;
  157237. int i,ret;
  157238. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157239. ret=_ov_initset(vf);
  157240. if(ret)return(ret);
  157241. vi=ov_info(vf,-1);
  157242. hs=ov_halfrate_p(vf);
  157243. ch1=vi->channels;
  157244. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157245. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157246. persistent; even if the decode state
  157247. from this link gets dumped, this
  157248. window array continues to exist */
  157249. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157250. for(i=0;i<ch1;i++)
  157251. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157252. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157253. /* have lapping data; seek and prime the buffer */
  157254. ret=localseek(vf,pos);
  157255. if(ret)return ret;
  157256. ret=_ov_initprime(vf);
  157257. if(ret)return(ret);
  157258. /* Guard against cross-link changes; they're perfectly legal */
  157259. vi=ov_info(vf,-1);
  157260. ch2=vi->channels;
  157261. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157262. w2=vorbis_window(&vf->vd,0);
  157263. /* consolidate and expose the buffer. */
  157264. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157265. /* splice */
  157266. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157267. /* done */
  157268. return(0);
  157269. }
  157270. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157271. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157272. }
  157273. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157274. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157275. }
  157276. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157277. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157278. }
  157279. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157280. int (*localseek)(OggVorbis_File *,double)){
  157281. vorbis_info *vi;
  157282. float **lappcm;
  157283. float **pcm;
  157284. float *w1,*w2;
  157285. int n1,n2,ch1,ch2,hs;
  157286. int i,ret;
  157287. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157288. ret=_ov_initset(vf);
  157289. if(ret)return(ret);
  157290. vi=ov_info(vf,-1);
  157291. hs=ov_halfrate_p(vf);
  157292. ch1=vi->channels;
  157293. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157294. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157295. persistent; even if the decode state
  157296. from this link gets dumped, this
  157297. window array continues to exist */
  157298. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157299. for(i=0;i<ch1;i++)
  157300. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157301. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157302. /* have lapping data; seek and prime the buffer */
  157303. ret=localseek(vf,pos);
  157304. if(ret)return ret;
  157305. ret=_ov_initprime(vf);
  157306. if(ret)return(ret);
  157307. /* Guard against cross-link changes; they're perfectly legal */
  157308. vi=ov_info(vf,-1);
  157309. ch2=vi->channels;
  157310. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157311. w2=vorbis_window(&vf->vd,0);
  157312. /* consolidate and expose the buffer. */
  157313. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157314. /* splice */
  157315. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157316. /* done */
  157317. return(0);
  157318. }
  157319. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157320. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157321. }
  157322. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157323. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157324. }
  157325. #endif
  157326. /*** End of inlined file: vorbisfile.c ***/
  157327. /*** Start of inlined file: window.c ***/
  157328. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157329. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157330. // tasks..
  157331. #if JUCE_MSVC
  157332. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157333. #endif
  157334. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157335. #if JUCE_USE_OGGVORBIS
  157336. #include <stdlib.h>
  157337. #include <math.h>
  157338. static float vwin64[32] = {
  157339. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157340. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157341. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157342. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157343. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157344. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157345. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157346. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157347. };
  157348. static float vwin128[64] = {
  157349. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157350. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157351. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157352. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157353. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157354. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157355. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157356. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157357. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157358. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157359. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157360. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157361. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157362. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157363. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157364. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157365. };
  157366. static float vwin256[128] = {
  157367. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157368. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157369. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157370. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157371. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157372. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157373. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157374. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157375. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157376. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157377. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157378. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157379. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157380. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157381. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157382. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157383. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157384. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157385. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157386. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157387. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157388. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157389. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157390. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157391. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157392. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157393. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157394. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157395. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157396. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157397. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157398. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157399. };
  157400. static float vwin512[256] = {
  157401. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157402. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157403. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157404. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157405. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157406. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157407. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157408. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157409. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157410. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157411. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157412. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157413. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157414. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157415. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157416. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157417. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157418. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157419. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157420. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157421. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157422. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157423. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157424. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157425. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157426. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157427. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157428. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157429. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157430. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157431. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157432. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157433. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157434. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157435. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157436. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157437. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157438. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157439. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157440. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157441. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157442. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157443. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157444. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157445. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157446. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157447. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157448. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157449. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157450. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157451. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157452. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157453. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157454. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157455. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157456. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157457. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157458. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157459. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157460. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157461. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157462. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157463. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157464. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157465. };
  157466. static float vwin1024[512] = {
  157467. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157468. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157469. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157470. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157471. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157472. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157473. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157474. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157475. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157476. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157477. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157478. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157479. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157480. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157481. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157482. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157483. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157484. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157485. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157486. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157487. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157488. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157489. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157490. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157491. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157492. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157493. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157494. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157495. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157496. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157497. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157498. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157499. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157500. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157501. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157502. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157503. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157504. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157505. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157506. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157507. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157508. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157509. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157510. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157511. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157512. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157513. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157514. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157515. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157516. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157517. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157518. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157519. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157520. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157521. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157522. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157523. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157524. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157525. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157526. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157527. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157528. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157529. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157530. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157531. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157532. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157533. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157534. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157535. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157536. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157537. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157538. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157539. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157540. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157541. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157542. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157543. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157544. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157545. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157546. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157547. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157548. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157549. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157550. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157551. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157552. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157553. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157554. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157555. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157556. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157557. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157558. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157559. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157560. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157561. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157562. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157563. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157564. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157565. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157566. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157567. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157568. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157569. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157570. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157571. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157572. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157573. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157574. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157575. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157576. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157577. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157578. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157579. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157580. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157581. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157582. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157583. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157584. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157585. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157586. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157587. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157588. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157589. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157590. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157591. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157592. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157593. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157594. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157595. };
  157596. static float vwin2048[1024] = {
  157597. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157598. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157599. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157600. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157601. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157602. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157603. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157604. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157605. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157606. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157607. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157608. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157609. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157610. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157611. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157612. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157613. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157614. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157615. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157616. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157617. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157618. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157619. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157620. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157621. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157622. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157623. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157624. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157625. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157626. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157627. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157628. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157629. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157630. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157631. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157632. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157633. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157634. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157635. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157636. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157637. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157638. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157639. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157640. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157641. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157642. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157643. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157644. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157645. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157646. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157647. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157648. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157649. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157650. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157651. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157652. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157653. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157654. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157655. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157656. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157657. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157658. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157659. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157660. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157661. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157662. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157663. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157664. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157665. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157666. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157667. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157668. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157669. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157670. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157671. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157672. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157673. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157674. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157675. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157676. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157677. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157678. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157679. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157680. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157681. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157682. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157683. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157684. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157685. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157686. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157687. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157688. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157689. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157690. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157691. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157692. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157693. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157694. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157695. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157696. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157697. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157698. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157699. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157700. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157701. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157702. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157703. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157704. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157705. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157706. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157707. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157708. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157709. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157710. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157711. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157712. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157713. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157714. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157715. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157716. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157717. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157718. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157719. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157720. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157721. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157722. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157723. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157724. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157725. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157726. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157727. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157728. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157729. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157730. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157731. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157732. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157733. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157734. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157735. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157736. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157737. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157738. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157739. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157740. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157741. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157742. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157743. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157744. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157745. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157746. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157747. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157748. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157749. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157750. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157751. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157752. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157753. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157754. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157755. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157756. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157757. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157758. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157759. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157760. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157761. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157762. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157763. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157764. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157765. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157766. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157767. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157768. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157769. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157770. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157771. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157772. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157773. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157774. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157775. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157776. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157777. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157778. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157779. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157780. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157781. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157782. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157783. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157784. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157785. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157786. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157787. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157788. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157789. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157790. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157791. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157792. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157793. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157794. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157795. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157796. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157797. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157798. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157799. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157800. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157801. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157802. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157803. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157804. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157805. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157806. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157807. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157808. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157809. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157810. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157811. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157812. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157813. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157814. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157815. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157816. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157817. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157818. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157819. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157820. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157821. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157822. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157823. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157824. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157825. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157826. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157827. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157828. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157829. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157830. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157831. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157832. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157833. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157834. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157835. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157836. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157837. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157838. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157839. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157840. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157841. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157842. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157843. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157844. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157845. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157846. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157847. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157848. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157849. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157850. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157851. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157852. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157853. };
  157854. static float vwin4096[2048] = {
  157855. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157856. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157857. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157858. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157859. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157860. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157861. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157862. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157863. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157864. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157865. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157866. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157867. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157868. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157869. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157870. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157871. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157872. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157873. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157874. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157875. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157876. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157877. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157878. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157879. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157880. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157881. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157882. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157883. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157884. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157885. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157886. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157887. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157888. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157889. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157890. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157891. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157892. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157893. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157894. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157895. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157896. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157897. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157898. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157899. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157900. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157901. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157902. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157903. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157904. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157905. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157906. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157907. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157908. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157909. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157910. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157911. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157912. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157913. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157914. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157915. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157916. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157917. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157918. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157919. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157920. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157921. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157922. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157923. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157924. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157925. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157926. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157927. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157928. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157929. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157930. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157931. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157932. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157933. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157934. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157935. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157936. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157937. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157938. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157939. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157940. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157941. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157942. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157943. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157944. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157945. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157946. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157947. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157948. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157949. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157950. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157951. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157952. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157953. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157954. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157955. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157956. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157957. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157958. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157959. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157960. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157961. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157962. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157963. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157964. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157965. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157966. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157967. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157968. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157969. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157970. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157971. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157972. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157973. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157974. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157975. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157976. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157977. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157978. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157979. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157980. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157981. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157982. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157983. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157984. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157985. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157986. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157987. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157988. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157989. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157990. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157991. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157992. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157993. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157994. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157995. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157996. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157997. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157998. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157999. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  158000. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  158001. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  158002. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  158003. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  158004. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  158005. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  158006. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  158007. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  158008. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  158009. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  158010. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  158011. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  158012. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  158013. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  158014. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  158015. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  158016. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  158017. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  158018. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  158019. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  158020. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  158021. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  158022. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  158023. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  158024. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  158025. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  158026. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  158027. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  158028. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  158029. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158030. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158031. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158032. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158033. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158034. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158035. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158036. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158037. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158038. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158039. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158040. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158041. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158042. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158043. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158044. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158045. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158046. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158047. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158048. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158049. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158050. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158051. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158052. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158053. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158054. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158055. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158056. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158057. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158058. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158059. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158060. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158061. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158062. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158063. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158064. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158065. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158066. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158067. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158068. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158069. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158070. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158071. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158072. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158073. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158074. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158075. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158076. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158077. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158078. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158079. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158080. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158081. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158082. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158083. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158084. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158085. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158086. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158087. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158088. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158089. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158090. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158091. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158092. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158093. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158094. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158095. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158096. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158097. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158098. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158099. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158100. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158101. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158102. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158103. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158104. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158105. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158106. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158107. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158108. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158109. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158110. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158111. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158112. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158113. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158114. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158115. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158116. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158117. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158118. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158119. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158120. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158121. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158122. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158123. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158124. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158125. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158126. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158127. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158128. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158129. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158130. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158131. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158132. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158133. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158134. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158135. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158136. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158137. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158138. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158139. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158140. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158141. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158142. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158143. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158144. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158145. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158146. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158147. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158148. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158149. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158150. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158151. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158152. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158153. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158154. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158155. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158156. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158157. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158158. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158159. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158160. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158161. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158162. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158163. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158164. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158165. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158166. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158167. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158168. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158169. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158170. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158171. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158172. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158173. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158174. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158175. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158176. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158177. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158178. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158179. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158180. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158181. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158182. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158183. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158184. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158185. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158186. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158187. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158188. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158189. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158190. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158191. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158192. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158193. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158194. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158195. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158196. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158197. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158198. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158199. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158200. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158201. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158202. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158203. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158204. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158205. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158206. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158207. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158208. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158209. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158210. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158211. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158212. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158213. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158214. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158215. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158216. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158217. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158218. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158219. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158220. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158221. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158222. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158223. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158224. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158225. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158226. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158227. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158228. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158229. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158230. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158231. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158232. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158233. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158234. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158235. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158236. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158237. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158238. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158239. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158240. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158241. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158242. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158243. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158244. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158245. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158246. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158247. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158248. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158249. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158250. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158251. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158252. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158253. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158254. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158255. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158256. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158257. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158258. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158259. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158260. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158261. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158262. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158263. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158264. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158265. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158266. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158267. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158268. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158269. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158270. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158271. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158272. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158273. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158274. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158275. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158276. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158277. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158278. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158279. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158280. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158281. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158282. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158283. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158284. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158285. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158286. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158287. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158288. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158289. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158290. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158291. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158292. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158293. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158294. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158295. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158296. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158297. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158298. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158299. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158300. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158301. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158302. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158303. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158304. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158305. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158306. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158307. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158308. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158309. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158310. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158311. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158312. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158313. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158314. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158315. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158316. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158317. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158318. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158319. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158320. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158321. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158322. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158323. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158324. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158325. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158326. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158327. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158328. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158329. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158330. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158331. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158332. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158333. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158334. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158335. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158336. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158337. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158338. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158339. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158340. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158341. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158342. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158343. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158344. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158345. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158346. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158347. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158348. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158349. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158350. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158351. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158352. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158353. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158354. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158355. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158356. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158357. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158358. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158359. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158360. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158361. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158362. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158363. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158364. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158365. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158366. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158367. };
  158368. static float vwin8192[4096] = {
  158369. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158370. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158371. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158372. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158373. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158374. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158375. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158376. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158377. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158378. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158379. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158380. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158381. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158382. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158383. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158384. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158385. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158386. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158387. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158388. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158389. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158390. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158391. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158392. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158393. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158394. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158395. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158396. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158397. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158398. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158399. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158400. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158401. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158402. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158403. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158404. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158405. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158406. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158407. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158408. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158409. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158410. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158411. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158412. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158413. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158414. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158415. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158416. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158417. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158418. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158419. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158420. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158421. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158422. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158423. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158424. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158425. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158426. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158427. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158428. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158429. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158430. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158431. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158432. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158433. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158434. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158435. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158436. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158437. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158438. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158439. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158440. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158441. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158442. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158443. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158444. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158445. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158446. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158447. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158448. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158449. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158450. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158451. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158452. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158453. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158454. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158455. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158456. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158457. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158458. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158459. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158460. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158461. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158462. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158463. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158464. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158465. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158466. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158467. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158468. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158469. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158470. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158471. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158472. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158473. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158474. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158475. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158476. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158477. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158478. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158479. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158480. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158481. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158482. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158483. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158484. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158485. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158486. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158487. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158488. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158489. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158490. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158491. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158492. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158493. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158494. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158495. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158496. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158497. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158498. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158499. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158500. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158501. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158502. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158503. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158504. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158505. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158506. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158507. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158508. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158509. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158510. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158511. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158512. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158513. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158514. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158515. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158516. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158517. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158518. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158519. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158520. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158521. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158522. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158523. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158524. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158525. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158526. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158527. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158528. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158529. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158530. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158531. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158532. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158533. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158534. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158535. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158536. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158537. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158538. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158539. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158540. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158541. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158542. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158543. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158544. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158545. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158546. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158547. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158548. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158549. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158550. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158551. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158552. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158553. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158554. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158555. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158556. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158557. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158558. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158559. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158560. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158561. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158562. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158563. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158564. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158565. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158566. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158567. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158568. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158569. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158570. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158571. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158572. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158573. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158574. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158575. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158576. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158577. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158578. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158579. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158580. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158581. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158582. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158583. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158584. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158585. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158586. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158587. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158588. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158589. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158590. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158591. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158592. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158593. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158594. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158595. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158596. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158597. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158598. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158599. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158600. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158601. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158602. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158603. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158604. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158605. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158606. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158607. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158608. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158609. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158610. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158611. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158612. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158613. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158614. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158615. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158616. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158617. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158618. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158619. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158620. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158621. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158622. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158623. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158624. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158625. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158626. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158627. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158628. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158629. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158630. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158631. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158632. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158633. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158634. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158635. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158636. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158637. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158638. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158639. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158640. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158641. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158642. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158643. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158644. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158645. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158646. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158647. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158648. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158649. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158650. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158651. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158652. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158653. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158654. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158655. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158656. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158657. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158658. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158659. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158660. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158661. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158662. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158663. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158664. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158665. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158666. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158667. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158668. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158669. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158670. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158671. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158672. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158673. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158674. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158675. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158676. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158677. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158678. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158679. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158680. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158681. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158682. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158683. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158684. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158685. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158686. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158687. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158688. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158689. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158690. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158691. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158692. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158693. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158694. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158695. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158696. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158697. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158698. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158699. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158700. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158701. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158702. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158703. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158704. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158705. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158706. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158707. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158708. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158709. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158710. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158711. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158712. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158713. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158714. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158715. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158716. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158717. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158718. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158719. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158720. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158721. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158722. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158723. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158724. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158725. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158726. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158727. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158728. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158729. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158730. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158731. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158732. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158733. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158734. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158735. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158736. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158737. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158738. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158739. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158740. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158741. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158742. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158743. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158744. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158745. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158746. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158747. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158748. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158749. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158750. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158751. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158752. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158753. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158754. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158755. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158756. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158757. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158758. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158759. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158760. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158761. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158762. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158763. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158764. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158765. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158766. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158767. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158768. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158769. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158770. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158771. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158772. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158773. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158774. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158775. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158776. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158777. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158778. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158779. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158780. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158781. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158782. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158783. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158784. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158785. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158786. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158787. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158788. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158789. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158790. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158791. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158792. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158793. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158794. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158795. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158796. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158797. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158798. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158799. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158800. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158801. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158802. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158803. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158804. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158805. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158806. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158807. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158808. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158809. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158810. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158811. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158812. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158813. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158814. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158815. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158816. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158817. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158818. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158819. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158820. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158821. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158822. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158823. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158824. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158825. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158826. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158827. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158828. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158829. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158830. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158831. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158832. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158833. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158834. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158835. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158836. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158837. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158838. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158839. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158840. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158841. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158842. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158843. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158844. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158845. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158846. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158847. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158848. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158849. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158850. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158851. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158852. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158853. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158854. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158855. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158856. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158857. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158858. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158859. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158860. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158861. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158862. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158863. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158864. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158865. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158866. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158867. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158868. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158869. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158870. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158871. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158872. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158873. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158874. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158875. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158876. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158877. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158878. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158879. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158880. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158881. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158882. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158883. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158884. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158885. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158886. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158887. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158888. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158889. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158890. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158891. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158892. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158893. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158894. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158895. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158896. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158897. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158898. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158899. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158900. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158901. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158902. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158903. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158904. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158905. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158906. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158907. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158908. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158909. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158910. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158911. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158912. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158913. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158914. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158915. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158916. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158917. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158918. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158919. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158920. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158921. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158922. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158923. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158924. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158925. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158926. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158927. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158928. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158929. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158930. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158931. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158932. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158933. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158934. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158935. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158936. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158937. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158938. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158939. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158940. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158941. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158942. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158943. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158944. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158945. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158946. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158947. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158948. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158949. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158950. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158951. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158952. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158953. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158954. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158955. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158956. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158957. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158958. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158959. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158960. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158961. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158962. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158963. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158964. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158965. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158966. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158967. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158968. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158969. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158970. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158971. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158972. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158973. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158974. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158975. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158976. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158977. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158978. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158979. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158980. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158981. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158982. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158983. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158984. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158985. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158986. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158987. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158988. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158989. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158990. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158991. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158992. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158993. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158994. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158995. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158996. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158997. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158998. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158999. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  159000. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  159001. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  159002. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  159003. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  159004. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  159005. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  159006. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  159007. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  159008. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  159009. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  159010. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  159011. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  159012. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  159013. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  159014. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  159015. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  159016. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  159017. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  159018. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  159019. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  159020. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  159021. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  159022. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  159023. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  159024. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  159025. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  159026. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  159027. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  159028. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  159029. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159030. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159031. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159032. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159033. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159034. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159035. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159036. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159037. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159038. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159039. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159040. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159041. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159042. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159043. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159044. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159045. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159046. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159047. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159048. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159049. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159050. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159051. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159052. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159053. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159054. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159055. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159056. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159057. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159058. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159059. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159060. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159061. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159062. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159063. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159064. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159065. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159066. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159067. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159068. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159069. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159070. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159071. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159072. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159073. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159074. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159075. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159076. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159077. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159078. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159079. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159080. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159081. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159082. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159083. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159084. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159085. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159086. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159087. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159088. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159089. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159090. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159091. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159092. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159093. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159094. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159095. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159096. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159097. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159098. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159099. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159100. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159101. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159102. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159103. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159104. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159105. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159106. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159107. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159108. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159109. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159110. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159111. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159112. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159113. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159114. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159115. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159116. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159117. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159118. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159119. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159120. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159121. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159122. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159123. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159124. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159125. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159126. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159127. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159128. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159129. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159130. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159131. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159132. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159133. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159134. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159135. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159136. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159137. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159138. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159139. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159140. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159141. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159142. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159143. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159144. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159145. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159146. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159147. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159148. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159149. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159150. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159151. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159152. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159153. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159154. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159155. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159156. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159157. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159158. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159159. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159160. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159161. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159162. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159163. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159164. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159165. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159166. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159167. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159168. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159169. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159170. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159171. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159172. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159173. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159174. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159175. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159176. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159177. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159178. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159179. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159180. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159181. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159182. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159183. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159184. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159185. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159186. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159187. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159188. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159189. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159190. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159191. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159192. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159193. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159194. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159195. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159196. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159197. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159198. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159199. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159200. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159201. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159202. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159203. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159204. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159205. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159206. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159207. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159208. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159209. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159210. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159211. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159212. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159213. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159214. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159215. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159216. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159217. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159218. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159219. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159220. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159221. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159222. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159223. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159224. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159225. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159226. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159227. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159228. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159229. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159230. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159231. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159232. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159233. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159234. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159235. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159236. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159237. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159238. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159239. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159240. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159241. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159242. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159243. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159244. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159245. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159246. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159247. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159248. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159249. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159250. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159251. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159252. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159253. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159254. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159255. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159256. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159257. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159258. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159259. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159260. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159261. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159262. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159263. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159264. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159265. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159266. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159267. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159268. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159269. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159270. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159271. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159272. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159273. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159274. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159275. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159276. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159277. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159278. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159279. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159280. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159281. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159282. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159283. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159284. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159285. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159286. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159287. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159288. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159289. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159290. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159291. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159292. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159293. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159294. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159295. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159296. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159297. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159298. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159299. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159300. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159301. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159302. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159303. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159304. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159305. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159306. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159307. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159308. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159309. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159310. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159311. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159312. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159313. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159314. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159315. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159316. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159317. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159318. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159319. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159320. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159321. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159322. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159323. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159324. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159325. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159326. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159327. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159328. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159329. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159330. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159331. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159332. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159333. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159334. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159335. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159336. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159337. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159338. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159339. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159340. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159341. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159342. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159343. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159344. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159345. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159346. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159347. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159348. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159349. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159350. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159351. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159352. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159353. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159354. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159355. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159356. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159357. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159358. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159359. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159360. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159361. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159362. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159363. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159364. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159365. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159366. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159367. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159368. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159369. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159370. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159371. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159372. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159373. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159374. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159375. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159376. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159377. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159378. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159379. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159380. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159381. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159382. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159383. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159384. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159385. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159386. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159387. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159388. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159389. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159390. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159391. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159392. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159393. };
  159394. static float *vwin[8] = {
  159395. vwin64,
  159396. vwin128,
  159397. vwin256,
  159398. vwin512,
  159399. vwin1024,
  159400. vwin2048,
  159401. vwin4096,
  159402. vwin8192,
  159403. };
  159404. float *_vorbis_window_get(int n){
  159405. return vwin[n];
  159406. }
  159407. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159408. int lW,int W,int nW){
  159409. lW=(W?lW:0);
  159410. nW=(W?nW:0);
  159411. {
  159412. float *windowLW=vwin[winno[lW]];
  159413. float *windowNW=vwin[winno[nW]];
  159414. long n=blocksizes[W];
  159415. long ln=blocksizes[lW];
  159416. long rn=blocksizes[nW];
  159417. long leftbegin=n/4-ln/4;
  159418. long leftend=leftbegin+ln/2;
  159419. long rightbegin=n/2+n/4-rn/4;
  159420. long rightend=rightbegin+rn/2;
  159421. int i,p;
  159422. for(i=0;i<leftbegin;i++)
  159423. d[i]=0.f;
  159424. for(p=0;i<leftend;i++,p++)
  159425. d[i]*=windowLW[p];
  159426. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159427. d[i]*=windowNW[p];
  159428. for(;i<n;i++)
  159429. d[i]=0.f;
  159430. }
  159431. }
  159432. #endif
  159433. /*** End of inlined file: window.c ***/
  159434. #else
  159435. #include <vorbis/vorbisenc.h>
  159436. #include <vorbis/codec.h>
  159437. #include <vorbis/vorbisfile.h>
  159438. #endif
  159439. }
  159440. #undef max
  159441. #undef min
  159442. BEGIN_JUCE_NAMESPACE
  159443. static const char* const oggFormatName = "Ogg-Vorbis file";
  159444. static const char* const oggExtensions[] = { ".ogg", 0 };
  159445. class OggReader : public AudioFormatReader
  159446. {
  159447. OggVorbisNamespace::OggVorbis_File ovFile;
  159448. OggVorbisNamespace::ov_callbacks callbacks;
  159449. AudioSampleBuffer reservoir;
  159450. int reservoirStart, samplesInReservoir;
  159451. public:
  159452. OggReader (InputStream* const inp)
  159453. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159454. reservoir (2, 4096),
  159455. reservoirStart (0),
  159456. samplesInReservoir (0)
  159457. {
  159458. using namespace OggVorbisNamespace;
  159459. sampleRate = 0;
  159460. usesFloatingPointData = true;
  159461. callbacks.read_func = &oggReadCallback;
  159462. callbacks.seek_func = &oggSeekCallback;
  159463. callbacks.close_func = &oggCloseCallback;
  159464. callbacks.tell_func = &oggTellCallback;
  159465. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159466. if (err == 0)
  159467. {
  159468. vorbis_info* info = ov_info (&ovFile, -1);
  159469. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159470. numChannels = info->channels;
  159471. bitsPerSample = 16;
  159472. sampleRate = info->rate;
  159473. reservoir.setSize (numChannels,
  159474. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159475. }
  159476. }
  159477. ~OggReader()
  159478. {
  159479. OggVorbisNamespace::ov_clear (&ovFile);
  159480. }
  159481. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159482. int64 startSampleInFile, int numSamples)
  159483. {
  159484. while (numSamples > 0)
  159485. {
  159486. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159487. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159488. {
  159489. // got a few samples overlapping, so use them before seeking..
  159490. const int numToUse = jmin (numSamples, numAvailable);
  159491. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159492. if (destSamples[i] != 0)
  159493. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159494. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159495. sizeof (float) * numToUse);
  159496. startSampleInFile += numToUse;
  159497. numSamples -= numToUse;
  159498. startOffsetInDestBuffer += numToUse;
  159499. if (numSamples == 0)
  159500. break;
  159501. }
  159502. if (startSampleInFile < reservoirStart
  159503. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159504. {
  159505. // buffer miss, so refill the reservoir
  159506. int bitStream = 0;
  159507. reservoirStart = jmax (0, (int) startSampleInFile);
  159508. samplesInReservoir = reservoir.getNumSamples();
  159509. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159510. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159511. int offset = 0;
  159512. int numToRead = samplesInReservoir;
  159513. while (numToRead > 0)
  159514. {
  159515. float** dataIn = 0;
  159516. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159517. if (samps <= 0)
  159518. break;
  159519. jassert (samps <= numToRead);
  159520. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159521. {
  159522. memcpy (reservoir.getSampleData (i, offset),
  159523. dataIn[i],
  159524. sizeof (float) * samps);
  159525. }
  159526. numToRead -= samps;
  159527. offset += samps;
  159528. }
  159529. if (numToRead > 0)
  159530. reservoir.clear (offset, numToRead);
  159531. }
  159532. }
  159533. if (numSamples > 0)
  159534. {
  159535. for (int i = numDestChannels; --i >= 0;)
  159536. if (destSamples[i] != 0)
  159537. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159538. sizeof (int) * numSamples);
  159539. }
  159540. return true;
  159541. }
  159542. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159543. {
  159544. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159545. }
  159546. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159547. {
  159548. InputStream* const in = static_cast <InputStream*> (datasource);
  159549. if (whence == SEEK_CUR)
  159550. offset += in->getPosition();
  159551. else if (whence == SEEK_END)
  159552. offset += in->getTotalLength();
  159553. in->setPosition (offset);
  159554. return 0;
  159555. }
  159556. static int oggCloseCallback (void*)
  159557. {
  159558. return 0;
  159559. }
  159560. static long oggTellCallback (void* datasource)
  159561. {
  159562. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159563. }
  159564. juce_UseDebuggingNewOperator
  159565. };
  159566. class OggWriter : public AudioFormatWriter
  159567. {
  159568. OggVorbisNamespace::ogg_stream_state os;
  159569. OggVorbisNamespace::ogg_page og;
  159570. OggVorbisNamespace::ogg_packet op;
  159571. OggVorbisNamespace::vorbis_info vi;
  159572. OggVorbisNamespace::vorbis_comment vc;
  159573. OggVorbisNamespace::vorbis_dsp_state vd;
  159574. OggVorbisNamespace::vorbis_block vb;
  159575. public:
  159576. bool ok;
  159577. OggWriter (OutputStream* const out,
  159578. const double sampleRate,
  159579. const int numChannels,
  159580. const int bitsPerSample,
  159581. const int qualityIndex)
  159582. : AudioFormatWriter (out, TRANS (oggFormatName),
  159583. sampleRate,
  159584. numChannels,
  159585. bitsPerSample)
  159586. {
  159587. using namespace OggVorbisNamespace;
  159588. ok = false;
  159589. vorbis_info_init (&vi);
  159590. if (vorbis_encode_init_vbr (&vi,
  159591. numChannels,
  159592. (int) sampleRate,
  159593. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159594. {
  159595. vorbis_comment_init (&vc);
  159596. if (JUCEApplication::getInstance() != 0)
  159597. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159598. vorbis_analysis_init (&vd, &vi);
  159599. vorbis_block_init (&vd, &vb);
  159600. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159601. ogg_packet header;
  159602. ogg_packet header_comm;
  159603. ogg_packet header_code;
  159604. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159605. ogg_stream_packetin (&os, &header);
  159606. ogg_stream_packetin (&os, &header_comm);
  159607. ogg_stream_packetin (&os, &header_code);
  159608. for (;;)
  159609. {
  159610. if (ogg_stream_flush (&os, &og) == 0)
  159611. break;
  159612. output->write (og.header, og.header_len);
  159613. output->write (og.body, og.body_len);
  159614. }
  159615. ok = true;
  159616. }
  159617. }
  159618. ~OggWriter()
  159619. {
  159620. using namespace OggVorbisNamespace;
  159621. if (ok)
  159622. {
  159623. // write a zero-length packet to show ogg that we're finished..
  159624. write (0, 0);
  159625. ogg_stream_clear (&os);
  159626. vorbis_block_clear (&vb);
  159627. vorbis_dsp_clear (&vd);
  159628. vorbis_comment_clear (&vc);
  159629. vorbis_info_clear (&vi);
  159630. output->flush();
  159631. }
  159632. else
  159633. {
  159634. vorbis_info_clear (&vi);
  159635. output = 0; // to stop the base class deleting this, as it needs to be returned
  159636. // to the caller of createWriter()
  159637. }
  159638. }
  159639. bool write (const int** samplesToWrite, int numSamples)
  159640. {
  159641. using namespace OggVorbisNamespace;
  159642. if (! ok)
  159643. return false;
  159644. if (numSamples > 0)
  159645. {
  159646. const double gain = 1.0 / 0x80000000u;
  159647. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159648. for (int i = numChannels; --i >= 0;)
  159649. {
  159650. float* const dst = vorbisBuffer[i];
  159651. const int* const src = samplesToWrite [i];
  159652. if (src != 0 && dst != 0)
  159653. {
  159654. for (int j = 0; j < numSamples; ++j)
  159655. dst[j] = (float) (src[j] * gain);
  159656. }
  159657. }
  159658. }
  159659. vorbis_analysis_wrote (&vd, numSamples);
  159660. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159661. {
  159662. vorbis_analysis (&vb, 0);
  159663. vorbis_bitrate_addblock (&vb);
  159664. while (vorbis_bitrate_flushpacket (&vd, &op))
  159665. {
  159666. ogg_stream_packetin (&os, &op);
  159667. for (;;)
  159668. {
  159669. if (ogg_stream_pageout (&os, &og) == 0)
  159670. break;
  159671. output->write (og.header, og.header_len);
  159672. output->write (og.body, og.body_len);
  159673. if (ogg_page_eos (&og))
  159674. break;
  159675. }
  159676. }
  159677. }
  159678. return true;
  159679. }
  159680. juce_UseDebuggingNewOperator
  159681. };
  159682. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159683. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159684. {
  159685. }
  159686. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159687. {
  159688. }
  159689. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159690. {
  159691. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159692. return Array <int> (rates);
  159693. }
  159694. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159695. {
  159696. const int depths[] = { 32, 0 };
  159697. return Array <int> (depths);
  159698. }
  159699. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159700. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159701. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159702. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159703. const bool deleteStreamIfOpeningFails)
  159704. {
  159705. ScopedPointer <OggReader> r (new OggReader (in));
  159706. if (r->sampleRate != 0)
  159707. return r.release();
  159708. if (! deleteStreamIfOpeningFails)
  159709. r->input = 0;
  159710. return 0;
  159711. }
  159712. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159713. double sampleRate,
  159714. unsigned int numChannels,
  159715. int bitsPerSample,
  159716. const StringPairArray& /*metadataValues*/,
  159717. int qualityOptionIndex)
  159718. {
  159719. ScopedPointer <OggWriter> w (new OggWriter (out,
  159720. sampleRate,
  159721. numChannels,
  159722. bitsPerSample,
  159723. qualityOptionIndex));
  159724. return w->ok ? w.release() : 0;
  159725. }
  159726. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159727. {
  159728. StringArray s;
  159729. s.add ("Low Quality");
  159730. s.add ("Medium Quality");
  159731. s.add ("High Quality");
  159732. return s;
  159733. }
  159734. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159735. {
  159736. FileInputStream* const in = source.createInputStream();
  159737. if (in != 0)
  159738. {
  159739. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159740. if (r != 0)
  159741. {
  159742. const int64 numSamps = r->lengthInSamples;
  159743. r = 0;
  159744. const int64 fileNumSamps = source.getSize() / 4;
  159745. const double ratio = numSamps / (double) fileNumSamps;
  159746. if (ratio > 12.0)
  159747. return 0;
  159748. else if (ratio > 6.0)
  159749. return 1;
  159750. else
  159751. return 2;
  159752. }
  159753. }
  159754. return 1;
  159755. }
  159756. END_JUCE_NAMESPACE
  159757. #endif
  159758. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159759. #endif
  159760. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159761. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159762. #if JUCE_MSVC
  159763. #pragma warning (push)
  159764. #endif
  159765. namespace jpeglibNamespace
  159766. {
  159767. #if JUCE_INCLUDE_JPEGLIB_CODE
  159768. #if JUCE_MINGW
  159769. typedef unsigned char boolean;
  159770. #endif
  159771. #define JPEG_INTERNALS
  159772. #undef FAR
  159773. /*** Start of inlined file: jpeglib.h ***/
  159774. #ifndef JPEGLIB_H
  159775. #define JPEGLIB_H
  159776. /*
  159777. * First we include the configuration files that record how this
  159778. * installation of the JPEG library is set up. jconfig.h can be
  159779. * generated automatically for many systems. jmorecfg.h contains
  159780. * manual configuration options that most people need not worry about.
  159781. */
  159782. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159783. /*** Start of inlined file: jconfig.h ***/
  159784. /* see jconfig.doc for explanations */
  159785. // disable all the warnings under MSVC
  159786. #ifdef _MSC_VER
  159787. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159788. #endif
  159789. #ifdef __BORLANDC__
  159790. #pragma warn -8057
  159791. #pragma warn -8019
  159792. #pragma warn -8004
  159793. #pragma warn -8008
  159794. #endif
  159795. #define HAVE_PROTOTYPES
  159796. #define HAVE_UNSIGNED_CHAR
  159797. #define HAVE_UNSIGNED_SHORT
  159798. /* #define void char */
  159799. /* #define const */
  159800. #undef CHAR_IS_UNSIGNED
  159801. #define HAVE_STDDEF_H
  159802. #define HAVE_STDLIB_H
  159803. #undef NEED_BSD_STRINGS
  159804. #undef NEED_SYS_TYPES_H
  159805. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159806. #undef NEED_SHORT_EXTERNAL_NAMES
  159807. #undef INCOMPLETE_TYPES_BROKEN
  159808. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159809. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159810. typedef unsigned char boolean;
  159811. #endif
  159812. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159813. #ifdef JPEG_INTERNALS
  159814. #undef RIGHT_SHIFT_IS_UNSIGNED
  159815. #endif /* JPEG_INTERNALS */
  159816. #ifdef JPEG_CJPEG_DJPEG
  159817. #define BMP_SUPPORTED /* BMP image file format */
  159818. #define GIF_SUPPORTED /* GIF image file format */
  159819. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159820. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159821. #define TARGA_SUPPORTED /* Targa image file format */
  159822. #define TWO_FILE_COMMANDLINE /* optional */
  159823. #define USE_SETMODE /* Microsoft has setmode() */
  159824. #undef NEED_SIGNAL_CATCHER
  159825. #undef DONT_USE_B_MODE
  159826. #undef PROGRESS_REPORT /* optional */
  159827. #endif /* JPEG_CJPEG_DJPEG */
  159828. /*** End of inlined file: jconfig.h ***/
  159829. /* widely used configuration options */
  159830. #endif
  159831. /*** Start of inlined file: jmorecfg.h ***/
  159832. /*
  159833. * Define BITS_IN_JSAMPLE as either
  159834. * 8 for 8-bit sample values (the usual setting)
  159835. * 12 for 12-bit sample values
  159836. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159837. * JPEG standard, and the IJG code does not support anything else!
  159838. * We do not support run-time selection of data precision, sorry.
  159839. */
  159840. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159841. /*
  159842. * Maximum number of components (color channels) allowed in JPEG image.
  159843. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159844. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159845. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159846. * really short on memory. (Each allowed component costs a hundred or so
  159847. * bytes of storage, whether actually used in an image or not.)
  159848. */
  159849. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159850. /*
  159851. * Basic data types.
  159852. * You may need to change these if you have a machine with unusual data
  159853. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159854. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159855. * but it had better be at least 16.
  159856. */
  159857. /* Representation of a single sample (pixel element value).
  159858. * We frequently allocate large arrays of these, so it's important to keep
  159859. * them small. But if you have memory to burn and access to char or short
  159860. * arrays is very slow on your hardware, you might want to change these.
  159861. */
  159862. #if BITS_IN_JSAMPLE == 8
  159863. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159864. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159865. */
  159866. #ifdef HAVE_UNSIGNED_CHAR
  159867. typedef unsigned char JSAMPLE;
  159868. #define GETJSAMPLE(value) ((int) (value))
  159869. #else /* not HAVE_UNSIGNED_CHAR */
  159870. typedef char JSAMPLE;
  159871. #ifdef CHAR_IS_UNSIGNED
  159872. #define GETJSAMPLE(value) ((int) (value))
  159873. #else
  159874. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159875. #endif /* CHAR_IS_UNSIGNED */
  159876. #endif /* HAVE_UNSIGNED_CHAR */
  159877. #define MAXJSAMPLE 255
  159878. #define CENTERJSAMPLE 128
  159879. #endif /* BITS_IN_JSAMPLE == 8 */
  159880. #if BITS_IN_JSAMPLE == 12
  159881. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159882. * On nearly all machines "short" will do nicely.
  159883. */
  159884. typedef short JSAMPLE;
  159885. #define GETJSAMPLE(value) ((int) (value))
  159886. #define MAXJSAMPLE 4095
  159887. #define CENTERJSAMPLE 2048
  159888. #endif /* BITS_IN_JSAMPLE == 12 */
  159889. /* Representation of a DCT frequency coefficient.
  159890. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159891. * Again, we allocate large arrays of these, but you can change to int
  159892. * if you have memory to burn and "short" is really slow.
  159893. */
  159894. typedef short JCOEF;
  159895. /* Compressed datastreams are represented as arrays of JOCTET.
  159896. * These must be EXACTLY 8 bits wide, at least once they are written to
  159897. * external storage. Note that when using the stdio data source/destination
  159898. * managers, this is also the data type passed to fread/fwrite.
  159899. */
  159900. #ifdef HAVE_UNSIGNED_CHAR
  159901. typedef unsigned char JOCTET;
  159902. #define GETJOCTET(value) (value)
  159903. #else /* not HAVE_UNSIGNED_CHAR */
  159904. typedef char JOCTET;
  159905. #ifdef CHAR_IS_UNSIGNED
  159906. #define GETJOCTET(value) (value)
  159907. #else
  159908. #define GETJOCTET(value) ((value) & 0xFF)
  159909. #endif /* CHAR_IS_UNSIGNED */
  159910. #endif /* HAVE_UNSIGNED_CHAR */
  159911. /* These typedefs are used for various table entries and so forth.
  159912. * They must be at least as wide as specified; but making them too big
  159913. * won't cost a huge amount of memory, so we don't provide special
  159914. * extraction code like we did for JSAMPLE. (In other words, these
  159915. * typedefs live at a different point on the speed/space tradeoff curve.)
  159916. */
  159917. /* UINT8 must hold at least the values 0..255. */
  159918. #ifdef HAVE_UNSIGNED_CHAR
  159919. typedef unsigned char UINT8;
  159920. #else /* not HAVE_UNSIGNED_CHAR */
  159921. #ifdef CHAR_IS_UNSIGNED
  159922. typedef char UINT8;
  159923. #else /* not CHAR_IS_UNSIGNED */
  159924. typedef short UINT8;
  159925. #endif /* CHAR_IS_UNSIGNED */
  159926. #endif /* HAVE_UNSIGNED_CHAR */
  159927. /* UINT16 must hold at least the values 0..65535. */
  159928. #ifdef HAVE_UNSIGNED_SHORT
  159929. typedef unsigned short UINT16;
  159930. #else /* not HAVE_UNSIGNED_SHORT */
  159931. typedef unsigned int UINT16;
  159932. #endif /* HAVE_UNSIGNED_SHORT */
  159933. /* INT16 must hold at least the values -32768..32767. */
  159934. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159935. typedef short INT16;
  159936. #endif
  159937. /* INT32 must hold at least signed 32-bit values. */
  159938. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159939. typedef long INT32;
  159940. #endif
  159941. /* Datatype used for image dimensions. The JPEG standard only supports
  159942. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159943. * "unsigned int" is sufficient on all machines. However, if you need to
  159944. * handle larger images and you don't mind deviating from the spec, you
  159945. * can change this datatype.
  159946. */
  159947. typedef unsigned int JDIMENSION;
  159948. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159949. /* These macros are used in all function definitions and extern declarations.
  159950. * You could modify them if you need to change function linkage conventions;
  159951. * in particular, you'll need to do that to make the library a Windows DLL.
  159952. * Another application is to make all functions global for use with debuggers
  159953. * or code profilers that require it.
  159954. */
  159955. /* a function called through method pointers: */
  159956. #define METHODDEF(type) static type
  159957. /* a function used only in its module: */
  159958. #define LOCAL(type) static type
  159959. /* a function referenced thru EXTERNs: */
  159960. #define GLOBAL(type) type
  159961. /* a reference to a GLOBAL function: */
  159962. #define EXTERN(type) extern type
  159963. /* This macro is used to declare a "method", that is, a function pointer.
  159964. * We want to supply prototype parameters if the compiler can cope.
  159965. * Note that the arglist parameter must be parenthesized!
  159966. * Again, you can customize this if you need special linkage keywords.
  159967. */
  159968. #ifdef HAVE_PROTOTYPES
  159969. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159970. #else
  159971. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159972. #endif
  159973. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159974. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159975. * by just saying "FAR *" where such a pointer is needed. In a few places
  159976. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159977. */
  159978. #ifdef NEED_FAR_POINTERS
  159979. #define FAR far
  159980. #else
  159981. #define FAR
  159982. #endif
  159983. /*
  159984. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159985. * in standard header files. Or you may have conflicts with application-
  159986. * specific header files that you want to include together with these files.
  159987. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159988. */
  159989. #ifndef HAVE_BOOLEAN
  159990. typedef int boolean;
  159991. #endif
  159992. #ifndef FALSE /* in case these macros already exist */
  159993. #define FALSE 0 /* values of boolean */
  159994. #endif
  159995. #ifndef TRUE
  159996. #define TRUE 1
  159997. #endif
  159998. /*
  159999. * The remaining options affect code selection within the JPEG library,
  160000. * but they don't need to be visible to most applications using the library.
  160001. * To minimize application namespace pollution, the symbols won't be
  160002. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  160003. */
  160004. #ifdef JPEG_INTERNALS
  160005. #define JPEG_INTERNAL_OPTIONS
  160006. #endif
  160007. #ifdef JPEG_INTERNAL_OPTIONS
  160008. /*
  160009. * These defines indicate whether to include various optional functions.
  160010. * Undefining some of these symbols will produce a smaller but less capable
  160011. * library. Note that you can leave certain source files out of the
  160012. * compilation/linking process if you've #undef'd the corresponding symbols.
  160013. * (You may HAVE to do that if your compiler doesn't like null source files.)
  160014. */
  160015. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  160016. /* Capability options common to encoder and decoder: */
  160017. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  160018. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  160019. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  160020. /* Encoder capability options: */
  160021. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160022. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160023. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160024. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  160025. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  160026. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  160027. * precision, so jchuff.c normally uses entropy optimization to compute
  160028. * usable tables for higher precision. If you don't want to do optimization,
  160029. * you'll have to supply different default Huffman tables.
  160030. * The exact same statements apply for progressive JPEG: the default tables
  160031. * don't work for progressive mode. (This may get fixed, however.)
  160032. */
  160033. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160034. /* Decoder capability options: */
  160035. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160036. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160037. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160038. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160039. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160040. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160041. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160042. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160043. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160044. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160045. /* more capability options later, no doubt */
  160046. /*
  160047. * Ordering of RGB data in scanlines passed to or from the application.
  160048. * If your application wants to deal with data in the order B,G,R, just
  160049. * change these macros. You can also deal with formats such as R,G,B,X
  160050. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160051. * the offsets will also change the order in which colormap data is organized.
  160052. * RESTRICTIONS:
  160053. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160054. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160055. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160056. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160057. * is not 3 (they don't understand about dummy color components!). So you
  160058. * can't use color quantization if you change that value.
  160059. */
  160060. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160061. #define RGB_GREEN 1 /* Offset of Green */
  160062. #define RGB_BLUE 2 /* Offset of Blue */
  160063. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160064. /* Definitions for speed-related optimizations. */
  160065. /* If your compiler supports inline functions, define INLINE
  160066. * as the inline keyword; otherwise define it as empty.
  160067. */
  160068. #ifndef INLINE
  160069. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160070. #define INLINE __inline__
  160071. #endif
  160072. #ifndef INLINE
  160073. #define INLINE /* default is to define it as empty */
  160074. #endif
  160075. #endif
  160076. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160077. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160078. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160079. */
  160080. #ifndef MULTIPLIER
  160081. #define MULTIPLIER int /* type for fastest integer multiply */
  160082. #endif
  160083. /* FAST_FLOAT should be either float or double, whichever is done faster
  160084. * by your compiler. (Note that this type is only used in the floating point
  160085. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160086. * Typically, float is faster in ANSI C compilers, while double is faster in
  160087. * pre-ANSI compilers (because they insist on converting to double anyway).
  160088. * The code below therefore chooses float if we have ANSI-style prototypes.
  160089. */
  160090. #ifndef FAST_FLOAT
  160091. #ifdef HAVE_PROTOTYPES
  160092. #define FAST_FLOAT float
  160093. #else
  160094. #define FAST_FLOAT double
  160095. #endif
  160096. #endif
  160097. #endif /* JPEG_INTERNAL_OPTIONS */
  160098. /*** End of inlined file: jmorecfg.h ***/
  160099. /* seldom changed options */
  160100. /* Version ID for the JPEG library.
  160101. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160102. */
  160103. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160104. /* Various constants determining the sizes of things.
  160105. * All of these are specified by the JPEG standard, so don't change them
  160106. * if you want to be compatible.
  160107. */
  160108. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160109. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160110. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160111. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160112. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160113. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160114. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160115. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160116. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160117. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160118. * to handle it. We even let you do this from the jconfig.h file. However,
  160119. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160120. * sometimes emits noncompliant files doesn't mean you should too.
  160121. */
  160122. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160123. #ifndef D_MAX_BLOCKS_IN_MCU
  160124. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160125. #endif
  160126. /* Data structures for images (arrays of samples and of DCT coefficients).
  160127. * On 80x86 machines, the image arrays are too big for near pointers,
  160128. * but the pointer arrays can fit in near memory.
  160129. */
  160130. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160131. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160132. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160133. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160134. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160135. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160136. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160137. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160138. /* Types for JPEG compression parameters and working tables. */
  160139. /* DCT coefficient quantization tables. */
  160140. typedef struct {
  160141. /* This array gives the coefficient quantizers in natural array order
  160142. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160143. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160144. */
  160145. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160146. /* This field is used only during compression. It's initialized FALSE when
  160147. * the table is created, and set TRUE when it's been output to the file.
  160148. * You could suppress output of a table by setting this to TRUE.
  160149. * (See jpeg_suppress_tables for an example.)
  160150. */
  160151. boolean sent_table; /* TRUE when table has been output */
  160152. } JQUANT_TBL;
  160153. /* Huffman coding tables. */
  160154. typedef struct {
  160155. /* These two fields directly represent the contents of a JPEG DHT marker */
  160156. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160157. /* length k bits; bits[0] is unused */
  160158. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160159. /* This field is used only during compression. It's initialized FALSE when
  160160. * the table is created, and set TRUE when it's been output to the file.
  160161. * You could suppress output of a table by setting this to TRUE.
  160162. * (See jpeg_suppress_tables for an example.)
  160163. */
  160164. boolean sent_table; /* TRUE when table has been output */
  160165. } JHUFF_TBL;
  160166. /* Basic info about one component (color channel). */
  160167. typedef struct {
  160168. /* These values are fixed over the whole image. */
  160169. /* For compression, they must be supplied by parameter setup; */
  160170. /* for decompression, they are read from the SOF marker. */
  160171. int component_id; /* identifier for this component (0..255) */
  160172. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160173. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160174. int v_samp_factor; /* vertical sampling factor (1..4) */
  160175. int quant_tbl_no; /* quantization table selector (0..3) */
  160176. /* These values may vary between scans. */
  160177. /* For compression, they must be supplied by parameter setup; */
  160178. /* for decompression, they are read from the SOS marker. */
  160179. /* The decompressor output side may not use these variables. */
  160180. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160181. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160182. /* Remaining fields should be treated as private by applications. */
  160183. /* These values are computed during compression or decompression startup: */
  160184. /* Component's size in DCT blocks.
  160185. * Any dummy blocks added to complete an MCU are not counted; therefore
  160186. * these values do not depend on whether a scan is interleaved or not.
  160187. */
  160188. JDIMENSION width_in_blocks;
  160189. JDIMENSION height_in_blocks;
  160190. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160191. * For decompression this is the size of the output from one DCT block,
  160192. * reflecting any scaling we choose to apply during the IDCT step.
  160193. * Values of 1,2,4,8 are likely to be supported. Note that different
  160194. * components may receive different IDCT scalings.
  160195. */
  160196. int DCT_scaled_size;
  160197. /* The downsampled dimensions are the component's actual, unpadded number
  160198. * of samples at the main buffer (preprocessing/compression interface), thus
  160199. * downsampled_width = ceil(image_width * Hi/Hmax)
  160200. * and similarly for height. For decompression, IDCT scaling is included, so
  160201. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160202. */
  160203. JDIMENSION downsampled_width; /* actual width in samples */
  160204. JDIMENSION downsampled_height; /* actual height in samples */
  160205. /* This flag is used only for decompression. In cases where some of the
  160206. * components will be ignored (eg grayscale output from YCbCr image),
  160207. * we can skip most computations for the unused components.
  160208. */
  160209. boolean component_needed; /* do we need the value of this component? */
  160210. /* These values are computed before starting a scan of the component. */
  160211. /* The decompressor output side may not use these variables. */
  160212. int MCU_width; /* number of blocks per MCU, horizontally */
  160213. int MCU_height; /* number of blocks per MCU, vertically */
  160214. int MCU_blocks; /* MCU_width * MCU_height */
  160215. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160216. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160217. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160218. /* Saved quantization table for component; NULL if none yet saved.
  160219. * See jdinput.c comments about the need for this information.
  160220. * This field is currently used only for decompression.
  160221. */
  160222. JQUANT_TBL * quant_table;
  160223. /* Private per-component storage for DCT or IDCT subsystem. */
  160224. void * dct_table;
  160225. } jpeg_component_info;
  160226. /* The script for encoding a multiple-scan file is an array of these: */
  160227. typedef struct {
  160228. int comps_in_scan; /* number of components encoded in this scan */
  160229. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160230. int Ss, Se; /* progressive JPEG spectral selection parms */
  160231. int Ah, Al; /* progressive JPEG successive approx. parms */
  160232. } jpeg_scan_info;
  160233. /* The decompressor can save APPn and COM markers in a list of these: */
  160234. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160235. struct jpeg_marker_struct {
  160236. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160237. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160238. unsigned int original_length; /* # bytes of data in the file */
  160239. unsigned int data_length; /* # bytes of data saved at data[] */
  160240. JOCTET FAR * data; /* the data contained in the marker */
  160241. /* the marker length word is not counted in data_length or original_length */
  160242. };
  160243. /* Known color spaces. */
  160244. typedef enum {
  160245. JCS_UNKNOWN, /* error/unspecified */
  160246. JCS_GRAYSCALE, /* monochrome */
  160247. JCS_RGB, /* red/green/blue */
  160248. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160249. JCS_CMYK, /* C/M/Y/K */
  160250. JCS_YCCK /* Y/Cb/Cr/K */
  160251. } J_COLOR_SPACE;
  160252. /* DCT/IDCT algorithm options. */
  160253. typedef enum {
  160254. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160255. JDCT_IFAST, /* faster, less accurate integer method */
  160256. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160257. } J_DCT_METHOD;
  160258. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160259. #define JDCT_DEFAULT JDCT_ISLOW
  160260. #endif
  160261. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160262. #define JDCT_FASTEST JDCT_IFAST
  160263. #endif
  160264. /* Dithering options for decompression. */
  160265. typedef enum {
  160266. JDITHER_NONE, /* no dithering */
  160267. JDITHER_ORDERED, /* simple ordered dither */
  160268. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160269. } J_DITHER_MODE;
  160270. /* Common fields between JPEG compression and decompression master structs. */
  160271. #define jpeg_common_fields \
  160272. struct jpeg_error_mgr * err; /* Error handler module */\
  160273. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160274. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160275. void * client_data; /* Available for use by application */\
  160276. boolean is_decompressor; /* So common code can tell which is which */\
  160277. int global_state /* For checking call sequence validity */
  160278. /* Routines that are to be used by both halves of the library are declared
  160279. * to receive a pointer to this structure. There are no actual instances of
  160280. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160281. */
  160282. struct jpeg_common_struct {
  160283. jpeg_common_fields; /* Fields common to both master struct types */
  160284. /* Additional fields follow in an actual jpeg_compress_struct or
  160285. * jpeg_decompress_struct. All three structs must agree on these
  160286. * initial fields! (This would be a lot cleaner in C++.)
  160287. */
  160288. };
  160289. typedef struct jpeg_common_struct * j_common_ptr;
  160290. typedef struct jpeg_compress_struct * j_compress_ptr;
  160291. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160292. /* Master record for a compression instance */
  160293. struct jpeg_compress_struct {
  160294. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160295. /* Destination for compressed data */
  160296. struct jpeg_destination_mgr * dest;
  160297. /* Description of source image --- these fields must be filled in by
  160298. * outer application before starting compression. in_color_space must
  160299. * be correct before you can even call jpeg_set_defaults().
  160300. */
  160301. JDIMENSION image_width; /* input image width */
  160302. JDIMENSION image_height; /* input image height */
  160303. int input_components; /* # of color components in input image */
  160304. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160305. double input_gamma; /* image gamma of input image */
  160306. /* Compression parameters --- these fields must be set before calling
  160307. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160308. * initialize everything to reasonable defaults, then changing anything
  160309. * the application specifically wants to change. That way you won't get
  160310. * burnt when new parameters are added. Also note that there are several
  160311. * helper routines to simplify changing parameters.
  160312. */
  160313. int data_precision; /* bits of precision in image data */
  160314. int num_components; /* # of color components in JPEG image */
  160315. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160316. jpeg_component_info * comp_info;
  160317. /* comp_info[i] describes component that appears i'th in SOF */
  160318. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160319. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160320. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160321. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160322. /* ptrs to Huffman coding tables, or NULL if not defined */
  160323. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160324. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160325. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160326. int num_scans; /* # of entries in scan_info array */
  160327. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160328. /* The default value of scan_info is NULL, which causes a single-scan
  160329. * sequential JPEG file to be emitted. To create a multi-scan file,
  160330. * set num_scans and scan_info to point to an array of scan definitions.
  160331. */
  160332. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160333. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160334. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160335. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160336. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160337. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160338. /* The restart interval can be specified in absolute MCUs by setting
  160339. * restart_interval, or in MCU rows by setting restart_in_rows
  160340. * (in which case the correct restart_interval will be figured
  160341. * for each scan).
  160342. */
  160343. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160344. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160345. /* Parameters controlling emission of special markers. */
  160346. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160347. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160348. UINT8 JFIF_minor_version;
  160349. /* These three values are not used by the JPEG code, merely copied */
  160350. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160351. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160352. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160353. UINT8 density_unit; /* JFIF code for pixel size units */
  160354. UINT16 X_density; /* Horizontal pixel density */
  160355. UINT16 Y_density; /* Vertical pixel density */
  160356. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160357. /* State variable: index of next scanline to be written to
  160358. * jpeg_write_scanlines(). Application may use this to control its
  160359. * processing loop, e.g., "while (next_scanline < image_height)".
  160360. */
  160361. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160362. /* Remaining fields are known throughout compressor, but generally
  160363. * should not be touched by a surrounding application.
  160364. */
  160365. /*
  160366. * These fields are computed during compression startup
  160367. */
  160368. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160369. int max_h_samp_factor; /* largest h_samp_factor */
  160370. int max_v_samp_factor; /* largest v_samp_factor */
  160371. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160372. /* The coefficient controller receives data in units of MCU rows as defined
  160373. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160374. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160375. * "iMCU" (interleaved MCU) row.
  160376. */
  160377. /*
  160378. * These fields are valid during any one scan.
  160379. * They describe the components and MCUs actually appearing in the scan.
  160380. */
  160381. int comps_in_scan; /* # of JPEG components in this scan */
  160382. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160383. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160384. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160385. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160386. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160387. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160388. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160389. /* i'th block in an MCU */
  160390. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160391. /*
  160392. * Links to compression subobjects (methods and private variables of modules)
  160393. */
  160394. struct jpeg_comp_master * master;
  160395. struct jpeg_c_main_controller * main;
  160396. struct jpeg_c_prep_controller * prep;
  160397. struct jpeg_c_coef_controller * coef;
  160398. struct jpeg_marker_writer * marker;
  160399. struct jpeg_color_converter * cconvert;
  160400. struct jpeg_downsampler * downsample;
  160401. struct jpeg_forward_dct * fdct;
  160402. struct jpeg_entropy_encoder * entropy;
  160403. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160404. int script_space_size;
  160405. };
  160406. /* Master record for a decompression instance */
  160407. struct jpeg_decompress_struct {
  160408. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160409. /* Source of compressed data */
  160410. struct jpeg_source_mgr * src;
  160411. /* Basic description of image --- filled in by jpeg_read_header(). */
  160412. /* Application may inspect these values to decide how to process image. */
  160413. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160414. JDIMENSION image_height; /* nominal image height */
  160415. int num_components; /* # of color components in JPEG image */
  160416. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160417. /* Decompression processing parameters --- these fields must be set before
  160418. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160419. * them to default values.
  160420. */
  160421. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160422. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160423. double output_gamma; /* image gamma wanted in output */
  160424. boolean buffered_image; /* TRUE=multiple output passes */
  160425. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160426. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160427. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160428. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160429. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160430. /* the following are ignored if not quantize_colors: */
  160431. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160432. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160433. int desired_number_of_colors; /* max # colors to use in created colormap */
  160434. /* these are significant only in buffered-image mode: */
  160435. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160436. boolean enable_external_quant;/* enable future use of external colormap */
  160437. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160438. /* Description of actual output image that will be returned to application.
  160439. * These fields are computed by jpeg_start_decompress().
  160440. * You can also use jpeg_calc_output_dimensions() to determine these values
  160441. * in advance of calling jpeg_start_decompress().
  160442. */
  160443. JDIMENSION output_width; /* scaled image width */
  160444. JDIMENSION output_height; /* scaled image height */
  160445. int out_color_components; /* # of color components in out_color_space */
  160446. int output_components; /* # of color components returned */
  160447. /* output_components is 1 (a colormap index) when quantizing colors;
  160448. * otherwise it equals out_color_components.
  160449. */
  160450. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160451. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160452. * high, space and time will be wasted due to unnecessary data copying.
  160453. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160454. */
  160455. /* When quantizing colors, the output colormap is described by these fields.
  160456. * The application can supply a colormap by setting colormap non-NULL before
  160457. * calling jpeg_start_decompress; otherwise a colormap is created during
  160458. * jpeg_start_decompress or jpeg_start_output.
  160459. * The map has out_color_components rows and actual_number_of_colors columns.
  160460. */
  160461. int actual_number_of_colors; /* number of entries in use */
  160462. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160463. /* State variables: these variables indicate the progress of decompression.
  160464. * The application may examine these but must not modify them.
  160465. */
  160466. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160467. * Application may use this to control its processing loop, e.g.,
  160468. * "while (output_scanline < output_height)".
  160469. */
  160470. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160471. /* Current input scan number and number of iMCU rows completed in scan.
  160472. * These indicate the progress of the decompressor input side.
  160473. */
  160474. int input_scan_number; /* Number of SOS markers seen so far */
  160475. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160476. /* The "output scan number" is the notional scan being displayed by the
  160477. * output side. The decompressor will not allow output scan/row number
  160478. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160479. */
  160480. int output_scan_number; /* Nominal scan number being displayed */
  160481. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160482. /* Current progression status. coef_bits[c][i] indicates the precision
  160483. * with which component c's DCT coefficient i (in zigzag order) is known.
  160484. * It is -1 when no data has yet been received, otherwise it is the point
  160485. * transform (shift) value for the most recent scan of the coefficient
  160486. * (thus, 0 at completion of the progression).
  160487. * This pointer is NULL when reading a non-progressive file.
  160488. */
  160489. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160490. /* Internal JPEG parameters --- the application usually need not look at
  160491. * these fields. Note that the decompressor output side may not use
  160492. * any parameters that can change between scans.
  160493. */
  160494. /* Quantization and Huffman tables are carried forward across input
  160495. * datastreams when processing abbreviated JPEG datastreams.
  160496. */
  160497. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160498. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160499. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160500. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160501. /* ptrs to Huffman coding tables, or NULL if not defined */
  160502. /* These parameters are never carried across datastreams, since they
  160503. * are given in SOF/SOS markers or defined to be reset by SOI.
  160504. */
  160505. int data_precision; /* bits of precision in image data */
  160506. jpeg_component_info * comp_info;
  160507. /* comp_info[i] describes component that appears i'th in SOF */
  160508. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160509. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160510. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160511. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160512. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160513. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160514. /* These fields record data obtained from optional markers recognized by
  160515. * the JPEG library.
  160516. */
  160517. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160518. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160519. UINT8 JFIF_major_version; /* JFIF version number */
  160520. UINT8 JFIF_minor_version;
  160521. UINT8 density_unit; /* JFIF code for pixel size units */
  160522. UINT16 X_density; /* Horizontal pixel density */
  160523. UINT16 Y_density; /* Vertical pixel density */
  160524. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160525. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160526. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160527. /* Aside from the specific data retained from APPn markers known to the
  160528. * library, the uninterpreted contents of any or all APPn and COM markers
  160529. * can be saved in a list for examination by the application.
  160530. */
  160531. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160532. /* Remaining fields are known throughout decompressor, but generally
  160533. * should not be touched by a surrounding application.
  160534. */
  160535. /*
  160536. * These fields are computed during decompression startup
  160537. */
  160538. int max_h_samp_factor; /* largest h_samp_factor */
  160539. int max_v_samp_factor; /* largest v_samp_factor */
  160540. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160541. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160542. /* The coefficient controller's input and output progress is measured in
  160543. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160544. * in fully interleaved JPEG scans, but are used whether the scan is
  160545. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160546. * rows of each component. Therefore, the IDCT output contains
  160547. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160548. */
  160549. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160550. /*
  160551. * These fields are valid during any one scan.
  160552. * They describe the components and MCUs actually appearing in the scan.
  160553. * Note that the decompressor output side must not use these fields.
  160554. */
  160555. int comps_in_scan; /* # of JPEG components in this scan */
  160556. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160557. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160558. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160559. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160560. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160561. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160562. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160563. /* i'th block in an MCU */
  160564. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160565. /* This field is shared between entropy decoder and marker parser.
  160566. * It is either zero or the code of a JPEG marker that has been
  160567. * read from the data source, but has not yet been processed.
  160568. */
  160569. int unread_marker;
  160570. /*
  160571. * Links to decompression subobjects (methods, private variables of modules)
  160572. */
  160573. struct jpeg_decomp_master * master;
  160574. struct jpeg_d_main_controller * main;
  160575. struct jpeg_d_coef_controller * coef;
  160576. struct jpeg_d_post_controller * post;
  160577. struct jpeg_input_controller * inputctl;
  160578. struct jpeg_marker_reader * marker;
  160579. struct jpeg_entropy_decoder * entropy;
  160580. struct jpeg_inverse_dct * idct;
  160581. struct jpeg_upsampler * upsample;
  160582. struct jpeg_color_deconverter * cconvert;
  160583. struct jpeg_color_quantizer * cquantize;
  160584. };
  160585. /* "Object" declarations for JPEG modules that may be supplied or called
  160586. * directly by the surrounding application.
  160587. * As with all objects in the JPEG library, these structs only define the
  160588. * publicly visible methods and state variables of a module. Additional
  160589. * private fields may exist after the public ones.
  160590. */
  160591. /* Error handler object */
  160592. struct jpeg_error_mgr {
  160593. /* Error exit handler: does not return to caller */
  160594. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160595. /* Conditionally emit a trace or warning message */
  160596. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160597. /* Routine that actually outputs a trace or error message */
  160598. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160599. /* Format a message string for the most recent JPEG error or message */
  160600. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160601. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160602. /* Reset error state variables at start of a new image */
  160603. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160604. /* The message ID code and any parameters are saved here.
  160605. * A message can have one string parameter or up to 8 int parameters.
  160606. */
  160607. int msg_code;
  160608. #define JMSG_STR_PARM_MAX 80
  160609. union {
  160610. int i[8];
  160611. char s[JMSG_STR_PARM_MAX];
  160612. } msg_parm;
  160613. /* Standard state variables for error facility */
  160614. int trace_level; /* max msg_level that will be displayed */
  160615. /* For recoverable corrupt-data errors, we emit a warning message,
  160616. * but keep going unless emit_message chooses to abort. emit_message
  160617. * should count warnings in num_warnings. The surrounding application
  160618. * can check for bad data by seeing if num_warnings is nonzero at the
  160619. * end of processing.
  160620. */
  160621. long num_warnings; /* number of corrupt-data warnings */
  160622. /* These fields point to the table(s) of error message strings.
  160623. * An application can change the table pointer to switch to a different
  160624. * message list (typically, to change the language in which errors are
  160625. * reported). Some applications may wish to add additional error codes
  160626. * that will be handled by the JPEG library error mechanism; the second
  160627. * table pointer is used for this purpose.
  160628. *
  160629. * First table includes all errors generated by JPEG library itself.
  160630. * Error code 0 is reserved for a "no such error string" message.
  160631. */
  160632. const char * const * jpeg_message_table; /* Library errors */
  160633. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160634. /* Second table can be added by application (see cjpeg/djpeg for example).
  160635. * It contains strings numbered first_addon_message..last_addon_message.
  160636. */
  160637. const char * const * addon_message_table; /* Non-library errors */
  160638. int first_addon_message; /* code for first string in addon table */
  160639. int last_addon_message; /* code for last string in addon table */
  160640. };
  160641. /* Progress monitor object */
  160642. struct jpeg_progress_mgr {
  160643. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160644. long pass_counter; /* work units completed in this pass */
  160645. long pass_limit; /* total number of work units in this pass */
  160646. int completed_passes; /* passes completed so far */
  160647. int total_passes; /* total number of passes expected */
  160648. };
  160649. /* Data destination object for compression */
  160650. struct jpeg_destination_mgr {
  160651. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160652. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160653. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160654. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160655. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160656. };
  160657. /* Data source object for decompression */
  160658. struct jpeg_source_mgr {
  160659. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160660. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160661. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160662. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160663. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160664. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160665. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160666. };
  160667. /* Memory manager object.
  160668. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160669. * and "really big" objects (virtual arrays with backing store if needed).
  160670. * The memory manager does not allow individual objects to be freed; rather,
  160671. * each created object is assigned to a pool, and whole pools can be freed
  160672. * at once. This is faster and more convenient than remembering exactly what
  160673. * to free, especially where malloc()/free() are not too speedy.
  160674. * NB: alloc routines never return NULL. They exit to error_exit if not
  160675. * successful.
  160676. */
  160677. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160678. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160679. #define JPOOL_NUMPOOLS 2
  160680. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160681. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160682. struct jpeg_memory_mgr {
  160683. /* Method pointers */
  160684. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160685. size_t sizeofobject));
  160686. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160687. size_t sizeofobject));
  160688. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160689. JDIMENSION samplesperrow,
  160690. JDIMENSION numrows));
  160691. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160692. JDIMENSION blocksperrow,
  160693. JDIMENSION numrows));
  160694. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160695. int pool_id,
  160696. boolean pre_zero,
  160697. JDIMENSION samplesperrow,
  160698. JDIMENSION numrows,
  160699. JDIMENSION maxaccess));
  160700. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160701. int pool_id,
  160702. boolean pre_zero,
  160703. JDIMENSION blocksperrow,
  160704. JDIMENSION numrows,
  160705. JDIMENSION maxaccess));
  160706. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160707. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160708. jvirt_sarray_ptr ptr,
  160709. JDIMENSION start_row,
  160710. JDIMENSION num_rows,
  160711. boolean writable));
  160712. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160713. jvirt_barray_ptr ptr,
  160714. JDIMENSION start_row,
  160715. JDIMENSION num_rows,
  160716. boolean writable));
  160717. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160718. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160719. /* Limit on memory allocation for this JPEG object. (Note that this is
  160720. * merely advisory, not a guaranteed maximum; it only affects the space
  160721. * used for virtual-array buffers.) May be changed by outer application
  160722. * after creating the JPEG object.
  160723. */
  160724. long max_memory_to_use;
  160725. /* Maximum allocation request accepted by alloc_large. */
  160726. long max_alloc_chunk;
  160727. };
  160728. /* Routine signature for application-supplied marker processing methods.
  160729. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160730. */
  160731. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160732. /* Declarations for routines called by application.
  160733. * The JPP macro hides prototype parameters from compilers that can't cope.
  160734. * Note JPP requires double parentheses.
  160735. */
  160736. #ifdef HAVE_PROTOTYPES
  160737. #define JPP(arglist) arglist
  160738. #else
  160739. #define JPP(arglist) ()
  160740. #endif
  160741. /* Short forms of external names for systems with brain-damaged linkers.
  160742. * We shorten external names to be unique in the first six letters, which
  160743. * is good enough for all known systems.
  160744. * (If your compiler itself needs names to be unique in less than 15
  160745. * characters, you are out of luck. Get a better compiler.)
  160746. */
  160747. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160748. #define jpeg_std_error jStdError
  160749. #define jpeg_CreateCompress jCreaCompress
  160750. #define jpeg_CreateDecompress jCreaDecompress
  160751. #define jpeg_destroy_compress jDestCompress
  160752. #define jpeg_destroy_decompress jDestDecompress
  160753. #define jpeg_stdio_dest jStdDest
  160754. #define jpeg_stdio_src jStdSrc
  160755. #define jpeg_set_defaults jSetDefaults
  160756. #define jpeg_set_colorspace jSetColorspace
  160757. #define jpeg_default_colorspace jDefColorspace
  160758. #define jpeg_set_quality jSetQuality
  160759. #define jpeg_set_linear_quality jSetLQuality
  160760. #define jpeg_add_quant_table jAddQuantTable
  160761. #define jpeg_quality_scaling jQualityScaling
  160762. #define jpeg_simple_progression jSimProgress
  160763. #define jpeg_suppress_tables jSuppressTables
  160764. #define jpeg_alloc_quant_table jAlcQTable
  160765. #define jpeg_alloc_huff_table jAlcHTable
  160766. #define jpeg_start_compress jStrtCompress
  160767. #define jpeg_write_scanlines jWrtScanlines
  160768. #define jpeg_finish_compress jFinCompress
  160769. #define jpeg_write_raw_data jWrtRawData
  160770. #define jpeg_write_marker jWrtMarker
  160771. #define jpeg_write_m_header jWrtMHeader
  160772. #define jpeg_write_m_byte jWrtMByte
  160773. #define jpeg_write_tables jWrtTables
  160774. #define jpeg_read_header jReadHeader
  160775. #define jpeg_start_decompress jStrtDecompress
  160776. #define jpeg_read_scanlines jReadScanlines
  160777. #define jpeg_finish_decompress jFinDecompress
  160778. #define jpeg_read_raw_data jReadRawData
  160779. #define jpeg_has_multiple_scans jHasMultScn
  160780. #define jpeg_start_output jStrtOutput
  160781. #define jpeg_finish_output jFinOutput
  160782. #define jpeg_input_complete jInComplete
  160783. #define jpeg_new_colormap jNewCMap
  160784. #define jpeg_consume_input jConsumeInput
  160785. #define jpeg_calc_output_dimensions jCalcDimensions
  160786. #define jpeg_save_markers jSaveMarkers
  160787. #define jpeg_set_marker_processor jSetMarker
  160788. #define jpeg_read_coefficients jReadCoefs
  160789. #define jpeg_write_coefficients jWrtCoefs
  160790. #define jpeg_copy_critical_parameters jCopyCrit
  160791. #define jpeg_abort_compress jAbrtCompress
  160792. #define jpeg_abort_decompress jAbrtDecompress
  160793. #define jpeg_abort jAbort
  160794. #define jpeg_destroy jDestroy
  160795. #define jpeg_resync_to_restart jResyncRestart
  160796. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160797. /* Default error-management setup */
  160798. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160799. JPP((struct jpeg_error_mgr * err));
  160800. /* Initialization of JPEG compression objects.
  160801. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160802. * names that applications should call. These expand to calls on
  160803. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160804. * passed for version mismatch checking.
  160805. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160806. */
  160807. #define jpeg_create_compress(cinfo) \
  160808. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160809. (size_t) sizeof(struct jpeg_compress_struct))
  160810. #define jpeg_create_decompress(cinfo) \
  160811. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160812. (size_t) sizeof(struct jpeg_decompress_struct))
  160813. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160814. int version, size_t structsize));
  160815. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160816. int version, size_t structsize));
  160817. /* Destruction of JPEG compression objects */
  160818. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160819. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160820. /* Standard data source and destination managers: stdio streams. */
  160821. /* Caller is responsible for opening the file before and closing after. */
  160822. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160823. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160824. /* Default parameter setup for compression */
  160825. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160826. /* Compression parameter setup aids */
  160827. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160828. J_COLOR_SPACE colorspace));
  160829. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160830. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160831. boolean force_baseline));
  160832. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160833. int scale_factor,
  160834. boolean force_baseline));
  160835. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160836. const unsigned int *basic_table,
  160837. int scale_factor,
  160838. boolean force_baseline));
  160839. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160840. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160841. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160842. boolean suppress));
  160843. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160844. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160845. /* Main entry points for compression */
  160846. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160847. boolean write_all_tables));
  160848. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160849. JSAMPARRAY scanlines,
  160850. JDIMENSION num_lines));
  160851. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160852. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160853. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160854. JSAMPIMAGE data,
  160855. JDIMENSION num_lines));
  160856. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160857. EXTERN(void) jpeg_write_marker
  160858. JPP((j_compress_ptr cinfo, int marker,
  160859. const JOCTET * dataptr, unsigned int datalen));
  160860. /* Same, but piecemeal. */
  160861. EXTERN(void) jpeg_write_m_header
  160862. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160863. EXTERN(void) jpeg_write_m_byte
  160864. JPP((j_compress_ptr cinfo, int val));
  160865. /* Alternate compression function: just write an abbreviated table file */
  160866. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160867. /* Decompression startup: read start of JPEG datastream to see what's there */
  160868. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160869. boolean require_image));
  160870. /* Return value is one of: */
  160871. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160872. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160873. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160874. /* If you pass require_image = TRUE (normal case), you need not check for
  160875. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160876. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160877. * give a suspension return (the stdio source module doesn't).
  160878. */
  160879. /* Main entry points for decompression */
  160880. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160881. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160882. JSAMPARRAY scanlines,
  160883. JDIMENSION max_lines));
  160884. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160885. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160886. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160887. JSAMPIMAGE data,
  160888. JDIMENSION max_lines));
  160889. /* Additional entry points for buffered-image mode. */
  160890. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160891. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160892. int scan_number));
  160893. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160894. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160895. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160896. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160897. /* Return value is one of: */
  160898. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160899. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160900. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160901. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160902. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160903. /* Precalculate output dimensions for current decompression parameters. */
  160904. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160905. /* Control saving of COM and APPn markers into marker_list. */
  160906. EXTERN(void) jpeg_save_markers
  160907. JPP((j_decompress_ptr cinfo, int marker_code,
  160908. unsigned int length_limit));
  160909. /* Install a special processing method for COM or APPn markers. */
  160910. EXTERN(void) jpeg_set_marker_processor
  160911. JPP((j_decompress_ptr cinfo, int marker_code,
  160912. jpeg_marker_parser_method routine));
  160913. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160914. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160915. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160916. jvirt_barray_ptr * coef_arrays));
  160917. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160918. j_compress_ptr dstinfo));
  160919. /* If you choose to abort compression or decompression before completing
  160920. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160921. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160922. * if you're done with the JPEG object, but if you want to clean it up and
  160923. * reuse it, call this:
  160924. */
  160925. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160926. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160927. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160928. * flavor of JPEG object. These may be more convenient in some places.
  160929. */
  160930. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160931. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160932. /* Default restart-marker-resync procedure for use by data source modules */
  160933. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160934. int desired));
  160935. /* These marker codes are exported since applications and data source modules
  160936. * are likely to want to use them.
  160937. */
  160938. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160939. #define JPEG_EOI 0xD9 /* EOI marker code */
  160940. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160941. #define JPEG_COM 0xFE /* COM marker code */
  160942. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160943. * for structure definitions that are never filled in, keep it quiet by
  160944. * supplying dummy definitions for the various substructures.
  160945. */
  160946. #ifdef INCOMPLETE_TYPES_BROKEN
  160947. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160948. struct jvirt_sarray_control { long dummy; };
  160949. struct jvirt_barray_control { long dummy; };
  160950. struct jpeg_comp_master { long dummy; };
  160951. struct jpeg_c_main_controller { long dummy; };
  160952. struct jpeg_c_prep_controller { long dummy; };
  160953. struct jpeg_c_coef_controller { long dummy; };
  160954. struct jpeg_marker_writer { long dummy; };
  160955. struct jpeg_color_converter { long dummy; };
  160956. struct jpeg_downsampler { long dummy; };
  160957. struct jpeg_forward_dct { long dummy; };
  160958. struct jpeg_entropy_encoder { long dummy; };
  160959. struct jpeg_decomp_master { long dummy; };
  160960. struct jpeg_d_main_controller { long dummy; };
  160961. struct jpeg_d_coef_controller { long dummy; };
  160962. struct jpeg_d_post_controller { long dummy; };
  160963. struct jpeg_input_controller { long dummy; };
  160964. struct jpeg_marker_reader { long dummy; };
  160965. struct jpeg_entropy_decoder { long dummy; };
  160966. struct jpeg_inverse_dct { long dummy; };
  160967. struct jpeg_upsampler { long dummy; };
  160968. struct jpeg_color_deconverter { long dummy; };
  160969. struct jpeg_color_quantizer { long dummy; };
  160970. #endif /* JPEG_INTERNALS */
  160971. #endif /* INCOMPLETE_TYPES_BROKEN */
  160972. /*
  160973. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160974. * The internal structure declarations are read only when that is true.
  160975. * Applications using the library should not include jpegint.h, but may wish
  160976. * to include jerror.h.
  160977. */
  160978. #ifdef JPEG_INTERNALS
  160979. /*** Start of inlined file: jpegint.h ***/
  160980. /* Declarations for both compression & decompression */
  160981. typedef enum { /* Operating modes for buffer controllers */
  160982. JBUF_PASS_THRU, /* Plain stripwise operation */
  160983. /* Remaining modes require a full-image buffer to have been created */
  160984. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160985. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160986. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160987. } J_BUF_MODE;
  160988. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160989. #define CSTATE_START 100 /* after create_compress */
  160990. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160991. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160992. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160993. #define DSTATE_START 200 /* after create_decompress */
  160994. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160995. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160996. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160997. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160998. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160999. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  161000. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  161001. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  161002. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  161003. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  161004. /* Declarations for compression modules */
  161005. /* Master control module */
  161006. struct jpeg_comp_master {
  161007. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  161008. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  161009. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161010. /* State variables made visible to other modules */
  161011. boolean call_pass_startup; /* True if pass_startup must be called */
  161012. boolean is_last_pass; /* True during last pass */
  161013. };
  161014. /* Main buffer control (downsampled-data buffer) */
  161015. struct jpeg_c_main_controller {
  161016. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161017. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  161018. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161019. JDIMENSION in_rows_avail));
  161020. };
  161021. /* Compression preprocessing (downsampling input buffer control) */
  161022. struct jpeg_c_prep_controller {
  161023. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161024. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  161025. JSAMPARRAY input_buf,
  161026. JDIMENSION *in_row_ctr,
  161027. JDIMENSION in_rows_avail,
  161028. JSAMPIMAGE output_buf,
  161029. JDIMENSION *out_row_group_ctr,
  161030. JDIMENSION out_row_groups_avail));
  161031. };
  161032. /* Coefficient buffer control */
  161033. struct jpeg_c_coef_controller {
  161034. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161035. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161036. JSAMPIMAGE input_buf));
  161037. };
  161038. /* Colorspace conversion */
  161039. struct jpeg_color_converter {
  161040. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161041. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161042. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161043. JDIMENSION output_row, int num_rows));
  161044. };
  161045. /* Downsampling */
  161046. struct jpeg_downsampler {
  161047. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161048. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161049. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161050. JSAMPIMAGE output_buf,
  161051. JDIMENSION out_row_group_index));
  161052. boolean need_context_rows; /* TRUE if need rows above & below */
  161053. };
  161054. /* Forward DCT (also controls coefficient quantization) */
  161055. struct jpeg_forward_dct {
  161056. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161057. /* perhaps this should be an array??? */
  161058. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161059. jpeg_component_info * compptr,
  161060. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161061. JDIMENSION start_row, JDIMENSION start_col,
  161062. JDIMENSION num_blocks));
  161063. };
  161064. /* Entropy encoding */
  161065. struct jpeg_entropy_encoder {
  161066. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161067. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161068. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161069. };
  161070. /* Marker writing */
  161071. struct jpeg_marker_writer {
  161072. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161073. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161074. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161075. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161076. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161077. /* These routines are exported to allow insertion of extra markers */
  161078. /* Probably only COM and APPn markers should be written this way */
  161079. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161080. unsigned int datalen));
  161081. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161082. };
  161083. /* Declarations for decompression modules */
  161084. /* Master control module */
  161085. struct jpeg_decomp_master {
  161086. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161087. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161088. /* State variables made visible to other modules */
  161089. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161090. };
  161091. /* Input control module */
  161092. struct jpeg_input_controller {
  161093. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161094. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161095. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161096. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161097. /* State variables made visible to other modules */
  161098. boolean has_multiple_scans; /* True if file has multiple scans */
  161099. boolean eoi_reached; /* True when EOI has been consumed */
  161100. };
  161101. /* Main buffer control (downsampled-data buffer) */
  161102. struct jpeg_d_main_controller {
  161103. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161104. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161105. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161106. JDIMENSION out_rows_avail));
  161107. };
  161108. /* Coefficient buffer control */
  161109. struct jpeg_d_coef_controller {
  161110. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161111. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161112. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161113. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161114. JSAMPIMAGE output_buf));
  161115. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161116. jvirt_barray_ptr *coef_arrays;
  161117. };
  161118. /* Decompression postprocessing (color quantization buffer control) */
  161119. struct jpeg_d_post_controller {
  161120. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161121. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161122. JSAMPIMAGE input_buf,
  161123. JDIMENSION *in_row_group_ctr,
  161124. JDIMENSION in_row_groups_avail,
  161125. JSAMPARRAY output_buf,
  161126. JDIMENSION *out_row_ctr,
  161127. JDIMENSION out_rows_avail));
  161128. };
  161129. /* Marker reading & parsing */
  161130. struct jpeg_marker_reader {
  161131. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161132. /* Read markers until SOS or EOI.
  161133. * Returns same codes as are defined for jpeg_consume_input:
  161134. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161135. */
  161136. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161137. /* Read a restart marker --- exported for use by entropy decoder only */
  161138. jpeg_marker_parser_method read_restart_marker;
  161139. /* State of marker reader --- nominally internal, but applications
  161140. * supplying COM or APPn handlers might like to know the state.
  161141. */
  161142. boolean saw_SOI; /* found SOI? */
  161143. boolean saw_SOF; /* found SOF? */
  161144. int next_restart_num; /* next restart number expected (0-7) */
  161145. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161146. };
  161147. /* Entropy decoding */
  161148. struct jpeg_entropy_decoder {
  161149. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161150. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161151. JBLOCKROW *MCU_data));
  161152. /* This is here to share code between baseline and progressive decoders; */
  161153. /* other modules probably should not use it */
  161154. boolean insufficient_data; /* set TRUE after emitting warning */
  161155. };
  161156. /* Inverse DCT (also performs dequantization) */
  161157. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161158. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161159. JCOEFPTR coef_block,
  161160. JSAMPARRAY output_buf, JDIMENSION output_col));
  161161. struct jpeg_inverse_dct {
  161162. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161163. /* It is useful to allow each component to have a separate IDCT method. */
  161164. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161165. };
  161166. /* Upsampling (note that upsampler must also call color converter) */
  161167. struct jpeg_upsampler {
  161168. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161169. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161170. JSAMPIMAGE input_buf,
  161171. JDIMENSION *in_row_group_ctr,
  161172. JDIMENSION in_row_groups_avail,
  161173. JSAMPARRAY output_buf,
  161174. JDIMENSION *out_row_ctr,
  161175. JDIMENSION out_rows_avail));
  161176. boolean need_context_rows; /* TRUE if need rows above & below */
  161177. };
  161178. /* Colorspace conversion */
  161179. struct jpeg_color_deconverter {
  161180. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161181. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161182. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161183. JSAMPARRAY output_buf, int num_rows));
  161184. };
  161185. /* Color quantization or color precision reduction */
  161186. struct jpeg_color_quantizer {
  161187. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161188. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161189. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161190. int num_rows));
  161191. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161192. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161193. };
  161194. /* Miscellaneous useful macros */
  161195. #undef MAX
  161196. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161197. #undef MIN
  161198. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161199. /* We assume that right shift corresponds to signed division by 2 with
  161200. * rounding towards minus infinity. This is correct for typical "arithmetic
  161201. * shift" instructions that shift in copies of the sign bit. But some
  161202. * C compilers implement >> with an unsigned shift. For these machines you
  161203. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161204. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161205. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161206. * included in the variables of any routine using RIGHT_SHIFT.
  161207. */
  161208. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161209. #define SHIFT_TEMPS INT32 shift_temp;
  161210. #define RIGHT_SHIFT(x,shft) \
  161211. ((shift_temp = (x)) < 0 ? \
  161212. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161213. (shift_temp >> (shft)))
  161214. #else
  161215. #define SHIFT_TEMPS
  161216. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161217. #endif
  161218. /* Short forms of external names for systems with brain-damaged linkers. */
  161219. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161220. #define jinit_compress_master jICompress
  161221. #define jinit_c_master_control jICMaster
  161222. #define jinit_c_main_controller jICMainC
  161223. #define jinit_c_prep_controller jICPrepC
  161224. #define jinit_c_coef_controller jICCoefC
  161225. #define jinit_color_converter jICColor
  161226. #define jinit_downsampler jIDownsampler
  161227. #define jinit_forward_dct jIFDCT
  161228. #define jinit_huff_encoder jIHEncoder
  161229. #define jinit_phuff_encoder jIPHEncoder
  161230. #define jinit_marker_writer jIMWriter
  161231. #define jinit_master_decompress jIDMaster
  161232. #define jinit_d_main_controller jIDMainC
  161233. #define jinit_d_coef_controller jIDCoefC
  161234. #define jinit_d_post_controller jIDPostC
  161235. #define jinit_input_controller jIInCtlr
  161236. #define jinit_marker_reader jIMReader
  161237. #define jinit_huff_decoder jIHDecoder
  161238. #define jinit_phuff_decoder jIPHDecoder
  161239. #define jinit_inverse_dct jIIDCT
  161240. #define jinit_upsampler jIUpsampler
  161241. #define jinit_color_deconverter jIDColor
  161242. #define jinit_1pass_quantizer jI1Quant
  161243. #define jinit_2pass_quantizer jI2Quant
  161244. #define jinit_merged_upsampler jIMUpsampler
  161245. #define jinit_memory_mgr jIMemMgr
  161246. #define jdiv_round_up jDivRound
  161247. #define jround_up jRound
  161248. #define jcopy_sample_rows jCopySamples
  161249. #define jcopy_block_row jCopyBlocks
  161250. #define jzero_far jZeroFar
  161251. #define jpeg_zigzag_order jZIGTable
  161252. #define jpeg_natural_order jZAGTable
  161253. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161254. /* Compression module initialization routines */
  161255. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161256. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161257. boolean transcode_only));
  161258. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161259. boolean need_full_buffer));
  161260. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161261. boolean need_full_buffer));
  161262. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161263. boolean need_full_buffer));
  161264. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161265. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161266. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161267. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161268. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161269. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161270. /* Decompression module initialization routines */
  161271. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161272. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161273. boolean need_full_buffer));
  161274. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161275. boolean need_full_buffer));
  161276. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161277. boolean need_full_buffer));
  161278. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161279. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161280. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161281. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161282. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161283. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161284. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161285. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161286. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161287. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161288. /* Memory manager initialization */
  161289. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161290. /* Utility routines in jutils.c */
  161291. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161292. EXTERN(long) jround_up JPP((long a, long b));
  161293. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161294. JSAMPARRAY output_array, int dest_row,
  161295. int num_rows, JDIMENSION num_cols));
  161296. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161297. JDIMENSION num_blocks));
  161298. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161299. /* Constant tables in jutils.c */
  161300. #if 0 /* This table is not actually needed in v6a */
  161301. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161302. #endif
  161303. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161304. /* Suppress undefined-structure complaints if necessary. */
  161305. #ifdef INCOMPLETE_TYPES_BROKEN
  161306. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161307. struct jvirt_sarray_control { long dummy; };
  161308. struct jvirt_barray_control { long dummy; };
  161309. #endif
  161310. #endif /* INCOMPLETE_TYPES_BROKEN */
  161311. /*** End of inlined file: jpegint.h ***/
  161312. /* fetch private declarations */
  161313. /*** Start of inlined file: jerror.h ***/
  161314. /*
  161315. * To define the enum list of message codes, include this file without
  161316. * defining macro JMESSAGE. To create a message string table, include it
  161317. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161318. */
  161319. #ifndef JMESSAGE
  161320. #ifndef JERROR_H
  161321. /* First time through, define the enum list */
  161322. #define JMAKE_ENUM_LIST
  161323. #else
  161324. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161325. #define JMESSAGE(code,string)
  161326. #endif /* JERROR_H */
  161327. #endif /* JMESSAGE */
  161328. #ifdef JMAKE_ENUM_LIST
  161329. typedef enum {
  161330. #define JMESSAGE(code,string) code ,
  161331. #endif /* JMAKE_ENUM_LIST */
  161332. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161333. /* For maintenance convenience, list is alphabetical by message code name */
  161334. JMESSAGE(JERR_ARITH_NOTIMPL,
  161335. "Sorry, there are legal restrictions on arithmetic coding")
  161336. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161337. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161338. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161339. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161340. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161341. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161342. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161343. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161344. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161345. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161346. JMESSAGE(JERR_BAD_LIB_VERSION,
  161347. "Wrong JPEG library version: library is %d, caller expects %d")
  161348. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161349. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161350. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161351. JMESSAGE(JERR_BAD_PROGRESSION,
  161352. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161353. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161354. "Invalid progressive parameters at scan script entry %d")
  161355. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161356. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161357. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161358. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161359. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161360. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161361. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161362. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161363. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161364. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161365. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161366. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161367. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161368. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161369. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161370. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161371. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161372. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161373. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161374. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161375. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161376. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161377. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161378. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161379. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161380. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161381. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161382. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161383. "Cannot transcode due to multiple use of quantization table %d")
  161384. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161385. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161386. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161387. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161388. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161389. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161390. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161391. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161392. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161393. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161394. JMESSAGE(JERR_QUANT_COMPONENTS,
  161395. "Cannot quantize more than %d color components")
  161396. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161397. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161398. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161399. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161400. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161401. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161402. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161403. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161404. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161405. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161406. JMESSAGE(JERR_TFILE_WRITE,
  161407. "Write failed on temporary file --- out of disk space?")
  161408. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161409. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161410. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161411. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161412. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161413. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161414. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161415. JMESSAGE(JMSG_VERSION, JVERSION)
  161416. JMESSAGE(JTRC_16BIT_TABLES,
  161417. "Caution: quantization tables are too coarse for baseline JPEG")
  161418. JMESSAGE(JTRC_ADOBE,
  161419. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161420. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161421. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161422. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161423. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161424. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161425. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161426. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161427. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161428. JMESSAGE(JTRC_EOI, "End Of Image")
  161429. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161430. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161431. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161432. "Warning: thumbnail image size does not match data length %u")
  161433. JMESSAGE(JTRC_JFIF_EXTENSION,
  161434. "JFIF extension marker: type 0x%02x, length %u")
  161435. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161436. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161437. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161438. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161439. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161440. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161441. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161442. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161443. JMESSAGE(JTRC_RST, "RST%d")
  161444. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161445. "Smoothing not supported with nonstandard sampling ratios")
  161446. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161447. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161448. JMESSAGE(JTRC_SOI, "Start of Image")
  161449. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161450. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161451. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161452. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161453. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161454. JMESSAGE(JTRC_THUMB_JPEG,
  161455. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161456. JMESSAGE(JTRC_THUMB_PALETTE,
  161457. "JFIF extension marker: palette thumbnail image, length %u")
  161458. JMESSAGE(JTRC_THUMB_RGB,
  161459. "JFIF extension marker: RGB thumbnail image, length %u")
  161460. JMESSAGE(JTRC_UNKNOWN_IDS,
  161461. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161462. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161463. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161464. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161465. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161466. "Inconsistent progression sequence for component %d coefficient %d")
  161467. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161468. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161469. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161470. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161471. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161472. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161473. JMESSAGE(JWRN_MUST_RESYNC,
  161474. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161475. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161476. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161477. #ifdef JMAKE_ENUM_LIST
  161478. JMSG_LASTMSGCODE
  161479. } J_MESSAGE_CODE;
  161480. #undef JMAKE_ENUM_LIST
  161481. #endif /* JMAKE_ENUM_LIST */
  161482. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161483. #undef JMESSAGE
  161484. #ifndef JERROR_H
  161485. #define JERROR_H
  161486. /* Macros to simplify using the error and trace message stuff */
  161487. /* The first parameter is either type of cinfo pointer */
  161488. /* Fatal errors (print message and exit) */
  161489. #define ERREXIT(cinfo,code) \
  161490. ((cinfo)->err->msg_code = (code), \
  161491. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161492. #define ERREXIT1(cinfo,code,p1) \
  161493. ((cinfo)->err->msg_code = (code), \
  161494. (cinfo)->err->msg_parm.i[0] = (p1), \
  161495. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161496. #define ERREXIT2(cinfo,code,p1,p2) \
  161497. ((cinfo)->err->msg_code = (code), \
  161498. (cinfo)->err->msg_parm.i[0] = (p1), \
  161499. (cinfo)->err->msg_parm.i[1] = (p2), \
  161500. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161501. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161502. ((cinfo)->err->msg_code = (code), \
  161503. (cinfo)->err->msg_parm.i[0] = (p1), \
  161504. (cinfo)->err->msg_parm.i[1] = (p2), \
  161505. (cinfo)->err->msg_parm.i[2] = (p3), \
  161506. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161507. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161508. ((cinfo)->err->msg_code = (code), \
  161509. (cinfo)->err->msg_parm.i[0] = (p1), \
  161510. (cinfo)->err->msg_parm.i[1] = (p2), \
  161511. (cinfo)->err->msg_parm.i[2] = (p3), \
  161512. (cinfo)->err->msg_parm.i[3] = (p4), \
  161513. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161514. #define ERREXITS(cinfo,code,str) \
  161515. ((cinfo)->err->msg_code = (code), \
  161516. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161517. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161518. #define MAKESTMT(stuff) do { stuff } while (0)
  161519. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161520. #define WARNMS(cinfo,code) \
  161521. ((cinfo)->err->msg_code = (code), \
  161522. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161523. #define WARNMS1(cinfo,code,p1) \
  161524. ((cinfo)->err->msg_code = (code), \
  161525. (cinfo)->err->msg_parm.i[0] = (p1), \
  161526. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161527. #define WARNMS2(cinfo,code,p1,p2) \
  161528. ((cinfo)->err->msg_code = (code), \
  161529. (cinfo)->err->msg_parm.i[0] = (p1), \
  161530. (cinfo)->err->msg_parm.i[1] = (p2), \
  161531. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161532. /* Informational/debugging messages */
  161533. #define TRACEMS(cinfo,lvl,code) \
  161534. ((cinfo)->err->msg_code = (code), \
  161535. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161536. #define TRACEMS1(cinfo,lvl,code,p1) \
  161537. ((cinfo)->err->msg_code = (code), \
  161538. (cinfo)->err->msg_parm.i[0] = (p1), \
  161539. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161540. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161541. ((cinfo)->err->msg_code = (code), \
  161542. (cinfo)->err->msg_parm.i[0] = (p1), \
  161543. (cinfo)->err->msg_parm.i[1] = (p2), \
  161544. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161545. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161546. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161547. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161548. (cinfo)->err->msg_code = (code); \
  161549. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161550. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161551. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161552. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161553. (cinfo)->err->msg_code = (code); \
  161554. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161555. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161556. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161557. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161558. _mp[4] = (p5); \
  161559. (cinfo)->err->msg_code = (code); \
  161560. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161561. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161562. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161563. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161564. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161565. (cinfo)->err->msg_code = (code); \
  161566. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161567. #define TRACEMSS(cinfo,lvl,code,str) \
  161568. ((cinfo)->err->msg_code = (code), \
  161569. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161570. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161571. #endif /* JERROR_H */
  161572. /*** End of inlined file: jerror.h ***/
  161573. /* fetch error codes too */
  161574. #endif
  161575. #endif /* JPEGLIB_H */
  161576. /*** End of inlined file: jpeglib.h ***/
  161577. /*** Start of inlined file: jcapimin.c ***/
  161578. #define JPEG_INTERNALS
  161579. /*** Start of inlined file: jinclude.h ***/
  161580. /* Include auto-config file to find out which system include files we need. */
  161581. #ifndef __jinclude_h__
  161582. #define __jinclude_h__
  161583. /*** Start of inlined file: jconfig.h ***/
  161584. /* see jconfig.doc for explanations */
  161585. // disable all the warnings under MSVC
  161586. #ifdef _MSC_VER
  161587. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161588. #endif
  161589. #ifdef __BORLANDC__
  161590. #pragma warn -8057
  161591. #pragma warn -8019
  161592. #pragma warn -8004
  161593. #pragma warn -8008
  161594. #endif
  161595. #define HAVE_PROTOTYPES
  161596. #define HAVE_UNSIGNED_CHAR
  161597. #define HAVE_UNSIGNED_SHORT
  161598. /* #define void char */
  161599. /* #define const */
  161600. #undef CHAR_IS_UNSIGNED
  161601. #define HAVE_STDDEF_H
  161602. #define HAVE_STDLIB_H
  161603. #undef NEED_BSD_STRINGS
  161604. #undef NEED_SYS_TYPES_H
  161605. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161606. #undef NEED_SHORT_EXTERNAL_NAMES
  161607. #undef INCOMPLETE_TYPES_BROKEN
  161608. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161609. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161610. typedef unsigned char boolean;
  161611. #endif
  161612. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161613. #ifdef JPEG_INTERNALS
  161614. #undef RIGHT_SHIFT_IS_UNSIGNED
  161615. #endif /* JPEG_INTERNALS */
  161616. #ifdef JPEG_CJPEG_DJPEG
  161617. #define BMP_SUPPORTED /* BMP image file format */
  161618. #define GIF_SUPPORTED /* GIF image file format */
  161619. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161620. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161621. #define TARGA_SUPPORTED /* Targa image file format */
  161622. #define TWO_FILE_COMMANDLINE /* optional */
  161623. #define USE_SETMODE /* Microsoft has setmode() */
  161624. #undef NEED_SIGNAL_CATCHER
  161625. #undef DONT_USE_B_MODE
  161626. #undef PROGRESS_REPORT /* optional */
  161627. #endif /* JPEG_CJPEG_DJPEG */
  161628. /*** End of inlined file: jconfig.h ***/
  161629. /* auto configuration options */
  161630. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161631. /*
  161632. * We need the NULL macro and size_t typedef.
  161633. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161634. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161635. * pull in <sys/types.h> as well.
  161636. * Note that the core JPEG library does not require <stdio.h>;
  161637. * only the default error handler and data source/destination modules do.
  161638. * But we must pull it in because of the references to FILE in jpeglib.h.
  161639. * You can remove those references if you want to compile without <stdio.h>.
  161640. */
  161641. #ifdef HAVE_STDDEF_H
  161642. #include <stddef.h>
  161643. #endif
  161644. #ifdef HAVE_STDLIB_H
  161645. #include <stdlib.h>
  161646. #endif
  161647. #ifdef NEED_SYS_TYPES_H
  161648. #include <sys/types.h>
  161649. #endif
  161650. #include <stdio.h>
  161651. /*
  161652. * We need memory copying and zeroing functions, plus strncpy().
  161653. * ANSI and System V implementations declare these in <string.h>.
  161654. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161655. * Some systems may declare memset and memcpy in <memory.h>.
  161656. *
  161657. * NOTE: we assume the size parameters to these functions are of type size_t.
  161658. * Change the casts in these macros if not!
  161659. */
  161660. #ifdef NEED_BSD_STRINGS
  161661. #include <strings.h>
  161662. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161663. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161664. #else /* not BSD, assume ANSI/SysV string lib */
  161665. #include <string.h>
  161666. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161667. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161668. #endif
  161669. /*
  161670. * In ANSI C, and indeed any rational implementation, size_t is also the
  161671. * type returned by sizeof(). However, it seems there are some irrational
  161672. * implementations out there, in which sizeof() returns an int even though
  161673. * size_t is defined as long or unsigned long. To ensure consistent results
  161674. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161675. */
  161676. #define SIZEOF(object) ((size_t) sizeof(object))
  161677. /*
  161678. * The modules that use fread() and fwrite() always invoke them through
  161679. * these macros. On some systems you may need to twiddle the argument casts.
  161680. * CAUTION: argument order is different from underlying functions!
  161681. */
  161682. #define JFREAD(file,buf,sizeofbuf) \
  161683. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161684. #define JFWRITE(file,buf,sizeofbuf) \
  161685. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161686. typedef enum { /* JPEG marker codes */
  161687. M_SOF0 = 0xc0,
  161688. M_SOF1 = 0xc1,
  161689. M_SOF2 = 0xc2,
  161690. M_SOF3 = 0xc3,
  161691. M_SOF5 = 0xc5,
  161692. M_SOF6 = 0xc6,
  161693. M_SOF7 = 0xc7,
  161694. M_JPG = 0xc8,
  161695. M_SOF9 = 0xc9,
  161696. M_SOF10 = 0xca,
  161697. M_SOF11 = 0xcb,
  161698. M_SOF13 = 0xcd,
  161699. M_SOF14 = 0xce,
  161700. M_SOF15 = 0xcf,
  161701. M_DHT = 0xc4,
  161702. M_DAC = 0xcc,
  161703. M_RST0 = 0xd0,
  161704. M_RST1 = 0xd1,
  161705. M_RST2 = 0xd2,
  161706. M_RST3 = 0xd3,
  161707. M_RST4 = 0xd4,
  161708. M_RST5 = 0xd5,
  161709. M_RST6 = 0xd6,
  161710. M_RST7 = 0xd7,
  161711. M_SOI = 0xd8,
  161712. M_EOI = 0xd9,
  161713. M_SOS = 0xda,
  161714. M_DQT = 0xdb,
  161715. M_DNL = 0xdc,
  161716. M_DRI = 0xdd,
  161717. M_DHP = 0xde,
  161718. M_EXP = 0xdf,
  161719. M_APP0 = 0xe0,
  161720. M_APP1 = 0xe1,
  161721. M_APP2 = 0xe2,
  161722. M_APP3 = 0xe3,
  161723. M_APP4 = 0xe4,
  161724. M_APP5 = 0xe5,
  161725. M_APP6 = 0xe6,
  161726. M_APP7 = 0xe7,
  161727. M_APP8 = 0xe8,
  161728. M_APP9 = 0xe9,
  161729. M_APP10 = 0xea,
  161730. M_APP11 = 0xeb,
  161731. M_APP12 = 0xec,
  161732. M_APP13 = 0xed,
  161733. M_APP14 = 0xee,
  161734. M_APP15 = 0xef,
  161735. M_JPG0 = 0xf0,
  161736. M_JPG13 = 0xfd,
  161737. M_COM = 0xfe,
  161738. M_TEM = 0x01,
  161739. M_ERROR = 0x100
  161740. } JPEG_MARKER;
  161741. /*
  161742. * Figure F.12: extend sign bit.
  161743. * On some machines, a shift and add will be faster than a table lookup.
  161744. */
  161745. #ifdef AVOID_TABLES
  161746. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161747. #else
  161748. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161749. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161750. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161751. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161752. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161753. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161754. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161755. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161756. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161757. #endif /* AVOID_TABLES */
  161758. #endif
  161759. /*** End of inlined file: jinclude.h ***/
  161760. /*
  161761. * Initialization of a JPEG compression object.
  161762. * The error manager must already be set up (in case memory manager fails).
  161763. */
  161764. GLOBAL(void)
  161765. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161766. {
  161767. int i;
  161768. /* Guard against version mismatches between library and caller. */
  161769. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161770. if (version != JPEG_LIB_VERSION)
  161771. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161772. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161773. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161774. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161775. /* For debugging purposes, we zero the whole master structure.
  161776. * But the application has already set the err pointer, and may have set
  161777. * client_data, so we have to save and restore those fields.
  161778. * Note: if application hasn't set client_data, tools like Purify may
  161779. * complain here.
  161780. */
  161781. {
  161782. struct jpeg_error_mgr * err = cinfo->err;
  161783. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161784. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161785. cinfo->err = err;
  161786. cinfo->client_data = client_data;
  161787. }
  161788. cinfo->is_decompressor = FALSE;
  161789. /* Initialize a memory manager instance for this object */
  161790. jinit_memory_mgr((j_common_ptr) cinfo);
  161791. /* Zero out pointers to permanent structures. */
  161792. cinfo->progress = NULL;
  161793. cinfo->dest = NULL;
  161794. cinfo->comp_info = NULL;
  161795. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161796. cinfo->quant_tbl_ptrs[i] = NULL;
  161797. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161798. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161799. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161800. }
  161801. cinfo->script_space = NULL;
  161802. cinfo->input_gamma = 1.0; /* in case application forgets */
  161803. /* OK, I'm ready */
  161804. cinfo->global_state = CSTATE_START;
  161805. }
  161806. /*
  161807. * Destruction of a JPEG compression object
  161808. */
  161809. GLOBAL(void)
  161810. jpeg_destroy_compress (j_compress_ptr cinfo)
  161811. {
  161812. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161813. }
  161814. /*
  161815. * Abort processing of a JPEG compression operation,
  161816. * but don't destroy the object itself.
  161817. */
  161818. GLOBAL(void)
  161819. jpeg_abort_compress (j_compress_ptr cinfo)
  161820. {
  161821. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161822. }
  161823. /*
  161824. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161825. * Marks all currently defined tables as already written (if suppress)
  161826. * or not written (if !suppress). This will control whether they get emitted
  161827. * by a subsequent jpeg_start_compress call.
  161828. *
  161829. * This routine is exported for use by applications that want to produce
  161830. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161831. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161832. * jcparam.o would be linked whether the application used it or not.
  161833. */
  161834. GLOBAL(void)
  161835. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161836. {
  161837. int i;
  161838. JQUANT_TBL * qtbl;
  161839. JHUFF_TBL * htbl;
  161840. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161841. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161842. qtbl->sent_table = suppress;
  161843. }
  161844. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161845. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161846. htbl->sent_table = suppress;
  161847. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161848. htbl->sent_table = suppress;
  161849. }
  161850. }
  161851. /*
  161852. * Finish JPEG compression.
  161853. *
  161854. * If a multipass operating mode was selected, this may do a great deal of
  161855. * work including most of the actual output.
  161856. */
  161857. GLOBAL(void)
  161858. jpeg_finish_compress (j_compress_ptr cinfo)
  161859. {
  161860. JDIMENSION iMCU_row;
  161861. if (cinfo->global_state == CSTATE_SCANNING ||
  161862. cinfo->global_state == CSTATE_RAW_OK) {
  161863. /* Terminate first pass */
  161864. if (cinfo->next_scanline < cinfo->image_height)
  161865. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161866. (*cinfo->master->finish_pass) (cinfo);
  161867. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161868. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161869. /* Perform any remaining passes */
  161870. while (! cinfo->master->is_last_pass) {
  161871. (*cinfo->master->prepare_for_pass) (cinfo);
  161872. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161873. if (cinfo->progress != NULL) {
  161874. cinfo->progress->pass_counter = (long) iMCU_row;
  161875. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161876. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161877. }
  161878. /* We bypass the main controller and invoke coef controller directly;
  161879. * all work is being done from the coefficient buffer.
  161880. */
  161881. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161882. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161883. }
  161884. (*cinfo->master->finish_pass) (cinfo);
  161885. }
  161886. /* Write EOI, do final cleanup */
  161887. (*cinfo->marker->write_file_trailer) (cinfo);
  161888. (*cinfo->dest->term_destination) (cinfo);
  161889. /* We can use jpeg_abort to release memory and reset global_state */
  161890. jpeg_abort((j_common_ptr) cinfo);
  161891. }
  161892. /*
  161893. * Write a special marker.
  161894. * This is only recommended for writing COM or APPn markers.
  161895. * Must be called after jpeg_start_compress() and before
  161896. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161897. */
  161898. GLOBAL(void)
  161899. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161900. const JOCTET *dataptr, unsigned int datalen)
  161901. {
  161902. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161903. if (cinfo->next_scanline != 0 ||
  161904. (cinfo->global_state != CSTATE_SCANNING &&
  161905. cinfo->global_state != CSTATE_RAW_OK &&
  161906. cinfo->global_state != CSTATE_WRCOEFS))
  161907. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161908. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161909. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161910. while (datalen--) {
  161911. (*write_marker_byte) (cinfo, *dataptr);
  161912. dataptr++;
  161913. }
  161914. }
  161915. /* Same, but piecemeal. */
  161916. GLOBAL(void)
  161917. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161918. {
  161919. if (cinfo->next_scanline != 0 ||
  161920. (cinfo->global_state != CSTATE_SCANNING &&
  161921. cinfo->global_state != CSTATE_RAW_OK &&
  161922. cinfo->global_state != CSTATE_WRCOEFS))
  161923. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161924. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161925. }
  161926. GLOBAL(void)
  161927. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161928. {
  161929. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161930. }
  161931. /*
  161932. * Alternate compression function: just write an abbreviated table file.
  161933. * Before calling this, all parameters and a data destination must be set up.
  161934. *
  161935. * To produce a pair of files containing abbreviated tables and abbreviated
  161936. * image data, one would proceed as follows:
  161937. *
  161938. * initialize JPEG object
  161939. * set JPEG parameters
  161940. * set destination to table file
  161941. * jpeg_write_tables(cinfo);
  161942. * set destination to image file
  161943. * jpeg_start_compress(cinfo, FALSE);
  161944. * write data...
  161945. * jpeg_finish_compress(cinfo);
  161946. *
  161947. * jpeg_write_tables has the side effect of marking all tables written
  161948. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161949. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161950. */
  161951. GLOBAL(void)
  161952. jpeg_write_tables (j_compress_ptr cinfo)
  161953. {
  161954. if (cinfo->global_state != CSTATE_START)
  161955. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161956. /* (Re)initialize error mgr and destination modules */
  161957. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161958. (*cinfo->dest->init_destination) (cinfo);
  161959. /* Initialize the marker writer ... bit of a crock to do it here. */
  161960. jinit_marker_writer(cinfo);
  161961. /* Write them tables! */
  161962. (*cinfo->marker->write_tables_only) (cinfo);
  161963. /* And clean up. */
  161964. (*cinfo->dest->term_destination) (cinfo);
  161965. /*
  161966. * In library releases up through v6a, we called jpeg_abort() here to free
  161967. * any working memory allocated by the destination manager and marker
  161968. * writer. Some applications had a problem with that: they allocated space
  161969. * of their own from the library memory manager, and didn't want it to go
  161970. * away during write_tables. So now we do nothing. This will cause a
  161971. * memory leak if an app calls write_tables repeatedly without doing a full
  161972. * compression cycle or otherwise resetting the JPEG object. However, that
  161973. * seems less bad than unexpectedly freeing memory in the normal case.
  161974. * An app that prefers the old behavior can call jpeg_abort for itself after
  161975. * each call to jpeg_write_tables().
  161976. */
  161977. }
  161978. /*** End of inlined file: jcapimin.c ***/
  161979. /*** Start of inlined file: jcapistd.c ***/
  161980. #define JPEG_INTERNALS
  161981. /*
  161982. * Compression initialization.
  161983. * Before calling this, all parameters and a data destination must be set up.
  161984. *
  161985. * We require a write_all_tables parameter as a failsafe check when writing
  161986. * multiple datastreams from the same compression object. Since prior runs
  161987. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161988. * would emit an abbreviated stream (no tables) by default. This may be what
  161989. * is wanted, but for safety's sake it should not be the default behavior:
  161990. * programmers should have to make a deliberate choice to emit abbreviated
  161991. * images. Therefore the documentation and examples should encourage people
  161992. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161993. * wrong thing.
  161994. */
  161995. GLOBAL(void)
  161996. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161997. {
  161998. if (cinfo->global_state != CSTATE_START)
  161999. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162000. if (write_all_tables)
  162001. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  162002. /* (Re)initialize error mgr and destination modules */
  162003. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162004. (*cinfo->dest->init_destination) (cinfo);
  162005. /* Perform master selection of active modules */
  162006. jinit_compress_master(cinfo);
  162007. /* Set up for the first pass */
  162008. (*cinfo->master->prepare_for_pass) (cinfo);
  162009. /* Ready for application to drive first pass through jpeg_write_scanlines
  162010. * or jpeg_write_raw_data.
  162011. */
  162012. cinfo->next_scanline = 0;
  162013. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  162014. }
  162015. /*
  162016. * Write some scanlines of data to the JPEG compressor.
  162017. *
  162018. * The return value will be the number of lines actually written.
  162019. * This should be less than the supplied num_lines only in case that
  162020. * the data destination module has requested suspension of the compressor,
  162021. * or if more than image_height scanlines are passed in.
  162022. *
  162023. * Note: we warn about excess calls to jpeg_write_scanlines() since
  162024. * this likely signals an application programmer error. However,
  162025. * excess scanlines passed in the last valid call are *silently* ignored,
  162026. * so that the application need not adjust num_lines for end-of-image
  162027. * when using a multiple-scanline buffer.
  162028. */
  162029. GLOBAL(JDIMENSION)
  162030. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162031. JDIMENSION num_lines)
  162032. {
  162033. JDIMENSION row_ctr, rows_left;
  162034. if (cinfo->global_state != CSTATE_SCANNING)
  162035. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162036. if (cinfo->next_scanline >= cinfo->image_height)
  162037. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162038. /* Call progress monitor hook if present */
  162039. if (cinfo->progress != NULL) {
  162040. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162041. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162042. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162043. }
  162044. /* Give master control module another chance if this is first call to
  162045. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162046. * delayed so that application can write COM, etc, markers between
  162047. * jpeg_start_compress and jpeg_write_scanlines.
  162048. */
  162049. if (cinfo->master->call_pass_startup)
  162050. (*cinfo->master->pass_startup) (cinfo);
  162051. /* Ignore any extra scanlines at bottom of image. */
  162052. rows_left = cinfo->image_height - cinfo->next_scanline;
  162053. if (num_lines > rows_left)
  162054. num_lines = rows_left;
  162055. row_ctr = 0;
  162056. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162057. cinfo->next_scanline += row_ctr;
  162058. return row_ctr;
  162059. }
  162060. /*
  162061. * Alternate entry point to write raw data.
  162062. * Processes exactly one iMCU row per call, unless suspended.
  162063. */
  162064. GLOBAL(JDIMENSION)
  162065. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162066. JDIMENSION num_lines)
  162067. {
  162068. JDIMENSION lines_per_iMCU_row;
  162069. if (cinfo->global_state != CSTATE_RAW_OK)
  162070. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162071. if (cinfo->next_scanline >= cinfo->image_height) {
  162072. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162073. return 0;
  162074. }
  162075. /* Call progress monitor hook if present */
  162076. if (cinfo->progress != NULL) {
  162077. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162078. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162079. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162080. }
  162081. /* Give master control module another chance if this is first call to
  162082. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162083. * delayed so that application can write COM, etc, markers between
  162084. * jpeg_start_compress and jpeg_write_raw_data.
  162085. */
  162086. if (cinfo->master->call_pass_startup)
  162087. (*cinfo->master->pass_startup) (cinfo);
  162088. /* Verify that at least one iMCU row has been passed. */
  162089. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162090. if (num_lines < lines_per_iMCU_row)
  162091. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162092. /* Directly compress the row. */
  162093. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162094. /* If compressor did not consume the whole row, suspend processing. */
  162095. return 0;
  162096. }
  162097. /* OK, we processed one iMCU row. */
  162098. cinfo->next_scanline += lines_per_iMCU_row;
  162099. return lines_per_iMCU_row;
  162100. }
  162101. /*** End of inlined file: jcapistd.c ***/
  162102. /*** Start of inlined file: jccoefct.c ***/
  162103. #define JPEG_INTERNALS
  162104. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162105. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162106. * step is run during the first pass, and subsequent passes need only read
  162107. * the buffered coefficients.
  162108. */
  162109. #ifdef ENTROPY_OPT_SUPPORTED
  162110. #define FULL_COEF_BUFFER_SUPPORTED
  162111. #else
  162112. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162113. #define FULL_COEF_BUFFER_SUPPORTED
  162114. #endif
  162115. #endif
  162116. /* Private buffer controller object */
  162117. typedef struct {
  162118. struct jpeg_c_coef_controller pub; /* public fields */
  162119. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162120. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162121. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162122. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162123. /* For single-pass compression, it's sufficient to buffer just one MCU
  162124. * (although this may prove a bit slow in practice). We allocate a
  162125. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162126. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162127. * it's not really very big; this is to keep the module interfaces unchanged
  162128. * when a large coefficient buffer is necessary.)
  162129. * In multi-pass modes, this array points to the current MCU's blocks
  162130. * within the virtual arrays.
  162131. */
  162132. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162133. /* In multi-pass modes, we need a virtual block array for each component. */
  162134. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162135. } my_coef_controller;
  162136. typedef my_coef_controller * my_coef_ptr;
  162137. /* Forward declarations */
  162138. METHODDEF(boolean) compress_data
  162139. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162140. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162141. METHODDEF(boolean) compress_first_pass
  162142. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162143. METHODDEF(boolean) compress_output
  162144. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162145. #endif
  162146. LOCAL(void)
  162147. start_iMCU_row (j_compress_ptr cinfo)
  162148. /* Reset within-iMCU-row counters for a new row */
  162149. {
  162150. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162151. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162152. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162153. * But at the bottom of the image, process only what's left.
  162154. */
  162155. if (cinfo->comps_in_scan > 1) {
  162156. coef->MCU_rows_per_iMCU_row = 1;
  162157. } else {
  162158. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162159. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162160. else
  162161. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162162. }
  162163. coef->mcu_ctr = 0;
  162164. coef->MCU_vert_offset = 0;
  162165. }
  162166. /*
  162167. * Initialize for a processing pass.
  162168. */
  162169. METHODDEF(void)
  162170. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162171. {
  162172. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162173. coef->iMCU_row_num = 0;
  162174. start_iMCU_row(cinfo);
  162175. switch (pass_mode) {
  162176. case JBUF_PASS_THRU:
  162177. if (coef->whole_image[0] != NULL)
  162178. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162179. coef->pub.compress_data = compress_data;
  162180. break;
  162181. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162182. case JBUF_SAVE_AND_PASS:
  162183. if (coef->whole_image[0] == NULL)
  162184. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162185. coef->pub.compress_data = compress_first_pass;
  162186. break;
  162187. case JBUF_CRANK_DEST:
  162188. if (coef->whole_image[0] == NULL)
  162189. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162190. coef->pub.compress_data = compress_output;
  162191. break;
  162192. #endif
  162193. default:
  162194. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162195. break;
  162196. }
  162197. }
  162198. /*
  162199. * Process some data in the single-pass case.
  162200. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162201. * per call, ie, v_samp_factor block rows for each component in the image.
  162202. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162203. *
  162204. * NB: input_buf contains a plane for each component in image,
  162205. * which we index according to the component's SOF position.
  162206. */
  162207. METHODDEF(boolean)
  162208. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162209. {
  162210. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162211. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162212. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162213. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162214. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162215. JDIMENSION ypos, xpos;
  162216. jpeg_component_info *compptr;
  162217. /* Loop to write as much as one whole iMCU row */
  162218. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162219. yoffset++) {
  162220. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162221. MCU_col_num++) {
  162222. /* Determine where data comes from in input_buf and do the DCT thing.
  162223. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162224. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162225. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162226. * specially. The data in them does not matter for image reconstruction,
  162227. * so we fill them with values that will encode to the smallest amount of
  162228. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162229. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162230. */
  162231. blkn = 0;
  162232. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162233. compptr = cinfo->cur_comp_info[ci];
  162234. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162235. : compptr->last_col_width;
  162236. xpos = MCU_col_num * compptr->MCU_sample_width;
  162237. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162238. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162239. if (coef->iMCU_row_num < last_iMCU_row ||
  162240. yoffset+yindex < compptr->last_row_height) {
  162241. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162242. input_buf[compptr->component_index],
  162243. coef->MCU_buffer[blkn],
  162244. ypos, xpos, (JDIMENSION) blockcnt);
  162245. if (blockcnt < compptr->MCU_width) {
  162246. /* Create some dummy blocks at the right edge of the image. */
  162247. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162248. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162249. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162250. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162251. }
  162252. }
  162253. } else {
  162254. /* Create a row of dummy blocks at the bottom of the image. */
  162255. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162256. compptr->MCU_width * SIZEOF(JBLOCK));
  162257. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162258. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162259. }
  162260. }
  162261. blkn += compptr->MCU_width;
  162262. ypos += DCTSIZE;
  162263. }
  162264. }
  162265. /* Try to write the MCU. In event of a suspension failure, we will
  162266. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162267. */
  162268. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162269. /* Suspension forced; update state counters and exit */
  162270. coef->MCU_vert_offset = yoffset;
  162271. coef->mcu_ctr = MCU_col_num;
  162272. return FALSE;
  162273. }
  162274. }
  162275. /* Completed an MCU row, but perhaps not an iMCU row */
  162276. coef->mcu_ctr = 0;
  162277. }
  162278. /* Completed the iMCU row, advance counters for next one */
  162279. coef->iMCU_row_num++;
  162280. start_iMCU_row(cinfo);
  162281. return TRUE;
  162282. }
  162283. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162284. /*
  162285. * Process some data in the first pass of a multi-pass case.
  162286. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162287. * per call, ie, v_samp_factor block rows for each component in the image.
  162288. * This amount of data is read from the source buffer, DCT'd and quantized,
  162289. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162290. * as needed at the right and lower edges. (The dummy blocks are constructed
  162291. * in the virtual arrays, which have been padded appropriately.) This makes
  162292. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162293. *
  162294. * We must also emit the data to the entropy encoder. This is conveniently
  162295. * done by calling compress_output() after we've loaded the current strip
  162296. * of the virtual arrays.
  162297. *
  162298. * NB: input_buf contains a plane for each component in image. All
  162299. * components are DCT'd and loaded into the virtual arrays in this pass.
  162300. * However, it may be that only a subset of the components are emitted to
  162301. * the entropy encoder during this first pass; be careful about looking
  162302. * at the scan-dependent variables (MCU dimensions, etc).
  162303. */
  162304. METHODDEF(boolean)
  162305. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162306. {
  162307. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162308. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162309. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162310. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162311. JCOEF lastDC;
  162312. jpeg_component_info *compptr;
  162313. JBLOCKARRAY buffer;
  162314. JBLOCKROW thisblockrow, lastblockrow;
  162315. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162316. ci++, compptr++) {
  162317. /* Align the virtual buffer for this component. */
  162318. buffer = (*cinfo->mem->access_virt_barray)
  162319. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162320. coef->iMCU_row_num * compptr->v_samp_factor,
  162321. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162322. /* Count non-dummy DCT block rows in this iMCU row. */
  162323. if (coef->iMCU_row_num < last_iMCU_row)
  162324. block_rows = compptr->v_samp_factor;
  162325. else {
  162326. /* NB: can't use last_row_height here, since may not be set! */
  162327. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162328. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162329. }
  162330. blocks_across = compptr->width_in_blocks;
  162331. h_samp_factor = compptr->h_samp_factor;
  162332. /* Count number of dummy blocks to be added at the right margin. */
  162333. ndummy = (int) (blocks_across % h_samp_factor);
  162334. if (ndummy > 0)
  162335. ndummy = h_samp_factor - ndummy;
  162336. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162337. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162338. */
  162339. for (block_row = 0; block_row < block_rows; block_row++) {
  162340. thisblockrow = buffer[block_row];
  162341. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162342. input_buf[ci], thisblockrow,
  162343. (JDIMENSION) (block_row * DCTSIZE),
  162344. (JDIMENSION) 0, blocks_across);
  162345. if (ndummy > 0) {
  162346. /* Create dummy blocks at the right edge of the image. */
  162347. thisblockrow += blocks_across; /* => first dummy block */
  162348. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162349. lastDC = thisblockrow[-1][0];
  162350. for (bi = 0; bi < ndummy; bi++) {
  162351. thisblockrow[bi][0] = lastDC;
  162352. }
  162353. }
  162354. }
  162355. /* If at end of image, create dummy block rows as needed.
  162356. * The tricky part here is that within each MCU, we want the DC values
  162357. * of the dummy blocks to match the last real block's DC value.
  162358. * This squeezes a few more bytes out of the resulting file...
  162359. */
  162360. if (coef->iMCU_row_num == last_iMCU_row) {
  162361. blocks_across += ndummy; /* include lower right corner */
  162362. MCUs_across = blocks_across / h_samp_factor;
  162363. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162364. block_row++) {
  162365. thisblockrow = buffer[block_row];
  162366. lastblockrow = buffer[block_row-1];
  162367. jzero_far((void FAR *) thisblockrow,
  162368. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162369. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162370. lastDC = lastblockrow[h_samp_factor-1][0];
  162371. for (bi = 0; bi < h_samp_factor; bi++) {
  162372. thisblockrow[bi][0] = lastDC;
  162373. }
  162374. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162375. lastblockrow += h_samp_factor;
  162376. }
  162377. }
  162378. }
  162379. }
  162380. /* NB: compress_output will increment iMCU_row_num if successful.
  162381. * A suspension return will result in redoing all the work above next time.
  162382. */
  162383. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162384. return compress_output(cinfo, input_buf);
  162385. }
  162386. /*
  162387. * Process some data in subsequent passes of a multi-pass case.
  162388. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162389. * per call, ie, v_samp_factor block rows for each component in the scan.
  162390. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162391. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162392. *
  162393. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162394. */
  162395. METHODDEF(boolean)
  162396. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162397. {
  162398. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162399. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162400. int blkn, ci, xindex, yindex, yoffset;
  162401. JDIMENSION start_col;
  162402. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162403. JBLOCKROW buffer_ptr;
  162404. jpeg_component_info *compptr;
  162405. /* Align the virtual buffers for the components used in this scan.
  162406. * NB: during first pass, this is safe only because the buffers will
  162407. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162408. */
  162409. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162410. compptr = cinfo->cur_comp_info[ci];
  162411. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162412. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162413. coef->iMCU_row_num * compptr->v_samp_factor,
  162414. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162415. }
  162416. /* Loop to process one whole iMCU row */
  162417. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162418. yoffset++) {
  162419. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162420. MCU_col_num++) {
  162421. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162422. blkn = 0; /* index of current DCT block within MCU */
  162423. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162424. compptr = cinfo->cur_comp_info[ci];
  162425. start_col = MCU_col_num * compptr->MCU_width;
  162426. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162427. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162428. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162429. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162430. }
  162431. }
  162432. }
  162433. /* Try to write the MCU. */
  162434. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162435. /* Suspension forced; update state counters and exit */
  162436. coef->MCU_vert_offset = yoffset;
  162437. coef->mcu_ctr = MCU_col_num;
  162438. return FALSE;
  162439. }
  162440. }
  162441. /* Completed an MCU row, but perhaps not an iMCU row */
  162442. coef->mcu_ctr = 0;
  162443. }
  162444. /* Completed the iMCU row, advance counters for next one */
  162445. coef->iMCU_row_num++;
  162446. start_iMCU_row(cinfo);
  162447. return TRUE;
  162448. }
  162449. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162450. /*
  162451. * Initialize coefficient buffer controller.
  162452. */
  162453. GLOBAL(void)
  162454. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162455. {
  162456. my_coef_ptr coef;
  162457. coef = (my_coef_ptr)
  162458. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162459. SIZEOF(my_coef_controller));
  162460. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162461. coef->pub.start_pass = start_pass_coef;
  162462. /* Create the coefficient buffer. */
  162463. if (need_full_buffer) {
  162464. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162465. /* Allocate a full-image virtual array for each component, */
  162466. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162467. int ci;
  162468. jpeg_component_info *compptr;
  162469. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162470. ci++, compptr++) {
  162471. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162472. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162473. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162474. (long) compptr->h_samp_factor),
  162475. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162476. (long) compptr->v_samp_factor),
  162477. (JDIMENSION) compptr->v_samp_factor);
  162478. }
  162479. #else
  162480. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162481. #endif
  162482. } else {
  162483. /* We only need a single-MCU buffer. */
  162484. JBLOCKROW buffer;
  162485. int i;
  162486. buffer = (JBLOCKROW)
  162487. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162488. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162489. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162490. coef->MCU_buffer[i] = buffer + i;
  162491. }
  162492. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162493. }
  162494. }
  162495. /*** End of inlined file: jccoefct.c ***/
  162496. /*** Start of inlined file: jccolor.c ***/
  162497. #define JPEG_INTERNALS
  162498. /* Private subobject */
  162499. typedef struct {
  162500. struct jpeg_color_converter pub; /* public fields */
  162501. /* Private state for RGB->YCC conversion */
  162502. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162503. } my_color_converter;
  162504. typedef my_color_converter * my_cconvert_ptr;
  162505. /**************** RGB -> YCbCr conversion: most common case **************/
  162506. /*
  162507. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162508. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162509. * The conversion equations to be implemented are therefore
  162510. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162511. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162512. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162513. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162514. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162515. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162516. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162517. * were not represented exactly. Now we sacrifice exact representation of
  162518. * maximum red and maximum blue in order to get exact grayscales.
  162519. *
  162520. * To avoid floating-point arithmetic, we represent the fractional constants
  162521. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162522. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162523. *
  162524. * For even more speed, we avoid doing any multiplications in the inner loop
  162525. * by precalculating the constants times R,G,B for all possible values.
  162526. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162527. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162528. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162529. * colorspace anyway.
  162530. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162531. * in the tables to save adding them separately in the inner loop.
  162532. */
  162533. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162534. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162535. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162536. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162537. /* We allocate one big table and divide it up into eight parts, instead of
  162538. * doing eight alloc_small requests. This lets us use a single table base
  162539. * address, which can be held in a register in the inner loops on many
  162540. * machines (more than can hold all eight addresses, anyway).
  162541. */
  162542. #define R_Y_OFF 0 /* offset to R => Y section */
  162543. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162544. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162545. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162546. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162547. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162548. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162549. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162550. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162551. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162552. /*
  162553. * Initialize for RGB->YCC colorspace conversion.
  162554. */
  162555. METHODDEF(void)
  162556. rgb_ycc_start (j_compress_ptr cinfo)
  162557. {
  162558. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162559. INT32 * rgb_ycc_tab;
  162560. INT32 i;
  162561. /* Allocate and fill in the conversion tables. */
  162562. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162563. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162564. (TABLE_SIZE * SIZEOF(INT32)));
  162565. for (i = 0; i <= MAXJSAMPLE; i++) {
  162566. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162567. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162568. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162569. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162570. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162571. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162572. * This ensures that the maximum output will round to MAXJSAMPLE
  162573. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162574. */
  162575. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162576. /* B=>Cb and R=>Cr tables are the same
  162577. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162578. */
  162579. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162580. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162581. }
  162582. }
  162583. /*
  162584. * Convert some rows of samples to the JPEG colorspace.
  162585. *
  162586. * Note that we change from the application's interleaved-pixel format
  162587. * to our internal noninterleaved, one-plane-per-component format.
  162588. * The input buffer is therefore three times as wide as the output buffer.
  162589. *
  162590. * A starting row offset is provided only for the output buffer. The caller
  162591. * can easily adjust the passed input_buf value to accommodate any row
  162592. * offset required on that side.
  162593. */
  162594. METHODDEF(void)
  162595. rgb_ycc_convert (j_compress_ptr cinfo,
  162596. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162597. JDIMENSION output_row, int num_rows)
  162598. {
  162599. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162600. register int r, g, b;
  162601. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162602. register JSAMPROW inptr;
  162603. register JSAMPROW outptr0, outptr1, outptr2;
  162604. register JDIMENSION col;
  162605. JDIMENSION num_cols = cinfo->image_width;
  162606. while (--num_rows >= 0) {
  162607. inptr = *input_buf++;
  162608. outptr0 = output_buf[0][output_row];
  162609. outptr1 = output_buf[1][output_row];
  162610. outptr2 = output_buf[2][output_row];
  162611. output_row++;
  162612. for (col = 0; col < num_cols; col++) {
  162613. r = GETJSAMPLE(inptr[RGB_RED]);
  162614. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162615. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162616. inptr += RGB_PIXELSIZE;
  162617. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162618. * must be too; we do not need an explicit range-limiting operation.
  162619. * Hence the value being shifted is never negative, and we don't
  162620. * need the general RIGHT_SHIFT macro.
  162621. */
  162622. /* Y */
  162623. outptr0[col] = (JSAMPLE)
  162624. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162625. >> SCALEBITS);
  162626. /* Cb */
  162627. outptr1[col] = (JSAMPLE)
  162628. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162629. >> SCALEBITS);
  162630. /* Cr */
  162631. outptr2[col] = (JSAMPLE)
  162632. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162633. >> SCALEBITS);
  162634. }
  162635. }
  162636. }
  162637. /**************** Cases other than RGB -> YCbCr **************/
  162638. /*
  162639. * Convert some rows of samples to the JPEG colorspace.
  162640. * This version handles RGB->grayscale conversion, which is the same
  162641. * as the RGB->Y portion of RGB->YCbCr.
  162642. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162643. */
  162644. METHODDEF(void)
  162645. rgb_gray_convert (j_compress_ptr cinfo,
  162646. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162647. JDIMENSION output_row, int num_rows)
  162648. {
  162649. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162650. register int r, g, b;
  162651. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162652. register JSAMPROW inptr;
  162653. register JSAMPROW outptr;
  162654. register JDIMENSION col;
  162655. JDIMENSION num_cols = cinfo->image_width;
  162656. while (--num_rows >= 0) {
  162657. inptr = *input_buf++;
  162658. outptr = output_buf[0][output_row];
  162659. output_row++;
  162660. for (col = 0; col < num_cols; col++) {
  162661. r = GETJSAMPLE(inptr[RGB_RED]);
  162662. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162663. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162664. inptr += RGB_PIXELSIZE;
  162665. /* Y */
  162666. outptr[col] = (JSAMPLE)
  162667. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162668. >> SCALEBITS);
  162669. }
  162670. }
  162671. }
  162672. /*
  162673. * Convert some rows of samples to the JPEG colorspace.
  162674. * This version handles Adobe-style CMYK->YCCK conversion,
  162675. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162676. * conversion as above, while passing K (black) unchanged.
  162677. * We assume rgb_ycc_start has been called.
  162678. */
  162679. METHODDEF(void)
  162680. cmyk_ycck_convert (j_compress_ptr cinfo,
  162681. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162682. JDIMENSION output_row, int num_rows)
  162683. {
  162684. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162685. register int r, g, b;
  162686. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162687. register JSAMPROW inptr;
  162688. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162689. register JDIMENSION col;
  162690. JDIMENSION num_cols = cinfo->image_width;
  162691. while (--num_rows >= 0) {
  162692. inptr = *input_buf++;
  162693. outptr0 = output_buf[0][output_row];
  162694. outptr1 = output_buf[1][output_row];
  162695. outptr2 = output_buf[2][output_row];
  162696. outptr3 = output_buf[3][output_row];
  162697. output_row++;
  162698. for (col = 0; col < num_cols; col++) {
  162699. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162700. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162701. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162702. /* K passes through as-is */
  162703. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162704. inptr += 4;
  162705. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162706. * must be too; we do not need an explicit range-limiting operation.
  162707. * Hence the value being shifted is never negative, and we don't
  162708. * need the general RIGHT_SHIFT macro.
  162709. */
  162710. /* Y */
  162711. outptr0[col] = (JSAMPLE)
  162712. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162713. >> SCALEBITS);
  162714. /* Cb */
  162715. outptr1[col] = (JSAMPLE)
  162716. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162717. >> SCALEBITS);
  162718. /* Cr */
  162719. outptr2[col] = (JSAMPLE)
  162720. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162721. >> SCALEBITS);
  162722. }
  162723. }
  162724. }
  162725. /*
  162726. * Convert some rows of samples to the JPEG colorspace.
  162727. * This version handles grayscale output with no conversion.
  162728. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162729. */
  162730. METHODDEF(void)
  162731. grayscale_convert (j_compress_ptr cinfo,
  162732. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162733. JDIMENSION output_row, int num_rows)
  162734. {
  162735. register JSAMPROW inptr;
  162736. register JSAMPROW outptr;
  162737. register JDIMENSION col;
  162738. JDIMENSION num_cols = cinfo->image_width;
  162739. int instride = cinfo->input_components;
  162740. while (--num_rows >= 0) {
  162741. inptr = *input_buf++;
  162742. outptr = output_buf[0][output_row];
  162743. output_row++;
  162744. for (col = 0; col < num_cols; col++) {
  162745. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162746. inptr += instride;
  162747. }
  162748. }
  162749. }
  162750. /*
  162751. * Convert some rows of samples to the JPEG colorspace.
  162752. * This version handles multi-component colorspaces without conversion.
  162753. * We assume input_components == num_components.
  162754. */
  162755. METHODDEF(void)
  162756. null_convert (j_compress_ptr cinfo,
  162757. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162758. JDIMENSION output_row, int num_rows)
  162759. {
  162760. register JSAMPROW inptr;
  162761. register JSAMPROW outptr;
  162762. register JDIMENSION col;
  162763. register int ci;
  162764. int nc = cinfo->num_components;
  162765. JDIMENSION num_cols = cinfo->image_width;
  162766. while (--num_rows >= 0) {
  162767. /* It seems fastest to make a separate pass for each component. */
  162768. for (ci = 0; ci < nc; ci++) {
  162769. inptr = *input_buf;
  162770. outptr = output_buf[ci][output_row];
  162771. for (col = 0; col < num_cols; col++) {
  162772. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162773. inptr += nc;
  162774. }
  162775. }
  162776. input_buf++;
  162777. output_row++;
  162778. }
  162779. }
  162780. /*
  162781. * Empty method for start_pass.
  162782. */
  162783. METHODDEF(void)
  162784. null_method (j_compress_ptr)
  162785. {
  162786. /* no work needed */
  162787. }
  162788. /*
  162789. * Module initialization routine for input colorspace conversion.
  162790. */
  162791. GLOBAL(void)
  162792. jinit_color_converter (j_compress_ptr cinfo)
  162793. {
  162794. my_cconvert_ptr cconvert;
  162795. cconvert = (my_cconvert_ptr)
  162796. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162797. SIZEOF(my_color_converter));
  162798. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162799. /* set start_pass to null method until we find out differently */
  162800. cconvert->pub.start_pass = null_method;
  162801. /* Make sure input_components agrees with in_color_space */
  162802. switch (cinfo->in_color_space) {
  162803. case JCS_GRAYSCALE:
  162804. if (cinfo->input_components != 1)
  162805. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162806. break;
  162807. case JCS_RGB:
  162808. #if RGB_PIXELSIZE != 3
  162809. if (cinfo->input_components != RGB_PIXELSIZE)
  162810. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162811. break;
  162812. #endif /* else share code with YCbCr */
  162813. case JCS_YCbCr:
  162814. if (cinfo->input_components != 3)
  162815. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162816. break;
  162817. case JCS_CMYK:
  162818. case JCS_YCCK:
  162819. if (cinfo->input_components != 4)
  162820. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162821. break;
  162822. default: /* JCS_UNKNOWN can be anything */
  162823. if (cinfo->input_components < 1)
  162824. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162825. break;
  162826. }
  162827. /* Check num_components, set conversion method based on requested space */
  162828. switch (cinfo->jpeg_color_space) {
  162829. case JCS_GRAYSCALE:
  162830. if (cinfo->num_components != 1)
  162831. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162832. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162833. cconvert->pub.color_convert = grayscale_convert;
  162834. else if (cinfo->in_color_space == JCS_RGB) {
  162835. cconvert->pub.start_pass = rgb_ycc_start;
  162836. cconvert->pub.color_convert = rgb_gray_convert;
  162837. } else if (cinfo->in_color_space == JCS_YCbCr)
  162838. cconvert->pub.color_convert = grayscale_convert;
  162839. else
  162840. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162841. break;
  162842. case JCS_RGB:
  162843. if (cinfo->num_components != 3)
  162844. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162845. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162846. cconvert->pub.color_convert = null_convert;
  162847. else
  162848. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162849. break;
  162850. case JCS_YCbCr:
  162851. if (cinfo->num_components != 3)
  162852. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162853. if (cinfo->in_color_space == JCS_RGB) {
  162854. cconvert->pub.start_pass = rgb_ycc_start;
  162855. cconvert->pub.color_convert = rgb_ycc_convert;
  162856. } else if (cinfo->in_color_space == JCS_YCbCr)
  162857. cconvert->pub.color_convert = null_convert;
  162858. else
  162859. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162860. break;
  162861. case JCS_CMYK:
  162862. if (cinfo->num_components != 4)
  162863. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162864. if (cinfo->in_color_space == JCS_CMYK)
  162865. cconvert->pub.color_convert = null_convert;
  162866. else
  162867. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162868. break;
  162869. case JCS_YCCK:
  162870. if (cinfo->num_components != 4)
  162871. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162872. if (cinfo->in_color_space == JCS_CMYK) {
  162873. cconvert->pub.start_pass = rgb_ycc_start;
  162874. cconvert->pub.color_convert = cmyk_ycck_convert;
  162875. } else if (cinfo->in_color_space == JCS_YCCK)
  162876. cconvert->pub.color_convert = null_convert;
  162877. else
  162878. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162879. break;
  162880. default: /* allow null conversion of JCS_UNKNOWN */
  162881. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162882. cinfo->num_components != cinfo->input_components)
  162883. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162884. cconvert->pub.color_convert = null_convert;
  162885. break;
  162886. }
  162887. }
  162888. /*** End of inlined file: jccolor.c ***/
  162889. #undef FIX
  162890. /*** Start of inlined file: jcdctmgr.c ***/
  162891. #define JPEG_INTERNALS
  162892. /*** Start of inlined file: jdct.h ***/
  162893. /*
  162894. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162895. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162896. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162897. * implementations use an array of type FAST_FLOAT, instead.)
  162898. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162899. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162900. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162901. * convention improves accuracy in integer implementations and saves some
  162902. * work in floating-point ones.
  162903. * Quantization of the output coefficients is done by jcdctmgr.c.
  162904. */
  162905. #ifndef __jdct_h__
  162906. #define __jdct_h__
  162907. #if BITS_IN_JSAMPLE == 8
  162908. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162909. #else
  162910. typedef INT32 DCTELEM; /* must have 32 bits */
  162911. #endif
  162912. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162913. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162914. /*
  162915. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162916. * to an output sample array. The routine must dequantize the input data as
  162917. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162918. * pointed to by compptr->dct_table. The output data is to be placed into the
  162919. * sample array starting at a specified column. (Any row offset needed will
  162920. * be applied to the array pointer before it is passed to the IDCT code.)
  162921. * Note that the number of samples emitted by the IDCT routine is
  162922. * DCT_scaled_size * DCT_scaled_size.
  162923. */
  162924. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162925. /*
  162926. * Each IDCT routine has its own ideas about the best dct_table element type.
  162927. */
  162928. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162929. #if BITS_IN_JSAMPLE == 8
  162930. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162931. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162932. #else
  162933. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162934. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162935. #endif
  162936. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162937. /*
  162938. * Each IDCT routine is responsible for range-limiting its results and
  162939. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162940. * be quite far out of range if the input data is corrupt, so a bulletproof
  162941. * range-limiting step is required. We use a mask-and-table-lookup method
  162942. * to do the combined operations quickly. See the comments with
  162943. * prepare_range_limit_table (in jdmaster.c) for more info.
  162944. */
  162945. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162946. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162947. /* Short forms of external names for systems with brain-damaged linkers. */
  162948. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162949. #define jpeg_fdct_islow jFDislow
  162950. #define jpeg_fdct_ifast jFDifast
  162951. #define jpeg_fdct_float jFDfloat
  162952. #define jpeg_idct_islow jRDislow
  162953. #define jpeg_idct_ifast jRDifast
  162954. #define jpeg_idct_float jRDfloat
  162955. #define jpeg_idct_4x4 jRD4x4
  162956. #define jpeg_idct_2x2 jRD2x2
  162957. #define jpeg_idct_1x1 jRD1x1
  162958. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162959. /* Extern declarations for the forward and inverse DCT routines. */
  162960. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162961. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162962. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162963. EXTERN(void) jpeg_idct_islow
  162964. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162965. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162966. EXTERN(void) jpeg_idct_ifast
  162967. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162968. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162969. EXTERN(void) jpeg_idct_float
  162970. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162971. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162972. EXTERN(void) jpeg_idct_4x4
  162973. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162974. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162975. EXTERN(void) jpeg_idct_2x2
  162976. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162977. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162978. EXTERN(void) jpeg_idct_1x1
  162979. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162980. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162981. /*
  162982. * Macros for handling fixed-point arithmetic; these are used by many
  162983. * but not all of the DCT/IDCT modules.
  162984. *
  162985. * All values are expected to be of type INT32.
  162986. * Fractional constants are scaled left by CONST_BITS bits.
  162987. * CONST_BITS is defined within each module using these macros,
  162988. * and may differ from one module to the next.
  162989. */
  162990. #define ONE ((INT32) 1)
  162991. #define CONST_SCALE (ONE << CONST_BITS)
  162992. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162993. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162994. * thus causing a lot of useless floating-point operations at run time.
  162995. */
  162996. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162997. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162998. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162999. * the fudge factor is correct for either sign of X.
  163000. */
  163001. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  163002. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  163003. * This macro is used only when the two inputs will actually be no more than
  163004. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  163005. * full 32x32 multiply. This provides a useful speedup on many machines.
  163006. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  163007. * in C, but some C compilers will do the right thing if you provide the
  163008. * correct combination of casts.
  163009. */
  163010. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163011. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  163012. #endif
  163013. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  163014. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  163015. #endif
  163016. #ifndef MULTIPLY16C16 /* default definition */
  163017. #define MULTIPLY16C16(var,const) ((var) * (const))
  163018. #endif
  163019. /* Same except both inputs are variables. */
  163020. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163021. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  163022. #endif
  163023. #ifndef MULTIPLY16V16 /* default definition */
  163024. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  163025. #endif
  163026. #endif
  163027. /*** End of inlined file: jdct.h ***/
  163028. /* Private declarations for DCT subsystem */
  163029. /* Private subobject for this module */
  163030. typedef struct {
  163031. struct jpeg_forward_dct pub; /* public fields */
  163032. /* Pointer to the DCT routine actually in use */
  163033. forward_DCT_method_ptr do_dct;
  163034. /* The actual post-DCT divisors --- not identical to the quant table
  163035. * entries, because of scaling (especially for an unnormalized DCT).
  163036. * Each table is given in normal array order.
  163037. */
  163038. DCTELEM * divisors[NUM_QUANT_TBLS];
  163039. #ifdef DCT_FLOAT_SUPPORTED
  163040. /* Same as above for the floating-point case. */
  163041. float_DCT_method_ptr do_float_dct;
  163042. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163043. #endif
  163044. } my_fdct_controller;
  163045. typedef my_fdct_controller * my_fdct_ptr;
  163046. /*
  163047. * Initialize for a processing pass.
  163048. * Verify that all referenced Q-tables are present, and set up
  163049. * the divisor table for each one.
  163050. * In the current implementation, DCT of all components is done during
  163051. * the first pass, even if only some components will be output in the
  163052. * first scan. Hence all components should be examined here.
  163053. */
  163054. METHODDEF(void)
  163055. start_pass_fdctmgr (j_compress_ptr cinfo)
  163056. {
  163057. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163058. int ci, qtblno, i;
  163059. jpeg_component_info *compptr;
  163060. JQUANT_TBL * qtbl;
  163061. DCTELEM * dtbl;
  163062. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163063. ci++, compptr++) {
  163064. qtblno = compptr->quant_tbl_no;
  163065. /* Make sure specified quantization table is present */
  163066. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163067. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163068. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163069. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163070. /* Compute divisors for this quant table */
  163071. /* We may do this more than once for same table, but it's not a big deal */
  163072. switch (cinfo->dct_method) {
  163073. #ifdef DCT_ISLOW_SUPPORTED
  163074. case JDCT_ISLOW:
  163075. /* For LL&M IDCT method, divisors are equal to raw quantization
  163076. * coefficients multiplied by 8 (to counteract scaling).
  163077. */
  163078. if (fdct->divisors[qtblno] == NULL) {
  163079. fdct->divisors[qtblno] = (DCTELEM *)
  163080. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163081. DCTSIZE2 * SIZEOF(DCTELEM));
  163082. }
  163083. dtbl = fdct->divisors[qtblno];
  163084. for (i = 0; i < DCTSIZE2; i++) {
  163085. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163086. }
  163087. break;
  163088. #endif
  163089. #ifdef DCT_IFAST_SUPPORTED
  163090. case JDCT_IFAST:
  163091. {
  163092. /* For AA&N IDCT method, divisors are equal to quantization
  163093. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163094. * scalefactor[0] = 1
  163095. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163096. * We apply a further scale factor of 8.
  163097. */
  163098. #define CONST_BITS 14
  163099. static const INT16 aanscales[DCTSIZE2] = {
  163100. /* precomputed values scaled up by 14 bits */
  163101. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163102. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163103. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163104. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163105. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163106. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163107. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163108. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163109. };
  163110. SHIFT_TEMPS
  163111. if (fdct->divisors[qtblno] == NULL) {
  163112. fdct->divisors[qtblno] = (DCTELEM *)
  163113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163114. DCTSIZE2 * SIZEOF(DCTELEM));
  163115. }
  163116. dtbl = fdct->divisors[qtblno];
  163117. for (i = 0; i < DCTSIZE2; i++) {
  163118. dtbl[i] = (DCTELEM)
  163119. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163120. (INT32) aanscales[i]),
  163121. CONST_BITS-3);
  163122. }
  163123. }
  163124. break;
  163125. #endif
  163126. #ifdef DCT_FLOAT_SUPPORTED
  163127. case JDCT_FLOAT:
  163128. {
  163129. /* For float AA&N IDCT method, divisors are equal to quantization
  163130. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163131. * scalefactor[0] = 1
  163132. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163133. * We apply a further scale factor of 8.
  163134. * What's actually stored is 1/divisor so that the inner loop can
  163135. * use a multiplication rather than a division.
  163136. */
  163137. FAST_FLOAT * fdtbl;
  163138. int row, col;
  163139. static const double aanscalefactor[DCTSIZE] = {
  163140. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163141. 1.0, 0.785694958, 0.541196100, 0.275899379
  163142. };
  163143. if (fdct->float_divisors[qtblno] == NULL) {
  163144. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163146. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163147. }
  163148. fdtbl = fdct->float_divisors[qtblno];
  163149. i = 0;
  163150. for (row = 0; row < DCTSIZE; row++) {
  163151. for (col = 0; col < DCTSIZE; col++) {
  163152. fdtbl[i] = (FAST_FLOAT)
  163153. (1.0 / (((double) qtbl->quantval[i] *
  163154. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163155. i++;
  163156. }
  163157. }
  163158. }
  163159. break;
  163160. #endif
  163161. default:
  163162. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163163. break;
  163164. }
  163165. }
  163166. }
  163167. /*
  163168. * Perform forward DCT on one or more blocks of a component.
  163169. *
  163170. * The input samples are taken from the sample_data[] array starting at
  163171. * position start_row/start_col, and moving to the right for any additional
  163172. * blocks. The quantized coefficients are returned in coef_blocks[].
  163173. */
  163174. METHODDEF(void)
  163175. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163176. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163177. JDIMENSION start_row, JDIMENSION start_col,
  163178. JDIMENSION num_blocks)
  163179. /* This version is used for integer DCT implementations. */
  163180. {
  163181. /* This routine is heavily used, so it's worth coding it tightly. */
  163182. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163183. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163184. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163185. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163186. JDIMENSION bi;
  163187. sample_data += start_row; /* fold in the vertical offset once */
  163188. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163189. /* Load data into workspace, applying unsigned->signed conversion */
  163190. { register DCTELEM *workspaceptr;
  163191. register JSAMPROW elemptr;
  163192. register int elemr;
  163193. workspaceptr = workspace;
  163194. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163195. elemptr = sample_data[elemr] + start_col;
  163196. #if DCTSIZE == 8 /* unroll the inner loop */
  163197. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163198. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163199. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163200. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163201. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163202. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163203. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163204. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163205. #else
  163206. { register int elemc;
  163207. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163208. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163209. }
  163210. }
  163211. #endif
  163212. }
  163213. }
  163214. /* Perform the DCT */
  163215. (*do_dct) (workspace);
  163216. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163217. { register DCTELEM temp, qval;
  163218. register int i;
  163219. register JCOEFPTR output_ptr = coef_blocks[bi];
  163220. for (i = 0; i < DCTSIZE2; i++) {
  163221. qval = divisors[i];
  163222. temp = workspace[i];
  163223. /* Divide the coefficient value by qval, ensuring proper rounding.
  163224. * Since C does not specify the direction of rounding for negative
  163225. * quotients, we have to force the dividend positive for portability.
  163226. *
  163227. * In most files, at least half of the output values will be zero
  163228. * (at default quantization settings, more like three-quarters...)
  163229. * so we should ensure that this case is fast. On many machines,
  163230. * a comparison is enough cheaper than a divide to make a special test
  163231. * a win. Since both inputs will be nonnegative, we need only test
  163232. * for a < b to discover whether a/b is 0.
  163233. * If your machine's division is fast enough, define FAST_DIVIDE.
  163234. */
  163235. #ifdef FAST_DIVIDE
  163236. #define DIVIDE_BY(a,b) a /= b
  163237. #else
  163238. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163239. #endif
  163240. if (temp < 0) {
  163241. temp = -temp;
  163242. temp += qval>>1; /* for rounding */
  163243. DIVIDE_BY(temp, qval);
  163244. temp = -temp;
  163245. } else {
  163246. temp += qval>>1; /* for rounding */
  163247. DIVIDE_BY(temp, qval);
  163248. }
  163249. output_ptr[i] = (JCOEF) temp;
  163250. }
  163251. }
  163252. }
  163253. }
  163254. #ifdef DCT_FLOAT_SUPPORTED
  163255. METHODDEF(void)
  163256. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163257. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163258. JDIMENSION start_row, JDIMENSION start_col,
  163259. JDIMENSION num_blocks)
  163260. /* This version is used for floating-point DCT implementations. */
  163261. {
  163262. /* This routine is heavily used, so it's worth coding it tightly. */
  163263. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163264. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163265. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163266. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163267. JDIMENSION bi;
  163268. sample_data += start_row; /* fold in the vertical offset once */
  163269. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163270. /* Load data into workspace, applying unsigned->signed conversion */
  163271. { register FAST_FLOAT *workspaceptr;
  163272. register JSAMPROW elemptr;
  163273. register int elemr;
  163274. workspaceptr = workspace;
  163275. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163276. elemptr = sample_data[elemr] + start_col;
  163277. #if DCTSIZE == 8 /* unroll the inner loop */
  163278. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163279. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163280. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163281. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163282. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163283. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163284. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163285. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163286. #else
  163287. { register int elemc;
  163288. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163289. *workspaceptr++ = (FAST_FLOAT)
  163290. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163291. }
  163292. }
  163293. #endif
  163294. }
  163295. }
  163296. /* Perform the DCT */
  163297. (*do_dct) (workspace);
  163298. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163299. { register FAST_FLOAT temp;
  163300. register int i;
  163301. register JCOEFPTR output_ptr = coef_blocks[bi];
  163302. for (i = 0; i < DCTSIZE2; i++) {
  163303. /* Apply the quantization and scaling factor */
  163304. temp = workspace[i] * divisors[i];
  163305. /* Round to nearest integer.
  163306. * Since C does not specify the direction of rounding for negative
  163307. * quotients, we have to force the dividend positive for portability.
  163308. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163309. * code should work for either 16-bit or 32-bit ints.
  163310. */
  163311. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163312. }
  163313. }
  163314. }
  163315. }
  163316. #endif /* DCT_FLOAT_SUPPORTED */
  163317. /*
  163318. * Initialize FDCT manager.
  163319. */
  163320. GLOBAL(void)
  163321. jinit_forward_dct (j_compress_ptr cinfo)
  163322. {
  163323. my_fdct_ptr fdct;
  163324. int i;
  163325. fdct = (my_fdct_ptr)
  163326. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163327. SIZEOF(my_fdct_controller));
  163328. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163329. fdct->pub.start_pass = start_pass_fdctmgr;
  163330. switch (cinfo->dct_method) {
  163331. #ifdef DCT_ISLOW_SUPPORTED
  163332. case JDCT_ISLOW:
  163333. fdct->pub.forward_DCT = forward_DCT;
  163334. fdct->do_dct = jpeg_fdct_islow;
  163335. break;
  163336. #endif
  163337. #ifdef DCT_IFAST_SUPPORTED
  163338. case JDCT_IFAST:
  163339. fdct->pub.forward_DCT = forward_DCT;
  163340. fdct->do_dct = jpeg_fdct_ifast;
  163341. break;
  163342. #endif
  163343. #ifdef DCT_FLOAT_SUPPORTED
  163344. case JDCT_FLOAT:
  163345. fdct->pub.forward_DCT = forward_DCT_float;
  163346. fdct->do_float_dct = jpeg_fdct_float;
  163347. break;
  163348. #endif
  163349. default:
  163350. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163351. break;
  163352. }
  163353. /* Mark divisor tables unallocated */
  163354. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163355. fdct->divisors[i] = NULL;
  163356. #ifdef DCT_FLOAT_SUPPORTED
  163357. fdct->float_divisors[i] = NULL;
  163358. #endif
  163359. }
  163360. }
  163361. /*** End of inlined file: jcdctmgr.c ***/
  163362. #undef CONST_BITS
  163363. /*** Start of inlined file: jchuff.c ***/
  163364. #define JPEG_INTERNALS
  163365. /*** Start of inlined file: jchuff.h ***/
  163366. /* The legal range of a DCT coefficient is
  163367. * -1024 .. +1023 for 8-bit data;
  163368. * -16384 .. +16383 for 12-bit data.
  163369. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163370. */
  163371. #ifndef _jchuff_h_
  163372. #define _jchuff_h_
  163373. #if BITS_IN_JSAMPLE == 8
  163374. #define MAX_COEF_BITS 10
  163375. #else
  163376. #define MAX_COEF_BITS 14
  163377. #endif
  163378. /* Derived data constructed for each Huffman table */
  163379. typedef struct {
  163380. unsigned int ehufco[256]; /* code for each symbol */
  163381. char ehufsi[256]; /* length of code for each symbol */
  163382. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163383. } c_derived_tbl;
  163384. /* Short forms of external names for systems with brain-damaged linkers. */
  163385. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163386. #define jpeg_make_c_derived_tbl jMkCDerived
  163387. #define jpeg_gen_optimal_table jGenOptTbl
  163388. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163389. /* Expand a Huffman table definition into the derived format */
  163390. EXTERN(void) jpeg_make_c_derived_tbl
  163391. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163392. c_derived_tbl ** pdtbl));
  163393. /* Generate an optimal table definition given the specified counts */
  163394. EXTERN(void) jpeg_gen_optimal_table
  163395. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163396. #endif
  163397. /*** End of inlined file: jchuff.h ***/
  163398. /* Declarations shared with jcphuff.c */
  163399. /* Expanded entropy encoder object for Huffman encoding.
  163400. *
  163401. * The savable_state subrecord contains fields that change within an MCU,
  163402. * but must not be updated permanently until we complete the MCU.
  163403. */
  163404. typedef struct {
  163405. INT32 put_buffer; /* current bit-accumulation buffer */
  163406. int put_bits; /* # of bits now in it */
  163407. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163408. } savable_state;
  163409. /* This macro is to work around compilers with missing or broken
  163410. * structure assignment. You'll need to fix this code if you have
  163411. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163412. */
  163413. #ifndef NO_STRUCT_ASSIGN
  163414. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163415. #else
  163416. #if MAX_COMPS_IN_SCAN == 4
  163417. #define ASSIGN_STATE(dest,src) \
  163418. ((dest).put_buffer = (src).put_buffer, \
  163419. (dest).put_bits = (src).put_bits, \
  163420. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163421. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163422. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163423. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163424. #endif
  163425. #endif
  163426. typedef struct {
  163427. struct jpeg_entropy_encoder pub; /* public fields */
  163428. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163429. /* These fields are NOT loaded into local working state. */
  163430. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163431. int next_restart_num; /* next restart number to write (0-7) */
  163432. /* Pointers to derived tables (these workspaces have image lifespan) */
  163433. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163434. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163435. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163436. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163437. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163438. #endif
  163439. } huff_entropy_encoder;
  163440. typedef huff_entropy_encoder * huff_entropy_ptr;
  163441. /* Working state while writing an MCU.
  163442. * This struct contains all the fields that are needed by subroutines.
  163443. */
  163444. typedef struct {
  163445. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163446. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163447. savable_state cur; /* Current bit buffer & DC state */
  163448. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163449. } working_state;
  163450. /* Forward declarations */
  163451. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163452. JBLOCKROW *MCU_data));
  163453. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163454. #ifdef ENTROPY_OPT_SUPPORTED
  163455. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163456. JBLOCKROW *MCU_data));
  163457. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163458. #endif
  163459. /*
  163460. * Initialize for a Huffman-compressed scan.
  163461. * If gather_statistics is TRUE, we do not output anything during the scan,
  163462. * just count the Huffman symbols used and generate Huffman code tables.
  163463. */
  163464. METHODDEF(void)
  163465. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163466. {
  163467. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163468. int ci, dctbl, actbl;
  163469. jpeg_component_info * compptr;
  163470. if (gather_statistics) {
  163471. #ifdef ENTROPY_OPT_SUPPORTED
  163472. entropy->pub.encode_mcu = encode_mcu_gather;
  163473. entropy->pub.finish_pass = finish_pass_gather;
  163474. #else
  163475. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163476. #endif
  163477. } else {
  163478. entropy->pub.encode_mcu = encode_mcu_huff;
  163479. entropy->pub.finish_pass = finish_pass_huff;
  163480. }
  163481. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163482. compptr = cinfo->cur_comp_info[ci];
  163483. dctbl = compptr->dc_tbl_no;
  163484. actbl = compptr->ac_tbl_no;
  163485. if (gather_statistics) {
  163486. #ifdef ENTROPY_OPT_SUPPORTED
  163487. /* Check for invalid table indexes */
  163488. /* (make_c_derived_tbl does this in the other path) */
  163489. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163490. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163491. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163492. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163493. /* Allocate and zero the statistics tables */
  163494. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163495. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163496. entropy->dc_count_ptrs[dctbl] = (long *)
  163497. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163498. 257 * SIZEOF(long));
  163499. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163500. if (entropy->ac_count_ptrs[actbl] == NULL)
  163501. entropy->ac_count_ptrs[actbl] = (long *)
  163502. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163503. 257 * SIZEOF(long));
  163504. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163505. #endif
  163506. } else {
  163507. /* Compute derived values for Huffman tables */
  163508. /* We may do this more than once for a table, but it's not expensive */
  163509. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163510. & entropy->dc_derived_tbls[dctbl]);
  163511. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163512. & entropy->ac_derived_tbls[actbl]);
  163513. }
  163514. /* Initialize DC predictions to 0 */
  163515. entropy->saved.last_dc_val[ci] = 0;
  163516. }
  163517. /* Initialize bit buffer to empty */
  163518. entropy->saved.put_buffer = 0;
  163519. entropy->saved.put_bits = 0;
  163520. /* Initialize restart stuff */
  163521. entropy->restarts_to_go = cinfo->restart_interval;
  163522. entropy->next_restart_num = 0;
  163523. }
  163524. /*
  163525. * Compute the derived values for a Huffman table.
  163526. * This routine also performs some validation checks on the table.
  163527. *
  163528. * Note this is also used by jcphuff.c.
  163529. */
  163530. GLOBAL(void)
  163531. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163532. c_derived_tbl ** pdtbl)
  163533. {
  163534. JHUFF_TBL *htbl;
  163535. c_derived_tbl *dtbl;
  163536. int p, i, l, lastp, si, maxsymbol;
  163537. char huffsize[257];
  163538. unsigned int huffcode[257];
  163539. unsigned int code;
  163540. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163541. * paralleling the order of the symbols themselves in htbl->huffval[].
  163542. */
  163543. /* Find the input Huffman table */
  163544. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163545. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163546. htbl =
  163547. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163548. if (htbl == NULL)
  163549. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163550. /* Allocate a workspace if we haven't already done so. */
  163551. if (*pdtbl == NULL)
  163552. *pdtbl = (c_derived_tbl *)
  163553. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163554. SIZEOF(c_derived_tbl));
  163555. dtbl = *pdtbl;
  163556. /* Figure C.1: make table of Huffman code length for each symbol */
  163557. p = 0;
  163558. for (l = 1; l <= 16; l++) {
  163559. i = (int) htbl->bits[l];
  163560. if (i < 0 || p + i > 256) /* protect against table overrun */
  163561. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163562. while (i--)
  163563. huffsize[p++] = (char) l;
  163564. }
  163565. huffsize[p] = 0;
  163566. lastp = p;
  163567. /* Figure C.2: generate the codes themselves */
  163568. /* We also validate that the counts represent a legal Huffman code tree. */
  163569. code = 0;
  163570. si = huffsize[0];
  163571. p = 0;
  163572. while (huffsize[p]) {
  163573. while (((int) huffsize[p]) == si) {
  163574. huffcode[p++] = code;
  163575. code++;
  163576. }
  163577. /* code is now 1 more than the last code used for codelength si; but
  163578. * it must still fit in si bits, since no code is allowed to be all ones.
  163579. */
  163580. if (((INT32) code) >= (((INT32) 1) << si))
  163581. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163582. code <<= 1;
  163583. si++;
  163584. }
  163585. /* Figure C.3: generate encoding tables */
  163586. /* These are code and size indexed by symbol value */
  163587. /* Set all codeless symbols to have code length 0;
  163588. * this lets us detect duplicate VAL entries here, and later
  163589. * allows emit_bits to detect any attempt to emit such symbols.
  163590. */
  163591. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163592. /* This is also a convenient place to check for out-of-range
  163593. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163594. * but only 0..15 for DC. (We could constrain them further
  163595. * based on data depth and mode, but this seems enough.)
  163596. */
  163597. maxsymbol = isDC ? 15 : 255;
  163598. for (p = 0; p < lastp; p++) {
  163599. i = htbl->huffval[p];
  163600. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163601. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163602. dtbl->ehufco[i] = huffcode[p];
  163603. dtbl->ehufsi[i] = huffsize[p];
  163604. }
  163605. }
  163606. /* Outputting bytes to the file */
  163607. /* Emit a byte, taking 'action' if must suspend. */
  163608. #define emit_byte(state,val,action) \
  163609. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163610. if (--(state)->free_in_buffer == 0) \
  163611. if (! dump_buffer(state)) \
  163612. { action; } }
  163613. LOCAL(boolean)
  163614. dump_buffer (working_state * state)
  163615. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163616. {
  163617. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163618. if (! (*dest->empty_output_buffer) (state->cinfo))
  163619. return FALSE;
  163620. /* After a successful buffer dump, must reset buffer pointers */
  163621. state->next_output_byte = dest->next_output_byte;
  163622. state->free_in_buffer = dest->free_in_buffer;
  163623. return TRUE;
  163624. }
  163625. /* Outputting bits to the file */
  163626. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163627. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163628. * in one call, and we never retain more than 7 bits in put_buffer
  163629. * between calls, so 24 bits are sufficient.
  163630. */
  163631. INLINE
  163632. LOCAL(boolean)
  163633. emit_bits (working_state * state, unsigned int code, int size)
  163634. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163635. {
  163636. /* This routine is heavily used, so it's worth coding tightly. */
  163637. register INT32 put_buffer = (INT32) code;
  163638. register int put_bits = state->cur.put_bits;
  163639. /* if size is 0, caller used an invalid Huffman table entry */
  163640. if (size == 0)
  163641. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163642. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163643. put_bits += size; /* new number of bits in buffer */
  163644. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163645. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163646. while (put_bits >= 8) {
  163647. int c = (int) ((put_buffer >> 16) & 0xFF);
  163648. emit_byte(state, c, return FALSE);
  163649. if (c == 0xFF) { /* need to stuff a zero byte? */
  163650. emit_byte(state, 0, return FALSE);
  163651. }
  163652. put_buffer <<= 8;
  163653. put_bits -= 8;
  163654. }
  163655. state->cur.put_buffer = put_buffer; /* update state variables */
  163656. state->cur.put_bits = put_bits;
  163657. return TRUE;
  163658. }
  163659. LOCAL(boolean)
  163660. flush_bits (working_state * state)
  163661. {
  163662. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163663. return FALSE;
  163664. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163665. state->cur.put_bits = 0;
  163666. return TRUE;
  163667. }
  163668. /* Encode a single block's worth of coefficients */
  163669. LOCAL(boolean)
  163670. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163671. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163672. {
  163673. register int temp, temp2;
  163674. register int nbits;
  163675. register int k, r, i;
  163676. /* Encode the DC coefficient difference per section F.1.2.1 */
  163677. temp = temp2 = block[0] - last_dc_val;
  163678. if (temp < 0) {
  163679. temp = -temp; /* temp is abs value of input */
  163680. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163681. /* This code assumes we are on a two's complement machine */
  163682. temp2--;
  163683. }
  163684. /* Find the number of bits needed for the magnitude of the coefficient */
  163685. nbits = 0;
  163686. while (temp) {
  163687. nbits++;
  163688. temp >>= 1;
  163689. }
  163690. /* Check for out-of-range coefficient values.
  163691. * Since we're encoding a difference, the range limit is twice as much.
  163692. */
  163693. if (nbits > MAX_COEF_BITS+1)
  163694. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163695. /* Emit the Huffman-coded symbol for the number of bits */
  163696. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163697. return FALSE;
  163698. /* Emit that number of bits of the value, if positive, */
  163699. /* or the complement of its magnitude, if negative. */
  163700. if (nbits) /* emit_bits rejects calls with size 0 */
  163701. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163702. return FALSE;
  163703. /* Encode the AC coefficients per section F.1.2.2 */
  163704. r = 0; /* r = run length of zeros */
  163705. for (k = 1; k < DCTSIZE2; k++) {
  163706. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163707. r++;
  163708. } else {
  163709. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163710. while (r > 15) {
  163711. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163712. return FALSE;
  163713. r -= 16;
  163714. }
  163715. temp2 = temp;
  163716. if (temp < 0) {
  163717. temp = -temp; /* temp is abs value of input */
  163718. /* This code assumes we are on a two's complement machine */
  163719. temp2--;
  163720. }
  163721. /* Find the number of bits needed for the magnitude of the coefficient */
  163722. nbits = 1; /* there must be at least one 1 bit */
  163723. while ((temp >>= 1))
  163724. nbits++;
  163725. /* Check for out-of-range coefficient values */
  163726. if (nbits > MAX_COEF_BITS)
  163727. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163728. /* Emit Huffman symbol for run length / number of bits */
  163729. i = (r << 4) + nbits;
  163730. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163731. return FALSE;
  163732. /* Emit that number of bits of the value, if positive, */
  163733. /* or the complement of its magnitude, if negative. */
  163734. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163735. return FALSE;
  163736. r = 0;
  163737. }
  163738. }
  163739. /* If the last coef(s) were zero, emit an end-of-block code */
  163740. if (r > 0)
  163741. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163742. return FALSE;
  163743. return TRUE;
  163744. }
  163745. /*
  163746. * Emit a restart marker & resynchronize predictions.
  163747. */
  163748. LOCAL(boolean)
  163749. emit_restart (working_state * state, int restart_num)
  163750. {
  163751. int ci;
  163752. if (! flush_bits(state))
  163753. return FALSE;
  163754. emit_byte(state, 0xFF, return FALSE);
  163755. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163756. /* Re-initialize DC predictions to 0 */
  163757. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163758. state->cur.last_dc_val[ci] = 0;
  163759. /* The restart counter is not updated until we successfully write the MCU. */
  163760. return TRUE;
  163761. }
  163762. /*
  163763. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163764. */
  163765. METHODDEF(boolean)
  163766. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163767. {
  163768. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163769. working_state state;
  163770. int blkn, ci;
  163771. jpeg_component_info * compptr;
  163772. /* Load up working state */
  163773. state.next_output_byte = cinfo->dest->next_output_byte;
  163774. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163775. ASSIGN_STATE(state.cur, entropy->saved);
  163776. state.cinfo = cinfo;
  163777. /* Emit restart marker if needed */
  163778. if (cinfo->restart_interval) {
  163779. if (entropy->restarts_to_go == 0)
  163780. if (! emit_restart(&state, entropy->next_restart_num))
  163781. return FALSE;
  163782. }
  163783. /* Encode the MCU data blocks */
  163784. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163785. ci = cinfo->MCU_membership[blkn];
  163786. compptr = cinfo->cur_comp_info[ci];
  163787. if (! encode_one_block(&state,
  163788. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163789. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163790. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163791. return FALSE;
  163792. /* Update last_dc_val */
  163793. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163794. }
  163795. /* Completed MCU, so update state */
  163796. cinfo->dest->next_output_byte = state.next_output_byte;
  163797. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163798. ASSIGN_STATE(entropy->saved, state.cur);
  163799. /* Update restart-interval state too */
  163800. if (cinfo->restart_interval) {
  163801. if (entropy->restarts_to_go == 0) {
  163802. entropy->restarts_to_go = cinfo->restart_interval;
  163803. entropy->next_restart_num++;
  163804. entropy->next_restart_num &= 7;
  163805. }
  163806. entropy->restarts_to_go--;
  163807. }
  163808. return TRUE;
  163809. }
  163810. /*
  163811. * Finish up at the end of a Huffman-compressed scan.
  163812. */
  163813. METHODDEF(void)
  163814. finish_pass_huff (j_compress_ptr cinfo)
  163815. {
  163816. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163817. working_state state;
  163818. /* Load up working state ... flush_bits needs it */
  163819. state.next_output_byte = cinfo->dest->next_output_byte;
  163820. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163821. ASSIGN_STATE(state.cur, entropy->saved);
  163822. state.cinfo = cinfo;
  163823. /* Flush out the last data */
  163824. if (! flush_bits(&state))
  163825. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163826. /* Update state */
  163827. cinfo->dest->next_output_byte = state.next_output_byte;
  163828. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163829. ASSIGN_STATE(entropy->saved, state.cur);
  163830. }
  163831. /*
  163832. * Huffman coding optimization.
  163833. *
  163834. * We first scan the supplied data and count the number of uses of each symbol
  163835. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163836. * Then we build a Huffman coding tree for the observed counts.
  163837. * Symbols which are not needed at all for the particular image are not
  163838. * assigned any code, which saves space in the DHT marker as well as in
  163839. * the compressed data.
  163840. */
  163841. #ifdef ENTROPY_OPT_SUPPORTED
  163842. /* Process a single block's worth of coefficients */
  163843. LOCAL(void)
  163844. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163845. long dc_counts[], long ac_counts[])
  163846. {
  163847. register int temp;
  163848. register int nbits;
  163849. register int k, r;
  163850. /* Encode the DC coefficient difference per section F.1.2.1 */
  163851. temp = block[0] - last_dc_val;
  163852. if (temp < 0)
  163853. temp = -temp;
  163854. /* Find the number of bits needed for the magnitude of the coefficient */
  163855. nbits = 0;
  163856. while (temp) {
  163857. nbits++;
  163858. temp >>= 1;
  163859. }
  163860. /* Check for out-of-range coefficient values.
  163861. * Since we're encoding a difference, the range limit is twice as much.
  163862. */
  163863. if (nbits > MAX_COEF_BITS+1)
  163864. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163865. /* Count the Huffman symbol for the number of bits */
  163866. dc_counts[nbits]++;
  163867. /* Encode the AC coefficients per section F.1.2.2 */
  163868. r = 0; /* r = run length of zeros */
  163869. for (k = 1; k < DCTSIZE2; k++) {
  163870. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163871. r++;
  163872. } else {
  163873. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163874. while (r > 15) {
  163875. ac_counts[0xF0]++;
  163876. r -= 16;
  163877. }
  163878. /* Find the number of bits needed for the magnitude of the coefficient */
  163879. if (temp < 0)
  163880. temp = -temp;
  163881. /* Find the number of bits needed for the magnitude of the coefficient */
  163882. nbits = 1; /* there must be at least one 1 bit */
  163883. while ((temp >>= 1))
  163884. nbits++;
  163885. /* Check for out-of-range coefficient values */
  163886. if (nbits > MAX_COEF_BITS)
  163887. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163888. /* Count Huffman symbol for run length / number of bits */
  163889. ac_counts[(r << 4) + nbits]++;
  163890. r = 0;
  163891. }
  163892. }
  163893. /* If the last coef(s) were zero, emit an end-of-block code */
  163894. if (r > 0)
  163895. ac_counts[0]++;
  163896. }
  163897. /*
  163898. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163899. * No data is actually output, so no suspension return is possible.
  163900. */
  163901. METHODDEF(boolean)
  163902. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163903. {
  163904. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163905. int blkn, ci;
  163906. jpeg_component_info * compptr;
  163907. /* Take care of restart intervals if needed */
  163908. if (cinfo->restart_interval) {
  163909. if (entropy->restarts_to_go == 0) {
  163910. /* Re-initialize DC predictions to 0 */
  163911. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163912. entropy->saved.last_dc_val[ci] = 0;
  163913. /* Update restart state */
  163914. entropy->restarts_to_go = cinfo->restart_interval;
  163915. }
  163916. entropy->restarts_to_go--;
  163917. }
  163918. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163919. ci = cinfo->MCU_membership[blkn];
  163920. compptr = cinfo->cur_comp_info[ci];
  163921. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163922. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163923. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163924. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163925. }
  163926. return TRUE;
  163927. }
  163928. /*
  163929. * Generate the best Huffman code table for the given counts, fill htbl.
  163930. * Note this is also used by jcphuff.c.
  163931. *
  163932. * The JPEG standard requires that no symbol be assigned a codeword of all
  163933. * one bits (so that padding bits added at the end of a compressed segment
  163934. * can't look like a valid code). Because of the canonical ordering of
  163935. * codewords, this just means that there must be an unused slot in the
  163936. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163937. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163938. * with count 1. In theory that's not optimal; giving it count zero but
  163939. * including it in the symbol set anyway should give a better Huffman code.
  163940. * But the theoretically better code actually seems to come out worse in
  163941. * practice, because it produces more all-ones bytes (which incur stuffed
  163942. * zero bytes in the final file). In any case the difference is tiny.
  163943. *
  163944. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163945. * If some symbols have a very small but nonzero probability, the Huffman tree
  163946. * must be adjusted to meet the code length restriction. We currently use
  163947. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163948. * optimal; it may not choose the best possible limited-length code. But
  163949. * typically only very-low-frequency symbols will be given less-than-optimal
  163950. * lengths, so the code is almost optimal. Experimental comparisons against
  163951. * an optimal limited-length-code algorithm indicate that the difference is
  163952. * microscopic --- usually less than a hundredth of a percent of total size.
  163953. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163954. */
  163955. GLOBAL(void)
  163956. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163957. {
  163958. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163959. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163960. int codesize[257]; /* codesize[k] = code length of symbol k */
  163961. int others[257]; /* next symbol in current branch of tree */
  163962. int c1, c2;
  163963. int p, i, j;
  163964. long v;
  163965. /* This algorithm is explained in section K.2 of the JPEG standard */
  163966. MEMZERO(bits, SIZEOF(bits));
  163967. MEMZERO(codesize, SIZEOF(codesize));
  163968. for (i = 0; i < 257; i++)
  163969. others[i] = -1; /* init links to empty */
  163970. freq[256] = 1; /* make sure 256 has a nonzero count */
  163971. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163972. * that no real symbol is given code-value of all ones, because 256
  163973. * will be placed last in the largest codeword category.
  163974. */
  163975. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163976. for (;;) {
  163977. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163978. /* In case of ties, take the larger symbol number */
  163979. c1 = -1;
  163980. v = 1000000000L;
  163981. for (i = 0; i <= 256; i++) {
  163982. if (freq[i] && freq[i] <= v) {
  163983. v = freq[i];
  163984. c1 = i;
  163985. }
  163986. }
  163987. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163988. /* In case of ties, take the larger symbol number */
  163989. c2 = -1;
  163990. v = 1000000000L;
  163991. for (i = 0; i <= 256; i++) {
  163992. if (freq[i] && freq[i] <= v && i != c1) {
  163993. v = freq[i];
  163994. c2 = i;
  163995. }
  163996. }
  163997. /* Done if we've merged everything into one frequency */
  163998. if (c2 < 0)
  163999. break;
  164000. /* Else merge the two counts/trees */
  164001. freq[c1] += freq[c2];
  164002. freq[c2] = 0;
  164003. /* Increment the codesize of everything in c1's tree branch */
  164004. codesize[c1]++;
  164005. while (others[c1] >= 0) {
  164006. c1 = others[c1];
  164007. codesize[c1]++;
  164008. }
  164009. others[c1] = c2; /* chain c2 onto c1's tree branch */
  164010. /* Increment the codesize of everything in c2's tree branch */
  164011. codesize[c2]++;
  164012. while (others[c2] >= 0) {
  164013. c2 = others[c2];
  164014. codesize[c2]++;
  164015. }
  164016. }
  164017. /* Now count the number of symbols of each code length */
  164018. for (i = 0; i <= 256; i++) {
  164019. if (codesize[i]) {
  164020. /* The JPEG standard seems to think that this can't happen, */
  164021. /* but I'm paranoid... */
  164022. if (codesize[i] > MAX_CLEN)
  164023. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  164024. bits[codesize[i]]++;
  164025. }
  164026. }
  164027. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164028. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164029. * Here is what the JPEG spec says about how this next bit works:
  164030. * Since symbols are paired for the longest Huffman code, the symbols are
  164031. * removed from this length category two at a time. The prefix for the pair
  164032. * (which is one bit shorter) is allocated to one of the pair; then,
  164033. * skipping the BITS entry for that prefix length, a code word from the next
  164034. * shortest nonzero BITS entry is converted into a prefix for two code words
  164035. * one bit longer.
  164036. */
  164037. for (i = MAX_CLEN; i > 16; i--) {
  164038. while (bits[i] > 0) {
  164039. j = i - 2; /* find length of new prefix to be used */
  164040. while (bits[j] == 0)
  164041. j--;
  164042. bits[i] -= 2; /* remove two symbols */
  164043. bits[i-1]++; /* one goes in this length */
  164044. bits[j+1] += 2; /* two new symbols in this length */
  164045. bits[j]--; /* symbol of this length is now a prefix */
  164046. }
  164047. }
  164048. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164049. while (bits[i] == 0) /* find largest codelength still in use */
  164050. i--;
  164051. bits[i]--;
  164052. /* Return final symbol counts (only for lengths 0..16) */
  164053. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164054. /* Return a list of the symbols sorted by code length */
  164055. /* It's not real clear to me why we don't need to consider the codelength
  164056. * changes made above, but the JPEG spec seems to think this works.
  164057. */
  164058. p = 0;
  164059. for (i = 1; i <= MAX_CLEN; i++) {
  164060. for (j = 0; j <= 255; j++) {
  164061. if (codesize[j] == i) {
  164062. htbl->huffval[p] = (UINT8) j;
  164063. p++;
  164064. }
  164065. }
  164066. }
  164067. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164068. htbl->sent_table = FALSE;
  164069. }
  164070. /*
  164071. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164072. */
  164073. METHODDEF(void)
  164074. finish_pass_gather (j_compress_ptr cinfo)
  164075. {
  164076. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164077. int ci, dctbl, actbl;
  164078. jpeg_component_info * compptr;
  164079. JHUFF_TBL **htblptr;
  164080. boolean did_dc[NUM_HUFF_TBLS];
  164081. boolean did_ac[NUM_HUFF_TBLS];
  164082. /* It's important not to apply jpeg_gen_optimal_table more than once
  164083. * per table, because it clobbers the input frequency counts!
  164084. */
  164085. MEMZERO(did_dc, SIZEOF(did_dc));
  164086. MEMZERO(did_ac, SIZEOF(did_ac));
  164087. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164088. compptr = cinfo->cur_comp_info[ci];
  164089. dctbl = compptr->dc_tbl_no;
  164090. actbl = compptr->ac_tbl_no;
  164091. if (! did_dc[dctbl]) {
  164092. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164093. if (*htblptr == NULL)
  164094. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164095. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164096. did_dc[dctbl] = TRUE;
  164097. }
  164098. if (! did_ac[actbl]) {
  164099. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164100. if (*htblptr == NULL)
  164101. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164102. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164103. did_ac[actbl] = TRUE;
  164104. }
  164105. }
  164106. }
  164107. #endif /* ENTROPY_OPT_SUPPORTED */
  164108. /*
  164109. * Module initialization routine for Huffman entropy encoding.
  164110. */
  164111. GLOBAL(void)
  164112. jinit_huff_encoder (j_compress_ptr cinfo)
  164113. {
  164114. huff_entropy_ptr entropy;
  164115. int i;
  164116. entropy = (huff_entropy_ptr)
  164117. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164118. SIZEOF(huff_entropy_encoder));
  164119. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164120. entropy->pub.start_pass = start_pass_huff;
  164121. /* Mark tables unallocated */
  164122. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164123. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164124. #ifdef ENTROPY_OPT_SUPPORTED
  164125. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164126. #endif
  164127. }
  164128. }
  164129. /*** End of inlined file: jchuff.c ***/
  164130. #undef emit_byte
  164131. /*** Start of inlined file: jcinit.c ***/
  164132. #define JPEG_INTERNALS
  164133. /*
  164134. * Master selection of compression modules.
  164135. * This is done once at the start of processing an image. We determine
  164136. * which modules will be used and give them appropriate initialization calls.
  164137. */
  164138. GLOBAL(void)
  164139. jinit_compress_master (j_compress_ptr cinfo)
  164140. {
  164141. /* Initialize master control (includes parameter checking/processing) */
  164142. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164143. /* Preprocessing */
  164144. if (! cinfo->raw_data_in) {
  164145. jinit_color_converter(cinfo);
  164146. jinit_downsampler(cinfo);
  164147. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164148. }
  164149. /* Forward DCT */
  164150. jinit_forward_dct(cinfo);
  164151. /* Entropy encoding: either Huffman or arithmetic coding. */
  164152. if (cinfo->arith_code) {
  164153. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164154. } else {
  164155. if (cinfo->progressive_mode) {
  164156. #ifdef C_PROGRESSIVE_SUPPORTED
  164157. jinit_phuff_encoder(cinfo);
  164158. #else
  164159. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164160. #endif
  164161. } else
  164162. jinit_huff_encoder(cinfo);
  164163. }
  164164. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164165. jinit_c_coef_controller(cinfo,
  164166. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164167. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164168. jinit_marker_writer(cinfo);
  164169. /* We can now tell the memory manager to allocate virtual arrays. */
  164170. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164171. /* Write the datastream header (SOI) immediately.
  164172. * Frame and scan headers are postponed till later.
  164173. * This lets application insert special markers after the SOI.
  164174. */
  164175. (*cinfo->marker->write_file_header) (cinfo);
  164176. }
  164177. /*** End of inlined file: jcinit.c ***/
  164178. /*** Start of inlined file: jcmainct.c ***/
  164179. #define JPEG_INTERNALS
  164180. /* Note: currently, there is no operating mode in which a full-image buffer
  164181. * is needed at this step. If there were, that mode could not be used with
  164182. * "raw data" input, since this module is bypassed in that case. However,
  164183. * we've left the code here for possible use in special applications.
  164184. */
  164185. #undef FULL_MAIN_BUFFER_SUPPORTED
  164186. /* Private buffer controller object */
  164187. typedef struct {
  164188. struct jpeg_c_main_controller pub; /* public fields */
  164189. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164190. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164191. boolean suspended; /* remember if we suspended output */
  164192. J_BUF_MODE pass_mode; /* current operating mode */
  164193. /* If using just a strip buffer, this points to the entire set of buffers
  164194. * (we allocate one for each component). In the full-image case, this
  164195. * points to the currently accessible strips of the virtual arrays.
  164196. */
  164197. JSAMPARRAY buffer[MAX_COMPONENTS];
  164198. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164199. /* If using full-image storage, this array holds pointers to virtual-array
  164200. * control blocks for each component. Unused if not full-image storage.
  164201. */
  164202. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164203. #endif
  164204. } my_main_controller;
  164205. typedef my_main_controller * my_main_ptr;
  164206. /* Forward declarations */
  164207. METHODDEF(void) process_data_simple_main
  164208. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164209. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164210. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164211. METHODDEF(void) process_data_buffer_main
  164212. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164213. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164214. #endif
  164215. /*
  164216. * Initialize for a processing pass.
  164217. */
  164218. METHODDEF(void)
  164219. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164220. {
  164221. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164222. /* Do nothing in raw-data mode. */
  164223. if (cinfo->raw_data_in)
  164224. return;
  164225. main_->cur_iMCU_row = 0; /* initialize counters */
  164226. main_->rowgroup_ctr = 0;
  164227. main_->suspended = FALSE;
  164228. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164229. switch (pass_mode) {
  164230. case JBUF_PASS_THRU:
  164231. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164232. if (main_->whole_image[0] != NULL)
  164233. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164234. #endif
  164235. main_->pub.process_data = process_data_simple_main;
  164236. break;
  164237. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164238. case JBUF_SAVE_SOURCE:
  164239. case JBUF_CRANK_DEST:
  164240. case JBUF_SAVE_AND_PASS:
  164241. if (main_->whole_image[0] == NULL)
  164242. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164243. main_->pub.process_data = process_data_buffer_main;
  164244. break;
  164245. #endif
  164246. default:
  164247. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164248. break;
  164249. }
  164250. }
  164251. /*
  164252. * Process some data.
  164253. * This routine handles the simple pass-through mode,
  164254. * where we have only a strip buffer.
  164255. */
  164256. METHODDEF(void)
  164257. process_data_simple_main (j_compress_ptr cinfo,
  164258. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164259. JDIMENSION in_rows_avail)
  164260. {
  164261. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164262. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164263. /* Read input data if we haven't filled the main buffer yet */
  164264. if (main_->rowgroup_ctr < DCTSIZE)
  164265. (*cinfo->prep->pre_process_data) (cinfo,
  164266. input_buf, in_row_ctr, in_rows_avail,
  164267. main_->buffer, &main_->rowgroup_ctr,
  164268. (JDIMENSION) DCTSIZE);
  164269. /* If we don't have a full iMCU row buffered, return to application for
  164270. * more data. Note that preprocessor will always pad to fill the iMCU row
  164271. * at the bottom of the image.
  164272. */
  164273. if (main_->rowgroup_ctr != DCTSIZE)
  164274. return;
  164275. /* Send the completed row to the compressor */
  164276. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164277. /* If compressor did not consume the whole row, then we must need to
  164278. * suspend processing and return to the application. In this situation
  164279. * we pretend we didn't yet consume the last input row; otherwise, if
  164280. * it happened to be the last row of the image, the application would
  164281. * think we were done.
  164282. */
  164283. if (! main_->suspended) {
  164284. (*in_row_ctr)--;
  164285. main_->suspended = TRUE;
  164286. }
  164287. return;
  164288. }
  164289. /* We did finish the row. Undo our little suspension hack if a previous
  164290. * call suspended; then mark the main buffer empty.
  164291. */
  164292. if (main_->suspended) {
  164293. (*in_row_ctr)++;
  164294. main_->suspended = FALSE;
  164295. }
  164296. main_->rowgroup_ctr = 0;
  164297. main_->cur_iMCU_row++;
  164298. }
  164299. }
  164300. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164301. /*
  164302. * Process some data.
  164303. * This routine handles all of the modes that use a full-size buffer.
  164304. */
  164305. METHODDEF(void)
  164306. process_data_buffer_main (j_compress_ptr cinfo,
  164307. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164308. JDIMENSION in_rows_avail)
  164309. {
  164310. my_main_ptr main = (my_main_ptr) cinfo->main;
  164311. int ci;
  164312. jpeg_component_info *compptr;
  164313. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164314. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164315. /* Realign the virtual buffers if at the start of an iMCU row. */
  164316. if (main->rowgroup_ctr == 0) {
  164317. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164318. ci++, compptr++) {
  164319. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164320. ((j_common_ptr) cinfo, main->whole_image[ci],
  164321. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164322. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164323. }
  164324. /* In a read pass, pretend we just read some source data. */
  164325. if (! writing) {
  164326. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164327. main->rowgroup_ctr = DCTSIZE;
  164328. }
  164329. }
  164330. /* If a write pass, read input data until the current iMCU row is full. */
  164331. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164332. if (writing) {
  164333. (*cinfo->prep->pre_process_data) (cinfo,
  164334. input_buf, in_row_ctr, in_rows_avail,
  164335. main->buffer, &main->rowgroup_ctr,
  164336. (JDIMENSION) DCTSIZE);
  164337. /* Return to application if we need more data to fill the iMCU row. */
  164338. if (main->rowgroup_ctr < DCTSIZE)
  164339. return;
  164340. }
  164341. /* Emit data, unless this is a sink-only pass. */
  164342. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164343. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164344. /* If compressor did not consume the whole row, then we must need to
  164345. * suspend processing and return to the application. In this situation
  164346. * we pretend we didn't yet consume the last input row; otherwise, if
  164347. * it happened to be the last row of the image, the application would
  164348. * think we were done.
  164349. */
  164350. if (! main->suspended) {
  164351. (*in_row_ctr)--;
  164352. main->suspended = TRUE;
  164353. }
  164354. return;
  164355. }
  164356. /* We did finish the row. Undo our little suspension hack if a previous
  164357. * call suspended; then mark the main buffer empty.
  164358. */
  164359. if (main->suspended) {
  164360. (*in_row_ctr)++;
  164361. main->suspended = FALSE;
  164362. }
  164363. }
  164364. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164365. main->rowgroup_ctr = 0;
  164366. main->cur_iMCU_row++;
  164367. }
  164368. }
  164369. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164370. /*
  164371. * Initialize main buffer controller.
  164372. */
  164373. GLOBAL(void)
  164374. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164375. {
  164376. my_main_ptr main_;
  164377. int ci;
  164378. jpeg_component_info *compptr;
  164379. main_ = (my_main_ptr)
  164380. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164381. SIZEOF(my_main_controller));
  164382. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164383. main_->pub.start_pass = start_pass_main;
  164384. /* We don't need to create a buffer in raw-data mode. */
  164385. if (cinfo->raw_data_in)
  164386. return;
  164387. /* Create the buffer. It holds downsampled data, so each component
  164388. * may be of a different size.
  164389. */
  164390. if (need_full_buffer) {
  164391. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164392. /* Allocate a full-image virtual array for each component */
  164393. /* Note we pad the bottom to a multiple of the iMCU height */
  164394. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164395. ci++, compptr++) {
  164396. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164397. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164398. compptr->width_in_blocks * DCTSIZE,
  164399. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164400. (long) compptr->v_samp_factor) * DCTSIZE,
  164401. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164402. }
  164403. #else
  164404. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164405. #endif
  164406. } else {
  164407. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164408. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164409. #endif
  164410. /* Allocate a strip buffer for each component */
  164411. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164412. ci++, compptr++) {
  164413. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164414. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164415. compptr->width_in_blocks * DCTSIZE,
  164416. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164417. }
  164418. }
  164419. }
  164420. /*** End of inlined file: jcmainct.c ***/
  164421. /*** Start of inlined file: jcmarker.c ***/
  164422. #define JPEG_INTERNALS
  164423. /* Private state */
  164424. typedef struct {
  164425. struct jpeg_marker_writer pub; /* public fields */
  164426. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164427. } my_marker_writer;
  164428. typedef my_marker_writer * my_marker_ptr;
  164429. /*
  164430. * Basic output routines.
  164431. *
  164432. * Note that we do not support suspension while writing a marker.
  164433. * Therefore, an application using suspension must ensure that there is
  164434. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164435. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164436. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164437. * modes are not supported at all with suspension, so those two are the only
  164438. * points where markers will be written.
  164439. */
  164440. LOCAL(void)
  164441. emit_byte (j_compress_ptr cinfo, int val)
  164442. /* Emit a byte */
  164443. {
  164444. struct jpeg_destination_mgr * dest = cinfo->dest;
  164445. *(dest->next_output_byte)++ = (JOCTET) val;
  164446. if (--dest->free_in_buffer == 0) {
  164447. if (! (*dest->empty_output_buffer) (cinfo))
  164448. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164449. }
  164450. }
  164451. LOCAL(void)
  164452. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164453. /* Emit a marker code */
  164454. {
  164455. emit_byte(cinfo, 0xFF);
  164456. emit_byte(cinfo, (int) mark);
  164457. }
  164458. LOCAL(void)
  164459. emit_2bytes (j_compress_ptr cinfo, int value)
  164460. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164461. {
  164462. emit_byte(cinfo, (value >> 8) & 0xFF);
  164463. emit_byte(cinfo, value & 0xFF);
  164464. }
  164465. /*
  164466. * Routines to write specific marker types.
  164467. */
  164468. LOCAL(int)
  164469. emit_dqt (j_compress_ptr cinfo, int index)
  164470. /* Emit a DQT marker */
  164471. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164472. {
  164473. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164474. int prec;
  164475. int i;
  164476. if (qtbl == NULL)
  164477. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164478. prec = 0;
  164479. for (i = 0; i < DCTSIZE2; i++) {
  164480. if (qtbl->quantval[i] > 255)
  164481. prec = 1;
  164482. }
  164483. if (! qtbl->sent_table) {
  164484. emit_marker(cinfo, M_DQT);
  164485. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164486. emit_byte(cinfo, index + (prec<<4));
  164487. for (i = 0; i < DCTSIZE2; i++) {
  164488. /* The table entries must be emitted in zigzag order. */
  164489. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164490. if (prec)
  164491. emit_byte(cinfo, (int) (qval >> 8));
  164492. emit_byte(cinfo, (int) (qval & 0xFF));
  164493. }
  164494. qtbl->sent_table = TRUE;
  164495. }
  164496. return prec;
  164497. }
  164498. LOCAL(void)
  164499. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164500. /* Emit a DHT marker */
  164501. {
  164502. JHUFF_TBL * htbl;
  164503. int length, i;
  164504. if (is_ac) {
  164505. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164506. index += 0x10; /* output index has AC bit set */
  164507. } else {
  164508. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164509. }
  164510. if (htbl == NULL)
  164511. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164512. if (! htbl->sent_table) {
  164513. emit_marker(cinfo, M_DHT);
  164514. length = 0;
  164515. for (i = 1; i <= 16; i++)
  164516. length += htbl->bits[i];
  164517. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164518. emit_byte(cinfo, index);
  164519. for (i = 1; i <= 16; i++)
  164520. emit_byte(cinfo, htbl->bits[i]);
  164521. for (i = 0; i < length; i++)
  164522. emit_byte(cinfo, htbl->huffval[i]);
  164523. htbl->sent_table = TRUE;
  164524. }
  164525. }
  164526. LOCAL(void)
  164527. emit_dac (j_compress_ptr)
  164528. /* Emit a DAC marker */
  164529. /* Since the useful info is so small, we want to emit all the tables in */
  164530. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164531. {
  164532. #ifdef C_ARITH_CODING_SUPPORTED
  164533. char dc_in_use[NUM_ARITH_TBLS];
  164534. char ac_in_use[NUM_ARITH_TBLS];
  164535. int length, i;
  164536. jpeg_component_info *compptr;
  164537. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164538. dc_in_use[i] = ac_in_use[i] = 0;
  164539. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164540. compptr = cinfo->cur_comp_info[i];
  164541. dc_in_use[compptr->dc_tbl_no] = 1;
  164542. ac_in_use[compptr->ac_tbl_no] = 1;
  164543. }
  164544. length = 0;
  164545. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164546. length += dc_in_use[i] + ac_in_use[i];
  164547. emit_marker(cinfo, M_DAC);
  164548. emit_2bytes(cinfo, length*2 + 2);
  164549. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164550. if (dc_in_use[i]) {
  164551. emit_byte(cinfo, i);
  164552. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164553. }
  164554. if (ac_in_use[i]) {
  164555. emit_byte(cinfo, i + 0x10);
  164556. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164557. }
  164558. }
  164559. #endif /* C_ARITH_CODING_SUPPORTED */
  164560. }
  164561. LOCAL(void)
  164562. emit_dri (j_compress_ptr cinfo)
  164563. /* Emit a DRI marker */
  164564. {
  164565. emit_marker(cinfo, M_DRI);
  164566. emit_2bytes(cinfo, 4); /* fixed length */
  164567. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164568. }
  164569. LOCAL(void)
  164570. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164571. /* Emit a SOF marker */
  164572. {
  164573. int ci;
  164574. jpeg_component_info *compptr;
  164575. emit_marker(cinfo, code);
  164576. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164577. /* Make sure image isn't bigger than SOF field can handle */
  164578. if ((long) cinfo->image_height > 65535L ||
  164579. (long) cinfo->image_width > 65535L)
  164580. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164581. emit_byte(cinfo, cinfo->data_precision);
  164582. emit_2bytes(cinfo, (int) cinfo->image_height);
  164583. emit_2bytes(cinfo, (int) cinfo->image_width);
  164584. emit_byte(cinfo, cinfo->num_components);
  164585. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164586. ci++, compptr++) {
  164587. emit_byte(cinfo, compptr->component_id);
  164588. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164589. emit_byte(cinfo, compptr->quant_tbl_no);
  164590. }
  164591. }
  164592. LOCAL(void)
  164593. emit_sos (j_compress_ptr cinfo)
  164594. /* Emit a SOS marker */
  164595. {
  164596. int i, td, ta;
  164597. jpeg_component_info *compptr;
  164598. emit_marker(cinfo, M_SOS);
  164599. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164600. emit_byte(cinfo, cinfo->comps_in_scan);
  164601. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164602. compptr = cinfo->cur_comp_info[i];
  164603. emit_byte(cinfo, compptr->component_id);
  164604. td = compptr->dc_tbl_no;
  164605. ta = compptr->ac_tbl_no;
  164606. if (cinfo->progressive_mode) {
  164607. /* Progressive mode: only DC or only AC tables are used in one scan;
  164608. * furthermore, Huffman coding of DC refinement uses no table at all.
  164609. * We emit 0 for unused field(s); this is recommended by the P&M text
  164610. * but does not seem to be specified in the standard.
  164611. */
  164612. if (cinfo->Ss == 0) {
  164613. ta = 0; /* DC scan */
  164614. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164615. td = 0; /* no DC table either */
  164616. } else {
  164617. td = 0; /* AC scan */
  164618. }
  164619. }
  164620. emit_byte(cinfo, (td << 4) + ta);
  164621. }
  164622. emit_byte(cinfo, cinfo->Ss);
  164623. emit_byte(cinfo, cinfo->Se);
  164624. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164625. }
  164626. LOCAL(void)
  164627. emit_jfif_app0 (j_compress_ptr cinfo)
  164628. /* Emit a JFIF-compliant APP0 marker */
  164629. {
  164630. /*
  164631. * Length of APP0 block (2 bytes)
  164632. * Block ID (4 bytes - ASCII "JFIF")
  164633. * Zero byte (1 byte to terminate the ID string)
  164634. * Version Major, Minor (2 bytes - major first)
  164635. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164636. * Xdpu (2 bytes - dots per unit horizontal)
  164637. * Ydpu (2 bytes - dots per unit vertical)
  164638. * Thumbnail X size (1 byte)
  164639. * Thumbnail Y size (1 byte)
  164640. */
  164641. emit_marker(cinfo, M_APP0);
  164642. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164643. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164644. emit_byte(cinfo, 0x46);
  164645. emit_byte(cinfo, 0x49);
  164646. emit_byte(cinfo, 0x46);
  164647. emit_byte(cinfo, 0);
  164648. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164649. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164650. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164651. emit_2bytes(cinfo, (int) cinfo->X_density);
  164652. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164653. emit_byte(cinfo, 0); /* No thumbnail image */
  164654. emit_byte(cinfo, 0);
  164655. }
  164656. LOCAL(void)
  164657. emit_adobe_app14 (j_compress_ptr cinfo)
  164658. /* Emit an Adobe APP14 marker */
  164659. {
  164660. /*
  164661. * Length of APP14 block (2 bytes)
  164662. * Block ID (5 bytes - ASCII "Adobe")
  164663. * Version Number (2 bytes - currently 100)
  164664. * Flags0 (2 bytes - currently 0)
  164665. * Flags1 (2 bytes - currently 0)
  164666. * Color transform (1 byte)
  164667. *
  164668. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164669. * now in circulation seem to use Version = 100, so that's what we write.
  164670. *
  164671. * We write the color transform byte as 1 if the JPEG color space is
  164672. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164673. * whether the encoder performed a transformation, which is pretty useless.
  164674. */
  164675. emit_marker(cinfo, M_APP14);
  164676. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164677. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164678. emit_byte(cinfo, 0x64);
  164679. emit_byte(cinfo, 0x6F);
  164680. emit_byte(cinfo, 0x62);
  164681. emit_byte(cinfo, 0x65);
  164682. emit_2bytes(cinfo, 100); /* Version */
  164683. emit_2bytes(cinfo, 0); /* Flags0 */
  164684. emit_2bytes(cinfo, 0); /* Flags1 */
  164685. switch (cinfo->jpeg_color_space) {
  164686. case JCS_YCbCr:
  164687. emit_byte(cinfo, 1); /* Color transform = 1 */
  164688. break;
  164689. case JCS_YCCK:
  164690. emit_byte(cinfo, 2); /* Color transform = 2 */
  164691. break;
  164692. default:
  164693. emit_byte(cinfo, 0); /* Color transform = 0 */
  164694. break;
  164695. }
  164696. }
  164697. /*
  164698. * These routines allow writing an arbitrary marker with parameters.
  164699. * The only intended use is to emit COM or APPn markers after calling
  164700. * write_file_header and before calling write_frame_header.
  164701. * Other uses are not guaranteed to produce desirable results.
  164702. * Counting the parameter bytes properly is the caller's responsibility.
  164703. */
  164704. METHODDEF(void)
  164705. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164706. /* Emit an arbitrary marker header */
  164707. {
  164708. if (datalen > (unsigned int) 65533) /* safety check */
  164709. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164710. emit_marker(cinfo, (JPEG_MARKER) marker);
  164711. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164712. }
  164713. METHODDEF(void)
  164714. write_marker_byte (j_compress_ptr cinfo, int val)
  164715. /* Emit one byte of marker parameters following write_marker_header */
  164716. {
  164717. emit_byte(cinfo, val);
  164718. }
  164719. /*
  164720. * Write datastream header.
  164721. * This consists of an SOI and optional APPn markers.
  164722. * We recommend use of the JFIF marker, but not the Adobe marker,
  164723. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164724. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164725. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164726. * Note that an application can write additional header markers after
  164727. * jpeg_start_compress returns.
  164728. */
  164729. METHODDEF(void)
  164730. write_file_header (j_compress_ptr cinfo)
  164731. {
  164732. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164733. emit_marker(cinfo, M_SOI); /* first the SOI */
  164734. /* SOI is defined to reset restart interval to 0 */
  164735. marker->last_restart_interval = 0;
  164736. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164737. emit_jfif_app0(cinfo);
  164738. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164739. emit_adobe_app14(cinfo);
  164740. }
  164741. /*
  164742. * Write frame header.
  164743. * This consists of DQT and SOFn markers.
  164744. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164745. * This avoids compatibility problems with incorrect implementations that
  164746. * try to error-check the quant table numbers as soon as they see the SOF.
  164747. */
  164748. METHODDEF(void)
  164749. write_frame_header (j_compress_ptr cinfo)
  164750. {
  164751. int ci, prec;
  164752. boolean is_baseline;
  164753. jpeg_component_info *compptr;
  164754. /* Emit DQT for each quantization table.
  164755. * Note that emit_dqt() suppresses any duplicate tables.
  164756. */
  164757. prec = 0;
  164758. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164759. ci++, compptr++) {
  164760. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164761. }
  164762. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164763. /* Check for a non-baseline specification.
  164764. * Note we assume that Huffman table numbers won't be changed later.
  164765. */
  164766. if (cinfo->arith_code || cinfo->progressive_mode ||
  164767. cinfo->data_precision != 8) {
  164768. is_baseline = FALSE;
  164769. } else {
  164770. is_baseline = TRUE;
  164771. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164772. ci++, compptr++) {
  164773. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164774. is_baseline = FALSE;
  164775. }
  164776. if (prec && is_baseline) {
  164777. is_baseline = FALSE;
  164778. /* If it's baseline except for quantizer size, warn the user */
  164779. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164780. }
  164781. }
  164782. /* Emit the proper SOF marker */
  164783. if (cinfo->arith_code) {
  164784. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164785. } else {
  164786. if (cinfo->progressive_mode)
  164787. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164788. else if (is_baseline)
  164789. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164790. else
  164791. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164792. }
  164793. }
  164794. /*
  164795. * Write scan header.
  164796. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164797. * Compressed data will be written following the SOS.
  164798. */
  164799. METHODDEF(void)
  164800. write_scan_header (j_compress_ptr cinfo)
  164801. {
  164802. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164803. int i;
  164804. jpeg_component_info *compptr;
  164805. if (cinfo->arith_code) {
  164806. /* Emit arith conditioning info. We may have some duplication
  164807. * if the file has multiple scans, but it's so small it's hardly
  164808. * worth worrying about.
  164809. */
  164810. emit_dac(cinfo);
  164811. } else {
  164812. /* Emit Huffman tables.
  164813. * Note that emit_dht() suppresses any duplicate tables.
  164814. */
  164815. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164816. compptr = cinfo->cur_comp_info[i];
  164817. if (cinfo->progressive_mode) {
  164818. /* Progressive mode: only DC or only AC tables are used in one scan */
  164819. if (cinfo->Ss == 0) {
  164820. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164821. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164822. } else {
  164823. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164824. }
  164825. } else {
  164826. /* Sequential mode: need both DC and AC tables */
  164827. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164828. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164829. }
  164830. }
  164831. }
  164832. /* Emit DRI if required --- note that DRI value could change for each scan.
  164833. * We avoid wasting space with unnecessary DRIs, however.
  164834. */
  164835. if (cinfo->restart_interval != marker->last_restart_interval) {
  164836. emit_dri(cinfo);
  164837. marker->last_restart_interval = cinfo->restart_interval;
  164838. }
  164839. emit_sos(cinfo);
  164840. }
  164841. /*
  164842. * Write datastream trailer.
  164843. */
  164844. METHODDEF(void)
  164845. write_file_trailer (j_compress_ptr cinfo)
  164846. {
  164847. emit_marker(cinfo, M_EOI);
  164848. }
  164849. /*
  164850. * Write an abbreviated table-specification datastream.
  164851. * This consists of SOI, DQT and DHT tables, and EOI.
  164852. * Any table that is defined and not marked sent_table = TRUE will be
  164853. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164854. */
  164855. METHODDEF(void)
  164856. write_tables_only (j_compress_ptr cinfo)
  164857. {
  164858. int i;
  164859. emit_marker(cinfo, M_SOI);
  164860. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164861. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164862. (void) emit_dqt(cinfo, i);
  164863. }
  164864. if (! cinfo->arith_code) {
  164865. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164866. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164867. emit_dht(cinfo, i, FALSE);
  164868. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164869. emit_dht(cinfo, i, TRUE);
  164870. }
  164871. }
  164872. emit_marker(cinfo, M_EOI);
  164873. }
  164874. /*
  164875. * Initialize the marker writer module.
  164876. */
  164877. GLOBAL(void)
  164878. jinit_marker_writer (j_compress_ptr cinfo)
  164879. {
  164880. my_marker_ptr marker;
  164881. /* Create the subobject */
  164882. marker = (my_marker_ptr)
  164883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164884. SIZEOF(my_marker_writer));
  164885. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164886. /* Initialize method pointers */
  164887. marker->pub.write_file_header = write_file_header;
  164888. marker->pub.write_frame_header = write_frame_header;
  164889. marker->pub.write_scan_header = write_scan_header;
  164890. marker->pub.write_file_trailer = write_file_trailer;
  164891. marker->pub.write_tables_only = write_tables_only;
  164892. marker->pub.write_marker_header = write_marker_header;
  164893. marker->pub.write_marker_byte = write_marker_byte;
  164894. /* Initialize private state */
  164895. marker->last_restart_interval = 0;
  164896. }
  164897. /*** End of inlined file: jcmarker.c ***/
  164898. /*** Start of inlined file: jcmaster.c ***/
  164899. #define JPEG_INTERNALS
  164900. /* Private state */
  164901. typedef enum {
  164902. main_pass, /* input data, also do first output step */
  164903. huff_opt_pass, /* Huffman code optimization pass */
  164904. output_pass /* data output pass */
  164905. } c_pass_type;
  164906. typedef struct {
  164907. struct jpeg_comp_master pub; /* public fields */
  164908. c_pass_type pass_type; /* the type of the current pass */
  164909. int pass_number; /* # of passes completed */
  164910. int total_passes; /* total # of passes needed */
  164911. int scan_number; /* current index in scan_info[] */
  164912. } my_comp_master;
  164913. typedef my_comp_master * my_master_ptr;
  164914. /*
  164915. * Support routines that do various essential calculations.
  164916. */
  164917. LOCAL(void)
  164918. initial_setup (j_compress_ptr cinfo)
  164919. /* Do computations that are needed before master selection phase */
  164920. {
  164921. int ci;
  164922. jpeg_component_info *compptr;
  164923. long samplesperrow;
  164924. JDIMENSION jd_samplesperrow;
  164925. /* Sanity check on image dimensions */
  164926. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164927. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164928. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164929. /* Make sure image isn't bigger than I can handle */
  164930. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164931. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164932. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164933. /* Width of an input scanline must be representable as JDIMENSION. */
  164934. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164935. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164936. if ((long) jd_samplesperrow != samplesperrow)
  164937. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164938. /* For now, precision must match compiled-in value... */
  164939. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164940. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164941. /* Check that number of components won't exceed internal array sizes */
  164942. if (cinfo->num_components > MAX_COMPONENTS)
  164943. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164944. MAX_COMPONENTS);
  164945. /* Compute maximum sampling factors; check factor validity */
  164946. cinfo->max_h_samp_factor = 1;
  164947. cinfo->max_v_samp_factor = 1;
  164948. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164949. ci++, compptr++) {
  164950. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164951. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164952. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164953. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164954. compptr->h_samp_factor);
  164955. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164956. compptr->v_samp_factor);
  164957. }
  164958. /* Compute dimensions of components */
  164959. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164960. ci++, compptr++) {
  164961. /* Fill in the correct component_index value; don't rely on application */
  164962. compptr->component_index = ci;
  164963. /* For compression, we never do DCT scaling. */
  164964. compptr->DCT_scaled_size = DCTSIZE;
  164965. /* Size in DCT blocks */
  164966. compptr->width_in_blocks = (JDIMENSION)
  164967. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164968. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164969. compptr->height_in_blocks = (JDIMENSION)
  164970. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164971. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164972. /* Size in samples */
  164973. compptr->downsampled_width = (JDIMENSION)
  164974. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164975. (long) cinfo->max_h_samp_factor);
  164976. compptr->downsampled_height = (JDIMENSION)
  164977. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164978. (long) cinfo->max_v_samp_factor);
  164979. /* Mark component needed (this flag isn't actually used for compression) */
  164980. compptr->component_needed = TRUE;
  164981. }
  164982. /* Compute number of fully interleaved MCU rows (number of times that
  164983. * main controller will call coefficient controller).
  164984. */
  164985. cinfo->total_iMCU_rows = (JDIMENSION)
  164986. jdiv_round_up((long) cinfo->image_height,
  164987. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164988. }
  164989. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164990. LOCAL(void)
  164991. validate_script (j_compress_ptr cinfo)
  164992. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164993. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164994. */
  164995. {
  164996. const jpeg_scan_info * scanptr;
  164997. int scanno, ncomps, ci, coefi, thisi;
  164998. int Ss, Se, Ah, Al;
  164999. boolean component_sent[MAX_COMPONENTS];
  165000. #ifdef C_PROGRESSIVE_SUPPORTED
  165001. int * last_bitpos_ptr;
  165002. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  165003. /* -1 until that coefficient has been seen; then last Al for it */
  165004. #endif
  165005. if (cinfo->num_scans <= 0)
  165006. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  165007. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  165008. * for progressive JPEG, no scan can have this.
  165009. */
  165010. scanptr = cinfo->scan_info;
  165011. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  165012. #ifdef C_PROGRESSIVE_SUPPORTED
  165013. cinfo->progressive_mode = TRUE;
  165014. last_bitpos_ptr = & last_bitpos[0][0];
  165015. for (ci = 0; ci < cinfo->num_components; ci++)
  165016. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  165017. *last_bitpos_ptr++ = -1;
  165018. #else
  165019. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165020. #endif
  165021. } else {
  165022. cinfo->progressive_mode = FALSE;
  165023. for (ci = 0; ci < cinfo->num_components; ci++)
  165024. component_sent[ci] = FALSE;
  165025. }
  165026. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  165027. /* Validate component indexes */
  165028. ncomps = scanptr->comps_in_scan;
  165029. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165030. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165031. for (ci = 0; ci < ncomps; ci++) {
  165032. thisi = scanptr->component_index[ci];
  165033. if (thisi < 0 || thisi >= cinfo->num_components)
  165034. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165035. /* Components must appear in SOF order within each scan */
  165036. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165037. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165038. }
  165039. /* Validate progression parameters */
  165040. Ss = scanptr->Ss;
  165041. Se = scanptr->Se;
  165042. Ah = scanptr->Ah;
  165043. Al = scanptr->Al;
  165044. if (cinfo->progressive_mode) {
  165045. #ifdef C_PROGRESSIVE_SUPPORTED
  165046. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165047. * seems wrong: the upper bound ought to depend on data precision.
  165048. * Perhaps they really meant 0..N+1 for N-bit precision.
  165049. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165050. * out-of-range reconstructed DC values during the first DC scan,
  165051. * which might cause problems for some decoders.
  165052. */
  165053. #if BITS_IN_JSAMPLE == 8
  165054. #define MAX_AH_AL 10
  165055. #else
  165056. #define MAX_AH_AL 13
  165057. #endif
  165058. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165059. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165060. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165061. if (Ss == 0) {
  165062. if (Se != 0) /* DC and AC together not OK */
  165063. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165064. } else {
  165065. if (ncomps != 1) /* AC scans must be for only one component */
  165066. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165067. }
  165068. for (ci = 0; ci < ncomps; ci++) {
  165069. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165070. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165071. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165072. for (coefi = Ss; coefi <= Se; coefi++) {
  165073. if (last_bitpos_ptr[coefi] < 0) {
  165074. /* first scan of this coefficient */
  165075. if (Ah != 0)
  165076. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165077. } else {
  165078. /* not first scan */
  165079. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165080. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165081. }
  165082. last_bitpos_ptr[coefi] = Al;
  165083. }
  165084. }
  165085. #endif
  165086. } else {
  165087. /* For sequential JPEG, all progression parameters must be these: */
  165088. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165089. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165090. /* Make sure components are not sent twice */
  165091. for (ci = 0; ci < ncomps; ci++) {
  165092. thisi = scanptr->component_index[ci];
  165093. if (component_sent[thisi])
  165094. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165095. component_sent[thisi] = TRUE;
  165096. }
  165097. }
  165098. }
  165099. /* Now verify that everything got sent. */
  165100. if (cinfo->progressive_mode) {
  165101. #ifdef C_PROGRESSIVE_SUPPORTED
  165102. /* For progressive mode, we only check that at least some DC data
  165103. * got sent for each component; the spec does not require that all bits
  165104. * of all coefficients be transmitted. Would it be wiser to enforce
  165105. * transmission of all coefficient bits??
  165106. */
  165107. for (ci = 0; ci < cinfo->num_components; ci++) {
  165108. if (last_bitpos[ci][0] < 0)
  165109. ERREXIT(cinfo, JERR_MISSING_DATA);
  165110. }
  165111. #endif
  165112. } else {
  165113. for (ci = 0; ci < cinfo->num_components; ci++) {
  165114. if (! component_sent[ci])
  165115. ERREXIT(cinfo, JERR_MISSING_DATA);
  165116. }
  165117. }
  165118. }
  165119. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165120. LOCAL(void)
  165121. select_scan_parameters (j_compress_ptr cinfo)
  165122. /* Set up the scan parameters for the current scan */
  165123. {
  165124. int ci;
  165125. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165126. if (cinfo->scan_info != NULL) {
  165127. /* Prepare for current scan --- the script is already validated */
  165128. my_master_ptr master = (my_master_ptr) cinfo->master;
  165129. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165130. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165131. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165132. cinfo->cur_comp_info[ci] =
  165133. &cinfo->comp_info[scanptr->component_index[ci]];
  165134. }
  165135. cinfo->Ss = scanptr->Ss;
  165136. cinfo->Se = scanptr->Se;
  165137. cinfo->Ah = scanptr->Ah;
  165138. cinfo->Al = scanptr->Al;
  165139. }
  165140. else
  165141. #endif
  165142. {
  165143. /* Prepare for single sequential-JPEG scan containing all components */
  165144. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165145. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165146. MAX_COMPS_IN_SCAN);
  165147. cinfo->comps_in_scan = cinfo->num_components;
  165148. for (ci = 0; ci < cinfo->num_components; ci++) {
  165149. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165150. }
  165151. cinfo->Ss = 0;
  165152. cinfo->Se = DCTSIZE2-1;
  165153. cinfo->Ah = 0;
  165154. cinfo->Al = 0;
  165155. }
  165156. }
  165157. LOCAL(void)
  165158. per_scan_setup (j_compress_ptr cinfo)
  165159. /* Do computations that are needed before processing a JPEG scan */
  165160. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165161. {
  165162. int ci, mcublks, tmp;
  165163. jpeg_component_info *compptr;
  165164. if (cinfo->comps_in_scan == 1) {
  165165. /* Noninterleaved (single-component) scan */
  165166. compptr = cinfo->cur_comp_info[0];
  165167. /* Overall image size in MCUs */
  165168. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165169. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165170. /* For noninterleaved scan, always one block per MCU */
  165171. compptr->MCU_width = 1;
  165172. compptr->MCU_height = 1;
  165173. compptr->MCU_blocks = 1;
  165174. compptr->MCU_sample_width = DCTSIZE;
  165175. compptr->last_col_width = 1;
  165176. /* For noninterleaved scans, it is convenient to define last_row_height
  165177. * as the number of block rows present in the last iMCU row.
  165178. */
  165179. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165180. if (tmp == 0) tmp = compptr->v_samp_factor;
  165181. compptr->last_row_height = tmp;
  165182. /* Prepare array describing MCU composition */
  165183. cinfo->blocks_in_MCU = 1;
  165184. cinfo->MCU_membership[0] = 0;
  165185. } else {
  165186. /* Interleaved (multi-component) scan */
  165187. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165188. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165189. MAX_COMPS_IN_SCAN);
  165190. /* Overall image size in MCUs */
  165191. cinfo->MCUs_per_row = (JDIMENSION)
  165192. jdiv_round_up((long) cinfo->image_width,
  165193. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165194. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165195. jdiv_round_up((long) cinfo->image_height,
  165196. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165197. cinfo->blocks_in_MCU = 0;
  165198. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165199. compptr = cinfo->cur_comp_info[ci];
  165200. /* Sampling factors give # of blocks of component in each MCU */
  165201. compptr->MCU_width = compptr->h_samp_factor;
  165202. compptr->MCU_height = compptr->v_samp_factor;
  165203. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165204. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165205. /* Figure number of non-dummy blocks in last MCU column & row */
  165206. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165207. if (tmp == 0) tmp = compptr->MCU_width;
  165208. compptr->last_col_width = tmp;
  165209. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165210. if (tmp == 0) tmp = compptr->MCU_height;
  165211. compptr->last_row_height = tmp;
  165212. /* Prepare array describing MCU composition */
  165213. mcublks = compptr->MCU_blocks;
  165214. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165215. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165216. while (mcublks-- > 0) {
  165217. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165218. }
  165219. }
  165220. }
  165221. /* Convert restart specified in rows to actual MCU count. */
  165222. /* Note that count must fit in 16 bits, so we provide limiting. */
  165223. if (cinfo->restart_in_rows > 0) {
  165224. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165225. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165226. }
  165227. }
  165228. /*
  165229. * Per-pass setup.
  165230. * This is called at the beginning of each pass. We determine which modules
  165231. * will be active during this pass and give them appropriate start_pass calls.
  165232. * We also set is_last_pass to indicate whether any more passes will be
  165233. * required.
  165234. */
  165235. METHODDEF(void)
  165236. prepare_for_pass (j_compress_ptr cinfo)
  165237. {
  165238. my_master_ptr master = (my_master_ptr) cinfo->master;
  165239. switch (master->pass_type) {
  165240. case main_pass:
  165241. /* Initial pass: will collect input data, and do either Huffman
  165242. * optimization or data output for the first scan.
  165243. */
  165244. select_scan_parameters(cinfo);
  165245. per_scan_setup(cinfo);
  165246. if (! cinfo->raw_data_in) {
  165247. (*cinfo->cconvert->start_pass) (cinfo);
  165248. (*cinfo->downsample->start_pass) (cinfo);
  165249. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165250. }
  165251. (*cinfo->fdct->start_pass) (cinfo);
  165252. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165253. (*cinfo->coef->start_pass) (cinfo,
  165254. (master->total_passes > 1 ?
  165255. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165256. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165257. if (cinfo->optimize_coding) {
  165258. /* No immediate data output; postpone writing frame/scan headers */
  165259. master->pub.call_pass_startup = FALSE;
  165260. } else {
  165261. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165262. master->pub.call_pass_startup = TRUE;
  165263. }
  165264. break;
  165265. #ifdef ENTROPY_OPT_SUPPORTED
  165266. case huff_opt_pass:
  165267. /* Do Huffman optimization for a scan after the first one. */
  165268. select_scan_parameters(cinfo);
  165269. per_scan_setup(cinfo);
  165270. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165271. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165272. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165273. master->pub.call_pass_startup = FALSE;
  165274. break;
  165275. }
  165276. /* Special case: Huffman DC refinement scans need no Huffman table
  165277. * and therefore we can skip the optimization pass for them.
  165278. */
  165279. master->pass_type = output_pass;
  165280. master->pass_number++;
  165281. /*FALLTHROUGH*/
  165282. #endif
  165283. case output_pass:
  165284. /* Do a data-output pass. */
  165285. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165286. if (! cinfo->optimize_coding) {
  165287. select_scan_parameters(cinfo);
  165288. per_scan_setup(cinfo);
  165289. }
  165290. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165291. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165292. /* We emit frame/scan headers now */
  165293. if (master->scan_number == 0)
  165294. (*cinfo->marker->write_frame_header) (cinfo);
  165295. (*cinfo->marker->write_scan_header) (cinfo);
  165296. master->pub.call_pass_startup = FALSE;
  165297. break;
  165298. default:
  165299. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165300. }
  165301. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165302. /* Set up progress monitor's pass info if present */
  165303. if (cinfo->progress != NULL) {
  165304. cinfo->progress->completed_passes = master->pass_number;
  165305. cinfo->progress->total_passes = master->total_passes;
  165306. }
  165307. }
  165308. /*
  165309. * Special start-of-pass hook.
  165310. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165311. * In single-pass processing, we need this hook because we don't want to
  165312. * write frame/scan headers during jpeg_start_compress; we want to let the
  165313. * application write COM markers etc. between jpeg_start_compress and the
  165314. * jpeg_write_scanlines loop.
  165315. * In multi-pass processing, this routine is not used.
  165316. */
  165317. METHODDEF(void)
  165318. pass_startup (j_compress_ptr cinfo)
  165319. {
  165320. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165321. (*cinfo->marker->write_frame_header) (cinfo);
  165322. (*cinfo->marker->write_scan_header) (cinfo);
  165323. }
  165324. /*
  165325. * Finish up at end of pass.
  165326. */
  165327. METHODDEF(void)
  165328. finish_pass_master (j_compress_ptr cinfo)
  165329. {
  165330. my_master_ptr master = (my_master_ptr) cinfo->master;
  165331. /* The entropy coder always needs an end-of-pass call,
  165332. * either to analyze statistics or to flush its output buffer.
  165333. */
  165334. (*cinfo->entropy->finish_pass) (cinfo);
  165335. /* Update state for next pass */
  165336. switch (master->pass_type) {
  165337. case main_pass:
  165338. /* next pass is either output of scan 0 (after optimization)
  165339. * or output of scan 1 (if no optimization).
  165340. */
  165341. master->pass_type = output_pass;
  165342. if (! cinfo->optimize_coding)
  165343. master->scan_number++;
  165344. break;
  165345. case huff_opt_pass:
  165346. /* next pass is always output of current scan */
  165347. master->pass_type = output_pass;
  165348. break;
  165349. case output_pass:
  165350. /* next pass is either optimization or output of next scan */
  165351. if (cinfo->optimize_coding)
  165352. master->pass_type = huff_opt_pass;
  165353. master->scan_number++;
  165354. break;
  165355. }
  165356. master->pass_number++;
  165357. }
  165358. /*
  165359. * Initialize master compression control.
  165360. */
  165361. GLOBAL(void)
  165362. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165363. {
  165364. my_master_ptr master;
  165365. master = (my_master_ptr)
  165366. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165367. SIZEOF(my_comp_master));
  165368. cinfo->master = (struct jpeg_comp_master *) master;
  165369. master->pub.prepare_for_pass = prepare_for_pass;
  165370. master->pub.pass_startup = pass_startup;
  165371. master->pub.finish_pass = finish_pass_master;
  165372. master->pub.is_last_pass = FALSE;
  165373. /* Validate parameters, determine derived values */
  165374. initial_setup(cinfo);
  165375. if (cinfo->scan_info != NULL) {
  165376. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165377. validate_script(cinfo);
  165378. #else
  165379. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165380. #endif
  165381. } else {
  165382. cinfo->progressive_mode = FALSE;
  165383. cinfo->num_scans = 1;
  165384. }
  165385. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165386. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165387. /* Initialize my private state */
  165388. if (transcode_only) {
  165389. /* no main pass in transcoding */
  165390. if (cinfo->optimize_coding)
  165391. master->pass_type = huff_opt_pass;
  165392. else
  165393. master->pass_type = output_pass;
  165394. } else {
  165395. /* for normal compression, first pass is always this type: */
  165396. master->pass_type = main_pass;
  165397. }
  165398. master->scan_number = 0;
  165399. master->pass_number = 0;
  165400. if (cinfo->optimize_coding)
  165401. master->total_passes = cinfo->num_scans * 2;
  165402. else
  165403. master->total_passes = cinfo->num_scans;
  165404. }
  165405. /*** End of inlined file: jcmaster.c ***/
  165406. /*** Start of inlined file: jcomapi.c ***/
  165407. #define JPEG_INTERNALS
  165408. /*
  165409. * Abort processing of a JPEG compression or decompression operation,
  165410. * but don't destroy the object itself.
  165411. *
  165412. * For this, we merely clean up all the nonpermanent memory pools.
  165413. * Note that temp files (virtual arrays) are not allowed to belong to
  165414. * the permanent pool, so we will be able to close all temp files here.
  165415. * Closing a data source or destination, if necessary, is the application's
  165416. * responsibility.
  165417. */
  165418. GLOBAL(void)
  165419. jpeg_abort (j_common_ptr cinfo)
  165420. {
  165421. int pool;
  165422. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165423. if (cinfo->mem == NULL)
  165424. return;
  165425. /* Releasing pools in reverse order might help avoid fragmentation
  165426. * with some (brain-damaged) malloc libraries.
  165427. */
  165428. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165429. (*cinfo->mem->free_pool) (cinfo, pool);
  165430. }
  165431. /* Reset overall state for possible reuse of object */
  165432. if (cinfo->is_decompressor) {
  165433. cinfo->global_state = DSTATE_START;
  165434. /* Try to keep application from accessing now-deleted marker list.
  165435. * A bit kludgy to do it here, but this is the most central place.
  165436. */
  165437. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165438. } else {
  165439. cinfo->global_state = CSTATE_START;
  165440. }
  165441. }
  165442. /*
  165443. * Destruction of a JPEG object.
  165444. *
  165445. * Everything gets deallocated except the master jpeg_compress_struct itself
  165446. * and the error manager struct. Both of these are supplied by the application
  165447. * and must be freed, if necessary, by the application. (Often they are on
  165448. * the stack and so don't need to be freed anyway.)
  165449. * Closing a data source or destination, if necessary, is the application's
  165450. * responsibility.
  165451. */
  165452. GLOBAL(void)
  165453. jpeg_destroy (j_common_ptr cinfo)
  165454. {
  165455. /* We need only tell the memory manager to release everything. */
  165456. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165457. if (cinfo->mem != NULL)
  165458. (*cinfo->mem->self_destruct) (cinfo);
  165459. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165460. cinfo->global_state = 0; /* mark it destroyed */
  165461. }
  165462. /*
  165463. * Convenience routines for allocating quantization and Huffman tables.
  165464. * (Would jutils.c be a more reasonable place to put these?)
  165465. */
  165466. GLOBAL(JQUANT_TBL *)
  165467. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165468. {
  165469. JQUANT_TBL *tbl;
  165470. tbl = (JQUANT_TBL *)
  165471. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165472. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165473. return tbl;
  165474. }
  165475. GLOBAL(JHUFF_TBL *)
  165476. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165477. {
  165478. JHUFF_TBL *tbl;
  165479. tbl = (JHUFF_TBL *)
  165480. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165481. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165482. return tbl;
  165483. }
  165484. /*** End of inlined file: jcomapi.c ***/
  165485. /*** Start of inlined file: jcparam.c ***/
  165486. #define JPEG_INTERNALS
  165487. /*
  165488. * Quantization table setup routines
  165489. */
  165490. GLOBAL(void)
  165491. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165492. const unsigned int *basic_table,
  165493. int scale_factor, boolean force_baseline)
  165494. /* Define a quantization table equal to the basic_table times
  165495. * a scale factor (given as a percentage).
  165496. * If force_baseline is TRUE, the computed quantization table entries
  165497. * are limited to 1..255 for JPEG baseline compatibility.
  165498. */
  165499. {
  165500. JQUANT_TBL ** qtblptr;
  165501. int i;
  165502. long temp;
  165503. /* Safety check to ensure start_compress not called yet. */
  165504. if (cinfo->global_state != CSTATE_START)
  165505. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165506. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165507. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165508. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165509. if (*qtblptr == NULL)
  165510. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165511. for (i = 0; i < DCTSIZE2; i++) {
  165512. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165513. /* limit the values to the valid range */
  165514. if (temp <= 0L) temp = 1L;
  165515. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165516. if (force_baseline && temp > 255L)
  165517. temp = 255L; /* limit to baseline range if requested */
  165518. (*qtblptr)->quantval[i] = (UINT16) temp;
  165519. }
  165520. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165521. (*qtblptr)->sent_table = FALSE;
  165522. }
  165523. GLOBAL(void)
  165524. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165525. boolean force_baseline)
  165526. /* Set or change the 'quality' (quantization) setting, using default tables
  165527. * and a straight percentage-scaling quality scale. In most cases it's better
  165528. * to use jpeg_set_quality (below); this entry point is provided for
  165529. * applications that insist on a linear percentage scaling.
  165530. */
  165531. {
  165532. /* These are the sample quantization tables given in JPEG spec section K.1.
  165533. * The spec says that the values given produce "good" quality, and
  165534. * when divided by 2, "very good" quality.
  165535. */
  165536. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165537. 16, 11, 10, 16, 24, 40, 51, 61,
  165538. 12, 12, 14, 19, 26, 58, 60, 55,
  165539. 14, 13, 16, 24, 40, 57, 69, 56,
  165540. 14, 17, 22, 29, 51, 87, 80, 62,
  165541. 18, 22, 37, 56, 68, 109, 103, 77,
  165542. 24, 35, 55, 64, 81, 104, 113, 92,
  165543. 49, 64, 78, 87, 103, 121, 120, 101,
  165544. 72, 92, 95, 98, 112, 100, 103, 99
  165545. };
  165546. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165547. 17, 18, 24, 47, 99, 99, 99, 99,
  165548. 18, 21, 26, 66, 99, 99, 99, 99,
  165549. 24, 26, 56, 99, 99, 99, 99, 99,
  165550. 47, 66, 99, 99, 99, 99, 99, 99,
  165551. 99, 99, 99, 99, 99, 99, 99, 99,
  165552. 99, 99, 99, 99, 99, 99, 99, 99,
  165553. 99, 99, 99, 99, 99, 99, 99, 99,
  165554. 99, 99, 99, 99, 99, 99, 99, 99
  165555. };
  165556. /* Set up two quantization tables using the specified scaling */
  165557. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165558. scale_factor, force_baseline);
  165559. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165560. scale_factor, force_baseline);
  165561. }
  165562. GLOBAL(int)
  165563. jpeg_quality_scaling (int quality)
  165564. /* Convert a user-specified quality rating to a percentage scaling factor
  165565. * for an underlying quantization table, using our recommended scaling curve.
  165566. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165567. */
  165568. {
  165569. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165570. if (quality <= 0) quality = 1;
  165571. if (quality > 100) quality = 100;
  165572. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165573. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165574. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165575. * to make all the table entries 1 (hence, minimum quantization loss).
  165576. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165577. */
  165578. if (quality < 50)
  165579. quality = 5000 / quality;
  165580. else
  165581. quality = 200 - quality*2;
  165582. return quality;
  165583. }
  165584. GLOBAL(void)
  165585. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165586. /* Set or change the 'quality' (quantization) setting, using default tables.
  165587. * This is the standard quality-adjusting entry point for typical user
  165588. * interfaces; only those who want detailed control over quantization tables
  165589. * would use the preceding three routines directly.
  165590. */
  165591. {
  165592. /* Convert user 0-100 rating to percentage scaling */
  165593. quality = jpeg_quality_scaling(quality);
  165594. /* Set up standard quality tables */
  165595. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165596. }
  165597. /*
  165598. * Huffman table setup routines
  165599. */
  165600. LOCAL(void)
  165601. add_huff_table (j_compress_ptr cinfo,
  165602. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165603. /* Define a Huffman table */
  165604. {
  165605. int nsymbols, len;
  165606. if (*htblptr == NULL)
  165607. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165608. /* Copy the number-of-symbols-of-each-code-length counts */
  165609. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165610. /* Validate the counts. We do this here mainly so we can copy the right
  165611. * number of symbols from the val[] array, without risking marching off
  165612. * the end of memory. jchuff.c will do a more thorough test later.
  165613. */
  165614. nsymbols = 0;
  165615. for (len = 1; len <= 16; len++)
  165616. nsymbols += bits[len];
  165617. if (nsymbols < 1 || nsymbols > 256)
  165618. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165619. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165620. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165621. (*htblptr)->sent_table = FALSE;
  165622. }
  165623. LOCAL(void)
  165624. std_huff_tables (j_compress_ptr cinfo)
  165625. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165626. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165627. {
  165628. static const UINT8 bits_dc_luminance[17] =
  165629. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165630. static const UINT8 val_dc_luminance[] =
  165631. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165632. static const UINT8 bits_dc_chrominance[17] =
  165633. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165634. static const UINT8 val_dc_chrominance[] =
  165635. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165636. static const UINT8 bits_ac_luminance[17] =
  165637. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165638. static const UINT8 val_ac_luminance[] =
  165639. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165640. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165641. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165642. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165643. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165644. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165645. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165646. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165647. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165648. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165649. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165650. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165651. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165652. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165653. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165654. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165655. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165656. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165657. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165658. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165659. 0xf9, 0xfa };
  165660. static const UINT8 bits_ac_chrominance[17] =
  165661. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165662. static const UINT8 val_ac_chrominance[] =
  165663. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165664. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165665. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165666. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165667. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165668. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165669. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165670. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165671. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165672. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165673. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165674. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165675. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165676. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165677. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165678. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165679. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165680. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165681. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165682. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165683. 0xf9, 0xfa };
  165684. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165685. bits_dc_luminance, val_dc_luminance);
  165686. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165687. bits_ac_luminance, val_ac_luminance);
  165688. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165689. bits_dc_chrominance, val_dc_chrominance);
  165690. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165691. bits_ac_chrominance, val_ac_chrominance);
  165692. }
  165693. /*
  165694. * Default parameter setup for compression.
  165695. *
  165696. * Applications that don't choose to use this routine must do their
  165697. * own setup of all these parameters. Alternately, you can call this
  165698. * to establish defaults and then alter parameters selectively. This
  165699. * is the recommended approach since, if we add any new parameters,
  165700. * your code will still work (they'll be set to reasonable defaults).
  165701. */
  165702. GLOBAL(void)
  165703. jpeg_set_defaults (j_compress_ptr cinfo)
  165704. {
  165705. int i;
  165706. /* Safety check to ensure start_compress not called yet. */
  165707. if (cinfo->global_state != CSTATE_START)
  165708. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165709. /* Allocate comp_info array large enough for maximum component count.
  165710. * Array is made permanent in case application wants to compress
  165711. * multiple images at same param settings.
  165712. */
  165713. if (cinfo->comp_info == NULL)
  165714. cinfo->comp_info = (jpeg_component_info *)
  165715. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165716. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165717. /* Initialize everything not dependent on the color space */
  165718. cinfo->data_precision = BITS_IN_JSAMPLE;
  165719. /* Set up two quantization tables using default quality of 75 */
  165720. jpeg_set_quality(cinfo, 75, TRUE);
  165721. /* Set up two Huffman tables */
  165722. std_huff_tables(cinfo);
  165723. /* Initialize default arithmetic coding conditioning */
  165724. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165725. cinfo->arith_dc_L[i] = 0;
  165726. cinfo->arith_dc_U[i] = 1;
  165727. cinfo->arith_ac_K[i] = 5;
  165728. }
  165729. /* Default is no multiple-scan output */
  165730. cinfo->scan_info = NULL;
  165731. cinfo->num_scans = 0;
  165732. /* Expect normal source image, not raw downsampled data */
  165733. cinfo->raw_data_in = FALSE;
  165734. /* Use Huffman coding, not arithmetic coding, by default */
  165735. cinfo->arith_code = FALSE;
  165736. /* By default, don't do extra passes to optimize entropy coding */
  165737. cinfo->optimize_coding = FALSE;
  165738. /* The standard Huffman tables are only valid for 8-bit data precision.
  165739. * If the precision is higher, force optimization on so that usable
  165740. * tables will be computed. This test can be removed if default tables
  165741. * are supplied that are valid for the desired precision.
  165742. */
  165743. if (cinfo->data_precision > 8)
  165744. cinfo->optimize_coding = TRUE;
  165745. /* By default, use the simpler non-cosited sampling alignment */
  165746. cinfo->CCIR601_sampling = FALSE;
  165747. /* No input smoothing */
  165748. cinfo->smoothing_factor = 0;
  165749. /* DCT algorithm preference */
  165750. cinfo->dct_method = JDCT_DEFAULT;
  165751. /* No restart markers */
  165752. cinfo->restart_interval = 0;
  165753. cinfo->restart_in_rows = 0;
  165754. /* Fill in default JFIF marker parameters. Note that whether the marker
  165755. * will actually be written is determined by jpeg_set_colorspace.
  165756. *
  165757. * By default, the library emits JFIF version code 1.01.
  165758. * An application that wants to emit JFIF 1.02 extension markers should set
  165759. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165760. * to 1.02, but there may still be some decoders in use that will complain
  165761. * about that; saying 1.01 should minimize compatibility problems.
  165762. */
  165763. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165764. cinfo->JFIF_minor_version = 1;
  165765. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165766. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165767. cinfo->Y_density = 1;
  165768. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165769. jpeg_default_colorspace(cinfo);
  165770. }
  165771. /*
  165772. * Select an appropriate JPEG colorspace for in_color_space.
  165773. */
  165774. GLOBAL(void)
  165775. jpeg_default_colorspace (j_compress_ptr cinfo)
  165776. {
  165777. switch (cinfo->in_color_space) {
  165778. case JCS_GRAYSCALE:
  165779. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165780. break;
  165781. case JCS_RGB:
  165782. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165783. break;
  165784. case JCS_YCbCr:
  165785. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165786. break;
  165787. case JCS_CMYK:
  165788. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165789. break;
  165790. case JCS_YCCK:
  165791. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165792. break;
  165793. case JCS_UNKNOWN:
  165794. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165795. break;
  165796. default:
  165797. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165798. }
  165799. }
  165800. /*
  165801. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165802. */
  165803. GLOBAL(void)
  165804. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165805. {
  165806. jpeg_component_info * compptr;
  165807. int ci;
  165808. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165809. (compptr = &cinfo->comp_info[index], \
  165810. compptr->component_id = (id), \
  165811. compptr->h_samp_factor = (hsamp), \
  165812. compptr->v_samp_factor = (vsamp), \
  165813. compptr->quant_tbl_no = (quant), \
  165814. compptr->dc_tbl_no = (dctbl), \
  165815. compptr->ac_tbl_no = (actbl) )
  165816. /* Safety check to ensure start_compress not called yet. */
  165817. if (cinfo->global_state != CSTATE_START)
  165818. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165819. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165820. * tables 1 for chrominance components.
  165821. */
  165822. cinfo->jpeg_color_space = colorspace;
  165823. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165824. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165825. switch (colorspace) {
  165826. case JCS_GRAYSCALE:
  165827. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165828. cinfo->num_components = 1;
  165829. /* JFIF specifies component ID 1 */
  165830. SET_COMP(0, 1, 1,1, 0, 0,0);
  165831. break;
  165832. case JCS_RGB:
  165833. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165834. cinfo->num_components = 3;
  165835. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165836. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165837. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165838. break;
  165839. case JCS_YCbCr:
  165840. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165841. cinfo->num_components = 3;
  165842. /* JFIF specifies component IDs 1,2,3 */
  165843. /* We default to 2x2 subsamples of chrominance */
  165844. SET_COMP(0, 1, 2,2, 0, 0,0);
  165845. SET_COMP(1, 2, 1,1, 1, 1,1);
  165846. SET_COMP(2, 3, 1,1, 1, 1,1);
  165847. break;
  165848. case JCS_CMYK:
  165849. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165850. cinfo->num_components = 4;
  165851. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165852. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165853. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165854. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165855. break;
  165856. case JCS_YCCK:
  165857. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165858. cinfo->num_components = 4;
  165859. SET_COMP(0, 1, 2,2, 0, 0,0);
  165860. SET_COMP(1, 2, 1,1, 1, 1,1);
  165861. SET_COMP(2, 3, 1,1, 1, 1,1);
  165862. SET_COMP(3, 4, 2,2, 0, 0,0);
  165863. break;
  165864. case JCS_UNKNOWN:
  165865. cinfo->num_components = cinfo->input_components;
  165866. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165867. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165868. MAX_COMPONENTS);
  165869. for (ci = 0; ci < cinfo->num_components; ci++) {
  165870. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165871. }
  165872. break;
  165873. default:
  165874. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165875. }
  165876. }
  165877. #ifdef C_PROGRESSIVE_SUPPORTED
  165878. LOCAL(jpeg_scan_info *)
  165879. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165880. int Ss, int Se, int Ah, int Al)
  165881. /* Support routine: generate one scan for specified component */
  165882. {
  165883. scanptr->comps_in_scan = 1;
  165884. scanptr->component_index[0] = ci;
  165885. scanptr->Ss = Ss;
  165886. scanptr->Se = Se;
  165887. scanptr->Ah = Ah;
  165888. scanptr->Al = Al;
  165889. scanptr++;
  165890. return scanptr;
  165891. }
  165892. LOCAL(jpeg_scan_info *)
  165893. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165894. int Ss, int Se, int Ah, int Al)
  165895. /* Support routine: generate one scan for each component */
  165896. {
  165897. int ci;
  165898. for (ci = 0; ci < ncomps; ci++) {
  165899. scanptr->comps_in_scan = 1;
  165900. scanptr->component_index[0] = ci;
  165901. scanptr->Ss = Ss;
  165902. scanptr->Se = Se;
  165903. scanptr->Ah = Ah;
  165904. scanptr->Al = Al;
  165905. scanptr++;
  165906. }
  165907. return scanptr;
  165908. }
  165909. LOCAL(jpeg_scan_info *)
  165910. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165911. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165912. {
  165913. int ci;
  165914. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165915. /* Single interleaved DC scan */
  165916. scanptr->comps_in_scan = ncomps;
  165917. for (ci = 0; ci < ncomps; ci++)
  165918. scanptr->component_index[ci] = ci;
  165919. scanptr->Ss = scanptr->Se = 0;
  165920. scanptr->Ah = Ah;
  165921. scanptr->Al = Al;
  165922. scanptr++;
  165923. } else {
  165924. /* Noninterleaved DC scan for each component */
  165925. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165926. }
  165927. return scanptr;
  165928. }
  165929. /*
  165930. * Create a recommended progressive-JPEG script.
  165931. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165932. */
  165933. GLOBAL(void)
  165934. jpeg_simple_progression (j_compress_ptr cinfo)
  165935. {
  165936. int ncomps = cinfo->num_components;
  165937. int nscans;
  165938. jpeg_scan_info * scanptr;
  165939. /* Safety check to ensure start_compress not called yet. */
  165940. if (cinfo->global_state != CSTATE_START)
  165941. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165942. /* Figure space needed for script. Calculation must match code below! */
  165943. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165944. /* Custom script for YCbCr color images. */
  165945. nscans = 10;
  165946. } else {
  165947. /* All-purpose script for other color spaces. */
  165948. if (ncomps > MAX_COMPS_IN_SCAN)
  165949. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165950. else
  165951. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165952. }
  165953. /* Allocate space for script.
  165954. * We need to put it in the permanent pool in case the application performs
  165955. * multiple compressions without changing the settings. To avoid a memory
  165956. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165957. * object, we try to re-use previously allocated space, and we allocate
  165958. * enough space to handle YCbCr even if initially asked for grayscale.
  165959. */
  165960. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165961. cinfo->script_space_size = MAX(nscans, 10);
  165962. cinfo->script_space = (jpeg_scan_info *)
  165963. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165964. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165965. }
  165966. scanptr = cinfo->script_space;
  165967. cinfo->scan_info = scanptr;
  165968. cinfo->num_scans = nscans;
  165969. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165970. /* Custom script for YCbCr color images. */
  165971. /* Initial DC scan */
  165972. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165973. /* Initial AC scan: get some luma data out in a hurry */
  165974. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165975. /* Chroma data is too small to be worth expending many scans on */
  165976. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165977. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165978. /* Complete spectral selection for luma AC */
  165979. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165980. /* Refine next bit of luma AC */
  165981. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165982. /* Finish DC successive approximation */
  165983. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165984. /* Finish AC successive approximation */
  165985. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165986. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165987. /* Luma bottom bit comes last since it's usually largest scan */
  165988. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165989. } else {
  165990. /* All-purpose script for other color spaces. */
  165991. /* Successive approximation first pass */
  165992. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165993. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165994. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165995. /* Successive approximation second pass */
  165996. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165997. /* Successive approximation final pass */
  165998. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165999. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  166000. }
  166001. }
  166002. #endif /* C_PROGRESSIVE_SUPPORTED */
  166003. /*** End of inlined file: jcparam.c ***/
  166004. /*** Start of inlined file: jcphuff.c ***/
  166005. #define JPEG_INTERNALS
  166006. #ifdef C_PROGRESSIVE_SUPPORTED
  166007. /* Expanded entropy encoder object for progressive Huffman encoding. */
  166008. typedef struct {
  166009. struct jpeg_entropy_encoder pub; /* public fields */
  166010. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  166011. boolean gather_statistics;
  166012. /* Bit-level coding status.
  166013. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  166014. */
  166015. JOCTET * next_output_byte; /* => next byte to write in buffer */
  166016. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  166017. INT32 put_buffer; /* current bit-accumulation buffer */
  166018. int put_bits; /* # of bits now in it */
  166019. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  166020. /* Coding status for DC components */
  166021. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166022. /* Coding status for AC components */
  166023. int ac_tbl_no; /* the table number of the single component */
  166024. unsigned int EOBRUN; /* run length of EOBs */
  166025. unsigned int BE; /* # of buffered correction bits before MCU */
  166026. char * bit_buffer; /* buffer for correction bits (1 per char) */
  166027. /* packing correction bits tightly would save some space but cost time... */
  166028. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166029. int next_restart_num; /* next restart number to write (0-7) */
  166030. /* Pointers to derived tables (these workspaces have image lifespan).
  166031. * Since any one scan codes only DC or only AC, we only need one set
  166032. * of tables, not one for DC and one for AC.
  166033. */
  166034. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166035. /* Statistics tables for optimization; again, one set is enough */
  166036. long * count_ptrs[NUM_HUFF_TBLS];
  166037. } phuff_entropy_encoder;
  166038. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166039. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166040. * buffer can hold. Larger sizes may slightly improve compression, but
  166041. * 1000 is already well into the realm of overkill.
  166042. * The minimum safe size is 64 bits.
  166043. */
  166044. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166045. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166046. * We assume that int right shift is unsigned if INT32 right shift is,
  166047. * which should be safe.
  166048. */
  166049. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166050. #define ISHIFT_TEMPS int ishift_temp;
  166051. #define IRIGHT_SHIFT(x,shft) \
  166052. ((ishift_temp = (x)) < 0 ? \
  166053. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166054. (ishift_temp >> (shft)))
  166055. #else
  166056. #define ISHIFT_TEMPS
  166057. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166058. #endif
  166059. /* Forward declarations */
  166060. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166061. JBLOCKROW *MCU_data));
  166062. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166063. JBLOCKROW *MCU_data));
  166064. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166065. JBLOCKROW *MCU_data));
  166066. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166067. JBLOCKROW *MCU_data));
  166068. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166069. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166070. /*
  166071. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166072. */
  166073. METHODDEF(void)
  166074. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166075. {
  166076. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166077. boolean is_DC_band;
  166078. int ci, tbl;
  166079. jpeg_component_info * compptr;
  166080. entropy->cinfo = cinfo;
  166081. entropy->gather_statistics = gather_statistics;
  166082. is_DC_band = (cinfo->Ss == 0);
  166083. /* We assume jcmaster.c already validated the scan parameters. */
  166084. /* Select execution routines */
  166085. if (cinfo->Ah == 0) {
  166086. if (is_DC_band)
  166087. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166088. else
  166089. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166090. } else {
  166091. if (is_DC_band)
  166092. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166093. else {
  166094. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166095. /* AC refinement needs a correction bit buffer */
  166096. if (entropy->bit_buffer == NULL)
  166097. entropy->bit_buffer = (char *)
  166098. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166099. MAX_CORR_BITS * SIZEOF(char));
  166100. }
  166101. }
  166102. if (gather_statistics)
  166103. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166104. else
  166105. entropy->pub.finish_pass = finish_pass_phuff;
  166106. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166107. * for AC coefficients.
  166108. */
  166109. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166110. compptr = cinfo->cur_comp_info[ci];
  166111. /* Initialize DC predictions to 0 */
  166112. entropy->last_dc_val[ci] = 0;
  166113. /* Get table index */
  166114. if (is_DC_band) {
  166115. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166116. continue;
  166117. tbl = compptr->dc_tbl_no;
  166118. } else {
  166119. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166120. }
  166121. if (gather_statistics) {
  166122. /* Check for invalid table index */
  166123. /* (make_c_derived_tbl does this in the other path) */
  166124. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166125. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166126. /* Allocate and zero the statistics tables */
  166127. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166128. if (entropy->count_ptrs[tbl] == NULL)
  166129. entropy->count_ptrs[tbl] = (long *)
  166130. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166131. 257 * SIZEOF(long));
  166132. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166133. } else {
  166134. /* Compute derived values for Huffman table */
  166135. /* We may do this more than once for a table, but it's not expensive */
  166136. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166137. & entropy->derived_tbls[tbl]);
  166138. }
  166139. }
  166140. /* Initialize AC stuff */
  166141. entropy->EOBRUN = 0;
  166142. entropy->BE = 0;
  166143. /* Initialize bit buffer to empty */
  166144. entropy->put_buffer = 0;
  166145. entropy->put_bits = 0;
  166146. /* Initialize restart stuff */
  166147. entropy->restarts_to_go = cinfo->restart_interval;
  166148. entropy->next_restart_num = 0;
  166149. }
  166150. /* Outputting bytes to the file.
  166151. * NB: these must be called only when actually outputting,
  166152. * that is, entropy->gather_statistics == FALSE.
  166153. */
  166154. /* Emit a byte */
  166155. #define emit_byte(entropy,val) \
  166156. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166157. if (--(entropy)->free_in_buffer == 0) \
  166158. dump_buffer_p(entropy); }
  166159. LOCAL(void)
  166160. dump_buffer_p (phuff_entropy_ptr entropy)
  166161. /* Empty the output buffer; we do not support suspension in this module. */
  166162. {
  166163. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166164. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166165. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166166. /* After a successful buffer dump, must reset buffer pointers */
  166167. entropy->next_output_byte = dest->next_output_byte;
  166168. entropy->free_in_buffer = dest->free_in_buffer;
  166169. }
  166170. /* Outputting bits to the file */
  166171. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166172. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166173. * in one call, and we never retain more than 7 bits in put_buffer
  166174. * between calls, so 24 bits are sufficient.
  166175. */
  166176. INLINE
  166177. LOCAL(void)
  166178. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166179. /* Emit some bits, unless we are in gather mode */
  166180. {
  166181. /* This routine is heavily used, so it's worth coding tightly. */
  166182. register INT32 put_buffer = (INT32) code;
  166183. register int put_bits = entropy->put_bits;
  166184. /* if size is 0, caller used an invalid Huffman table entry */
  166185. if (size == 0)
  166186. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166187. if (entropy->gather_statistics)
  166188. return; /* do nothing if we're only getting stats */
  166189. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166190. put_bits += size; /* new number of bits in buffer */
  166191. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166192. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166193. while (put_bits >= 8) {
  166194. int c = (int) ((put_buffer >> 16) & 0xFF);
  166195. emit_byte(entropy, c);
  166196. if (c == 0xFF) { /* need to stuff a zero byte? */
  166197. emit_byte(entropy, 0);
  166198. }
  166199. put_buffer <<= 8;
  166200. put_bits -= 8;
  166201. }
  166202. entropy->put_buffer = put_buffer; /* update variables */
  166203. entropy->put_bits = put_bits;
  166204. }
  166205. LOCAL(void)
  166206. flush_bits_p (phuff_entropy_ptr entropy)
  166207. {
  166208. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166209. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166210. entropy->put_bits = 0;
  166211. }
  166212. /*
  166213. * Emit (or just count) a Huffman symbol.
  166214. */
  166215. INLINE
  166216. LOCAL(void)
  166217. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166218. {
  166219. if (entropy->gather_statistics)
  166220. entropy->count_ptrs[tbl_no][symbol]++;
  166221. else {
  166222. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166223. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166224. }
  166225. }
  166226. /*
  166227. * Emit bits from a correction bit buffer.
  166228. */
  166229. LOCAL(void)
  166230. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166231. unsigned int nbits)
  166232. {
  166233. if (entropy->gather_statistics)
  166234. return; /* no real work */
  166235. while (nbits > 0) {
  166236. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166237. bufstart++;
  166238. nbits--;
  166239. }
  166240. }
  166241. /*
  166242. * Emit any pending EOBRUN symbol.
  166243. */
  166244. LOCAL(void)
  166245. emit_eobrun (phuff_entropy_ptr entropy)
  166246. {
  166247. register int temp, nbits;
  166248. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166249. temp = entropy->EOBRUN;
  166250. nbits = 0;
  166251. while ((temp >>= 1))
  166252. nbits++;
  166253. /* safety check: shouldn't happen given limited correction-bit buffer */
  166254. if (nbits > 14)
  166255. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166256. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166257. if (nbits)
  166258. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166259. entropy->EOBRUN = 0;
  166260. /* Emit any buffered correction bits */
  166261. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166262. entropy->BE = 0;
  166263. }
  166264. }
  166265. /*
  166266. * Emit a restart marker & resynchronize predictions.
  166267. */
  166268. LOCAL(void)
  166269. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166270. {
  166271. int ci;
  166272. emit_eobrun(entropy);
  166273. if (! entropy->gather_statistics) {
  166274. flush_bits_p(entropy);
  166275. emit_byte(entropy, 0xFF);
  166276. emit_byte(entropy, JPEG_RST0 + restart_num);
  166277. }
  166278. if (entropy->cinfo->Ss == 0) {
  166279. /* Re-initialize DC predictions to 0 */
  166280. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166281. entropy->last_dc_val[ci] = 0;
  166282. } else {
  166283. /* Re-initialize all AC-related fields to 0 */
  166284. entropy->EOBRUN = 0;
  166285. entropy->BE = 0;
  166286. }
  166287. }
  166288. /*
  166289. * MCU encoding for DC initial scan (either spectral selection,
  166290. * or first pass of successive approximation).
  166291. */
  166292. METHODDEF(boolean)
  166293. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166294. {
  166295. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166296. register int temp, temp2;
  166297. register int nbits;
  166298. int blkn, ci;
  166299. int Al = cinfo->Al;
  166300. JBLOCKROW block;
  166301. jpeg_component_info * compptr;
  166302. ISHIFT_TEMPS
  166303. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166304. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166305. /* Emit restart marker if needed */
  166306. if (cinfo->restart_interval)
  166307. if (entropy->restarts_to_go == 0)
  166308. emit_restart_p(entropy, entropy->next_restart_num);
  166309. /* Encode the MCU data blocks */
  166310. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166311. block = MCU_data[blkn];
  166312. ci = cinfo->MCU_membership[blkn];
  166313. compptr = cinfo->cur_comp_info[ci];
  166314. /* Compute the DC value after the required point transform by Al.
  166315. * This is simply an arithmetic right shift.
  166316. */
  166317. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166318. /* DC differences are figured on the point-transformed values. */
  166319. temp = temp2 - entropy->last_dc_val[ci];
  166320. entropy->last_dc_val[ci] = temp2;
  166321. /* Encode the DC coefficient difference per section G.1.2.1 */
  166322. temp2 = temp;
  166323. if (temp < 0) {
  166324. temp = -temp; /* temp is abs value of input */
  166325. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166326. /* This code assumes we are on a two's complement machine */
  166327. temp2--;
  166328. }
  166329. /* Find the number of bits needed for the magnitude of the coefficient */
  166330. nbits = 0;
  166331. while (temp) {
  166332. nbits++;
  166333. temp >>= 1;
  166334. }
  166335. /* Check for out-of-range coefficient values.
  166336. * Since we're encoding a difference, the range limit is twice as much.
  166337. */
  166338. if (nbits > MAX_COEF_BITS+1)
  166339. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166340. /* Count/emit the Huffman-coded symbol for the number of bits */
  166341. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166342. /* Emit that number of bits of the value, if positive, */
  166343. /* or the complement of its magnitude, if negative. */
  166344. if (nbits) /* emit_bits rejects calls with size 0 */
  166345. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166346. }
  166347. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166348. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166349. /* Update restart-interval state too */
  166350. if (cinfo->restart_interval) {
  166351. if (entropy->restarts_to_go == 0) {
  166352. entropy->restarts_to_go = cinfo->restart_interval;
  166353. entropy->next_restart_num++;
  166354. entropy->next_restart_num &= 7;
  166355. }
  166356. entropy->restarts_to_go--;
  166357. }
  166358. return TRUE;
  166359. }
  166360. /*
  166361. * MCU encoding for AC initial scan (either spectral selection,
  166362. * or first pass of successive approximation).
  166363. */
  166364. METHODDEF(boolean)
  166365. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166366. {
  166367. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166368. register int temp, temp2;
  166369. register int nbits;
  166370. register int r, k;
  166371. int Se = cinfo->Se;
  166372. int Al = cinfo->Al;
  166373. JBLOCKROW block;
  166374. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166375. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166376. /* Emit restart marker if needed */
  166377. if (cinfo->restart_interval)
  166378. if (entropy->restarts_to_go == 0)
  166379. emit_restart_p(entropy, entropy->next_restart_num);
  166380. /* Encode the MCU data block */
  166381. block = MCU_data[0];
  166382. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166383. r = 0; /* r = run length of zeros */
  166384. for (k = cinfo->Ss; k <= Se; k++) {
  166385. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166386. r++;
  166387. continue;
  166388. }
  166389. /* We must apply the point transform by Al. For AC coefficients this
  166390. * is an integer division with rounding towards 0. To do this portably
  166391. * in C, we shift after obtaining the absolute value; so the code is
  166392. * interwoven with finding the abs value (temp) and output bits (temp2).
  166393. */
  166394. if (temp < 0) {
  166395. temp = -temp; /* temp is abs value of input */
  166396. temp >>= Al; /* apply the point transform */
  166397. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166398. temp2 = ~temp;
  166399. } else {
  166400. temp >>= Al; /* apply the point transform */
  166401. temp2 = temp;
  166402. }
  166403. /* Watch out for case that nonzero coef is zero after point transform */
  166404. if (temp == 0) {
  166405. r++;
  166406. continue;
  166407. }
  166408. /* Emit any pending EOBRUN */
  166409. if (entropy->EOBRUN > 0)
  166410. emit_eobrun(entropy);
  166411. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166412. while (r > 15) {
  166413. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166414. r -= 16;
  166415. }
  166416. /* Find the number of bits needed for the magnitude of the coefficient */
  166417. nbits = 1; /* there must be at least one 1 bit */
  166418. while ((temp >>= 1))
  166419. nbits++;
  166420. /* Check for out-of-range coefficient values */
  166421. if (nbits > MAX_COEF_BITS)
  166422. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166423. /* Count/emit Huffman symbol for run length / number of bits */
  166424. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166425. /* Emit that number of bits of the value, if positive, */
  166426. /* or the complement of its magnitude, if negative. */
  166427. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166428. r = 0; /* reset zero run length */
  166429. }
  166430. if (r > 0) { /* If there are trailing zeroes, */
  166431. entropy->EOBRUN++; /* count an EOB */
  166432. if (entropy->EOBRUN == 0x7FFF)
  166433. emit_eobrun(entropy); /* force it out to avoid overflow */
  166434. }
  166435. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166436. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166437. /* Update restart-interval state too */
  166438. if (cinfo->restart_interval) {
  166439. if (entropy->restarts_to_go == 0) {
  166440. entropy->restarts_to_go = cinfo->restart_interval;
  166441. entropy->next_restart_num++;
  166442. entropy->next_restart_num &= 7;
  166443. }
  166444. entropy->restarts_to_go--;
  166445. }
  166446. return TRUE;
  166447. }
  166448. /*
  166449. * MCU encoding for DC successive approximation refinement scan.
  166450. * Note: we assume such scans can be multi-component, although the spec
  166451. * is not very clear on the point.
  166452. */
  166453. METHODDEF(boolean)
  166454. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166455. {
  166456. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166457. register int temp;
  166458. int blkn;
  166459. int Al = cinfo->Al;
  166460. JBLOCKROW block;
  166461. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166462. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166463. /* Emit restart marker if needed */
  166464. if (cinfo->restart_interval)
  166465. if (entropy->restarts_to_go == 0)
  166466. emit_restart_p(entropy, entropy->next_restart_num);
  166467. /* Encode the MCU data blocks */
  166468. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166469. block = MCU_data[blkn];
  166470. /* We simply emit the Al'th bit of the DC coefficient value. */
  166471. temp = (*block)[0];
  166472. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166473. }
  166474. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166475. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166476. /* Update restart-interval state too */
  166477. if (cinfo->restart_interval) {
  166478. if (entropy->restarts_to_go == 0) {
  166479. entropy->restarts_to_go = cinfo->restart_interval;
  166480. entropy->next_restart_num++;
  166481. entropy->next_restart_num &= 7;
  166482. }
  166483. entropy->restarts_to_go--;
  166484. }
  166485. return TRUE;
  166486. }
  166487. /*
  166488. * MCU encoding for AC successive approximation refinement scan.
  166489. */
  166490. METHODDEF(boolean)
  166491. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166492. {
  166493. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166494. register int temp;
  166495. register int r, k;
  166496. int EOB;
  166497. char *BR_buffer;
  166498. unsigned int BR;
  166499. int Se = cinfo->Se;
  166500. int Al = cinfo->Al;
  166501. JBLOCKROW block;
  166502. int absvalues[DCTSIZE2];
  166503. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166504. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166505. /* Emit restart marker if needed */
  166506. if (cinfo->restart_interval)
  166507. if (entropy->restarts_to_go == 0)
  166508. emit_restart_p(entropy, entropy->next_restart_num);
  166509. /* Encode the MCU data block */
  166510. block = MCU_data[0];
  166511. /* It is convenient to make a pre-pass to determine the transformed
  166512. * coefficients' absolute values and the EOB position.
  166513. */
  166514. EOB = 0;
  166515. for (k = cinfo->Ss; k <= Se; k++) {
  166516. temp = (*block)[jpeg_natural_order[k]];
  166517. /* We must apply the point transform by Al. For AC coefficients this
  166518. * is an integer division with rounding towards 0. To do this portably
  166519. * in C, we shift after obtaining the absolute value.
  166520. */
  166521. if (temp < 0)
  166522. temp = -temp; /* temp is abs value of input */
  166523. temp >>= Al; /* apply the point transform */
  166524. absvalues[k] = temp; /* save abs value for main pass */
  166525. if (temp == 1)
  166526. EOB = k; /* EOB = index of last newly-nonzero coef */
  166527. }
  166528. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166529. r = 0; /* r = run length of zeros */
  166530. BR = 0; /* BR = count of buffered bits added now */
  166531. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166532. for (k = cinfo->Ss; k <= Se; k++) {
  166533. if ((temp = absvalues[k]) == 0) {
  166534. r++;
  166535. continue;
  166536. }
  166537. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166538. while (r > 15 && k <= EOB) {
  166539. /* emit any pending EOBRUN and the BE correction bits */
  166540. emit_eobrun(entropy);
  166541. /* Emit ZRL */
  166542. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166543. r -= 16;
  166544. /* Emit buffered correction bits that must be associated with ZRL */
  166545. emit_buffered_bits(entropy, BR_buffer, BR);
  166546. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166547. BR = 0;
  166548. }
  166549. /* If the coef was previously nonzero, it only needs a correction bit.
  166550. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166551. * that we also need to test r > 15. But if r > 15, we can only get here
  166552. * if k > EOB, which implies that this coefficient is not 1.
  166553. */
  166554. if (temp > 1) {
  166555. /* The correction bit is the next bit of the absolute value. */
  166556. BR_buffer[BR++] = (char) (temp & 1);
  166557. continue;
  166558. }
  166559. /* Emit any pending EOBRUN and the BE correction bits */
  166560. emit_eobrun(entropy);
  166561. /* Count/emit Huffman symbol for run length / number of bits */
  166562. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166563. /* Emit output bit for newly-nonzero coef */
  166564. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166565. emit_bits_p(entropy, (unsigned int) temp, 1);
  166566. /* Emit buffered correction bits that must be associated with this code */
  166567. emit_buffered_bits(entropy, BR_buffer, BR);
  166568. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166569. BR = 0;
  166570. r = 0; /* reset zero run length */
  166571. }
  166572. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166573. entropy->EOBRUN++; /* count an EOB */
  166574. entropy->BE += BR; /* concat my correction bits to older ones */
  166575. /* We force out the EOB if we risk either:
  166576. * 1. overflow of the EOB counter;
  166577. * 2. overflow of the correction bit buffer during the next MCU.
  166578. */
  166579. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166580. emit_eobrun(entropy);
  166581. }
  166582. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166583. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166584. /* Update restart-interval state too */
  166585. if (cinfo->restart_interval) {
  166586. if (entropy->restarts_to_go == 0) {
  166587. entropy->restarts_to_go = cinfo->restart_interval;
  166588. entropy->next_restart_num++;
  166589. entropy->next_restart_num &= 7;
  166590. }
  166591. entropy->restarts_to_go--;
  166592. }
  166593. return TRUE;
  166594. }
  166595. /*
  166596. * Finish up at the end of a Huffman-compressed progressive scan.
  166597. */
  166598. METHODDEF(void)
  166599. finish_pass_phuff (j_compress_ptr cinfo)
  166600. {
  166601. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166602. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166603. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166604. /* Flush out any buffered data */
  166605. emit_eobrun(entropy);
  166606. flush_bits_p(entropy);
  166607. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166608. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166609. }
  166610. /*
  166611. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166612. */
  166613. METHODDEF(void)
  166614. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166615. {
  166616. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166617. boolean is_DC_band;
  166618. int ci, tbl;
  166619. jpeg_component_info * compptr;
  166620. JHUFF_TBL **htblptr;
  166621. boolean did[NUM_HUFF_TBLS];
  166622. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166623. emit_eobrun(entropy);
  166624. is_DC_band = (cinfo->Ss == 0);
  166625. /* It's important not to apply jpeg_gen_optimal_table more than once
  166626. * per table, because it clobbers the input frequency counts!
  166627. */
  166628. MEMZERO(did, SIZEOF(did));
  166629. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166630. compptr = cinfo->cur_comp_info[ci];
  166631. if (is_DC_band) {
  166632. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166633. continue;
  166634. tbl = compptr->dc_tbl_no;
  166635. } else {
  166636. tbl = compptr->ac_tbl_no;
  166637. }
  166638. if (! did[tbl]) {
  166639. if (is_DC_band)
  166640. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166641. else
  166642. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166643. if (*htblptr == NULL)
  166644. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166645. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166646. did[tbl] = TRUE;
  166647. }
  166648. }
  166649. }
  166650. /*
  166651. * Module initialization routine for progressive Huffman entropy encoding.
  166652. */
  166653. GLOBAL(void)
  166654. jinit_phuff_encoder (j_compress_ptr cinfo)
  166655. {
  166656. phuff_entropy_ptr entropy;
  166657. int i;
  166658. entropy = (phuff_entropy_ptr)
  166659. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166660. SIZEOF(phuff_entropy_encoder));
  166661. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166662. entropy->pub.start_pass = start_pass_phuff;
  166663. /* Mark tables unallocated */
  166664. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166665. entropy->derived_tbls[i] = NULL;
  166666. entropy->count_ptrs[i] = NULL;
  166667. }
  166668. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166669. }
  166670. #endif /* C_PROGRESSIVE_SUPPORTED */
  166671. /*** End of inlined file: jcphuff.c ***/
  166672. /*** Start of inlined file: jcprepct.c ***/
  166673. #define JPEG_INTERNALS
  166674. /* At present, jcsample.c can request context rows only for smoothing.
  166675. * In the future, we might also need context rows for CCIR601 sampling
  166676. * or other more-complex downsampling procedures. The code to support
  166677. * context rows should be compiled only if needed.
  166678. */
  166679. #ifdef INPUT_SMOOTHING_SUPPORTED
  166680. #define CONTEXT_ROWS_SUPPORTED
  166681. #endif
  166682. /*
  166683. * For the simple (no-context-row) case, we just need to buffer one
  166684. * row group's worth of pixels for the downsampling step. At the bottom of
  166685. * the image, we pad to a full row group by replicating the last pixel row.
  166686. * The downsampler's last output row is then replicated if needed to pad
  166687. * out to a full iMCU row.
  166688. *
  166689. * When providing context rows, we must buffer three row groups' worth of
  166690. * pixels. Three row groups are physically allocated, but the row pointer
  166691. * arrays are made five row groups high, with the extra pointers above and
  166692. * below "wrapping around" to point to the last and first real row groups.
  166693. * This allows the downsampler to access the proper context rows.
  166694. * At the top and bottom of the image, we create dummy context rows by
  166695. * copying the first or last real pixel row. This copying could be avoided
  166696. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166697. * trouble on the compression side.
  166698. */
  166699. /* Private buffer controller object */
  166700. typedef struct {
  166701. struct jpeg_c_prep_controller pub; /* public fields */
  166702. /* Downsampling input buffer. This buffer holds color-converted data
  166703. * until we have enough to do a downsample step.
  166704. */
  166705. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166706. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166707. int next_buf_row; /* index of next row to store in color_buf */
  166708. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166709. int this_row_group; /* starting row index of group to process */
  166710. int next_buf_stop; /* downsample when we reach this index */
  166711. #endif
  166712. } my_prep_controller;
  166713. typedef my_prep_controller * my_prep_ptr;
  166714. /*
  166715. * Initialize for a processing pass.
  166716. */
  166717. METHODDEF(void)
  166718. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166719. {
  166720. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166721. if (pass_mode != JBUF_PASS_THRU)
  166722. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166723. /* Initialize total-height counter for detecting bottom of image */
  166724. prep->rows_to_go = cinfo->image_height;
  166725. /* Mark the conversion buffer empty */
  166726. prep->next_buf_row = 0;
  166727. #ifdef CONTEXT_ROWS_SUPPORTED
  166728. /* Preset additional state variables for context mode.
  166729. * These aren't used in non-context mode, so we needn't test which mode.
  166730. */
  166731. prep->this_row_group = 0;
  166732. /* Set next_buf_stop to stop after two row groups have been read in. */
  166733. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166734. #endif
  166735. }
  166736. /*
  166737. * Expand an image vertically from height input_rows to height output_rows,
  166738. * by duplicating the bottom row.
  166739. */
  166740. LOCAL(void)
  166741. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166742. int input_rows, int output_rows)
  166743. {
  166744. register int row;
  166745. for (row = input_rows; row < output_rows; row++) {
  166746. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166747. 1, num_cols);
  166748. }
  166749. }
  166750. /*
  166751. * Process some data in the simple no-context case.
  166752. *
  166753. * Preprocessor output data is counted in "row groups". A row group
  166754. * is defined to be v_samp_factor sample rows of each component.
  166755. * Downsampling will produce this much data from each max_v_samp_factor
  166756. * input rows.
  166757. */
  166758. METHODDEF(void)
  166759. pre_process_data (j_compress_ptr cinfo,
  166760. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166761. JDIMENSION in_rows_avail,
  166762. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166763. JDIMENSION out_row_groups_avail)
  166764. {
  166765. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166766. int numrows, ci;
  166767. JDIMENSION inrows;
  166768. jpeg_component_info * compptr;
  166769. while (*in_row_ctr < in_rows_avail &&
  166770. *out_row_group_ctr < out_row_groups_avail) {
  166771. /* Do color conversion to fill the conversion buffer. */
  166772. inrows = in_rows_avail - *in_row_ctr;
  166773. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166774. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166775. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166776. prep->color_buf,
  166777. (JDIMENSION) prep->next_buf_row,
  166778. numrows);
  166779. *in_row_ctr += numrows;
  166780. prep->next_buf_row += numrows;
  166781. prep->rows_to_go -= numrows;
  166782. /* If at bottom of image, pad to fill the conversion buffer. */
  166783. if (prep->rows_to_go == 0 &&
  166784. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166785. for (ci = 0; ci < cinfo->num_components; ci++) {
  166786. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166787. prep->next_buf_row, cinfo->max_v_samp_factor);
  166788. }
  166789. prep->next_buf_row = cinfo->max_v_samp_factor;
  166790. }
  166791. /* If we've filled the conversion buffer, empty it. */
  166792. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166793. (*cinfo->downsample->downsample) (cinfo,
  166794. prep->color_buf, (JDIMENSION) 0,
  166795. output_buf, *out_row_group_ctr);
  166796. prep->next_buf_row = 0;
  166797. (*out_row_group_ctr)++;
  166798. }
  166799. /* If at bottom of image, pad the output to a full iMCU height.
  166800. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166801. */
  166802. if (prep->rows_to_go == 0 &&
  166803. *out_row_group_ctr < out_row_groups_avail) {
  166804. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166805. ci++, compptr++) {
  166806. expand_bottom_edge(output_buf[ci],
  166807. compptr->width_in_blocks * DCTSIZE,
  166808. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166809. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166810. }
  166811. *out_row_group_ctr = out_row_groups_avail;
  166812. break; /* can exit outer loop without test */
  166813. }
  166814. }
  166815. }
  166816. #ifdef CONTEXT_ROWS_SUPPORTED
  166817. /*
  166818. * Process some data in the context case.
  166819. */
  166820. METHODDEF(void)
  166821. pre_process_context (j_compress_ptr cinfo,
  166822. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166823. JDIMENSION in_rows_avail,
  166824. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166825. JDIMENSION out_row_groups_avail)
  166826. {
  166827. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166828. int numrows, ci;
  166829. int buf_height = cinfo->max_v_samp_factor * 3;
  166830. JDIMENSION inrows;
  166831. while (*out_row_group_ctr < out_row_groups_avail) {
  166832. if (*in_row_ctr < in_rows_avail) {
  166833. /* Do color conversion to fill the conversion buffer. */
  166834. inrows = in_rows_avail - *in_row_ctr;
  166835. numrows = prep->next_buf_stop - prep->next_buf_row;
  166836. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166837. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166838. prep->color_buf,
  166839. (JDIMENSION) prep->next_buf_row,
  166840. numrows);
  166841. /* Pad at top of image, if first time through */
  166842. if (prep->rows_to_go == cinfo->image_height) {
  166843. for (ci = 0; ci < cinfo->num_components; ci++) {
  166844. int row;
  166845. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166846. jcopy_sample_rows(prep->color_buf[ci], 0,
  166847. prep->color_buf[ci], -row,
  166848. 1, cinfo->image_width);
  166849. }
  166850. }
  166851. }
  166852. *in_row_ctr += numrows;
  166853. prep->next_buf_row += numrows;
  166854. prep->rows_to_go -= numrows;
  166855. } else {
  166856. /* Return for more data, unless we are at the bottom of the image. */
  166857. if (prep->rows_to_go != 0)
  166858. break;
  166859. /* When at bottom of image, pad to fill the conversion buffer. */
  166860. if (prep->next_buf_row < prep->next_buf_stop) {
  166861. for (ci = 0; ci < cinfo->num_components; ci++) {
  166862. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166863. prep->next_buf_row, prep->next_buf_stop);
  166864. }
  166865. prep->next_buf_row = prep->next_buf_stop;
  166866. }
  166867. }
  166868. /* If we've gotten enough data, downsample a row group. */
  166869. if (prep->next_buf_row == prep->next_buf_stop) {
  166870. (*cinfo->downsample->downsample) (cinfo,
  166871. prep->color_buf,
  166872. (JDIMENSION) prep->this_row_group,
  166873. output_buf, *out_row_group_ctr);
  166874. (*out_row_group_ctr)++;
  166875. /* Advance pointers with wraparound as necessary. */
  166876. prep->this_row_group += cinfo->max_v_samp_factor;
  166877. if (prep->this_row_group >= buf_height)
  166878. prep->this_row_group = 0;
  166879. if (prep->next_buf_row >= buf_height)
  166880. prep->next_buf_row = 0;
  166881. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166882. }
  166883. }
  166884. }
  166885. /*
  166886. * Create the wrapped-around downsampling input buffer needed for context mode.
  166887. */
  166888. LOCAL(void)
  166889. create_context_buffer (j_compress_ptr cinfo)
  166890. {
  166891. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166892. int rgroup_height = cinfo->max_v_samp_factor;
  166893. int ci, i;
  166894. jpeg_component_info * compptr;
  166895. JSAMPARRAY true_buffer, fake_buffer;
  166896. /* Grab enough space for fake row pointers for all the components;
  166897. * we need five row groups' worth of pointers for each component.
  166898. */
  166899. fake_buffer = (JSAMPARRAY)
  166900. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166901. (cinfo->num_components * 5 * rgroup_height) *
  166902. SIZEOF(JSAMPROW));
  166903. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166904. ci++, compptr++) {
  166905. /* Allocate the actual buffer space (3 row groups) for this component.
  166906. * We make the buffer wide enough to allow the downsampler to edge-expand
  166907. * horizontally within the buffer, if it so chooses.
  166908. */
  166909. true_buffer = (*cinfo->mem->alloc_sarray)
  166910. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166911. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166912. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166913. (JDIMENSION) (3 * rgroup_height));
  166914. /* Copy true buffer row pointers into the middle of the fake row array */
  166915. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166916. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166917. /* Fill in the above and below wraparound pointers */
  166918. for (i = 0; i < rgroup_height; i++) {
  166919. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166920. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166921. }
  166922. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166923. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166924. }
  166925. }
  166926. #endif /* CONTEXT_ROWS_SUPPORTED */
  166927. /*
  166928. * Initialize preprocessing controller.
  166929. */
  166930. GLOBAL(void)
  166931. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166932. {
  166933. my_prep_ptr prep;
  166934. int ci;
  166935. jpeg_component_info * compptr;
  166936. if (need_full_buffer) /* safety check */
  166937. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166938. prep = (my_prep_ptr)
  166939. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166940. SIZEOF(my_prep_controller));
  166941. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166942. prep->pub.start_pass = start_pass_prep;
  166943. /* Allocate the color conversion buffer.
  166944. * We make the buffer wide enough to allow the downsampler to edge-expand
  166945. * horizontally within the buffer, if it so chooses.
  166946. */
  166947. if (cinfo->downsample->need_context_rows) {
  166948. /* Set up to provide context rows */
  166949. #ifdef CONTEXT_ROWS_SUPPORTED
  166950. prep->pub.pre_process_data = pre_process_context;
  166951. create_context_buffer(cinfo);
  166952. #else
  166953. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166954. #endif
  166955. } else {
  166956. /* No context, just make it tall enough for one row group */
  166957. prep->pub.pre_process_data = pre_process_data;
  166958. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166959. ci++, compptr++) {
  166960. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166961. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166962. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166963. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166964. (JDIMENSION) cinfo->max_v_samp_factor);
  166965. }
  166966. }
  166967. }
  166968. /*** End of inlined file: jcprepct.c ***/
  166969. /*** Start of inlined file: jcsample.c ***/
  166970. #define JPEG_INTERNALS
  166971. /* Pointer to routine to downsample a single component */
  166972. typedef JMETHOD(void, downsample1_ptr,
  166973. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166974. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166975. /* Private subobject */
  166976. typedef struct {
  166977. struct jpeg_downsampler pub; /* public fields */
  166978. /* Downsampling method pointers, one per component */
  166979. downsample1_ptr methods[MAX_COMPONENTS];
  166980. } my_downsampler;
  166981. typedef my_downsampler * my_downsample_ptr;
  166982. /*
  166983. * Initialize for a downsampling pass.
  166984. */
  166985. METHODDEF(void)
  166986. start_pass_downsample (j_compress_ptr)
  166987. {
  166988. /* no work for now */
  166989. }
  166990. /*
  166991. * Expand a component horizontally from width input_cols to width output_cols,
  166992. * by duplicating the rightmost samples.
  166993. */
  166994. LOCAL(void)
  166995. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166996. JDIMENSION input_cols, JDIMENSION output_cols)
  166997. {
  166998. register JSAMPROW ptr;
  166999. register JSAMPLE pixval;
  167000. register int count;
  167001. int row;
  167002. int numcols = (int) (output_cols - input_cols);
  167003. if (numcols > 0) {
  167004. for (row = 0; row < num_rows; row++) {
  167005. ptr = image_data[row] + input_cols;
  167006. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  167007. for (count = numcols; count > 0; count--)
  167008. *ptr++ = pixval;
  167009. }
  167010. }
  167011. }
  167012. /*
  167013. * Do downsampling for a whole row group (all components).
  167014. *
  167015. * In this version we simply downsample each component independently.
  167016. */
  167017. METHODDEF(void)
  167018. sep_downsample (j_compress_ptr cinfo,
  167019. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  167020. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  167021. {
  167022. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  167023. int ci;
  167024. jpeg_component_info * compptr;
  167025. JSAMPARRAY in_ptr, out_ptr;
  167026. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167027. ci++, compptr++) {
  167028. in_ptr = input_buf[ci] + in_row_index;
  167029. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167030. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167031. }
  167032. }
  167033. /*
  167034. * Downsample pixel values of a single component.
  167035. * One row group is processed per call.
  167036. * This version handles arbitrary integral sampling ratios, without smoothing.
  167037. * Note that this version is not actually used for customary sampling ratios.
  167038. */
  167039. METHODDEF(void)
  167040. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167041. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167042. {
  167043. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167044. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167045. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167046. JSAMPROW inptr, outptr;
  167047. INT32 outvalue;
  167048. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167049. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167050. numpix = h_expand * v_expand;
  167051. numpix2 = numpix/2;
  167052. /* Expand input data enough to let all the output samples be generated
  167053. * by the standard loop. Special-casing padded output would be more
  167054. * efficient.
  167055. */
  167056. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167057. cinfo->image_width, output_cols * h_expand);
  167058. inrow = 0;
  167059. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167060. outptr = output_data[outrow];
  167061. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167062. outcol++, outcol_h += h_expand) {
  167063. outvalue = 0;
  167064. for (v = 0; v < v_expand; v++) {
  167065. inptr = input_data[inrow+v] + outcol_h;
  167066. for (h = 0; h < h_expand; h++) {
  167067. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167068. }
  167069. }
  167070. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167071. }
  167072. inrow += v_expand;
  167073. }
  167074. }
  167075. /*
  167076. * Downsample pixel values of a single component.
  167077. * This version handles the special case of a full-size component,
  167078. * without smoothing.
  167079. */
  167080. METHODDEF(void)
  167081. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167082. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167083. {
  167084. /* Copy the data */
  167085. jcopy_sample_rows(input_data, 0, output_data, 0,
  167086. cinfo->max_v_samp_factor, cinfo->image_width);
  167087. /* Edge-expand */
  167088. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167089. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167090. }
  167091. /*
  167092. * Downsample pixel values of a single component.
  167093. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167094. * without smoothing.
  167095. *
  167096. * A note about the "bias" calculations: when rounding fractional values to
  167097. * integer, we do not want to always round 0.5 up to the next integer.
  167098. * If we did that, we'd introduce a noticeable bias towards larger values.
  167099. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167100. * alternate pixel locations (a simple ordered dither pattern).
  167101. */
  167102. METHODDEF(void)
  167103. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167104. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167105. {
  167106. int outrow;
  167107. JDIMENSION outcol;
  167108. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167109. register JSAMPROW inptr, outptr;
  167110. register int bias;
  167111. /* Expand input data enough to let all the output samples be generated
  167112. * by the standard loop. Special-casing padded output would be more
  167113. * efficient.
  167114. */
  167115. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167116. cinfo->image_width, output_cols * 2);
  167117. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167118. outptr = output_data[outrow];
  167119. inptr = input_data[outrow];
  167120. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167121. for (outcol = 0; outcol < output_cols; outcol++) {
  167122. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167123. + bias) >> 1);
  167124. bias ^= 1; /* 0=>1, 1=>0 */
  167125. inptr += 2;
  167126. }
  167127. }
  167128. }
  167129. /*
  167130. * Downsample pixel values of a single component.
  167131. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167132. * without smoothing.
  167133. */
  167134. METHODDEF(void)
  167135. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167136. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167137. {
  167138. int inrow, outrow;
  167139. JDIMENSION outcol;
  167140. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167141. register JSAMPROW inptr0, inptr1, outptr;
  167142. register int bias;
  167143. /* Expand input data enough to let all the output samples be generated
  167144. * by the standard loop. Special-casing padded output would be more
  167145. * efficient.
  167146. */
  167147. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167148. cinfo->image_width, output_cols * 2);
  167149. inrow = 0;
  167150. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167151. outptr = output_data[outrow];
  167152. inptr0 = input_data[inrow];
  167153. inptr1 = input_data[inrow+1];
  167154. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167155. for (outcol = 0; outcol < output_cols; outcol++) {
  167156. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167157. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167158. + bias) >> 2);
  167159. bias ^= 3; /* 1=>2, 2=>1 */
  167160. inptr0 += 2; inptr1 += 2;
  167161. }
  167162. inrow += 2;
  167163. }
  167164. }
  167165. #ifdef INPUT_SMOOTHING_SUPPORTED
  167166. /*
  167167. * Downsample pixel values of a single component.
  167168. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167169. * with smoothing. One row of context is required.
  167170. */
  167171. METHODDEF(void)
  167172. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167173. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167174. {
  167175. int inrow, outrow;
  167176. JDIMENSION colctr;
  167177. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167178. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167179. INT32 membersum, neighsum, memberscale, neighscale;
  167180. /* Expand input data enough to let all the output samples be generated
  167181. * by the standard loop. Special-casing padded output would be more
  167182. * efficient.
  167183. */
  167184. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167185. cinfo->image_width, output_cols * 2);
  167186. /* We don't bother to form the individual "smoothed" input pixel values;
  167187. * we can directly compute the output which is the average of the four
  167188. * smoothed values. Each of the four member pixels contributes a fraction
  167189. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167190. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167191. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167192. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167193. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167194. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167195. * factors are scaled by 2^16 = 65536.
  167196. * Also recall that SF = smoothing_factor / 1024.
  167197. */
  167198. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167199. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167200. inrow = 0;
  167201. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167202. outptr = output_data[outrow];
  167203. inptr0 = input_data[inrow];
  167204. inptr1 = input_data[inrow+1];
  167205. above_ptr = input_data[inrow-1];
  167206. below_ptr = input_data[inrow+2];
  167207. /* Special case for first column: pretend column -1 is same as column 0 */
  167208. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167209. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167210. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167211. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167212. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167213. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167214. neighsum += neighsum;
  167215. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167216. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167217. membersum = membersum * memberscale + neighsum * neighscale;
  167218. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167219. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167220. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167221. /* sum of pixels directly mapped to this output element */
  167222. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167223. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167224. /* sum of edge-neighbor pixels */
  167225. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167226. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167227. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167228. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167229. /* The edge-neighbors count twice as much as corner-neighbors */
  167230. neighsum += neighsum;
  167231. /* Add in the corner-neighbors */
  167232. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167233. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167234. /* form final output scaled up by 2^16 */
  167235. membersum = membersum * memberscale + neighsum * neighscale;
  167236. /* round, descale and output it */
  167237. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167238. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167239. }
  167240. /* Special case for last column */
  167241. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167242. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167243. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167244. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167245. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167246. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167247. neighsum += neighsum;
  167248. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167249. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167250. membersum = membersum * memberscale + neighsum * neighscale;
  167251. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167252. inrow += 2;
  167253. }
  167254. }
  167255. /*
  167256. * Downsample pixel values of a single component.
  167257. * This version handles the special case of a full-size component,
  167258. * with smoothing. One row of context is required.
  167259. */
  167260. METHODDEF(void)
  167261. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167262. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167263. {
  167264. int outrow;
  167265. JDIMENSION colctr;
  167266. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167267. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167268. INT32 membersum, neighsum, memberscale, neighscale;
  167269. int colsum, lastcolsum, nextcolsum;
  167270. /* Expand input data enough to let all the output samples be generated
  167271. * by the standard loop. Special-casing padded output would be more
  167272. * efficient.
  167273. */
  167274. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167275. cinfo->image_width, output_cols);
  167276. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167277. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167278. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167279. * Also recall that SF = smoothing_factor / 1024.
  167280. */
  167281. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167282. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167283. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167284. outptr = output_data[outrow];
  167285. inptr = input_data[outrow];
  167286. above_ptr = input_data[outrow-1];
  167287. below_ptr = input_data[outrow+1];
  167288. /* Special case for first column */
  167289. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167290. GETJSAMPLE(*inptr);
  167291. membersum = GETJSAMPLE(*inptr++);
  167292. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167293. GETJSAMPLE(*inptr);
  167294. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167295. membersum = membersum * memberscale + neighsum * neighscale;
  167296. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167297. lastcolsum = colsum; colsum = nextcolsum;
  167298. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167299. membersum = GETJSAMPLE(*inptr++);
  167300. above_ptr++; below_ptr++;
  167301. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167302. GETJSAMPLE(*inptr);
  167303. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167304. membersum = membersum * memberscale + neighsum * neighscale;
  167305. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167306. lastcolsum = colsum; colsum = nextcolsum;
  167307. }
  167308. /* Special case for last column */
  167309. membersum = GETJSAMPLE(*inptr);
  167310. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167311. membersum = membersum * memberscale + neighsum * neighscale;
  167312. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167313. }
  167314. }
  167315. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167316. /*
  167317. * Module initialization routine for downsampling.
  167318. * Note that we must select a routine for each component.
  167319. */
  167320. GLOBAL(void)
  167321. jinit_downsampler (j_compress_ptr cinfo)
  167322. {
  167323. my_downsample_ptr downsample;
  167324. int ci;
  167325. jpeg_component_info * compptr;
  167326. boolean smoothok = TRUE;
  167327. downsample = (my_downsample_ptr)
  167328. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167329. SIZEOF(my_downsampler));
  167330. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167331. downsample->pub.start_pass = start_pass_downsample;
  167332. downsample->pub.downsample = sep_downsample;
  167333. downsample->pub.need_context_rows = FALSE;
  167334. if (cinfo->CCIR601_sampling)
  167335. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167336. /* Verify we can handle the sampling factors, and set up method pointers */
  167337. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167338. ci++, compptr++) {
  167339. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167340. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167341. #ifdef INPUT_SMOOTHING_SUPPORTED
  167342. if (cinfo->smoothing_factor) {
  167343. downsample->methods[ci] = fullsize_smooth_downsample;
  167344. downsample->pub.need_context_rows = TRUE;
  167345. } else
  167346. #endif
  167347. downsample->methods[ci] = fullsize_downsample;
  167348. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167349. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167350. smoothok = FALSE;
  167351. downsample->methods[ci] = h2v1_downsample;
  167352. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167353. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167354. #ifdef INPUT_SMOOTHING_SUPPORTED
  167355. if (cinfo->smoothing_factor) {
  167356. downsample->methods[ci] = h2v2_smooth_downsample;
  167357. downsample->pub.need_context_rows = TRUE;
  167358. } else
  167359. #endif
  167360. downsample->methods[ci] = h2v2_downsample;
  167361. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167362. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167363. smoothok = FALSE;
  167364. downsample->methods[ci] = int_downsample;
  167365. } else
  167366. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167367. }
  167368. #ifdef INPUT_SMOOTHING_SUPPORTED
  167369. if (cinfo->smoothing_factor && !smoothok)
  167370. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167371. #endif
  167372. }
  167373. /*** End of inlined file: jcsample.c ***/
  167374. /*** Start of inlined file: jctrans.c ***/
  167375. #define JPEG_INTERNALS
  167376. /* Forward declarations */
  167377. LOCAL(void) transencode_master_selection
  167378. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167379. LOCAL(void) transencode_coef_controller
  167380. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167381. /*
  167382. * Compression initialization for writing raw-coefficient data.
  167383. * Before calling this, all parameters and a data destination must be set up.
  167384. * Call jpeg_finish_compress() to actually write the data.
  167385. *
  167386. * The number of passed virtual arrays must match cinfo->num_components.
  167387. * Note that the virtual arrays need not be filled or even realized at
  167388. * the time write_coefficients is called; indeed, if the virtual arrays
  167389. * were requested from this compression object's memory manager, they
  167390. * typically will be realized during this routine and filled afterwards.
  167391. */
  167392. GLOBAL(void)
  167393. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167394. {
  167395. if (cinfo->global_state != CSTATE_START)
  167396. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167397. /* Mark all tables to be written */
  167398. jpeg_suppress_tables(cinfo, FALSE);
  167399. /* (Re)initialize error mgr and destination modules */
  167400. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167401. (*cinfo->dest->init_destination) (cinfo);
  167402. /* Perform master selection of active modules */
  167403. transencode_master_selection(cinfo, coef_arrays);
  167404. /* Wait for jpeg_finish_compress() call */
  167405. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167406. cinfo->global_state = CSTATE_WRCOEFS;
  167407. }
  167408. /*
  167409. * Initialize the compression object with default parameters,
  167410. * then copy from the source object all parameters needed for lossless
  167411. * transcoding. Parameters that can be varied without loss (such as
  167412. * scan script and Huffman optimization) are left in their default states.
  167413. */
  167414. GLOBAL(void)
  167415. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167416. j_compress_ptr dstinfo)
  167417. {
  167418. JQUANT_TBL ** qtblptr;
  167419. jpeg_component_info *incomp, *outcomp;
  167420. JQUANT_TBL *c_quant, *slot_quant;
  167421. int tblno, ci, coefi;
  167422. /* Safety check to ensure start_compress not called yet. */
  167423. if (dstinfo->global_state != CSTATE_START)
  167424. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167425. /* Copy fundamental image dimensions */
  167426. dstinfo->image_width = srcinfo->image_width;
  167427. dstinfo->image_height = srcinfo->image_height;
  167428. dstinfo->input_components = srcinfo->num_components;
  167429. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167430. /* Initialize all parameters to default values */
  167431. jpeg_set_defaults(dstinfo);
  167432. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167433. * Fix it to get the right header markers for the image colorspace.
  167434. */
  167435. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167436. dstinfo->data_precision = srcinfo->data_precision;
  167437. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167438. /* Copy the source's quantization tables. */
  167439. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167440. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167441. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167442. if (*qtblptr == NULL)
  167443. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167444. MEMCOPY((*qtblptr)->quantval,
  167445. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167446. SIZEOF((*qtblptr)->quantval));
  167447. (*qtblptr)->sent_table = FALSE;
  167448. }
  167449. }
  167450. /* Copy the source's per-component info.
  167451. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167452. */
  167453. dstinfo->num_components = srcinfo->num_components;
  167454. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167455. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167456. MAX_COMPONENTS);
  167457. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167458. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167459. outcomp->component_id = incomp->component_id;
  167460. outcomp->h_samp_factor = incomp->h_samp_factor;
  167461. outcomp->v_samp_factor = incomp->v_samp_factor;
  167462. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167463. /* Make sure saved quantization table for component matches the qtable
  167464. * slot. If not, the input file re-used this qtable slot.
  167465. * IJG encoder currently cannot duplicate this.
  167466. */
  167467. tblno = outcomp->quant_tbl_no;
  167468. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167469. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167470. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167471. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167472. c_quant = incomp->quant_table;
  167473. if (c_quant != NULL) {
  167474. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167475. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167476. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167477. }
  167478. }
  167479. /* Note: we do not copy the source's Huffman table assignments;
  167480. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167481. */
  167482. }
  167483. /* Also copy JFIF version and resolution information, if available.
  167484. * Strictly speaking this isn't "critical" info, but it's nearly
  167485. * always appropriate to copy it if available. In particular,
  167486. * if the application chooses to copy JFIF 1.02 extension markers from
  167487. * the source file, we need to copy the version to make sure we don't
  167488. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167489. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167490. */
  167491. if (srcinfo->saw_JFIF_marker) {
  167492. if (srcinfo->JFIF_major_version == 1) {
  167493. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167494. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167495. }
  167496. dstinfo->density_unit = srcinfo->density_unit;
  167497. dstinfo->X_density = srcinfo->X_density;
  167498. dstinfo->Y_density = srcinfo->Y_density;
  167499. }
  167500. }
  167501. /*
  167502. * Master selection of compression modules for transcoding.
  167503. * This substitutes for jcinit.c's initialization of the full compressor.
  167504. */
  167505. LOCAL(void)
  167506. transencode_master_selection (j_compress_ptr cinfo,
  167507. jvirt_barray_ptr * coef_arrays)
  167508. {
  167509. /* Although we don't actually use input_components for transcoding,
  167510. * jcmaster.c's initial_setup will complain if input_components is 0.
  167511. */
  167512. cinfo->input_components = 1;
  167513. /* Initialize master control (includes parameter checking/processing) */
  167514. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167515. /* Entropy encoding: either Huffman or arithmetic coding. */
  167516. if (cinfo->arith_code) {
  167517. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167518. } else {
  167519. if (cinfo->progressive_mode) {
  167520. #ifdef C_PROGRESSIVE_SUPPORTED
  167521. jinit_phuff_encoder(cinfo);
  167522. #else
  167523. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167524. #endif
  167525. } else
  167526. jinit_huff_encoder(cinfo);
  167527. }
  167528. /* We need a special coefficient buffer controller. */
  167529. transencode_coef_controller(cinfo, coef_arrays);
  167530. jinit_marker_writer(cinfo);
  167531. /* We can now tell the memory manager to allocate virtual arrays. */
  167532. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167533. /* Write the datastream header (SOI, JFIF) immediately.
  167534. * Frame and scan headers are postponed till later.
  167535. * This lets application insert special markers after the SOI.
  167536. */
  167537. (*cinfo->marker->write_file_header) (cinfo);
  167538. }
  167539. /*
  167540. * The rest of this file is a special implementation of the coefficient
  167541. * buffer controller. This is similar to jccoefct.c, but it handles only
  167542. * output from presupplied virtual arrays. Furthermore, we generate any
  167543. * dummy padding blocks on-the-fly rather than expecting them to be present
  167544. * in the arrays.
  167545. */
  167546. /* Private buffer controller object */
  167547. typedef struct {
  167548. struct jpeg_c_coef_controller pub; /* public fields */
  167549. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167550. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167551. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167552. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167553. /* Virtual block array for each component. */
  167554. jvirt_barray_ptr * whole_image;
  167555. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167556. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167557. } my_coef_controller2;
  167558. typedef my_coef_controller2 * my_coef_ptr2;
  167559. LOCAL(void)
  167560. start_iMCU_row2 (j_compress_ptr cinfo)
  167561. /* Reset within-iMCU-row counters for a new row */
  167562. {
  167563. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167564. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167565. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167566. * But at the bottom of the image, process only what's left.
  167567. */
  167568. if (cinfo->comps_in_scan > 1) {
  167569. coef->MCU_rows_per_iMCU_row = 1;
  167570. } else {
  167571. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167572. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167573. else
  167574. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167575. }
  167576. coef->mcu_ctr = 0;
  167577. coef->MCU_vert_offset = 0;
  167578. }
  167579. /*
  167580. * Initialize for a processing pass.
  167581. */
  167582. METHODDEF(void)
  167583. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167584. {
  167585. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167586. if (pass_mode != JBUF_CRANK_DEST)
  167587. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167588. coef->iMCU_row_num = 0;
  167589. start_iMCU_row2(cinfo);
  167590. }
  167591. /*
  167592. * Process some data.
  167593. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167594. * per call, ie, v_samp_factor block rows for each component in the scan.
  167595. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167596. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167597. *
  167598. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167599. */
  167600. METHODDEF(boolean)
  167601. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167602. {
  167603. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167604. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167605. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167606. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167607. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167608. JDIMENSION start_col;
  167609. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167610. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167611. JBLOCKROW buffer_ptr;
  167612. jpeg_component_info *compptr;
  167613. /* Align the virtual buffers for the components used in this scan. */
  167614. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167615. compptr = cinfo->cur_comp_info[ci];
  167616. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167617. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167618. coef->iMCU_row_num * compptr->v_samp_factor,
  167619. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167620. }
  167621. /* Loop to process one whole iMCU row */
  167622. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167623. yoffset++) {
  167624. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167625. MCU_col_num++) {
  167626. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167627. blkn = 0; /* index of current DCT block within MCU */
  167628. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167629. compptr = cinfo->cur_comp_info[ci];
  167630. start_col = MCU_col_num * compptr->MCU_width;
  167631. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167632. : compptr->last_col_width;
  167633. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167634. if (coef->iMCU_row_num < last_iMCU_row ||
  167635. yindex+yoffset < compptr->last_row_height) {
  167636. /* Fill in pointers to real blocks in this row */
  167637. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167638. for (xindex = 0; xindex < blockcnt; xindex++)
  167639. MCU_buffer[blkn++] = buffer_ptr++;
  167640. } else {
  167641. /* At bottom of image, need a whole row of dummy blocks */
  167642. xindex = 0;
  167643. }
  167644. /* Fill in any dummy blocks needed in this row.
  167645. * Dummy blocks are filled in the same way as in jccoefct.c:
  167646. * all zeroes in the AC entries, DC entries equal to previous
  167647. * block's DC value. The init routine has already zeroed the
  167648. * AC entries, so we need only set the DC entries correctly.
  167649. */
  167650. for (; xindex < compptr->MCU_width; xindex++) {
  167651. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167652. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167653. blkn++;
  167654. }
  167655. }
  167656. }
  167657. /* Try to write the MCU. */
  167658. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167659. /* Suspension forced; update state counters and exit */
  167660. coef->MCU_vert_offset = yoffset;
  167661. coef->mcu_ctr = MCU_col_num;
  167662. return FALSE;
  167663. }
  167664. }
  167665. /* Completed an MCU row, but perhaps not an iMCU row */
  167666. coef->mcu_ctr = 0;
  167667. }
  167668. /* Completed the iMCU row, advance counters for next one */
  167669. coef->iMCU_row_num++;
  167670. start_iMCU_row2(cinfo);
  167671. return TRUE;
  167672. }
  167673. /*
  167674. * Initialize coefficient buffer controller.
  167675. *
  167676. * Each passed coefficient array must be the right size for that
  167677. * coefficient: width_in_blocks wide and height_in_blocks high,
  167678. * with unitheight at least v_samp_factor.
  167679. */
  167680. LOCAL(void)
  167681. transencode_coef_controller (j_compress_ptr cinfo,
  167682. jvirt_barray_ptr * coef_arrays)
  167683. {
  167684. my_coef_ptr2 coef;
  167685. JBLOCKROW buffer;
  167686. int i;
  167687. coef = (my_coef_ptr2)
  167688. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167689. SIZEOF(my_coef_controller2));
  167690. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167691. coef->pub.start_pass = start_pass_coef2;
  167692. coef->pub.compress_data = compress_output2;
  167693. /* Save pointer to virtual arrays */
  167694. coef->whole_image = coef_arrays;
  167695. /* Allocate and pre-zero space for dummy DCT blocks. */
  167696. buffer = (JBLOCKROW)
  167697. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167698. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167699. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167700. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167701. coef->dummy_buffer[i] = buffer + i;
  167702. }
  167703. }
  167704. /*** End of inlined file: jctrans.c ***/
  167705. /*** Start of inlined file: jdapistd.c ***/
  167706. #define JPEG_INTERNALS
  167707. /* Forward declarations */
  167708. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167709. /*
  167710. * Decompression initialization.
  167711. * jpeg_read_header must be completed before calling this.
  167712. *
  167713. * If a multipass operating mode was selected, this will do all but the
  167714. * last pass, and thus may take a great deal of time.
  167715. *
  167716. * Returns FALSE if suspended. The return value need be inspected only if
  167717. * a suspending data source is used.
  167718. */
  167719. GLOBAL(boolean)
  167720. jpeg_start_decompress (j_decompress_ptr cinfo)
  167721. {
  167722. if (cinfo->global_state == DSTATE_READY) {
  167723. /* First call: initialize master control, select active modules */
  167724. jinit_master_decompress(cinfo);
  167725. if (cinfo->buffered_image) {
  167726. /* No more work here; expecting jpeg_start_output next */
  167727. cinfo->global_state = DSTATE_BUFIMAGE;
  167728. return TRUE;
  167729. }
  167730. cinfo->global_state = DSTATE_PRELOAD;
  167731. }
  167732. if (cinfo->global_state == DSTATE_PRELOAD) {
  167733. /* If file has multiple scans, absorb them all into the coef buffer */
  167734. if (cinfo->inputctl->has_multiple_scans) {
  167735. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167736. for (;;) {
  167737. int retcode;
  167738. /* Call progress monitor hook if present */
  167739. if (cinfo->progress != NULL)
  167740. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167741. /* Absorb some more input */
  167742. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167743. if (retcode == JPEG_SUSPENDED)
  167744. return FALSE;
  167745. if (retcode == JPEG_REACHED_EOI)
  167746. break;
  167747. /* Advance progress counter if appropriate */
  167748. if (cinfo->progress != NULL &&
  167749. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167750. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167751. /* jdmaster underestimated number of scans; ratchet up one scan */
  167752. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167753. }
  167754. }
  167755. }
  167756. #else
  167757. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167758. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167759. }
  167760. cinfo->output_scan_number = cinfo->input_scan_number;
  167761. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167762. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167763. /* Perform any dummy output passes, and set up for the final pass */
  167764. return output_pass_setup(cinfo);
  167765. }
  167766. /*
  167767. * Set up for an output pass, and perform any dummy pass(es) needed.
  167768. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167769. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167770. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167771. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167772. */
  167773. LOCAL(boolean)
  167774. output_pass_setup (j_decompress_ptr cinfo)
  167775. {
  167776. if (cinfo->global_state != DSTATE_PRESCAN) {
  167777. /* First call: do pass setup */
  167778. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167779. cinfo->output_scanline = 0;
  167780. cinfo->global_state = DSTATE_PRESCAN;
  167781. }
  167782. /* Loop over any required dummy passes */
  167783. while (cinfo->master->is_dummy_pass) {
  167784. #ifdef QUANT_2PASS_SUPPORTED
  167785. /* Crank through the dummy pass */
  167786. while (cinfo->output_scanline < cinfo->output_height) {
  167787. JDIMENSION last_scanline;
  167788. /* Call progress monitor hook if present */
  167789. if (cinfo->progress != NULL) {
  167790. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167791. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167792. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167793. }
  167794. /* Process some data */
  167795. last_scanline = cinfo->output_scanline;
  167796. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167797. &cinfo->output_scanline, (JDIMENSION) 0);
  167798. if (cinfo->output_scanline == last_scanline)
  167799. return FALSE; /* No progress made, must suspend */
  167800. }
  167801. /* Finish up dummy pass, and set up for another one */
  167802. (*cinfo->master->finish_output_pass) (cinfo);
  167803. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167804. cinfo->output_scanline = 0;
  167805. #else
  167806. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167807. #endif /* QUANT_2PASS_SUPPORTED */
  167808. }
  167809. /* Ready for application to drive output pass through
  167810. * jpeg_read_scanlines or jpeg_read_raw_data.
  167811. */
  167812. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167813. return TRUE;
  167814. }
  167815. /*
  167816. * Read some scanlines of data from the JPEG decompressor.
  167817. *
  167818. * The return value will be the number of lines actually read.
  167819. * This may be less than the number requested in several cases,
  167820. * including bottom of image, data source suspension, and operating
  167821. * modes that emit multiple scanlines at a time.
  167822. *
  167823. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167824. * this likely signals an application programmer error. However,
  167825. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167826. */
  167827. GLOBAL(JDIMENSION)
  167828. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167829. JDIMENSION max_lines)
  167830. {
  167831. JDIMENSION row_ctr;
  167832. if (cinfo->global_state != DSTATE_SCANNING)
  167833. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167834. if (cinfo->output_scanline >= cinfo->output_height) {
  167835. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167836. return 0;
  167837. }
  167838. /* Call progress monitor hook if present */
  167839. if (cinfo->progress != NULL) {
  167840. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167841. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167842. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167843. }
  167844. /* Process some data */
  167845. row_ctr = 0;
  167846. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167847. cinfo->output_scanline += row_ctr;
  167848. return row_ctr;
  167849. }
  167850. /*
  167851. * Alternate entry point to read raw data.
  167852. * Processes exactly one iMCU row per call, unless suspended.
  167853. */
  167854. GLOBAL(JDIMENSION)
  167855. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167856. JDIMENSION max_lines)
  167857. {
  167858. JDIMENSION lines_per_iMCU_row;
  167859. if (cinfo->global_state != DSTATE_RAW_OK)
  167860. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167861. if (cinfo->output_scanline >= cinfo->output_height) {
  167862. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167863. return 0;
  167864. }
  167865. /* Call progress monitor hook if present */
  167866. if (cinfo->progress != NULL) {
  167867. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167868. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167869. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167870. }
  167871. /* Verify that at least one iMCU row can be returned. */
  167872. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167873. if (max_lines < lines_per_iMCU_row)
  167874. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167875. /* Decompress directly into user's buffer. */
  167876. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167877. return 0; /* suspension forced, can do nothing more */
  167878. /* OK, we processed one iMCU row. */
  167879. cinfo->output_scanline += lines_per_iMCU_row;
  167880. return lines_per_iMCU_row;
  167881. }
  167882. /* Additional entry points for buffered-image mode. */
  167883. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167884. /*
  167885. * Initialize for an output pass in buffered-image mode.
  167886. */
  167887. GLOBAL(boolean)
  167888. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167889. {
  167890. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167891. cinfo->global_state != DSTATE_PRESCAN)
  167892. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167893. /* Limit scan number to valid range */
  167894. if (scan_number <= 0)
  167895. scan_number = 1;
  167896. if (cinfo->inputctl->eoi_reached &&
  167897. scan_number > cinfo->input_scan_number)
  167898. scan_number = cinfo->input_scan_number;
  167899. cinfo->output_scan_number = scan_number;
  167900. /* Perform any dummy output passes, and set up for the real pass */
  167901. return output_pass_setup(cinfo);
  167902. }
  167903. /*
  167904. * Finish up after an output pass in buffered-image mode.
  167905. *
  167906. * Returns FALSE if suspended. The return value need be inspected only if
  167907. * a suspending data source is used.
  167908. */
  167909. GLOBAL(boolean)
  167910. jpeg_finish_output (j_decompress_ptr cinfo)
  167911. {
  167912. if ((cinfo->global_state == DSTATE_SCANNING ||
  167913. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167914. /* Terminate this pass. */
  167915. /* We do not require the whole pass to have been completed. */
  167916. (*cinfo->master->finish_output_pass) (cinfo);
  167917. cinfo->global_state = DSTATE_BUFPOST;
  167918. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167919. /* BUFPOST = repeat call after a suspension, anything else is error */
  167920. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167921. }
  167922. /* Read markers looking for SOS or EOI */
  167923. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167924. ! cinfo->inputctl->eoi_reached) {
  167925. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167926. return FALSE; /* Suspend, come back later */
  167927. }
  167928. cinfo->global_state = DSTATE_BUFIMAGE;
  167929. return TRUE;
  167930. }
  167931. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167932. /*** End of inlined file: jdapistd.c ***/
  167933. /*** Start of inlined file: jdapimin.c ***/
  167934. #define JPEG_INTERNALS
  167935. /*
  167936. * Initialization of a JPEG decompression object.
  167937. * The error manager must already be set up (in case memory manager fails).
  167938. */
  167939. GLOBAL(void)
  167940. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167941. {
  167942. int i;
  167943. /* Guard against version mismatches between library and caller. */
  167944. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167945. if (version != JPEG_LIB_VERSION)
  167946. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167947. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167948. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167949. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167950. /* For debugging purposes, we zero the whole master structure.
  167951. * But the application has already set the err pointer, and may have set
  167952. * client_data, so we have to save and restore those fields.
  167953. * Note: if application hasn't set client_data, tools like Purify may
  167954. * complain here.
  167955. */
  167956. {
  167957. struct jpeg_error_mgr * err = cinfo->err;
  167958. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167959. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167960. cinfo->err = err;
  167961. cinfo->client_data = client_data;
  167962. }
  167963. cinfo->is_decompressor = TRUE;
  167964. /* Initialize a memory manager instance for this object */
  167965. jinit_memory_mgr((j_common_ptr) cinfo);
  167966. /* Zero out pointers to permanent structures. */
  167967. cinfo->progress = NULL;
  167968. cinfo->src = NULL;
  167969. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167970. cinfo->quant_tbl_ptrs[i] = NULL;
  167971. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167972. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167973. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167974. }
  167975. /* Initialize marker processor so application can override methods
  167976. * for COM, APPn markers before calling jpeg_read_header.
  167977. */
  167978. cinfo->marker_list = NULL;
  167979. jinit_marker_reader(cinfo);
  167980. /* And initialize the overall input controller. */
  167981. jinit_input_controller(cinfo);
  167982. /* OK, I'm ready */
  167983. cinfo->global_state = DSTATE_START;
  167984. }
  167985. /*
  167986. * Destruction of a JPEG decompression object
  167987. */
  167988. GLOBAL(void)
  167989. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167990. {
  167991. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167992. }
  167993. /*
  167994. * Abort processing of a JPEG decompression operation,
  167995. * but don't destroy the object itself.
  167996. */
  167997. GLOBAL(void)
  167998. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167999. {
  168000. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  168001. }
  168002. /*
  168003. * Set default decompression parameters.
  168004. */
  168005. LOCAL(void)
  168006. default_decompress_parms (j_decompress_ptr cinfo)
  168007. {
  168008. /* Guess the input colorspace, and set output colorspace accordingly. */
  168009. /* (Wish JPEG committee had provided a real way to specify this...) */
  168010. /* Note application may override our guesses. */
  168011. switch (cinfo->num_components) {
  168012. case 1:
  168013. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  168014. cinfo->out_color_space = JCS_GRAYSCALE;
  168015. break;
  168016. case 3:
  168017. if (cinfo->saw_JFIF_marker) {
  168018. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  168019. } else if (cinfo->saw_Adobe_marker) {
  168020. switch (cinfo->Adobe_transform) {
  168021. case 0:
  168022. cinfo->jpeg_color_space = JCS_RGB;
  168023. break;
  168024. case 1:
  168025. cinfo->jpeg_color_space = JCS_YCbCr;
  168026. break;
  168027. default:
  168028. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168029. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168030. break;
  168031. }
  168032. } else {
  168033. /* Saw no special markers, try to guess from the component IDs */
  168034. int cid0 = cinfo->comp_info[0].component_id;
  168035. int cid1 = cinfo->comp_info[1].component_id;
  168036. int cid2 = cinfo->comp_info[2].component_id;
  168037. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168038. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168039. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168040. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168041. else {
  168042. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168043. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168044. }
  168045. }
  168046. /* Always guess RGB is proper output colorspace. */
  168047. cinfo->out_color_space = JCS_RGB;
  168048. break;
  168049. case 4:
  168050. if (cinfo->saw_Adobe_marker) {
  168051. switch (cinfo->Adobe_transform) {
  168052. case 0:
  168053. cinfo->jpeg_color_space = JCS_CMYK;
  168054. break;
  168055. case 2:
  168056. cinfo->jpeg_color_space = JCS_YCCK;
  168057. break;
  168058. default:
  168059. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168060. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168061. break;
  168062. }
  168063. } else {
  168064. /* No special markers, assume straight CMYK. */
  168065. cinfo->jpeg_color_space = JCS_CMYK;
  168066. }
  168067. cinfo->out_color_space = JCS_CMYK;
  168068. break;
  168069. default:
  168070. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168071. cinfo->out_color_space = JCS_UNKNOWN;
  168072. break;
  168073. }
  168074. /* Set defaults for other decompression parameters. */
  168075. cinfo->scale_num = 1; /* 1:1 scaling */
  168076. cinfo->scale_denom = 1;
  168077. cinfo->output_gamma = 1.0;
  168078. cinfo->buffered_image = FALSE;
  168079. cinfo->raw_data_out = FALSE;
  168080. cinfo->dct_method = JDCT_DEFAULT;
  168081. cinfo->do_fancy_upsampling = TRUE;
  168082. cinfo->do_block_smoothing = TRUE;
  168083. cinfo->quantize_colors = FALSE;
  168084. /* We set these in case application only sets quantize_colors. */
  168085. cinfo->dither_mode = JDITHER_FS;
  168086. #ifdef QUANT_2PASS_SUPPORTED
  168087. cinfo->two_pass_quantize = TRUE;
  168088. #else
  168089. cinfo->two_pass_quantize = FALSE;
  168090. #endif
  168091. cinfo->desired_number_of_colors = 256;
  168092. cinfo->colormap = NULL;
  168093. /* Initialize for no mode change in buffered-image mode. */
  168094. cinfo->enable_1pass_quant = FALSE;
  168095. cinfo->enable_external_quant = FALSE;
  168096. cinfo->enable_2pass_quant = FALSE;
  168097. }
  168098. /*
  168099. * Decompression startup: read start of JPEG datastream to see what's there.
  168100. * Need only initialize JPEG object and supply a data source before calling.
  168101. *
  168102. * This routine will read as far as the first SOS marker (ie, actual start of
  168103. * compressed data), and will save all tables and parameters in the JPEG
  168104. * object. It will also initialize the decompression parameters to default
  168105. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168106. * adjust the decompression parameters and then call jpeg_start_decompress.
  168107. * (Or, if the application only wanted to determine the image parameters,
  168108. * the data need not be decompressed. In that case, call jpeg_abort or
  168109. * jpeg_destroy to release any temporary space.)
  168110. * If an abbreviated (tables only) datastream is presented, the routine will
  168111. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168112. * re-use the JPEG object to read the abbreviated image datastream(s).
  168113. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168114. * The JPEG_SUSPENDED return code only occurs if the data source module
  168115. * requests suspension of the decompressor. In this case the application
  168116. * should load more source data and then re-call jpeg_read_header to resume
  168117. * processing.
  168118. * If a non-suspending data source is used and require_image is TRUE, then the
  168119. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168120. *
  168121. * This routine is now just a front end to jpeg_consume_input, with some
  168122. * extra error checking.
  168123. */
  168124. GLOBAL(int)
  168125. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168126. {
  168127. int retcode;
  168128. if (cinfo->global_state != DSTATE_START &&
  168129. cinfo->global_state != DSTATE_INHEADER)
  168130. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168131. retcode = jpeg_consume_input(cinfo);
  168132. switch (retcode) {
  168133. case JPEG_REACHED_SOS:
  168134. retcode = JPEG_HEADER_OK;
  168135. break;
  168136. case JPEG_REACHED_EOI:
  168137. if (require_image) /* Complain if application wanted an image */
  168138. ERREXIT(cinfo, JERR_NO_IMAGE);
  168139. /* Reset to start state; it would be safer to require the application to
  168140. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168141. * A side effect is to free any temporary memory (there shouldn't be any).
  168142. */
  168143. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168144. retcode = JPEG_HEADER_TABLES_ONLY;
  168145. break;
  168146. case JPEG_SUSPENDED:
  168147. /* no work */
  168148. break;
  168149. }
  168150. return retcode;
  168151. }
  168152. /*
  168153. * Consume data in advance of what the decompressor requires.
  168154. * This can be called at any time once the decompressor object has
  168155. * been created and a data source has been set up.
  168156. *
  168157. * This routine is essentially a state machine that handles a couple
  168158. * of critical state-transition actions, namely initial setup and
  168159. * transition from header scanning to ready-for-start_decompress.
  168160. * All the actual input is done via the input controller's consume_input
  168161. * method.
  168162. */
  168163. GLOBAL(int)
  168164. jpeg_consume_input (j_decompress_ptr cinfo)
  168165. {
  168166. int retcode = JPEG_SUSPENDED;
  168167. /* NB: every possible DSTATE value should be listed in this switch */
  168168. switch (cinfo->global_state) {
  168169. case DSTATE_START:
  168170. /* Start-of-datastream actions: reset appropriate modules */
  168171. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168172. /* Initialize application's data source module */
  168173. (*cinfo->src->init_source) (cinfo);
  168174. cinfo->global_state = DSTATE_INHEADER;
  168175. /*FALLTHROUGH*/
  168176. case DSTATE_INHEADER:
  168177. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168178. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168179. /* Set up default parameters based on header data */
  168180. default_decompress_parms(cinfo);
  168181. /* Set global state: ready for start_decompress */
  168182. cinfo->global_state = DSTATE_READY;
  168183. }
  168184. break;
  168185. case DSTATE_READY:
  168186. /* Can't advance past first SOS until start_decompress is called */
  168187. retcode = JPEG_REACHED_SOS;
  168188. break;
  168189. case DSTATE_PRELOAD:
  168190. case DSTATE_PRESCAN:
  168191. case DSTATE_SCANNING:
  168192. case DSTATE_RAW_OK:
  168193. case DSTATE_BUFIMAGE:
  168194. case DSTATE_BUFPOST:
  168195. case DSTATE_STOPPING:
  168196. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168197. break;
  168198. default:
  168199. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168200. }
  168201. return retcode;
  168202. }
  168203. /*
  168204. * Have we finished reading the input file?
  168205. */
  168206. GLOBAL(boolean)
  168207. jpeg_input_complete (j_decompress_ptr cinfo)
  168208. {
  168209. /* Check for valid jpeg object */
  168210. if (cinfo->global_state < DSTATE_START ||
  168211. cinfo->global_state > DSTATE_STOPPING)
  168212. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168213. return cinfo->inputctl->eoi_reached;
  168214. }
  168215. /*
  168216. * Is there more than one scan?
  168217. */
  168218. GLOBAL(boolean)
  168219. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168220. {
  168221. /* Only valid after jpeg_read_header completes */
  168222. if (cinfo->global_state < DSTATE_READY ||
  168223. cinfo->global_state > DSTATE_STOPPING)
  168224. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168225. return cinfo->inputctl->has_multiple_scans;
  168226. }
  168227. /*
  168228. * Finish JPEG decompression.
  168229. *
  168230. * This will normally just verify the file trailer and release temp storage.
  168231. *
  168232. * Returns FALSE if suspended. The return value need be inspected only if
  168233. * a suspending data source is used.
  168234. */
  168235. GLOBAL(boolean)
  168236. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168237. {
  168238. if ((cinfo->global_state == DSTATE_SCANNING ||
  168239. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168240. /* Terminate final pass of non-buffered mode */
  168241. if (cinfo->output_scanline < cinfo->output_height)
  168242. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168243. (*cinfo->master->finish_output_pass) (cinfo);
  168244. cinfo->global_state = DSTATE_STOPPING;
  168245. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168246. /* Finishing after a buffered-image operation */
  168247. cinfo->global_state = DSTATE_STOPPING;
  168248. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168249. /* STOPPING = repeat call after a suspension, anything else is error */
  168250. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168251. }
  168252. /* Read until EOI */
  168253. while (! cinfo->inputctl->eoi_reached) {
  168254. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168255. return FALSE; /* Suspend, come back later */
  168256. }
  168257. /* Do final cleanup */
  168258. (*cinfo->src->term_source) (cinfo);
  168259. /* We can use jpeg_abort to release memory and reset global_state */
  168260. jpeg_abort((j_common_ptr) cinfo);
  168261. return TRUE;
  168262. }
  168263. /*** End of inlined file: jdapimin.c ***/
  168264. /*** Start of inlined file: jdatasrc.c ***/
  168265. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168266. /*** Start of inlined file: jerror.h ***/
  168267. /*
  168268. * To define the enum list of message codes, include this file without
  168269. * defining macro JMESSAGE. To create a message string table, include it
  168270. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168271. */
  168272. #ifndef JMESSAGE
  168273. #ifndef JERROR_H
  168274. /* First time through, define the enum list */
  168275. #define JMAKE_ENUM_LIST
  168276. #else
  168277. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168278. #define JMESSAGE(code,string)
  168279. #endif /* JERROR_H */
  168280. #endif /* JMESSAGE */
  168281. #ifdef JMAKE_ENUM_LIST
  168282. typedef enum {
  168283. #define JMESSAGE(code,string) code ,
  168284. #endif /* JMAKE_ENUM_LIST */
  168285. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168286. /* For maintenance convenience, list is alphabetical by message code name */
  168287. JMESSAGE(JERR_ARITH_NOTIMPL,
  168288. "Sorry, there are legal restrictions on arithmetic coding")
  168289. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168290. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168291. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168292. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168293. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168294. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168295. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168296. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168297. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168298. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168299. JMESSAGE(JERR_BAD_LIB_VERSION,
  168300. "Wrong JPEG library version: library is %d, caller expects %d")
  168301. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168302. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168303. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168304. JMESSAGE(JERR_BAD_PROGRESSION,
  168305. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168306. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168307. "Invalid progressive parameters at scan script entry %d")
  168308. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168309. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168310. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168311. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168312. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168313. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168314. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168315. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168316. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168317. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168318. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168319. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168320. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168321. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168322. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168323. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168324. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168325. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168326. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168327. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168328. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168329. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168330. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168331. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168332. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168333. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168334. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168335. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168336. "Cannot transcode due to multiple use of quantization table %d")
  168337. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168338. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168339. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168340. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168341. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168342. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168343. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168344. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168345. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168346. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168347. JMESSAGE(JERR_QUANT_COMPONENTS,
  168348. "Cannot quantize more than %d color components")
  168349. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168350. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168351. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168352. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168353. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168354. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168355. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168356. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168357. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168358. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168359. JMESSAGE(JERR_TFILE_WRITE,
  168360. "Write failed on temporary file --- out of disk space?")
  168361. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168362. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168363. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168364. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168365. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168366. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168367. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168368. JMESSAGE(JMSG_VERSION, JVERSION)
  168369. JMESSAGE(JTRC_16BIT_TABLES,
  168370. "Caution: quantization tables are too coarse for baseline JPEG")
  168371. JMESSAGE(JTRC_ADOBE,
  168372. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168373. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168374. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168375. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168376. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168377. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168378. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168379. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168380. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168381. JMESSAGE(JTRC_EOI, "End Of Image")
  168382. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168383. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168384. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168385. "Warning: thumbnail image size does not match data length %u")
  168386. JMESSAGE(JTRC_JFIF_EXTENSION,
  168387. "JFIF extension marker: type 0x%02x, length %u")
  168388. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168389. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168390. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168391. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168392. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168393. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168394. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168395. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168396. JMESSAGE(JTRC_RST, "RST%d")
  168397. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168398. "Smoothing not supported with nonstandard sampling ratios")
  168399. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168400. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168401. JMESSAGE(JTRC_SOI, "Start of Image")
  168402. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168403. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168404. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168405. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168406. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168407. JMESSAGE(JTRC_THUMB_JPEG,
  168408. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168409. JMESSAGE(JTRC_THUMB_PALETTE,
  168410. "JFIF extension marker: palette thumbnail image, length %u")
  168411. JMESSAGE(JTRC_THUMB_RGB,
  168412. "JFIF extension marker: RGB thumbnail image, length %u")
  168413. JMESSAGE(JTRC_UNKNOWN_IDS,
  168414. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168415. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168416. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168417. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168418. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168419. "Inconsistent progression sequence for component %d coefficient %d")
  168420. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168421. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168422. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168423. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168424. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168425. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168426. JMESSAGE(JWRN_MUST_RESYNC,
  168427. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168428. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168429. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168430. #ifdef JMAKE_ENUM_LIST
  168431. JMSG_LASTMSGCODE
  168432. } J_MESSAGE_CODE;
  168433. #undef JMAKE_ENUM_LIST
  168434. #endif /* JMAKE_ENUM_LIST */
  168435. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168436. #undef JMESSAGE
  168437. #ifndef JERROR_H
  168438. #define JERROR_H
  168439. /* Macros to simplify using the error and trace message stuff */
  168440. /* The first parameter is either type of cinfo pointer */
  168441. /* Fatal errors (print message and exit) */
  168442. #define ERREXIT(cinfo,code) \
  168443. ((cinfo)->err->msg_code = (code), \
  168444. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168445. #define ERREXIT1(cinfo,code,p1) \
  168446. ((cinfo)->err->msg_code = (code), \
  168447. (cinfo)->err->msg_parm.i[0] = (p1), \
  168448. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168449. #define ERREXIT2(cinfo,code,p1,p2) \
  168450. ((cinfo)->err->msg_code = (code), \
  168451. (cinfo)->err->msg_parm.i[0] = (p1), \
  168452. (cinfo)->err->msg_parm.i[1] = (p2), \
  168453. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168454. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168455. ((cinfo)->err->msg_code = (code), \
  168456. (cinfo)->err->msg_parm.i[0] = (p1), \
  168457. (cinfo)->err->msg_parm.i[1] = (p2), \
  168458. (cinfo)->err->msg_parm.i[2] = (p3), \
  168459. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168460. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168461. ((cinfo)->err->msg_code = (code), \
  168462. (cinfo)->err->msg_parm.i[0] = (p1), \
  168463. (cinfo)->err->msg_parm.i[1] = (p2), \
  168464. (cinfo)->err->msg_parm.i[2] = (p3), \
  168465. (cinfo)->err->msg_parm.i[3] = (p4), \
  168466. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168467. #define ERREXITS(cinfo,code,str) \
  168468. ((cinfo)->err->msg_code = (code), \
  168469. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168470. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168471. #define MAKESTMT(stuff) do { stuff } while (0)
  168472. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168473. #define WARNMS(cinfo,code) \
  168474. ((cinfo)->err->msg_code = (code), \
  168475. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168476. #define WARNMS1(cinfo,code,p1) \
  168477. ((cinfo)->err->msg_code = (code), \
  168478. (cinfo)->err->msg_parm.i[0] = (p1), \
  168479. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168480. #define WARNMS2(cinfo,code,p1,p2) \
  168481. ((cinfo)->err->msg_code = (code), \
  168482. (cinfo)->err->msg_parm.i[0] = (p1), \
  168483. (cinfo)->err->msg_parm.i[1] = (p2), \
  168484. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168485. /* Informational/debugging messages */
  168486. #define TRACEMS(cinfo,lvl,code) \
  168487. ((cinfo)->err->msg_code = (code), \
  168488. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168489. #define TRACEMS1(cinfo,lvl,code,p1) \
  168490. ((cinfo)->err->msg_code = (code), \
  168491. (cinfo)->err->msg_parm.i[0] = (p1), \
  168492. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168493. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168494. ((cinfo)->err->msg_code = (code), \
  168495. (cinfo)->err->msg_parm.i[0] = (p1), \
  168496. (cinfo)->err->msg_parm.i[1] = (p2), \
  168497. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168498. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168499. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168500. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168501. (cinfo)->err->msg_code = (code); \
  168502. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168503. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168504. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168505. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168506. (cinfo)->err->msg_code = (code); \
  168507. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168508. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168509. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168510. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168511. _mp[4] = (p5); \
  168512. (cinfo)->err->msg_code = (code); \
  168513. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168514. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168515. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168516. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168517. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168518. (cinfo)->err->msg_code = (code); \
  168519. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168520. #define TRACEMSS(cinfo,lvl,code,str) \
  168521. ((cinfo)->err->msg_code = (code), \
  168522. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168523. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168524. #endif /* JERROR_H */
  168525. /*** End of inlined file: jerror.h ***/
  168526. /* Expanded data source object for stdio input */
  168527. typedef struct {
  168528. struct jpeg_source_mgr pub; /* public fields */
  168529. FILE * infile; /* source stream */
  168530. JOCTET * buffer; /* start of buffer */
  168531. boolean start_of_file; /* have we gotten any data yet? */
  168532. } my_source_mgr;
  168533. typedef my_source_mgr * my_src_ptr;
  168534. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168535. /*
  168536. * Initialize source --- called by jpeg_read_header
  168537. * before any data is actually read.
  168538. */
  168539. METHODDEF(void)
  168540. init_source (j_decompress_ptr cinfo)
  168541. {
  168542. my_src_ptr src = (my_src_ptr) cinfo->src;
  168543. /* We reset the empty-input-file flag for each image,
  168544. * but we don't clear the input buffer.
  168545. * This is correct behavior for reading a series of images from one source.
  168546. */
  168547. src->start_of_file = TRUE;
  168548. }
  168549. /*
  168550. * Fill the input buffer --- called whenever buffer is emptied.
  168551. *
  168552. * In typical applications, this should read fresh data into the buffer
  168553. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168554. * reset the pointer & count to the start of the buffer, and return TRUE
  168555. * indicating that the buffer has been reloaded. It is not necessary to
  168556. * fill the buffer entirely, only to obtain at least one more byte.
  168557. *
  168558. * There is no such thing as an EOF return. If the end of the file has been
  168559. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168560. * the buffer. In most cases, generating a warning message and inserting a
  168561. * fake EOI marker is the best course of action --- this will allow the
  168562. * decompressor to output however much of the image is there. However,
  168563. * the resulting error message is misleading if the real problem is an empty
  168564. * input file, so we handle that case specially.
  168565. *
  168566. * In applications that need to be able to suspend compression due to input
  168567. * not being available yet, a FALSE return indicates that no more data can be
  168568. * obtained right now, but more may be forthcoming later. In this situation,
  168569. * the decompressor will return to its caller (with an indication of the
  168570. * number of scanlines it has read, if any). The application should resume
  168571. * decompression after it has loaded more data into the input buffer. Note
  168572. * that there are substantial restrictions on the use of suspension --- see
  168573. * the documentation.
  168574. *
  168575. * When suspending, the decompressor will back up to a convenient restart point
  168576. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168577. * indicate where the restart point will be if the current call returns FALSE.
  168578. * Data beyond this point must be rescanned after resumption, so move it to
  168579. * the front of the buffer rather than discarding it.
  168580. */
  168581. METHODDEF(boolean)
  168582. fill_input_buffer (j_decompress_ptr cinfo)
  168583. {
  168584. my_src_ptr src = (my_src_ptr) cinfo->src;
  168585. size_t nbytes;
  168586. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168587. if (nbytes <= 0) {
  168588. if (src->start_of_file) /* Treat empty input file as fatal error */
  168589. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168590. WARNMS(cinfo, JWRN_JPEG_EOF);
  168591. /* Insert a fake EOI marker */
  168592. src->buffer[0] = (JOCTET) 0xFF;
  168593. src->buffer[1] = (JOCTET) JPEG_EOI;
  168594. nbytes = 2;
  168595. }
  168596. src->pub.next_input_byte = src->buffer;
  168597. src->pub.bytes_in_buffer = nbytes;
  168598. src->start_of_file = FALSE;
  168599. return TRUE;
  168600. }
  168601. /*
  168602. * Skip data --- used to skip over a potentially large amount of
  168603. * uninteresting data (such as an APPn marker).
  168604. *
  168605. * Writers of suspendable-input applications must note that skip_input_data
  168606. * is not granted the right to give a suspension return. If the skip extends
  168607. * beyond the data currently in the buffer, the buffer can be marked empty so
  168608. * that the next read will cause a fill_input_buffer call that can suspend.
  168609. * Arranging for additional bytes to be discarded before reloading the input
  168610. * buffer is the application writer's problem.
  168611. */
  168612. METHODDEF(void)
  168613. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168614. {
  168615. my_src_ptr src = (my_src_ptr) cinfo->src;
  168616. /* Just a dumb implementation for now. Could use fseek() except
  168617. * it doesn't work on pipes. Not clear that being smart is worth
  168618. * any trouble anyway --- large skips are infrequent.
  168619. */
  168620. if (num_bytes > 0) {
  168621. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168622. num_bytes -= (long) src->pub.bytes_in_buffer;
  168623. (void) fill_input_buffer(cinfo);
  168624. /* note we assume that fill_input_buffer will never return FALSE,
  168625. * so suspension need not be handled.
  168626. */
  168627. }
  168628. src->pub.next_input_byte += (size_t) num_bytes;
  168629. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168630. }
  168631. }
  168632. /*
  168633. * An additional method that can be provided by data source modules is the
  168634. * resync_to_restart method for error recovery in the presence of RST markers.
  168635. * For the moment, this source module just uses the default resync method
  168636. * provided by the JPEG library. That method assumes that no backtracking
  168637. * is possible.
  168638. */
  168639. /*
  168640. * Terminate source --- called by jpeg_finish_decompress
  168641. * after all data has been read. Often a no-op.
  168642. *
  168643. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168644. * application must deal with any cleanup that should happen even
  168645. * for error exit.
  168646. */
  168647. METHODDEF(void)
  168648. term_source (j_decompress_ptr)
  168649. {
  168650. /* no work necessary here */
  168651. }
  168652. /*
  168653. * Prepare for input from a stdio stream.
  168654. * The caller must have already opened the stream, and is responsible
  168655. * for closing it after finishing decompression.
  168656. */
  168657. GLOBAL(void)
  168658. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168659. {
  168660. my_src_ptr src;
  168661. /* The source object and input buffer are made permanent so that a series
  168662. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168663. * only before the first one. (If we discarded the buffer at the end of
  168664. * one image, we'd likely lose the start of the next one.)
  168665. * This makes it unsafe to use this manager and a different source
  168666. * manager serially with the same JPEG object. Caveat programmer.
  168667. */
  168668. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168669. cinfo->src = (struct jpeg_source_mgr *)
  168670. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168671. SIZEOF(my_source_mgr));
  168672. src = (my_src_ptr) cinfo->src;
  168673. src->buffer = (JOCTET *)
  168674. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168675. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168676. }
  168677. src = (my_src_ptr) cinfo->src;
  168678. src->pub.init_source = init_source;
  168679. src->pub.fill_input_buffer = fill_input_buffer;
  168680. src->pub.skip_input_data = skip_input_data;
  168681. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168682. src->pub.term_source = term_source;
  168683. src->infile = infile;
  168684. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168685. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168686. }
  168687. /*** End of inlined file: jdatasrc.c ***/
  168688. /*** Start of inlined file: jdcoefct.c ***/
  168689. #define JPEG_INTERNALS
  168690. /* Block smoothing is only applicable for progressive JPEG, so: */
  168691. #ifndef D_PROGRESSIVE_SUPPORTED
  168692. #undef BLOCK_SMOOTHING_SUPPORTED
  168693. #endif
  168694. /* Private buffer controller object */
  168695. typedef struct {
  168696. struct jpeg_d_coef_controller pub; /* public fields */
  168697. /* These variables keep track of the current location of the input side. */
  168698. /* cinfo->input_iMCU_row is also used for this. */
  168699. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168700. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168701. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168702. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168703. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168704. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168705. * and let the entropy decoder write into that workspace each time.
  168706. * (On 80x86, the workspace is FAR even though it's not really very big;
  168707. * this is to keep the module interfaces unchanged when a large coefficient
  168708. * buffer is necessary.)
  168709. * In multi-pass modes, this array points to the current MCU's blocks
  168710. * within the virtual arrays; it is used only by the input side.
  168711. */
  168712. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168713. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168714. /* In multi-pass modes, we need a virtual block array for each component. */
  168715. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168716. #endif
  168717. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168718. /* When doing block smoothing, we latch coefficient Al values here */
  168719. int * coef_bits_latch;
  168720. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168721. #endif
  168722. } my_coef_controller3;
  168723. typedef my_coef_controller3 * my_coef_ptr3;
  168724. /* Forward declarations */
  168725. METHODDEF(int) decompress_onepass
  168726. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168727. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168728. METHODDEF(int) decompress_data
  168729. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168730. #endif
  168731. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168732. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168733. METHODDEF(int) decompress_smooth_data
  168734. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168735. #endif
  168736. LOCAL(void)
  168737. start_iMCU_row3 (j_decompress_ptr cinfo)
  168738. /* Reset within-iMCU-row counters for a new row (input side) */
  168739. {
  168740. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168741. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168742. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168743. * But at the bottom of the image, process only what's left.
  168744. */
  168745. if (cinfo->comps_in_scan > 1) {
  168746. coef->MCU_rows_per_iMCU_row = 1;
  168747. } else {
  168748. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168749. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168750. else
  168751. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168752. }
  168753. coef->MCU_ctr = 0;
  168754. coef->MCU_vert_offset = 0;
  168755. }
  168756. /*
  168757. * Initialize for an input processing pass.
  168758. */
  168759. METHODDEF(void)
  168760. start_input_pass (j_decompress_ptr cinfo)
  168761. {
  168762. cinfo->input_iMCU_row = 0;
  168763. start_iMCU_row3(cinfo);
  168764. }
  168765. /*
  168766. * Initialize for an output processing pass.
  168767. */
  168768. METHODDEF(void)
  168769. start_output_pass (j_decompress_ptr cinfo)
  168770. {
  168771. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168772. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168773. /* If multipass, check to see whether to use block smoothing on this pass */
  168774. if (coef->pub.coef_arrays != NULL) {
  168775. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168776. coef->pub.decompress_data = decompress_smooth_data;
  168777. else
  168778. coef->pub.decompress_data = decompress_data;
  168779. }
  168780. #endif
  168781. cinfo->output_iMCU_row = 0;
  168782. }
  168783. /*
  168784. * Decompress and return some data in the single-pass case.
  168785. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168786. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168787. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168788. *
  168789. * NB: output_buf contains a plane for each component in image,
  168790. * which we index according to the component's SOF position.
  168791. */
  168792. METHODDEF(int)
  168793. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168794. {
  168795. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168796. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168797. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168798. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168799. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168800. JSAMPARRAY output_ptr;
  168801. JDIMENSION start_col, output_col;
  168802. jpeg_component_info *compptr;
  168803. inverse_DCT_method_ptr inverse_DCT;
  168804. /* Loop to process as much as one whole iMCU row */
  168805. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168806. yoffset++) {
  168807. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168808. MCU_col_num++) {
  168809. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168810. jzero_far((void FAR *) coef->MCU_buffer[0],
  168811. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168812. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168813. /* Suspension forced; update state counters and exit */
  168814. coef->MCU_vert_offset = yoffset;
  168815. coef->MCU_ctr = MCU_col_num;
  168816. return JPEG_SUSPENDED;
  168817. }
  168818. /* Determine where data should go in output_buf and do the IDCT thing.
  168819. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168820. * incremented past them!). Note the inner loop relies on having
  168821. * allocated the MCU_buffer[] blocks sequentially.
  168822. */
  168823. blkn = 0; /* index of current DCT block within MCU */
  168824. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168825. compptr = cinfo->cur_comp_info[ci];
  168826. /* Don't bother to IDCT an uninteresting component. */
  168827. if (! compptr->component_needed) {
  168828. blkn += compptr->MCU_blocks;
  168829. continue;
  168830. }
  168831. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168832. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168833. : compptr->last_col_width;
  168834. output_ptr = output_buf[compptr->component_index] +
  168835. yoffset * compptr->DCT_scaled_size;
  168836. start_col = MCU_col_num * compptr->MCU_sample_width;
  168837. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168838. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168839. yoffset+yindex < compptr->last_row_height) {
  168840. output_col = start_col;
  168841. for (xindex = 0; xindex < useful_width; xindex++) {
  168842. (*inverse_DCT) (cinfo, compptr,
  168843. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168844. output_ptr, output_col);
  168845. output_col += compptr->DCT_scaled_size;
  168846. }
  168847. }
  168848. blkn += compptr->MCU_width;
  168849. output_ptr += compptr->DCT_scaled_size;
  168850. }
  168851. }
  168852. }
  168853. /* Completed an MCU row, but perhaps not an iMCU row */
  168854. coef->MCU_ctr = 0;
  168855. }
  168856. /* Completed the iMCU row, advance counters for next one */
  168857. cinfo->output_iMCU_row++;
  168858. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168859. start_iMCU_row3(cinfo);
  168860. return JPEG_ROW_COMPLETED;
  168861. }
  168862. /* Completed the scan */
  168863. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168864. return JPEG_SCAN_COMPLETED;
  168865. }
  168866. /*
  168867. * Dummy consume-input routine for single-pass operation.
  168868. */
  168869. METHODDEF(int)
  168870. dummy_consume_data (j_decompress_ptr)
  168871. {
  168872. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168873. }
  168874. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168875. /*
  168876. * Consume input data and store it in the full-image coefficient buffer.
  168877. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168878. * ie, v_samp_factor block rows for each component in the scan.
  168879. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168880. */
  168881. METHODDEF(int)
  168882. consume_data (j_decompress_ptr cinfo)
  168883. {
  168884. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168885. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168886. int blkn, ci, xindex, yindex, yoffset;
  168887. JDIMENSION start_col;
  168888. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168889. JBLOCKROW buffer_ptr;
  168890. jpeg_component_info *compptr;
  168891. /* Align the virtual buffers for the components used in this scan. */
  168892. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168893. compptr = cinfo->cur_comp_info[ci];
  168894. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168895. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168896. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168897. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168898. /* Note: entropy decoder expects buffer to be zeroed,
  168899. * but this is handled automatically by the memory manager
  168900. * because we requested a pre-zeroed array.
  168901. */
  168902. }
  168903. /* Loop to process one whole iMCU row */
  168904. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168905. yoffset++) {
  168906. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168907. MCU_col_num++) {
  168908. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168909. blkn = 0; /* index of current DCT block within MCU */
  168910. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168911. compptr = cinfo->cur_comp_info[ci];
  168912. start_col = MCU_col_num * compptr->MCU_width;
  168913. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168914. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168915. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168916. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168917. }
  168918. }
  168919. }
  168920. /* Try to fetch the MCU. */
  168921. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168922. /* Suspension forced; update state counters and exit */
  168923. coef->MCU_vert_offset = yoffset;
  168924. coef->MCU_ctr = MCU_col_num;
  168925. return JPEG_SUSPENDED;
  168926. }
  168927. }
  168928. /* Completed an MCU row, but perhaps not an iMCU row */
  168929. coef->MCU_ctr = 0;
  168930. }
  168931. /* Completed the iMCU row, advance counters for next one */
  168932. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168933. start_iMCU_row3(cinfo);
  168934. return JPEG_ROW_COMPLETED;
  168935. }
  168936. /* Completed the scan */
  168937. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168938. return JPEG_SCAN_COMPLETED;
  168939. }
  168940. /*
  168941. * Decompress and return some data in the multi-pass case.
  168942. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168943. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168944. *
  168945. * NB: output_buf contains a plane for each component in image.
  168946. */
  168947. METHODDEF(int)
  168948. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168949. {
  168950. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168951. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168952. JDIMENSION block_num;
  168953. int ci, block_row, block_rows;
  168954. JBLOCKARRAY buffer;
  168955. JBLOCKROW buffer_ptr;
  168956. JSAMPARRAY output_ptr;
  168957. JDIMENSION output_col;
  168958. jpeg_component_info *compptr;
  168959. inverse_DCT_method_ptr inverse_DCT;
  168960. /* Force some input to be done if we are getting ahead of the input. */
  168961. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168962. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168963. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168964. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168965. return JPEG_SUSPENDED;
  168966. }
  168967. /* OK, output from the virtual arrays. */
  168968. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168969. ci++, compptr++) {
  168970. /* Don't bother to IDCT an uninteresting component. */
  168971. if (! compptr->component_needed)
  168972. continue;
  168973. /* Align the virtual buffer for this component. */
  168974. buffer = (*cinfo->mem->access_virt_barray)
  168975. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168976. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168977. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168978. /* Count non-dummy DCT block rows in this iMCU row. */
  168979. if (cinfo->output_iMCU_row < last_iMCU_row)
  168980. block_rows = compptr->v_samp_factor;
  168981. else {
  168982. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168983. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168984. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168985. }
  168986. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168987. output_ptr = output_buf[ci];
  168988. /* Loop over all DCT blocks to be processed. */
  168989. for (block_row = 0; block_row < block_rows; block_row++) {
  168990. buffer_ptr = buffer[block_row];
  168991. output_col = 0;
  168992. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168993. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168994. output_ptr, output_col);
  168995. buffer_ptr++;
  168996. output_col += compptr->DCT_scaled_size;
  168997. }
  168998. output_ptr += compptr->DCT_scaled_size;
  168999. }
  169000. }
  169001. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169002. return JPEG_ROW_COMPLETED;
  169003. return JPEG_SCAN_COMPLETED;
  169004. }
  169005. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169006. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169007. /*
  169008. * This code applies interblock smoothing as described by section K.8
  169009. * of the JPEG standard: the first 5 AC coefficients are estimated from
  169010. * the DC values of a DCT block and its 8 neighboring blocks.
  169011. * We apply smoothing only for progressive JPEG decoding, and only if
  169012. * the coefficients it can estimate are not yet known to full precision.
  169013. */
  169014. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  169015. #define Q01_POS 1
  169016. #define Q10_POS 8
  169017. #define Q20_POS 16
  169018. #define Q11_POS 9
  169019. #define Q02_POS 2
  169020. /*
  169021. * Determine whether block smoothing is applicable and safe.
  169022. * We also latch the current states of the coef_bits[] entries for the
  169023. * AC coefficients; otherwise, if the input side of the decompressor
  169024. * advances into a new scan, we might think the coefficients are known
  169025. * more accurately than they really are.
  169026. */
  169027. LOCAL(boolean)
  169028. smoothing_ok (j_decompress_ptr cinfo)
  169029. {
  169030. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169031. boolean smoothing_useful = FALSE;
  169032. int ci, coefi;
  169033. jpeg_component_info *compptr;
  169034. JQUANT_TBL * qtable;
  169035. int * coef_bits;
  169036. int * coef_bits_latch;
  169037. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169038. return FALSE;
  169039. /* Allocate latch area if not already done */
  169040. if (coef->coef_bits_latch == NULL)
  169041. coef->coef_bits_latch = (int *)
  169042. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169043. cinfo->num_components *
  169044. (SAVED_COEFS * SIZEOF(int)));
  169045. coef_bits_latch = coef->coef_bits_latch;
  169046. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169047. ci++, compptr++) {
  169048. /* All components' quantization values must already be latched. */
  169049. if ((qtable = compptr->quant_table) == NULL)
  169050. return FALSE;
  169051. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169052. if (qtable->quantval[0] == 0 ||
  169053. qtable->quantval[Q01_POS] == 0 ||
  169054. qtable->quantval[Q10_POS] == 0 ||
  169055. qtable->quantval[Q20_POS] == 0 ||
  169056. qtable->quantval[Q11_POS] == 0 ||
  169057. qtable->quantval[Q02_POS] == 0)
  169058. return FALSE;
  169059. /* DC values must be at least partly known for all components. */
  169060. coef_bits = cinfo->coef_bits[ci];
  169061. if (coef_bits[0] < 0)
  169062. return FALSE;
  169063. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169064. for (coefi = 1; coefi <= 5; coefi++) {
  169065. coef_bits_latch[coefi] = coef_bits[coefi];
  169066. if (coef_bits[coefi] != 0)
  169067. smoothing_useful = TRUE;
  169068. }
  169069. coef_bits_latch += SAVED_COEFS;
  169070. }
  169071. return smoothing_useful;
  169072. }
  169073. /*
  169074. * Variant of decompress_data for use when doing block smoothing.
  169075. */
  169076. METHODDEF(int)
  169077. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169078. {
  169079. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169080. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169081. JDIMENSION block_num, last_block_column;
  169082. int ci, block_row, block_rows, access_rows;
  169083. JBLOCKARRAY buffer;
  169084. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169085. JSAMPARRAY output_ptr;
  169086. JDIMENSION output_col;
  169087. jpeg_component_info *compptr;
  169088. inverse_DCT_method_ptr inverse_DCT;
  169089. boolean first_row, last_row;
  169090. JBLOCK workspace;
  169091. int *coef_bits;
  169092. JQUANT_TBL *quanttbl;
  169093. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169094. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169095. int Al, pred;
  169096. /* Force some input to be done if we are getting ahead of the input. */
  169097. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169098. ! cinfo->inputctl->eoi_reached) {
  169099. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169100. /* If input is working on current scan, we ordinarily want it to
  169101. * have completed the current row. But if input scan is DC,
  169102. * we want it to keep one row ahead so that next block row's DC
  169103. * values are up to date.
  169104. */
  169105. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169106. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169107. break;
  169108. }
  169109. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169110. return JPEG_SUSPENDED;
  169111. }
  169112. /* OK, output from the virtual arrays. */
  169113. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169114. ci++, compptr++) {
  169115. /* Don't bother to IDCT an uninteresting component. */
  169116. if (! compptr->component_needed)
  169117. continue;
  169118. /* Count non-dummy DCT block rows in this iMCU row. */
  169119. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169120. block_rows = compptr->v_samp_factor;
  169121. access_rows = block_rows * 2; /* this and next iMCU row */
  169122. last_row = FALSE;
  169123. } else {
  169124. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169125. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169126. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169127. access_rows = block_rows; /* this iMCU row only */
  169128. last_row = TRUE;
  169129. }
  169130. /* Align the virtual buffer for this component. */
  169131. if (cinfo->output_iMCU_row > 0) {
  169132. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169133. buffer = (*cinfo->mem->access_virt_barray)
  169134. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169135. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169136. (JDIMENSION) access_rows, FALSE);
  169137. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169138. first_row = FALSE;
  169139. } else {
  169140. buffer = (*cinfo->mem->access_virt_barray)
  169141. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169142. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169143. first_row = TRUE;
  169144. }
  169145. /* Fetch component-dependent info */
  169146. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169147. quanttbl = compptr->quant_table;
  169148. Q00 = quanttbl->quantval[0];
  169149. Q01 = quanttbl->quantval[Q01_POS];
  169150. Q10 = quanttbl->quantval[Q10_POS];
  169151. Q20 = quanttbl->quantval[Q20_POS];
  169152. Q11 = quanttbl->quantval[Q11_POS];
  169153. Q02 = quanttbl->quantval[Q02_POS];
  169154. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169155. output_ptr = output_buf[ci];
  169156. /* Loop over all DCT blocks to be processed. */
  169157. for (block_row = 0; block_row < block_rows; block_row++) {
  169158. buffer_ptr = buffer[block_row];
  169159. if (first_row && block_row == 0)
  169160. prev_block_row = buffer_ptr;
  169161. else
  169162. prev_block_row = buffer[block_row-1];
  169163. if (last_row && block_row == block_rows-1)
  169164. next_block_row = buffer_ptr;
  169165. else
  169166. next_block_row = buffer[block_row+1];
  169167. /* We fetch the surrounding DC values using a sliding-register approach.
  169168. * Initialize all nine here so as to do the right thing on narrow pics.
  169169. */
  169170. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169171. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169172. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169173. output_col = 0;
  169174. last_block_column = compptr->width_in_blocks - 1;
  169175. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169176. /* Fetch current DCT block into workspace so we can modify it. */
  169177. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169178. /* Update DC values */
  169179. if (block_num < last_block_column) {
  169180. DC3 = (int) prev_block_row[1][0];
  169181. DC6 = (int) buffer_ptr[1][0];
  169182. DC9 = (int) next_block_row[1][0];
  169183. }
  169184. /* Compute coefficient estimates per K.8.
  169185. * An estimate is applied only if coefficient is still zero,
  169186. * and is not known to be fully accurate.
  169187. */
  169188. /* AC01 */
  169189. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169190. num = 36 * Q00 * (DC4 - DC6);
  169191. if (num >= 0) {
  169192. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169193. if (Al > 0 && pred >= (1<<Al))
  169194. pred = (1<<Al)-1;
  169195. } else {
  169196. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169197. if (Al > 0 && pred >= (1<<Al))
  169198. pred = (1<<Al)-1;
  169199. pred = -pred;
  169200. }
  169201. workspace[1] = (JCOEF) pred;
  169202. }
  169203. /* AC10 */
  169204. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169205. num = 36 * Q00 * (DC2 - DC8);
  169206. if (num >= 0) {
  169207. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169208. if (Al > 0 && pred >= (1<<Al))
  169209. pred = (1<<Al)-1;
  169210. } else {
  169211. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169212. if (Al > 0 && pred >= (1<<Al))
  169213. pred = (1<<Al)-1;
  169214. pred = -pred;
  169215. }
  169216. workspace[8] = (JCOEF) pred;
  169217. }
  169218. /* AC20 */
  169219. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169220. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169221. if (num >= 0) {
  169222. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169223. if (Al > 0 && pred >= (1<<Al))
  169224. pred = (1<<Al)-1;
  169225. } else {
  169226. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169227. if (Al > 0 && pred >= (1<<Al))
  169228. pred = (1<<Al)-1;
  169229. pred = -pred;
  169230. }
  169231. workspace[16] = (JCOEF) pred;
  169232. }
  169233. /* AC11 */
  169234. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169235. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169236. if (num >= 0) {
  169237. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169238. if (Al > 0 && pred >= (1<<Al))
  169239. pred = (1<<Al)-1;
  169240. } else {
  169241. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169242. if (Al > 0 && pred >= (1<<Al))
  169243. pred = (1<<Al)-1;
  169244. pred = -pred;
  169245. }
  169246. workspace[9] = (JCOEF) pred;
  169247. }
  169248. /* AC02 */
  169249. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169250. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169251. if (num >= 0) {
  169252. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169253. if (Al > 0 && pred >= (1<<Al))
  169254. pred = (1<<Al)-1;
  169255. } else {
  169256. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169257. if (Al > 0 && pred >= (1<<Al))
  169258. pred = (1<<Al)-1;
  169259. pred = -pred;
  169260. }
  169261. workspace[2] = (JCOEF) pred;
  169262. }
  169263. /* OK, do the IDCT */
  169264. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169265. output_ptr, output_col);
  169266. /* Advance for next column */
  169267. DC1 = DC2; DC2 = DC3;
  169268. DC4 = DC5; DC5 = DC6;
  169269. DC7 = DC8; DC8 = DC9;
  169270. buffer_ptr++, prev_block_row++, next_block_row++;
  169271. output_col += compptr->DCT_scaled_size;
  169272. }
  169273. output_ptr += compptr->DCT_scaled_size;
  169274. }
  169275. }
  169276. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169277. return JPEG_ROW_COMPLETED;
  169278. return JPEG_SCAN_COMPLETED;
  169279. }
  169280. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169281. /*
  169282. * Initialize coefficient buffer controller.
  169283. */
  169284. GLOBAL(void)
  169285. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169286. {
  169287. my_coef_ptr3 coef;
  169288. coef = (my_coef_ptr3)
  169289. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169290. SIZEOF(my_coef_controller3));
  169291. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169292. coef->pub.start_input_pass = start_input_pass;
  169293. coef->pub.start_output_pass = start_output_pass;
  169294. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169295. coef->coef_bits_latch = NULL;
  169296. #endif
  169297. /* Create the coefficient buffer. */
  169298. if (need_full_buffer) {
  169299. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169300. /* Allocate a full-image virtual array for each component, */
  169301. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169302. /* Note we ask for a pre-zeroed array. */
  169303. int ci, access_rows;
  169304. jpeg_component_info *compptr;
  169305. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169306. ci++, compptr++) {
  169307. access_rows = compptr->v_samp_factor;
  169308. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169309. /* If block smoothing could be used, need a bigger window */
  169310. if (cinfo->progressive_mode)
  169311. access_rows *= 3;
  169312. #endif
  169313. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169314. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169315. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169316. (long) compptr->h_samp_factor),
  169317. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169318. (long) compptr->v_samp_factor),
  169319. (JDIMENSION) access_rows);
  169320. }
  169321. coef->pub.consume_data = consume_data;
  169322. coef->pub.decompress_data = decompress_data;
  169323. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169324. #else
  169325. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169326. #endif
  169327. } else {
  169328. /* We only need a single-MCU buffer. */
  169329. JBLOCKROW buffer;
  169330. int i;
  169331. buffer = (JBLOCKROW)
  169332. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169333. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169334. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169335. coef->MCU_buffer[i] = buffer + i;
  169336. }
  169337. coef->pub.consume_data = dummy_consume_data;
  169338. coef->pub.decompress_data = decompress_onepass;
  169339. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169340. }
  169341. }
  169342. /*** End of inlined file: jdcoefct.c ***/
  169343. #undef FIX
  169344. /*** Start of inlined file: jdcolor.c ***/
  169345. #define JPEG_INTERNALS
  169346. /* Private subobject */
  169347. typedef struct {
  169348. struct jpeg_color_deconverter pub; /* public fields */
  169349. /* Private state for YCC->RGB conversion */
  169350. int * Cr_r_tab; /* => table for Cr to R conversion */
  169351. int * Cb_b_tab; /* => table for Cb to B conversion */
  169352. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169353. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169354. } my_color_deconverter2;
  169355. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169356. /**************** YCbCr -> RGB conversion: most common case **************/
  169357. /*
  169358. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169359. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169360. * The conversion equations to be implemented are therefore
  169361. * R = Y + 1.40200 * Cr
  169362. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169363. * B = Y + 1.77200 * Cb
  169364. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169365. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169366. *
  169367. * To avoid floating-point arithmetic, we represent the fractional constants
  169368. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169369. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169370. * Notice that Y, being an integral input, does not contribute any fraction
  169371. * so it need not participate in the rounding.
  169372. *
  169373. * For even more speed, we avoid doing any multiplications in the inner loop
  169374. * by precalculating the constants times Cb and Cr for all possible values.
  169375. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169376. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169377. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169378. * colorspace anyway.
  169379. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169380. * values for the G calculation are left scaled up, since we must add them
  169381. * together before rounding.
  169382. */
  169383. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169384. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169385. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169386. /*
  169387. * Initialize tables for YCC->RGB colorspace conversion.
  169388. */
  169389. LOCAL(void)
  169390. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169391. {
  169392. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169393. int i;
  169394. INT32 x;
  169395. SHIFT_TEMPS
  169396. cconvert->Cr_r_tab = (int *)
  169397. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169398. (MAXJSAMPLE+1) * SIZEOF(int));
  169399. cconvert->Cb_b_tab = (int *)
  169400. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169401. (MAXJSAMPLE+1) * SIZEOF(int));
  169402. cconvert->Cr_g_tab = (INT32 *)
  169403. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169404. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169405. cconvert->Cb_g_tab = (INT32 *)
  169406. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169407. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169408. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169409. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169410. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169411. /* Cr=>R value is nearest int to 1.40200 * x */
  169412. cconvert->Cr_r_tab[i] = (int)
  169413. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169414. /* Cb=>B value is nearest int to 1.77200 * x */
  169415. cconvert->Cb_b_tab[i] = (int)
  169416. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169417. /* Cr=>G value is scaled-up -0.71414 * x */
  169418. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169419. /* Cb=>G value is scaled-up -0.34414 * x */
  169420. /* We also add in ONE_HALF so that need not do it in inner loop */
  169421. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169422. }
  169423. }
  169424. /*
  169425. * Convert some rows of samples to the output colorspace.
  169426. *
  169427. * Note that we change from noninterleaved, one-plane-per-component format
  169428. * to interleaved-pixel format. The output buffer is therefore three times
  169429. * as wide as the input buffer.
  169430. * A starting row offset is provided only for the input buffer. The caller
  169431. * can easily adjust the passed output_buf value to accommodate any row
  169432. * offset required on that side.
  169433. */
  169434. METHODDEF(void)
  169435. ycc_rgb_convert (j_decompress_ptr cinfo,
  169436. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169437. JSAMPARRAY output_buf, int num_rows)
  169438. {
  169439. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169440. register int y, cb, cr;
  169441. register JSAMPROW outptr;
  169442. register JSAMPROW inptr0, inptr1, inptr2;
  169443. register JDIMENSION col;
  169444. JDIMENSION num_cols = cinfo->output_width;
  169445. /* copy these pointers into registers if possible */
  169446. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169447. register int * Crrtab = cconvert->Cr_r_tab;
  169448. register int * Cbbtab = cconvert->Cb_b_tab;
  169449. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169450. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169451. SHIFT_TEMPS
  169452. while (--num_rows >= 0) {
  169453. inptr0 = input_buf[0][input_row];
  169454. inptr1 = input_buf[1][input_row];
  169455. inptr2 = input_buf[2][input_row];
  169456. input_row++;
  169457. outptr = *output_buf++;
  169458. for (col = 0; col < num_cols; col++) {
  169459. y = GETJSAMPLE(inptr0[col]);
  169460. cb = GETJSAMPLE(inptr1[col]);
  169461. cr = GETJSAMPLE(inptr2[col]);
  169462. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169463. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169464. outptr[RGB_GREEN] = range_limit[y +
  169465. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169466. SCALEBITS))];
  169467. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169468. outptr += RGB_PIXELSIZE;
  169469. }
  169470. }
  169471. }
  169472. /**************** Cases other than YCbCr -> RGB **************/
  169473. /*
  169474. * Color conversion for no colorspace change: just copy the data,
  169475. * converting from separate-planes to interleaved representation.
  169476. */
  169477. METHODDEF(void)
  169478. null_convert2 (j_decompress_ptr cinfo,
  169479. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169480. JSAMPARRAY output_buf, int num_rows)
  169481. {
  169482. register JSAMPROW inptr, outptr;
  169483. register JDIMENSION count;
  169484. register int num_components = cinfo->num_components;
  169485. JDIMENSION num_cols = cinfo->output_width;
  169486. int ci;
  169487. while (--num_rows >= 0) {
  169488. for (ci = 0; ci < num_components; ci++) {
  169489. inptr = input_buf[ci][input_row];
  169490. outptr = output_buf[0] + ci;
  169491. for (count = num_cols; count > 0; count--) {
  169492. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169493. outptr += num_components;
  169494. }
  169495. }
  169496. input_row++;
  169497. output_buf++;
  169498. }
  169499. }
  169500. /*
  169501. * Color conversion for grayscale: just copy the data.
  169502. * This also works for YCbCr -> grayscale conversion, in which
  169503. * we just copy the Y (luminance) component and ignore chrominance.
  169504. */
  169505. METHODDEF(void)
  169506. grayscale_convert2 (j_decompress_ptr cinfo,
  169507. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169508. JSAMPARRAY output_buf, int num_rows)
  169509. {
  169510. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169511. num_rows, cinfo->output_width);
  169512. }
  169513. /*
  169514. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169515. * This is provided to support applications that don't want to cope
  169516. * with grayscale as a separate case.
  169517. */
  169518. METHODDEF(void)
  169519. gray_rgb_convert (j_decompress_ptr cinfo,
  169520. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169521. JSAMPARRAY output_buf, int num_rows)
  169522. {
  169523. register JSAMPROW inptr, outptr;
  169524. register JDIMENSION col;
  169525. JDIMENSION num_cols = cinfo->output_width;
  169526. while (--num_rows >= 0) {
  169527. inptr = input_buf[0][input_row++];
  169528. outptr = *output_buf++;
  169529. for (col = 0; col < num_cols; col++) {
  169530. /* We can dispense with GETJSAMPLE() here */
  169531. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169532. outptr += RGB_PIXELSIZE;
  169533. }
  169534. }
  169535. }
  169536. /*
  169537. * Adobe-style YCCK->CMYK conversion.
  169538. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169539. * conversion as above, while passing K (black) unchanged.
  169540. * We assume build_ycc_rgb_table has been called.
  169541. */
  169542. METHODDEF(void)
  169543. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169544. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169545. JSAMPARRAY output_buf, int num_rows)
  169546. {
  169547. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169548. register int y, cb, cr;
  169549. register JSAMPROW outptr;
  169550. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169551. register JDIMENSION col;
  169552. JDIMENSION num_cols = cinfo->output_width;
  169553. /* copy these pointers into registers if possible */
  169554. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169555. register int * Crrtab = cconvert->Cr_r_tab;
  169556. register int * Cbbtab = cconvert->Cb_b_tab;
  169557. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169558. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169559. SHIFT_TEMPS
  169560. while (--num_rows >= 0) {
  169561. inptr0 = input_buf[0][input_row];
  169562. inptr1 = input_buf[1][input_row];
  169563. inptr2 = input_buf[2][input_row];
  169564. inptr3 = input_buf[3][input_row];
  169565. input_row++;
  169566. outptr = *output_buf++;
  169567. for (col = 0; col < num_cols; col++) {
  169568. y = GETJSAMPLE(inptr0[col]);
  169569. cb = GETJSAMPLE(inptr1[col]);
  169570. cr = GETJSAMPLE(inptr2[col]);
  169571. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169572. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169573. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169574. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169575. SCALEBITS)))];
  169576. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169577. /* K passes through unchanged */
  169578. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169579. outptr += 4;
  169580. }
  169581. }
  169582. }
  169583. /*
  169584. * Empty method for start_pass.
  169585. */
  169586. METHODDEF(void)
  169587. start_pass_dcolor (j_decompress_ptr)
  169588. {
  169589. /* no work needed */
  169590. }
  169591. /*
  169592. * Module initialization routine for output colorspace conversion.
  169593. */
  169594. GLOBAL(void)
  169595. jinit_color_deconverter (j_decompress_ptr cinfo)
  169596. {
  169597. my_cconvert_ptr2 cconvert;
  169598. int ci;
  169599. cconvert = (my_cconvert_ptr2)
  169600. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169601. SIZEOF(my_color_deconverter2));
  169602. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169603. cconvert->pub.start_pass = start_pass_dcolor;
  169604. /* Make sure num_components agrees with jpeg_color_space */
  169605. switch (cinfo->jpeg_color_space) {
  169606. case JCS_GRAYSCALE:
  169607. if (cinfo->num_components != 1)
  169608. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169609. break;
  169610. case JCS_RGB:
  169611. case JCS_YCbCr:
  169612. if (cinfo->num_components != 3)
  169613. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169614. break;
  169615. case JCS_CMYK:
  169616. case JCS_YCCK:
  169617. if (cinfo->num_components != 4)
  169618. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169619. break;
  169620. default: /* JCS_UNKNOWN can be anything */
  169621. if (cinfo->num_components < 1)
  169622. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169623. break;
  169624. }
  169625. /* Set out_color_components and conversion method based on requested space.
  169626. * Also clear the component_needed flags for any unused components,
  169627. * so that earlier pipeline stages can avoid useless computation.
  169628. */
  169629. switch (cinfo->out_color_space) {
  169630. case JCS_GRAYSCALE:
  169631. cinfo->out_color_components = 1;
  169632. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169633. cinfo->jpeg_color_space == JCS_YCbCr) {
  169634. cconvert->pub.color_convert = grayscale_convert2;
  169635. /* For color->grayscale conversion, only the Y (0) component is needed */
  169636. for (ci = 1; ci < cinfo->num_components; ci++)
  169637. cinfo->comp_info[ci].component_needed = FALSE;
  169638. } else
  169639. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169640. break;
  169641. case JCS_RGB:
  169642. cinfo->out_color_components = RGB_PIXELSIZE;
  169643. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169644. cconvert->pub.color_convert = ycc_rgb_convert;
  169645. build_ycc_rgb_table(cinfo);
  169646. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169647. cconvert->pub.color_convert = gray_rgb_convert;
  169648. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169649. cconvert->pub.color_convert = null_convert2;
  169650. } else
  169651. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169652. break;
  169653. case JCS_CMYK:
  169654. cinfo->out_color_components = 4;
  169655. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169656. cconvert->pub.color_convert = ycck_cmyk_convert;
  169657. build_ycc_rgb_table(cinfo);
  169658. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169659. cconvert->pub.color_convert = null_convert2;
  169660. } else
  169661. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169662. break;
  169663. default:
  169664. /* Permit null conversion to same output space */
  169665. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169666. cinfo->out_color_components = cinfo->num_components;
  169667. cconvert->pub.color_convert = null_convert2;
  169668. } else /* unsupported non-null conversion */
  169669. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169670. break;
  169671. }
  169672. if (cinfo->quantize_colors)
  169673. cinfo->output_components = 1; /* single colormapped output component */
  169674. else
  169675. cinfo->output_components = cinfo->out_color_components;
  169676. }
  169677. /*** End of inlined file: jdcolor.c ***/
  169678. #undef FIX
  169679. /*** Start of inlined file: jddctmgr.c ***/
  169680. #define JPEG_INTERNALS
  169681. /*
  169682. * The decompressor input side (jdinput.c) saves away the appropriate
  169683. * quantization table for each component at the start of the first scan
  169684. * involving that component. (This is necessary in order to correctly
  169685. * decode files that reuse Q-table slots.)
  169686. * When we are ready to make an output pass, the saved Q-table is converted
  169687. * to a multiplier table that will actually be used by the IDCT routine.
  169688. * The multiplier table contents are IDCT-method-dependent. To support
  169689. * application changes in IDCT method between scans, we can remake the
  169690. * multiplier tables if necessary.
  169691. * In buffered-image mode, the first output pass may occur before any data
  169692. * has been seen for some components, and thus before their Q-tables have
  169693. * been saved away. To handle this case, multiplier tables are preset
  169694. * to zeroes; the result of the IDCT will be a neutral gray level.
  169695. */
  169696. /* Private subobject for this module */
  169697. typedef struct {
  169698. struct jpeg_inverse_dct pub; /* public fields */
  169699. /* This array contains the IDCT method code that each multiplier table
  169700. * is currently set up for, or -1 if it's not yet set up.
  169701. * The actual multiplier tables are pointed to by dct_table in the
  169702. * per-component comp_info structures.
  169703. */
  169704. int cur_method[MAX_COMPONENTS];
  169705. } my_idct_controller;
  169706. typedef my_idct_controller * my_idct_ptr;
  169707. /* Allocated multiplier tables: big enough for any supported variant */
  169708. typedef union {
  169709. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169710. #ifdef DCT_IFAST_SUPPORTED
  169711. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169712. #endif
  169713. #ifdef DCT_FLOAT_SUPPORTED
  169714. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169715. #endif
  169716. } multiplier_table;
  169717. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169718. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169719. */
  169720. #ifdef DCT_ISLOW_SUPPORTED
  169721. #define PROVIDE_ISLOW_TABLES
  169722. #else
  169723. #ifdef IDCT_SCALING_SUPPORTED
  169724. #define PROVIDE_ISLOW_TABLES
  169725. #endif
  169726. #endif
  169727. /*
  169728. * Prepare for an output pass.
  169729. * Here we select the proper IDCT routine for each component and build
  169730. * a matching multiplier table.
  169731. */
  169732. METHODDEF(void)
  169733. start_pass (j_decompress_ptr cinfo)
  169734. {
  169735. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169736. int ci, i;
  169737. jpeg_component_info *compptr;
  169738. int method = 0;
  169739. inverse_DCT_method_ptr method_ptr = NULL;
  169740. JQUANT_TBL * qtbl;
  169741. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169742. ci++, compptr++) {
  169743. /* Select the proper IDCT routine for this component's scaling */
  169744. switch (compptr->DCT_scaled_size) {
  169745. #ifdef IDCT_SCALING_SUPPORTED
  169746. case 1:
  169747. method_ptr = jpeg_idct_1x1;
  169748. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169749. break;
  169750. case 2:
  169751. method_ptr = jpeg_idct_2x2;
  169752. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169753. break;
  169754. case 4:
  169755. method_ptr = jpeg_idct_4x4;
  169756. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169757. break;
  169758. #endif
  169759. case DCTSIZE:
  169760. switch (cinfo->dct_method) {
  169761. #ifdef DCT_ISLOW_SUPPORTED
  169762. case JDCT_ISLOW:
  169763. method_ptr = jpeg_idct_islow;
  169764. method = JDCT_ISLOW;
  169765. break;
  169766. #endif
  169767. #ifdef DCT_IFAST_SUPPORTED
  169768. case JDCT_IFAST:
  169769. method_ptr = jpeg_idct_ifast;
  169770. method = JDCT_IFAST;
  169771. break;
  169772. #endif
  169773. #ifdef DCT_FLOAT_SUPPORTED
  169774. case JDCT_FLOAT:
  169775. method_ptr = jpeg_idct_float;
  169776. method = JDCT_FLOAT;
  169777. break;
  169778. #endif
  169779. default:
  169780. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169781. break;
  169782. }
  169783. break;
  169784. default:
  169785. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169786. break;
  169787. }
  169788. idct->pub.inverse_DCT[ci] = method_ptr;
  169789. /* Create multiplier table from quant table.
  169790. * However, we can skip this if the component is uninteresting
  169791. * or if we already built the table. Also, if no quant table
  169792. * has yet been saved for the component, we leave the
  169793. * multiplier table all-zero; we'll be reading zeroes from the
  169794. * coefficient controller's buffer anyway.
  169795. */
  169796. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169797. continue;
  169798. qtbl = compptr->quant_table;
  169799. if (qtbl == NULL) /* happens if no data yet for component */
  169800. continue;
  169801. idct->cur_method[ci] = method;
  169802. switch (method) {
  169803. #ifdef PROVIDE_ISLOW_TABLES
  169804. case JDCT_ISLOW:
  169805. {
  169806. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169807. * coefficients, but are stored as ints to ensure access efficiency.
  169808. */
  169809. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169810. for (i = 0; i < DCTSIZE2; i++) {
  169811. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169812. }
  169813. }
  169814. break;
  169815. #endif
  169816. #ifdef DCT_IFAST_SUPPORTED
  169817. case JDCT_IFAST:
  169818. {
  169819. /* For AA&N IDCT method, multipliers are equal to quantization
  169820. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169821. * scalefactor[0] = 1
  169822. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169823. * For integer operation, the multiplier table is to be scaled by
  169824. * IFAST_SCALE_BITS.
  169825. */
  169826. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169827. #define CONST_BITS 14
  169828. static const INT16 aanscales[DCTSIZE2] = {
  169829. /* precomputed values scaled up by 14 bits */
  169830. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169831. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169832. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169833. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169834. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169835. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169836. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169837. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169838. };
  169839. SHIFT_TEMPS
  169840. for (i = 0; i < DCTSIZE2; i++) {
  169841. ifmtbl[i] = (IFAST_MULT_TYPE)
  169842. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169843. (INT32) aanscales[i]),
  169844. CONST_BITS-IFAST_SCALE_BITS);
  169845. }
  169846. }
  169847. break;
  169848. #endif
  169849. #ifdef DCT_FLOAT_SUPPORTED
  169850. case JDCT_FLOAT:
  169851. {
  169852. /* For float AA&N IDCT method, multipliers are equal to quantization
  169853. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169854. * scalefactor[0] = 1
  169855. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169856. */
  169857. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169858. int row, col;
  169859. static const double aanscalefactor[DCTSIZE] = {
  169860. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169861. 1.0, 0.785694958, 0.541196100, 0.275899379
  169862. };
  169863. i = 0;
  169864. for (row = 0; row < DCTSIZE; row++) {
  169865. for (col = 0; col < DCTSIZE; col++) {
  169866. fmtbl[i] = (FLOAT_MULT_TYPE)
  169867. ((double) qtbl->quantval[i] *
  169868. aanscalefactor[row] * aanscalefactor[col]);
  169869. i++;
  169870. }
  169871. }
  169872. }
  169873. break;
  169874. #endif
  169875. default:
  169876. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169877. break;
  169878. }
  169879. }
  169880. }
  169881. /*
  169882. * Initialize IDCT manager.
  169883. */
  169884. GLOBAL(void)
  169885. jinit_inverse_dct (j_decompress_ptr cinfo)
  169886. {
  169887. my_idct_ptr idct;
  169888. int ci;
  169889. jpeg_component_info *compptr;
  169890. idct = (my_idct_ptr)
  169891. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169892. SIZEOF(my_idct_controller));
  169893. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169894. idct->pub.start_pass = start_pass;
  169895. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169896. ci++, compptr++) {
  169897. /* Allocate and pre-zero a multiplier table for each component */
  169898. compptr->dct_table =
  169899. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169900. SIZEOF(multiplier_table));
  169901. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169902. /* Mark multiplier table not yet set up for any method */
  169903. idct->cur_method[ci] = -1;
  169904. }
  169905. }
  169906. /*** End of inlined file: jddctmgr.c ***/
  169907. #undef CONST_BITS
  169908. #undef ASSIGN_STATE
  169909. /*** Start of inlined file: jdhuff.c ***/
  169910. #define JPEG_INTERNALS
  169911. /*** Start of inlined file: jdhuff.h ***/
  169912. /* Short forms of external names for systems with brain-damaged linkers. */
  169913. #ifndef __jdhuff_h__
  169914. #define __jdhuff_h__
  169915. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169916. #define jpeg_make_d_derived_tbl jMkDDerived
  169917. #define jpeg_fill_bit_buffer jFilBitBuf
  169918. #define jpeg_huff_decode jHufDecode
  169919. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169920. /* Derived data constructed for each Huffman table */
  169921. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169922. typedef struct {
  169923. /* Basic tables: (element [0] of each array is unused) */
  169924. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169925. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169926. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169927. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169928. * the smallest code of length k; so given a code of length k, the
  169929. * corresponding symbol is huffval[code + valoffset[k]]
  169930. */
  169931. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169932. JHUFF_TBL *pub;
  169933. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169934. * the input data stream. If the next Huffman code is no more
  169935. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169936. * the corresponding symbol directly from these tables.
  169937. */
  169938. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169939. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169940. } d_derived_tbl;
  169941. /* Expand a Huffman table definition into the derived format */
  169942. EXTERN(void) jpeg_make_d_derived_tbl
  169943. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169944. d_derived_tbl ** pdtbl));
  169945. /*
  169946. * Fetching the next N bits from the input stream is a time-critical operation
  169947. * for the Huffman decoders. We implement it with a combination of inline
  169948. * macros and out-of-line subroutines. Note that N (the number of bits
  169949. * demanded at one time) never exceeds 15 for JPEG use.
  169950. *
  169951. * We read source bytes into get_buffer and dole out bits as needed.
  169952. * If get_buffer already contains enough bits, they are fetched in-line
  169953. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169954. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169955. * as full as possible (not just to the number of bits needed; this
  169956. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169957. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169958. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169959. * at least the requested number of bits --- dummy zeroes are inserted if
  169960. * necessary.
  169961. */
  169962. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169963. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169964. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169965. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169966. * appropriately should be a win. Unfortunately we can't define the size
  169967. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169968. * because not all machines measure sizeof in 8-bit bytes.
  169969. */
  169970. typedef struct { /* Bitreading state saved across MCUs */
  169971. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169972. int bits_left; /* # of unused bits in it */
  169973. } bitread_perm_state;
  169974. typedef struct { /* Bitreading working state within an MCU */
  169975. /* Current data source location */
  169976. /* We need a copy, rather than munging the original, in case of suspension */
  169977. const JOCTET * next_input_byte; /* => next byte to read from source */
  169978. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169979. /* Bit input buffer --- note these values are kept in register variables,
  169980. * not in this struct, inside the inner loops.
  169981. */
  169982. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169983. int bits_left; /* # of unused bits in it */
  169984. /* Pointer needed by jpeg_fill_bit_buffer. */
  169985. j_decompress_ptr cinfo; /* back link to decompress master record */
  169986. } bitread_working_state;
  169987. /* Macros to declare and load/save bitread local variables. */
  169988. #define BITREAD_STATE_VARS \
  169989. register bit_buf_type get_buffer; \
  169990. register int bits_left; \
  169991. bitread_working_state br_state
  169992. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169993. br_state.cinfo = cinfop; \
  169994. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169995. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169996. get_buffer = permstate.get_buffer; \
  169997. bits_left = permstate.bits_left;
  169998. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169999. cinfop->src->next_input_byte = br_state.next_input_byte; \
  170000. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  170001. permstate.get_buffer = get_buffer; \
  170002. permstate.bits_left = bits_left
  170003. /*
  170004. * These macros provide the in-line portion of bit fetching.
  170005. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  170006. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  170007. * The variables get_buffer and bits_left are assumed to be locals,
  170008. * but the state struct might not be (jpeg_huff_decode needs this).
  170009. * CHECK_BIT_BUFFER(state,n,action);
  170010. * Ensure there are N bits in get_buffer; if suspend, take action.
  170011. * val = GET_BITS(n);
  170012. * Fetch next N bits.
  170013. * val = PEEK_BITS(n);
  170014. * Fetch next N bits without removing them from the buffer.
  170015. * DROP_BITS(n);
  170016. * Discard next N bits.
  170017. * The value N should be a simple variable, not an expression, because it
  170018. * is evaluated multiple times.
  170019. */
  170020. #define CHECK_BIT_BUFFER(state,nbits,action) \
  170021. { if (bits_left < (nbits)) { \
  170022. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  170023. { action; } \
  170024. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  170025. #define GET_BITS(nbits) \
  170026. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  170027. #define PEEK_BITS(nbits) \
  170028. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170029. #define DROP_BITS(nbits) \
  170030. (bits_left -= (nbits))
  170031. /* Load up the bit buffer to a depth of at least nbits */
  170032. EXTERN(boolean) jpeg_fill_bit_buffer
  170033. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170034. register int bits_left, int nbits));
  170035. /*
  170036. * Code for extracting next Huffman-coded symbol from input bit stream.
  170037. * Again, this is time-critical and we make the main paths be macros.
  170038. *
  170039. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170040. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170041. * or fewer bits long. The few overlength codes are handled with a loop,
  170042. * which need not be inline code.
  170043. *
  170044. * Notes about the HUFF_DECODE macro:
  170045. * 1. Near the end of the data segment, we may fail to get enough bits
  170046. * for a lookahead. In that case, we do it the hard way.
  170047. * 2. If the lookahead table contains no entry, the next code must be
  170048. * more than HUFF_LOOKAHEAD bits long.
  170049. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170050. */
  170051. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170052. { register int nb, look; \
  170053. if (bits_left < HUFF_LOOKAHEAD) { \
  170054. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170055. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170056. if (bits_left < HUFF_LOOKAHEAD) { \
  170057. nb = 1; goto slowlabel; \
  170058. } \
  170059. } \
  170060. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170061. if ((nb = htbl->look_nbits[look]) != 0) { \
  170062. DROP_BITS(nb); \
  170063. result = htbl->look_sym[look]; \
  170064. } else { \
  170065. nb = HUFF_LOOKAHEAD+1; \
  170066. slowlabel: \
  170067. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170068. { failaction; } \
  170069. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170070. } \
  170071. }
  170072. /* Out-of-line case for Huffman code fetching */
  170073. EXTERN(int) jpeg_huff_decode
  170074. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170075. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170076. #endif
  170077. /*** End of inlined file: jdhuff.h ***/
  170078. /* Declarations shared with jdphuff.c */
  170079. /*
  170080. * Expanded entropy decoder object for Huffman decoding.
  170081. *
  170082. * The savable_state subrecord contains fields that change within an MCU,
  170083. * but must not be updated permanently until we complete the MCU.
  170084. */
  170085. typedef struct {
  170086. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170087. } savable_state2;
  170088. /* This macro is to work around compilers with missing or broken
  170089. * structure assignment. You'll need to fix this code if you have
  170090. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170091. */
  170092. #ifndef NO_STRUCT_ASSIGN
  170093. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170094. #else
  170095. #if MAX_COMPS_IN_SCAN == 4
  170096. #define ASSIGN_STATE(dest,src) \
  170097. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170098. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170099. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170100. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170101. #endif
  170102. #endif
  170103. typedef struct {
  170104. struct jpeg_entropy_decoder pub; /* public fields */
  170105. /* These fields are loaded into local variables at start of each MCU.
  170106. * In case of suspension, we exit WITHOUT updating them.
  170107. */
  170108. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170109. savable_state2 saved; /* Other state at start of MCU */
  170110. /* These fields are NOT loaded into local working state. */
  170111. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170112. /* Pointers to derived tables (these workspaces have image lifespan) */
  170113. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170114. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170115. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170116. /* Pointers to derived tables to be used for each block within an MCU */
  170117. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170118. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170119. /* Whether we care about the DC and AC coefficient values for each block */
  170120. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170121. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170122. } huff_entropy_decoder2;
  170123. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170124. /*
  170125. * Initialize for a Huffman-compressed scan.
  170126. */
  170127. METHODDEF(void)
  170128. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170129. {
  170130. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170131. int ci, blkn, dctbl, actbl;
  170132. jpeg_component_info * compptr;
  170133. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170134. * This ought to be an error condition, but we make it a warning because
  170135. * there are some baseline files out there with all zeroes in these bytes.
  170136. */
  170137. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170138. cinfo->Ah != 0 || cinfo->Al != 0)
  170139. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170140. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170141. compptr = cinfo->cur_comp_info[ci];
  170142. dctbl = compptr->dc_tbl_no;
  170143. actbl = compptr->ac_tbl_no;
  170144. /* Compute derived values for Huffman tables */
  170145. /* We may do this more than once for a table, but it's not expensive */
  170146. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170147. & entropy->dc_derived_tbls[dctbl]);
  170148. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170149. & entropy->ac_derived_tbls[actbl]);
  170150. /* Initialize DC predictions to 0 */
  170151. entropy->saved.last_dc_val[ci] = 0;
  170152. }
  170153. /* Precalculate decoding info for each block in an MCU of this scan */
  170154. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170155. ci = cinfo->MCU_membership[blkn];
  170156. compptr = cinfo->cur_comp_info[ci];
  170157. /* Precalculate which table to use for each block */
  170158. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170159. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170160. /* Decide whether we really care about the coefficient values */
  170161. if (compptr->component_needed) {
  170162. entropy->dc_needed[blkn] = TRUE;
  170163. /* we don't need the ACs if producing a 1/8th-size image */
  170164. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170165. } else {
  170166. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170167. }
  170168. }
  170169. /* Initialize bitread state variables */
  170170. entropy->bitstate.bits_left = 0;
  170171. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170172. entropy->pub.insufficient_data = FALSE;
  170173. /* Initialize restart counter */
  170174. entropy->restarts_to_go = cinfo->restart_interval;
  170175. }
  170176. /*
  170177. * Compute the derived values for a Huffman table.
  170178. * This routine also performs some validation checks on the table.
  170179. *
  170180. * Note this is also used by jdphuff.c.
  170181. */
  170182. GLOBAL(void)
  170183. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170184. d_derived_tbl ** pdtbl)
  170185. {
  170186. JHUFF_TBL *htbl;
  170187. d_derived_tbl *dtbl;
  170188. int p, i, l, si, numsymbols;
  170189. int lookbits, ctr;
  170190. char huffsize[257];
  170191. unsigned int huffcode[257];
  170192. unsigned int code;
  170193. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170194. * paralleling the order of the symbols themselves in htbl->huffval[].
  170195. */
  170196. /* Find the input Huffman table */
  170197. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170198. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170199. htbl =
  170200. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170201. if (htbl == NULL)
  170202. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170203. /* Allocate a workspace if we haven't already done so. */
  170204. if (*pdtbl == NULL)
  170205. *pdtbl = (d_derived_tbl *)
  170206. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170207. SIZEOF(d_derived_tbl));
  170208. dtbl = *pdtbl;
  170209. dtbl->pub = htbl; /* fill in back link */
  170210. /* Figure C.1: make table of Huffman code length for each symbol */
  170211. p = 0;
  170212. for (l = 1; l <= 16; l++) {
  170213. i = (int) htbl->bits[l];
  170214. if (i < 0 || p + i > 256) /* protect against table overrun */
  170215. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170216. while (i--)
  170217. huffsize[p++] = (char) l;
  170218. }
  170219. huffsize[p] = 0;
  170220. numsymbols = p;
  170221. /* Figure C.2: generate the codes themselves */
  170222. /* We also validate that the counts represent a legal Huffman code tree. */
  170223. code = 0;
  170224. si = huffsize[0];
  170225. p = 0;
  170226. while (huffsize[p]) {
  170227. while (((int) huffsize[p]) == si) {
  170228. huffcode[p++] = code;
  170229. code++;
  170230. }
  170231. /* code is now 1 more than the last code used for codelength si; but
  170232. * it must still fit in si bits, since no code is allowed to be all ones.
  170233. */
  170234. if (((INT32) code) >= (((INT32) 1) << si))
  170235. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170236. code <<= 1;
  170237. si++;
  170238. }
  170239. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170240. p = 0;
  170241. for (l = 1; l <= 16; l++) {
  170242. if (htbl->bits[l]) {
  170243. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170244. * minus the minimum code of length l
  170245. */
  170246. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170247. p += htbl->bits[l];
  170248. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170249. } else {
  170250. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170251. }
  170252. }
  170253. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170254. /* Compute lookahead tables to speed up decoding.
  170255. * First we set all the table entries to 0, indicating "too long";
  170256. * then we iterate through the Huffman codes that are short enough and
  170257. * fill in all the entries that correspond to bit sequences starting
  170258. * with that code.
  170259. */
  170260. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170261. p = 0;
  170262. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170263. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170264. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170265. /* Generate left-justified code followed by all possible bit sequences */
  170266. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170267. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170268. dtbl->look_nbits[lookbits] = l;
  170269. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170270. lookbits++;
  170271. }
  170272. }
  170273. }
  170274. /* Validate symbols as being reasonable.
  170275. * For AC tables, we make no check, but accept all byte values 0..255.
  170276. * For DC tables, we require the symbols to be in range 0..15.
  170277. * (Tighter bounds could be applied depending on the data depth and mode,
  170278. * but this is sufficient to ensure safe decoding.)
  170279. */
  170280. if (isDC) {
  170281. for (i = 0; i < numsymbols; i++) {
  170282. int sym = htbl->huffval[i];
  170283. if (sym < 0 || sym > 15)
  170284. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170285. }
  170286. }
  170287. }
  170288. /*
  170289. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170290. * See jdhuff.h for info about usage.
  170291. * Note: current values of get_buffer and bits_left are passed as parameters,
  170292. * but are returned in the corresponding fields of the state struct.
  170293. *
  170294. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170295. * of get_buffer to be used. (On machines with wider words, an even larger
  170296. * buffer could be used.) However, on some machines 32-bit shifts are
  170297. * quite slow and take time proportional to the number of places shifted.
  170298. * (This is true with most PC compilers, for instance.) In this case it may
  170299. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170300. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170301. */
  170302. #ifdef SLOW_SHIFT_32
  170303. #define MIN_GET_BITS 15 /* minimum allowable value */
  170304. #else
  170305. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170306. #endif
  170307. GLOBAL(boolean)
  170308. jpeg_fill_bit_buffer (bitread_working_state * state,
  170309. register bit_buf_type get_buffer, register int bits_left,
  170310. int nbits)
  170311. /* Load up the bit buffer to a depth of at least nbits */
  170312. {
  170313. /* Copy heavily used state fields into locals (hopefully registers) */
  170314. register const JOCTET * next_input_byte = state->next_input_byte;
  170315. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170316. j_decompress_ptr cinfo = state->cinfo;
  170317. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170318. /* (It is assumed that no request will be for more than that many bits.) */
  170319. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170320. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170321. while (bits_left < MIN_GET_BITS) {
  170322. register int c;
  170323. /* Attempt to read a byte */
  170324. if (bytes_in_buffer == 0) {
  170325. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170326. return FALSE;
  170327. next_input_byte = cinfo->src->next_input_byte;
  170328. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170329. }
  170330. bytes_in_buffer--;
  170331. c = GETJOCTET(*next_input_byte++);
  170332. /* If it's 0xFF, check and discard stuffed zero byte */
  170333. if (c == 0xFF) {
  170334. /* Loop here to discard any padding FF's on terminating marker,
  170335. * so that we can save a valid unread_marker value. NOTE: we will
  170336. * accept multiple FF's followed by a 0 as meaning a single FF data
  170337. * byte. This data pattern is not valid according to the standard.
  170338. */
  170339. do {
  170340. if (bytes_in_buffer == 0) {
  170341. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170342. return FALSE;
  170343. next_input_byte = cinfo->src->next_input_byte;
  170344. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170345. }
  170346. bytes_in_buffer--;
  170347. c = GETJOCTET(*next_input_byte++);
  170348. } while (c == 0xFF);
  170349. if (c == 0) {
  170350. /* Found FF/00, which represents an FF data byte */
  170351. c = 0xFF;
  170352. } else {
  170353. /* Oops, it's actually a marker indicating end of compressed data.
  170354. * Save the marker code for later use.
  170355. * Fine point: it might appear that we should save the marker into
  170356. * bitread working state, not straight into permanent state. But
  170357. * once we have hit a marker, we cannot need to suspend within the
  170358. * current MCU, because we will read no more bytes from the data
  170359. * source. So it is OK to update permanent state right away.
  170360. */
  170361. cinfo->unread_marker = c;
  170362. /* See if we need to insert some fake zero bits. */
  170363. goto no_more_bytes;
  170364. }
  170365. }
  170366. /* OK, load c into get_buffer */
  170367. get_buffer = (get_buffer << 8) | c;
  170368. bits_left += 8;
  170369. } /* end while */
  170370. } else {
  170371. no_more_bytes:
  170372. /* We get here if we've read the marker that terminates the compressed
  170373. * data segment. There should be enough bits in the buffer register
  170374. * to satisfy the request; if so, no problem.
  170375. */
  170376. if (nbits > bits_left) {
  170377. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170378. * the data stream, so that we can produce some kind of image.
  170379. * We use a nonvolatile flag to ensure that only one warning message
  170380. * appears per data segment.
  170381. */
  170382. if (! cinfo->entropy->insufficient_data) {
  170383. WARNMS(cinfo, JWRN_HIT_MARKER);
  170384. cinfo->entropy->insufficient_data = TRUE;
  170385. }
  170386. /* Fill the buffer with zero bits */
  170387. get_buffer <<= MIN_GET_BITS - bits_left;
  170388. bits_left = MIN_GET_BITS;
  170389. }
  170390. }
  170391. /* Unload the local registers */
  170392. state->next_input_byte = next_input_byte;
  170393. state->bytes_in_buffer = bytes_in_buffer;
  170394. state->get_buffer = get_buffer;
  170395. state->bits_left = bits_left;
  170396. return TRUE;
  170397. }
  170398. /*
  170399. * Out-of-line code for Huffman code decoding.
  170400. * See jdhuff.h for info about usage.
  170401. */
  170402. GLOBAL(int)
  170403. jpeg_huff_decode (bitread_working_state * state,
  170404. register bit_buf_type get_buffer, register int bits_left,
  170405. d_derived_tbl * htbl, int min_bits)
  170406. {
  170407. register int l = min_bits;
  170408. register INT32 code;
  170409. /* HUFF_DECODE has determined that the code is at least min_bits */
  170410. /* bits long, so fetch that many bits in one swoop. */
  170411. CHECK_BIT_BUFFER(*state, l, return -1);
  170412. code = GET_BITS(l);
  170413. /* Collect the rest of the Huffman code one bit at a time. */
  170414. /* This is per Figure F.16 in the JPEG spec. */
  170415. while (code > htbl->maxcode[l]) {
  170416. code <<= 1;
  170417. CHECK_BIT_BUFFER(*state, 1, return -1);
  170418. code |= GET_BITS(1);
  170419. l++;
  170420. }
  170421. /* Unload the local registers */
  170422. state->get_buffer = get_buffer;
  170423. state->bits_left = bits_left;
  170424. /* With garbage input we may reach the sentinel value l = 17. */
  170425. if (l > 16) {
  170426. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170427. return 0; /* fake a zero as the safest result */
  170428. }
  170429. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170430. }
  170431. /*
  170432. * Check for a restart marker & resynchronize decoder.
  170433. * Returns FALSE if must suspend.
  170434. */
  170435. LOCAL(boolean)
  170436. process_restart (j_decompress_ptr cinfo)
  170437. {
  170438. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170439. int ci;
  170440. /* Throw away any unused bits remaining in bit buffer; */
  170441. /* include any full bytes in next_marker's count of discarded bytes */
  170442. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170443. entropy->bitstate.bits_left = 0;
  170444. /* Advance past the RSTn marker */
  170445. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170446. return FALSE;
  170447. /* Re-initialize DC predictions to 0 */
  170448. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170449. entropy->saved.last_dc_val[ci] = 0;
  170450. /* Reset restart counter */
  170451. entropy->restarts_to_go = cinfo->restart_interval;
  170452. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170453. * against a marker. In that case we will end up treating the next data
  170454. * segment as empty, and we can avoid producing bogus output pixels by
  170455. * leaving the flag set.
  170456. */
  170457. if (cinfo->unread_marker == 0)
  170458. entropy->pub.insufficient_data = FALSE;
  170459. return TRUE;
  170460. }
  170461. /*
  170462. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170463. * The coefficients are reordered from zigzag order into natural array order,
  170464. * but are not dequantized.
  170465. *
  170466. * The i'th block of the MCU is stored into the block pointed to by
  170467. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170468. * (Wholesale zeroing is usually a little faster than retail...)
  170469. *
  170470. * Returns FALSE if data source requested suspension. In that case no
  170471. * changes have been made to permanent state. (Exception: some output
  170472. * coefficients may already have been assigned. This is harmless for
  170473. * this module, since we'll just re-assign them on the next call.)
  170474. */
  170475. METHODDEF(boolean)
  170476. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170477. {
  170478. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170479. int blkn;
  170480. BITREAD_STATE_VARS;
  170481. savable_state2 state;
  170482. /* Process restart marker if needed; may have to suspend */
  170483. if (cinfo->restart_interval) {
  170484. if (entropy->restarts_to_go == 0)
  170485. if (! process_restart(cinfo))
  170486. return FALSE;
  170487. }
  170488. /* If we've run out of data, just leave the MCU set to zeroes.
  170489. * This way, we return uniform gray for the remainder of the segment.
  170490. */
  170491. if (! entropy->pub.insufficient_data) {
  170492. /* Load up working state */
  170493. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170494. ASSIGN_STATE(state, entropy->saved);
  170495. /* Outer loop handles each block in the MCU */
  170496. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170497. JBLOCKROW block = MCU_data[blkn];
  170498. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170499. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170500. register int s, k, r;
  170501. /* Decode a single block's worth of coefficients */
  170502. /* Section F.2.2.1: decode the DC coefficient difference */
  170503. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170504. if (s) {
  170505. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170506. r = GET_BITS(s);
  170507. s = HUFF_EXTEND(r, s);
  170508. }
  170509. if (entropy->dc_needed[blkn]) {
  170510. /* Convert DC difference to actual value, update last_dc_val */
  170511. int ci = cinfo->MCU_membership[blkn];
  170512. s += state.last_dc_val[ci];
  170513. state.last_dc_val[ci] = s;
  170514. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170515. (*block)[0] = (JCOEF) s;
  170516. }
  170517. if (entropy->ac_needed[blkn]) {
  170518. /* Section F.2.2.2: decode the AC coefficients */
  170519. /* Since zeroes are skipped, output area must be cleared beforehand */
  170520. for (k = 1; k < DCTSIZE2; k++) {
  170521. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170522. r = s >> 4;
  170523. s &= 15;
  170524. if (s) {
  170525. k += r;
  170526. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170527. r = GET_BITS(s);
  170528. s = HUFF_EXTEND(r, s);
  170529. /* Output coefficient in natural (dezigzagged) order.
  170530. * Note: the extra entries in jpeg_natural_order[] will save us
  170531. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170532. */
  170533. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170534. } else {
  170535. if (r != 15)
  170536. break;
  170537. k += 15;
  170538. }
  170539. }
  170540. } else {
  170541. /* Section F.2.2.2: decode the AC coefficients */
  170542. /* In this path we just discard the values */
  170543. for (k = 1; k < DCTSIZE2; k++) {
  170544. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170545. r = s >> 4;
  170546. s &= 15;
  170547. if (s) {
  170548. k += r;
  170549. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170550. DROP_BITS(s);
  170551. } else {
  170552. if (r != 15)
  170553. break;
  170554. k += 15;
  170555. }
  170556. }
  170557. }
  170558. }
  170559. /* Completed MCU, so update state */
  170560. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170561. ASSIGN_STATE(entropy->saved, state);
  170562. }
  170563. /* Account for restart interval (no-op if not using restarts) */
  170564. entropy->restarts_to_go--;
  170565. return TRUE;
  170566. }
  170567. /*
  170568. * Module initialization routine for Huffman entropy decoding.
  170569. */
  170570. GLOBAL(void)
  170571. jinit_huff_decoder (j_decompress_ptr cinfo)
  170572. {
  170573. huff_entropy_ptr2 entropy;
  170574. int i;
  170575. entropy = (huff_entropy_ptr2)
  170576. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170577. SIZEOF(huff_entropy_decoder2));
  170578. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170579. entropy->pub.start_pass = start_pass_huff_decoder;
  170580. entropy->pub.decode_mcu = decode_mcu;
  170581. /* Mark tables unallocated */
  170582. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170583. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170584. }
  170585. }
  170586. /*** End of inlined file: jdhuff.c ***/
  170587. /*** Start of inlined file: jdinput.c ***/
  170588. #define JPEG_INTERNALS
  170589. /* Private state */
  170590. typedef struct {
  170591. struct jpeg_input_controller pub; /* public fields */
  170592. boolean inheaders; /* TRUE until first SOS is reached */
  170593. } my_input_controller;
  170594. typedef my_input_controller * my_inputctl_ptr;
  170595. /* Forward declarations */
  170596. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170597. /*
  170598. * Routines to calculate various quantities related to the size of the image.
  170599. */
  170600. LOCAL(void)
  170601. initial_setup2 (j_decompress_ptr cinfo)
  170602. /* Called once, when first SOS marker is reached */
  170603. {
  170604. int ci;
  170605. jpeg_component_info *compptr;
  170606. /* Make sure image isn't bigger than I can handle */
  170607. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170608. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170609. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170610. /* For now, precision must match compiled-in value... */
  170611. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170612. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170613. /* Check that number of components won't exceed internal array sizes */
  170614. if (cinfo->num_components > MAX_COMPONENTS)
  170615. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170616. MAX_COMPONENTS);
  170617. /* Compute maximum sampling factors; check factor validity */
  170618. cinfo->max_h_samp_factor = 1;
  170619. cinfo->max_v_samp_factor = 1;
  170620. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170621. ci++, compptr++) {
  170622. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170623. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170624. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170625. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170626. compptr->h_samp_factor);
  170627. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170628. compptr->v_samp_factor);
  170629. }
  170630. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170631. * In the full decompressor, this will be overridden by jdmaster.c;
  170632. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170633. */
  170634. cinfo->min_DCT_scaled_size = DCTSIZE;
  170635. /* Compute dimensions of components */
  170636. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170637. ci++, compptr++) {
  170638. compptr->DCT_scaled_size = DCTSIZE;
  170639. /* Size in DCT blocks */
  170640. compptr->width_in_blocks = (JDIMENSION)
  170641. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170642. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170643. compptr->height_in_blocks = (JDIMENSION)
  170644. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170645. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170646. /* downsampled_width and downsampled_height will also be overridden by
  170647. * jdmaster.c if we are doing full decompression. The transcoder library
  170648. * doesn't use these values, but the calling application might.
  170649. */
  170650. /* Size in samples */
  170651. compptr->downsampled_width = (JDIMENSION)
  170652. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170653. (long) cinfo->max_h_samp_factor);
  170654. compptr->downsampled_height = (JDIMENSION)
  170655. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170656. (long) cinfo->max_v_samp_factor);
  170657. /* Mark component needed, until color conversion says otherwise */
  170658. compptr->component_needed = TRUE;
  170659. /* Mark no quantization table yet saved for component */
  170660. compptr->quant_table = NULL;
  170661. }
  170662. /* Compute number of fully interleaved MCU rows. */
  170663. cinfo->total_iMCU_rows = (JDIMENSION)
  170664. jdiv_round_up((long) cinfo->image_height,
  170665. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170666. /* Decide whether file contains multiple scans */
  170667. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170668. cinfo->inputctl->has_multiple_scans = TRUE;
  170669. else
  170670. cinfo->inputctl->has_multiple_scans = FALSE;
  170671. }
  170672. LOCAL(void)
  170673. per_scan_setup2 (j_decompress_ptr cinfo)
  170674. /* Do computations that are needed before processing a JPEG scan */
  170675. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170676. {
  170677. int ci, mcublks, tmp;
  170678. jpeg_component_info *compptr;
  170679. if (cinfo->comps_in_scan == 1) {
  170680. /* Noninterleaved (single-component) scan */
  170681. compptr = cinfo->cur_comp_info[0];
  170682. /* Overall image size in MCUs */
  170683. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170684. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170685. /* For noninterleaved scan, always one block per MCU */
  170686. compptr->MCU_width = 1;
  170687. compptr->MCU_height = 1;
  170688. compptr->MCU_blocks = 1;
  170689. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170690. compptr->last_col_width = 1;
  170691. /* For noninterleaved scans, it is convenient to define last_row_height
  170692. * as the number of block rows present in the last iMCU row.
  170693. */
  170694. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170695. if (tmp == 0) tmp = compptr->v_samp_factor;
  170696. compptr->last_row_height = tmp;
  170697. /* Prepare array describing MCU composition */
  170698. cinfo->blocks_in_MCU = 1;
  170699. cinfo->MCU_membership[0] = 0;
  170700. } else {
  170701. /* Interleaved (multi-component) scan */
  170702. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170703. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170704. MAX_COMPS_IN_SCAN);
  170705. /* Overall image size in MCUs */
  170706. cinfo->MCUs_per_row = (JDIMENSION)
  170707. jdiv_round_up((long) cinfo->image_width,
  170708. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170709. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170710. jdiv_round_up((long) cinfo->image_height,
  170711. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170712. cinfo->blocks_in_MCU = 0;
  170713. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170714. compptr = cinfo->cur_comp_info[ci];
  170715. /* Sampling factors give # of blocks of component in each MCU */
  170716. compptr->MCU_width = compptr->h_samp_factor;
  170717. compptr->MCU_height = compptr->v_samp_factor;
  170718. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170719. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170720. /* Figure number of non-dummy blocks in last MCU column & row */
  170721. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170722. if (tmp == 0) tmp = compptr->MCU_width;
  170723. compptr->last_col_width = tmp;
  170724. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170725. if (tmp == 0) tmp = compptr->MCU_height;
  170726. compptr->last_row_height = tmp;
  170727. /* Prepare array describing MCU composition */
  170728. mcublks = compptr->MCU_blocks;
  170729. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170730. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170731. while (mcublks-- > 0) {
  170732. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170733. }
  170734. }
  170735. }
  170736. }
  170737. /*
  170738. * Save away a copy of the Q-table referenced by each component present
  170739. * in the current scan, unless already saved during a prior scan.
  170740. *
  170741. * In a multiple-scan JPEG file, the encoder could assign different components
  170742. * the same Q-table slot number, but change table definitions between scans
  170743. * so that each component uses a different Q-table. (The IJG encoder is not
  170744. * currently capable of doing this, but other encoders might.) Since we want
  170745. * to be able to dequantize all the components at the end of the file, this
  170746. * means that we have to save away the table actually used for each component.
  170747. * We do this by copying the table at the start of the first scan containing
  170748. * the component.
  170749. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170750. * slot between scans of a component using that slot. If the encoder does so
  170751. * anyway, this decoder will simply use the Q-table values that were current
  170752. * at the start of the first scan for the component.
  170753. *
  170754. * The decompressor output side looks only at the saved quant tables,
  170755. * not at the current Q-table slots.
  170756. */
  170757. LOCAL(void)
  170758. latch_quant_tables (j_decompress_ptr cinfo)
  170759. {
  170760. int ci, qtblno;
  170761. jpeg_component_info *compptr;
  170762. JQUANT_TBL * qtbl;
  170763. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170764. compptr = cinfo->cur_comp_info[ci];
  170765. /* No work if we already saved Q-table for this component */
  170766. if (compptr->quant_table != NULL)
  170767. continue;
  170768. /* Make sure specified quantization table is present */
  170769. qtblno = compptr->quant_tbl_no;
  170770. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170771. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170772. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170773. /* OK, save away the quantization table */
  170774. qtbl = (JQUANT_TBL *)
  170775. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170776. SIZEOF(JQUANT_TBL));
  170777. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170778. compptr->quant_table = qtbl;
  170779. }
  170780. }
  170781. /*
  170782. * Initialize the input modules to read a scan of compressed data.
  170783. * The first call to this is done by jdmaster.c after initializing
  170784. * the entire decompressor (during jpeg_start_decompress).
  170785. * Subsequent calls come from consume_markers, below.
  170786. */
  170787. METHODDEF(void)
  170788. start_input_pass2 (j_decompress_ptr cinfo)
  170789. {
  170790. per_scan_setup2(cinfo);
  170791. latch_quant_tables(cinfo);
  170792. (*cinfo->entropy->start_pass) (cinfo);
  170793. (*cinfo->coef->start_input_pass) (cinfo);
  170794. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170795. }
  170796. /*
  170797. * Finish up after inputting a compressed-data scan.
  170798. * This is called by the coefficient controller after it's read all
  170799. * the expected data of the scan.
  170800. */
  170801. METHODDEF(void)
  170802. finish_input_pass (j_decompress_ptr cinfo)
  170803. {
  170804. cinfo->inputctl->consume_input = consume_markers;
  170805. }
  170806. /*
  170807. * Read JPEG markers before, between, or after compressed-data scans.
  170808. * Change state as necessary when a new scan is reached.
  170809. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170810. *
  170811. * The consume_input method pointer points either here or to the
  170812. * coefficient controller's consume_data routine, depending on whether
  170813. * we are reading a compressed data segment or inter-segment markers.
  170814. */
  170815. METHODDEF(int)
  170816. consume_markers (j_decompress_ptr cinfo)
  170817. {
  170818. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170819. int val;
  170820. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170821. return JPEG_REACHED_EOI;
  170822. val = (*cinfo->marker->read_markers) (cinfo);
  170823. switch (val) {
  170824. case JPEG_REACHED_SOS: /* Found SOS */
  170825. if (inputctl->inheaders) { /* 1st SOS */
  170826. initial_setup2(cinfo);
  170827. inputctl->inheaders = FALSE;
  170828. /* Note: start_input_pass must be called by jdmaster.c
  170829. * before any more input can be consumed. jdapimin.c is
  170830. * responsible for enforcing this sequencing.
  170831. */
  170832. } else { /* 2nd or later SOS marker */
  170833. if (! inputctl->pub.has_multiple_scans)
  170834. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170835. start_input_pass2(cinfo);
  170836. }
  170837. break;
  170838. case JPEG_REACHED_EOI: /* Found EOI */
  170839. inputctl->pub.eoi_reached = TRUE;
  170840. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170841. if (cinfo->marker->saw_SOF)
  170842. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170843. } else {
  170844. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170845. * if user set output_scan_number larger than number of scans.
  170846. */
  170847. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170848. cinfo->output_scan_number = cinfo->input_scan_number;
  170849. }
  170850. break;
  170851. case JPEG_SUSPENDED:
  170852. break;
  170853. }
  170854. return val;
  170855. }
  170856. /*
  170857. * Reset state to begin a fresh datastream.
  170858. */
  170859. METHODDEF(void)
  170860. reset_input_controller (j_decompress_ptr cinfo)
  170861. {
  170862. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170863. inputctl->pub.consume_input = consume_markers;
  170864. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170865. inputctl->pub.eoi_reached = FALSE;
  170866. inputctl->inheaders = TRUE;
  170867. /* Reset other modules */
  170868. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170869. (*cinfo->marker->reset_marker_reader) (cinfo);
  170870. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170871. cinfo->coef_bits = NULL;
  170872. }
  170873. /*
  170874. * Initialize the input controller module.
  170875. * This is called only once, when the decompression object is created.
  170876. */
  170877. GLOBAL(void)
  170878. jinit_input_controller (j_decompress_ptr cinfo)
  170879. {
  170880. my_inputctl_ptr inputctl;
  170881. /* Create subobject in permanent pool */
  170882. inputctl = (my_inputctl_ptr)
  170883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170884. SIZEOF(my_input_controller));
  170885. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170886. /* Initialize method pointers */
  170887. inputctl->pub.consume_input = consume_markers;
  170888. inputctl->pub.reset_input_controller = reset_input_controller;
  170889. inputctl->pub.start_input_pass = start_input_pass2;
  170890. inputctl->pub.finish_input_pass = finish_input_pass;
  170891. /* Initialize state: can't use reset_input_controller since we don't
  170892. * want to try to reset other modules yet.
  170893. */
  170894. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170895. inputctl->pub.eoi_reached = FALSE;
  170896. inputctl->inheaders = TRUE;
  170897. }
  170898. /*** End of inlined file: jdinput.c ***/
  170899. /*** Start of inlined file: jdmainct.c ***/
  170900. #define JPEG_INTERNALS
  170901. /*
  170902. * In the current system design, the main buffer need never be a full-image
  170903. * buffer; any full-height buffers will be found inside the coefficient or
  170904. * postprocessing controllers. Nonetheless, the main controller is not
  170905. * trivial. Its responsibility is to provide context rows for upsampling/
  170906. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170907. *
  170908. * Postprocessor input data is counted in "row groups". A row group
  170909. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170910. * sample rows of each component. (We require DCT_scaled_size values to be
  170911. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170912. * values will likely be powers of two, so we actually have the stronger
  170913. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170914. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170915. * row group (times any additional scale factor that the upsampler is
  170916. * applying).
  170917. *
  170918. * The coefficient controller will deliver data to us one iMCU row at a time;
  170919. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170920. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170921. * to one row of MCUs when the image is fully interleaved.) Note that the
  170922. * number of sample rows varies across components, but the number of row
  170923. * groups does not. Some garbage sample rows may be included in the last iMCU
  170924. * row at the bottom of the image.
  170925. *
  170926. * Depending on the vertical scaling algorithm used, the upsampler may need
  170927. * access to the sample row(s) above and below its current input row group.
  170928. * The upsampler is required to set need_context_rows TRUE at global selection
  170929. * time if so. When need_context_rows is FALSE, this controller can simply
  170930. * obtain one iMCU row at a time from the coefficient controller and dole it
  170931. * out as row groups to the postprocessor.
  170932. *
  170933. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170934. * passed to postprocessing contains at least one row group's worth of samples
  170935. * above and below the row group(s) being processed. Note that the context
  170936. * rows "above" the first passed row group appear at negative row offsets in
  170937. * the passed buffer. At the top and bottom of the image, the required
  170938. * context rows are manufactured by duplicating the first or last real sample
  170939. * row; this avoids having special cases in the upsampling inner loops.
  170940. *
  170941. * The amount of context is fixed at one row group just because that's a
  170942. * convenient number for this controller to work with. The existing
  170943. * upsamplers really only need one sample row of context. An upsampler
  170944. * supporting arbitrary output rescaling might wish for more than one row
  170945. * group of context when shrinking the image; tough, we don't handle that.
  170946. * (This is justified by the assumption that downsizing will be handled mostly
  170947. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170948. * the upsample step needn't be much less than one.)
  170949. *
  170950. * To provide the desired context, we have to retain the last two row groups
  170951. * of one iMCU row while reading in the next iMCU row. (The last row group
  170952. * can't be processed until we have another row group for its below-context,
  170953. * and so we have to save the next-to-last group too for its above-context.)
  170954. * We could do this most simply by copying data around in our buffer, but
  170955. * that'd be very slow. We can avoid copying any data by creating a rather
  170956. * strange pointer structure. Here's how it works. We allocate a workspace
  170957. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170958. * of row groups per iMCU row). We create two sets of redundant pointers to
  170959. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170960. * pointer lists look like this:
  170961. * M+1 M-1
  170962. * master pointer --> 0 master pointer --> 0
  170963. * 1 1
  170964. * ... ...
  170965. * M-3 M-3
  170966. * M-2 M
  170967. * M-1 M+1
  170968. * M M-2
  170969. * M+1 M-1
  170970. * 0 0
  170971. * We read alternate iMCU rows using each master pointer; thus the last two
  170972. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170973. * The pointer lists are set up so that the required context rows appear to
  170974. * be adjacent to the proper places when we pass the pointer lists to the
  170975. * upsampler.
  170976. *
  170977. * The above pictures describe the normal state of the pointer lists.
  170978. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170979. * the first or last sample row as necessary (this is cheaper than copying
  170980. * sample rows around).
  170981. *
  170982. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170983. * situation each iMCU row provides only one row group so the buffering logic
  170984. * must be different (eg, we must read two iMCU rows before we can emit the
  170985. * first row group). For now, we simply do not support providing context
  170986. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170987. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170988. * want it quick and dirty, so a context-free upsampler is sufficient.
  170989. */
  170990. /* Private buffer controller object */
  170991. typedef struct {
  170992. struct jpeg_d_main_controller pub; /* public fields */
  170993. /* Pointer to allocated workspace (M or M+2 row groups). */
  170994. JSAMPARRAY buffer[MAX_COMPONENTS];
  170995. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170996. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170997. /* Remaining fields are only used in the context case. */
  170998. /* These are the master pointers to the funny-order pointer lists. */
  170999. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  171000. int whichptr; /* indicates which pointer set is now in use */
  171001. int context_state; /* process_data state machine status */
  171002. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  171003. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  171004. } my_main_controller4;
  171005. typedef my_main_controller4 * my_main_ptr4;
  171006. /* context_state values: */
  171007. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  171008. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  171009. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  171010. /* Forward declarations */
  171011. METHODDEF(void) process_data_simple_main2
  171012. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171013. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171014. METHODDEF(void) process_data_context_main
  171015. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171016. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171017. #ifdef QUANT_2PASS_SUPPORTED
  171018. METHODDEF(void) process_data_crank_post
  171019. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171020. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171021. #endif
  171022. LOCAL(void)
  171023. alloc_funny_pointers (j_decompress_ptr cinfo)
  171024. /* Allocate space for the funny pointer lists.
  171025. * This is done only once, not once per pass.
  171026. */
  171027. {
  171028. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171029. int ci, rgroup;
  171030. int M = cinfo->min_DCT_scaled_size;
  171031. jpeg_component_info *compptr;
  171032. JSAMPARRAY xbuf;
  171033. /* Get top-level space for component array pointers.
  171034. * We alloc both arrays with one call to save a few cycles.
  171035. */
  171036. main_->xbuffer[0] = (JSAMPIMAGE)
  171037. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171038. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171039. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171040. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171041. ci++, compptr++) {
  171042. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171043. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171044. /* Get space for pointer lists --- M+4 row groups in each list.
  171045. * We alloc both pointer lists with one call to save a few cycles.
  171046. */
  171047. xbuf = (JSAMPARRAY)
  171048. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171049. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171050. xbuf += rgroup; /* want one row group at negative offsets */
  171051. main_->xbuffer[0][ci] = xbuf;
  171052. xbuf += rgroup * (M + 4);
  171053. main_->xbuffer[1][ci] = xbuf;
  171054. }
  171055. }
  171056. LOCAL(void)
  171057. make_funny_pointers (j_decompress_ptr cinfo)
  171058. /* Create the funny pointer lists discussed in the comments above.
  171059. * The actual workspace is already allocated (in main->buffer),
  171060. * and the space for the pointer lists is allocated too.
  171061. * This routine just fills in the curiously ordered lists.
  171062. * This will be repeated at the beginning of each pass.
  171063. */
  171064. {
  171065. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171066. int ci, i, rgroup;
  171067. int M = cinfo->min_DCT_scaled_size;
  171068. jpeg_component_info *compptr;
  171069. JSAMPARRAY buf, xbuf0, xbuf1;
  171070. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171071. ci++, compptr++) {
  171072. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171073. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171074. xbuf0 = main_->xbuffer[0][ci];
  171075. xbuf1 = main_->xbuffer[1][ci];
  171076. /* First copy the workspace pointers as-is */
  171077. buf = main_->buffer[ci];
  171078. for (i = 0; i < rgroup * (M + 2); i++) {
  171079. xbuf0[i] = xbuf1[i] = buf[i];
  171080. }
  171081. /* In the second list, put the last four row groups in swapped order */
  171082. for (i = 0; i < rgroup * 2; i++) {
  171083. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171084. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171085. }
  171086. /* The wraparound pointers at top and bottom will be filled later
  171087. * (see set_wraparound_pointers, below). Initially we want the "above"
  171088. * pointers to duplicate the first actual data line. This only needs
  171089. * to happen in xbuffer[0].
  171090. */
  171091. for (i = 0; i < rgroup; i++) {
  171092. xbuf0[i - rgroup] = xbuf0[0];
  171093. }
  171094. }
  171095. }
  171096. LOCAL(void)
  171097. set_wraparound_pointers (j_decompress_ptr cinfo)
  171098. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171099. * This changes the pointer list state from top-of-image to the normal state.
  171100. */
  171101. {
  171102. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171103. int ci, i, rgroup;
  171104. int M = cinfo->min_DCT_scaled_size;
  171105. jpeg_component_info *compptr;
  171106. JSAMPARRAY xbuf0, xbuf1;
  171107. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171108. ci++, compptr++) {
  171109. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171110. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171111. xbuf0 = main_->xbuffer[0][ci];
  171112. xbuf1 = main_->xbuffer[1][ci];
  171113. for (i = 0; i < rgroup; i++) {
  171114. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171115. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171116. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171117. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171118. }
  171119. }
  171120. }
  171121. LOCAL(void)
  171122. set_bottom_pointers (j_decompress_ptr cinfo)
  171123. /* Change the pointer lists to duplicate the last sample row at the bottom
  171124. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171125. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171126. */
  171127. {
  171128. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171129. int ci, i, rgroup, iMCUheight, rows_left;
  171130. jpeg_component_info *compptr;
  171131. JSAMPARRAY xbuf;
  171132. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171133. ci++, compptr++) {
  171134. /* Count sample rows in one iMCU row and in one row group */
  171135. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171136. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171137. /* Count nondummy sample rows remaining for this component */
  171138. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171139. if (rows_left == 0) rows_left = iMCUheight;
  171140. /* Count nondummy row groups. Should get same answer for each component,
  171141. * so we need only do it once.
  171142. */
  171143. if (ci == 0) {
  171144. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171145. }
  171146. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171147. * last partial rowgroup and ensures at least one full rowgroup of context.
  171148. */
  171149. xbuf = main_->xbuffer[main_->whichptr][ci];
  171150. for (i = 0; i < rgroup * 2; i++) {
  171151. xbuf[rows_left + i] = xbuf[rows_left-1];
  171152. }
  171153. }
  171154. }
  171155. /*
  171156. * Initialize for a processing pass.
  171157. */
  171158. METHODDEF(void)
  171159. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171160. {
  171161. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171162. switch (pass_mode) {
  171163. case JBUF_PASS_THRU:
  171164. if (cinfo->upsample->need_context_rows) {
  171165. main_->pub.process_data = process_data_context_main;
  171166. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171167. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171168. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171169. main_->iMCU_row_ctr = 0;
  171170. } else {
  171171. /* Simple case with no context needed */
  171172. main_->pub.process_data = process_data_simple_main2;
  171173. }
  171174. main_->buffer_full = FALSE; /* Mark buffer empty */
  171175. main_->rowgroup_ctr = 0;
  171176. break;
  171177. #ifdef QUANT_2PASS_SUPPORTED
  171178. case JBUF_CRANK_DEST:
  171179. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171180. main_->pub.process_data = process_data_crank_post;
  171181. break;
  171182. #endif
  171183. default:
  171184. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171185. break;
  171186. }
  171187. }
  171188. /*
  171189. * Process some data.
  171190. * This handles the simple case where no context is required.
  171191. */
  171192. METHODDEF(void)
  171193. process_data_simple_main2 (j_decompress_ptr cinfo,
  171194. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171195. JDIMENSION out_rows_avail)
  171196. {
  171197. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171198. JDIMENSION rowgroups_avail;
  171199. /* Read input data if we haven't filled the main buffer yet */
  171200. if (! main_->buffer_full) {
  171201. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171202. return; /* suspension forced, can do nothing more */
  171203. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171204. }
  171205. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171206. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171207. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171208. * to the postprocessor. The postprocessor has to check for bottom
  171209. * of image anyway (at row resolution), so no point in us doing it too.
  171210. */
  171211. /* Feed the postprocessor */
  171212. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171213. &main_->rowgroup_ctr, rowgroups_avail,
  171214. output_buf, out_row_ctr, out_rows_avail);
  171215. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171216. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171217. main_->buffer_full = FALSE;
  171218. main_->rowgroup_ctr = 0;
  171219. }
  171220. }
  171221. /*
  171222. * Process some data.
  171223. * This handles the case where context rows must be provided.
  171224. */
  171225. METHODDEF(void)
  171226. process_data_context_main (j_decompress_ptr cinfo,
  171227. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171228. JDIMENSION out_rows_avail)
  171229. {
  171230. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171231. /* Read input data if we haven't filled the main buffer yet */
  171232. if (! main_->buffer_full) {
  171233. if (! (*cinfo->coef->decompress_data) (cinfo,
  171234. main_->xbuffer[main_->whichptr]))
  171235. return; /* suspension forced, can do nothing more */
  171236. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171237. main_->iMCU_row_ctr++; /* count rows received */
  171238. }
  171239. /* Postprocessor typically will not swallow all the input data it is handed
  171240. * in one call (due to filling the output buffer first). Must be prepared
  171241. * to exit and restart. This switch lets us keep track of how far we got.
  171242. * Note that each case falls through to the next on successful completion.
  171243. */
  171244. switch (main_->context_state) {
  171245. case CTX_POSTPONED_ROW:
  171246. /* Call postprocessor using previously set pointers for postponed row */
  171247. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171248. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171249. output_buf, out_row_ctr, out_rows_avail);
  171250. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171251. return; /* Need to suspend */
  171252. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171253. if (*out_row_ctr >= out_rows_avail)
  171254. return; /* Postprocessor exactly filled output buf */
  171255. /*FALLTHROUGH*/
  171256. case CTX_PREPARE_FOR_IMCU:
  171257. /* Prepare to process first M-1 row groups of this iMCU row */
  171258. main_->rowgroup_ctr = 0;
  171259. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171260. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171261. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171262. */
  171263. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171264. set_bottom_pointers(cinfo);
  171265. main_->context_state = CTX_PROCESS_IMCU;
  171266. /*FALLTHROUGH*/
  171267. case CTX_PROCESS_IMCU:
  171268. /* Call postprocessor using previously set pointers */
  171269. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171270. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171271. output_buf, out_row_ctr, out_rows_avail);
  171272. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171273. return; /* Need to suspend */
  171274. /* After the first iMCU, change wraparound pointers to normal state */
  171275. if (main_->iMCU_row_ctr == 1)
  171276. set_wraparound_pointers(cinfo);
  171277. /* Prepare to load new iMCU row using other xbuffer list */
  171278. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171279. main_->buffer_full = FALSE;
  171280. /* Still need to process last row group of this iMCU row, */
  171281. /* which is saved at index M+1 of the other xbuffer */
  171282. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171283. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171284. main_->context_state = CTX_POSTPONED_ROW;
  171285. }
  171286. }
  171287. /*
  171288. * Process some data.
  171289. * Final pass of two-pass quantization: just call the postprocessor.
  171290. * Source data will be the postprocessor controller's internal buffer.
  171291. */
  171292. #ifdef QUANT_2PASS_SUPPORTED
  171293. METHODDEF(void)
  171294. process_data_crank_post (j_decompress_ptr cinfo,
  171295. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171296. JDIMENSION out_rows_avail)
  171297. {
  171298. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171299. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171300. output_buf, out_row_ctr, out_rows_avail);
  171301. }
  171302. #endif /* QUANT_2PASS_SUPPORTED */
  171303. /*
  171304. * Initialize main buffer controller.
  171305. */
  171306. GLOBAL(void)
  171307. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171308. {
  171309. my_main_ptr4 main_;
  171310. int ci, rgroup, ngroups;
  171311. jpeg_component_info *compptr;
  171312. main_ = (my_main_ptr4)
  171313. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171314. SIZEOF(my_main_controller4));
  171315. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171316. main_->pub.start_pass = start_pass_main2;
  171317. if (need_full_buffer) /* shouldn't happen */
  171318. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171319. /* Allocate the workspace.
  171320. * ngroups is the number of row groups we need.
  171321. */
  171322. if (cinfo->upsample->need_context_rows) {
  171323. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171324. ERREXIT(cinfo, JERR_NOTIMPL);
  171325. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171326. ngroups = cinfo->min_DCT_scaled_size + 2;
  171327. } else {
  171328. ngroups = cinfo->min_DCT_scaled_size;
  171329. }
  171330. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171331. ci++, compptr++) {
  171332. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171333. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171334. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171335. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171336. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171337. (JDIMENSION) (rgroup * ngroups));
  171338. }
  171339. }
  171340. /*** End of inlined file: jdmainct.c ***/
  171341. /*** Start of inlined file: jdmarker.c ***/
  171342. #define JPEG_INTERNALS
  171343. /* Private state */
  171344. typedef struct {
  171345. struct jpeg_marker_reader pub; /* public fields */
  171346. /* Application-overridable marker processing methods */
  171347. jpeg_marker_parser_method process_COM;
  171348. jpeg_marker_parser_method process_APPn[16];
  171349. /* Limit on marker data length to save for each marker type */
  171350. unsigned int length_limit_COM;
  171351. unsigned int length_limit_APPn[16];
  171352. /* Status of COM/APPn marker saving */
  171353. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171354. unsigned int bytes_read; /* data bytes read so far in marker */
  171355. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171356. } my_marker_reader;
  171357. typedef my_marker_reader * my_marker_ptr2;
  171358. /*
  171359. * Macros for fetching data from the data source module.
  171360. *
  171361. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171362. * the current restart point; we update them only when we have reached a
  171363. * suitable place to restart if a suspension occurs.
  171364. */
  171365. /* Declare and initialize local copies of input pointer/count */
  171366. #define INPUT_VARS(cinfo) \
  171367. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171368. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171369. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171370. /* Unload the local copies --- do this only at a restart boundary */
  171371. #define INPUT_SYNC(cinfo) \
  171372. ( datasrc->next_input_byte = next_input_byte, \
  171373. datasrc->bytes_in_buffer = bytes_in_buffer )
  171374. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171375. #define INPUT_RELOAD(cinfo) \
  171376. ( next_input_byte = datasrc->next_input_byte, \
  171377. bytes_in_buffer = datasrc->bytes_in_buffer )
  171378. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171379. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171380. * but we must reload the local copies after a successful fill.
  171381. */
  171382. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171383. if (bytes_in_buffer == 0) { \
  171384. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171385. { action; } \
  171386. INPUT_RELOAD(cinfo); \
  171387. }
  171388. /* Read a byte into variable V.
  171389. * If must suspend, take the specified action (typically "return FALSE").
  171390. */
  171391. #define INPUT_BYTE(cinfo,V,action) \
  171392. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171393. bytes_in_buffer--; \
  171394. V = GETJOCTET(*next_input_byte++); )
  171395. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171396. * V should be declared unsigned int or perhaps INT32.
  171397. */
  171398. #define INPUT_2BYTES(cinfo,V,action) \
  171399. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171400. bytes_in_buffer--; \
  171401. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171402. MAKE_BYTE_AVAIL(cinfo,action); \
  171403. bytes_in_buffer--; \
  171404. V += GETJOCTET(*next_input_byte++); )
  171405. /*
  171406. * Routines to process JPEG markers.
  171407. *
  171408. * Entry condition: JPEG marker itself has been read and its code saved
  171409. * in cinfo->unread_marker; input restart point is just after the marker.
  171410. *
  171411. * Exit: if return TRUE, have read and processed any parameters, and have
  171412. * updated the restart point to point after the parameters.
  171413. * If return FALSE, was forced to suspend before reaching end of
  171414. * marker parameters; restart point has not been moved. Same routine
  171415. * will be called again after application supplies more input data.
  171416. *
  171417. * This approach to suspension assumes that all of a marker's parameters
  171418. * can fit into a single input bufferload. This should hold for "normal"
  171419. * markers. Some COM/APPn markers might have large parameter segments
  171420. * that might not fit. If we are simply dropping such a marker, we use
  171421. * skip_input_data to get past it, and thereby put the problem on the
  171422. * source manager's shoulders. If we are saving the marker's contents
  171423. * into memory, we use a slightly different convention: when forced to
  171424. * suspend, the marker processor updates the restart point to the end of
  171425. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171426. * On resumption, cinfo->unread_marker still contains the marker code,
  171427. * but the data source will point to the next chunk of marker data.
  171428. * The marker processor must retain internal state to deal with this.
  171429. *
  171430. * Note that we don't bother to avoid duplicate trace messages if a
  171431. * suspension occurs within marker parameters. Other side effects
  171432. * require more care.
  171433. */
  171434. LOCAL(boolean)
  171435. get_soi (j_decompress_ptr cinfo)
  171436. /* Process an SOI marker */
  171437. {
  171438. int i;
  171439. TRACEMS(cinfo, 1, JTRC_SOI);
  171440. if (cinfo->marker->saw_SOI)
  171441. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171442. /* Reset all parameters that are defined to be reset by SOI */
  171443. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171444. cinfo->arith_dc_L[i] = 0;
  171445. cinfo->arith_dc_U[i] = 1;
  171446. cinfo->arith_ac_K[i] = 5;
  171447. }
  171448. cinfo->restart_interval = 0;
  171449. /* Set initial assumptions for colorspace etc */
  171450. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171451. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171452. cinfo->saw_JFIF_marker = FALSE;
  171453. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171454. cinfo->JFIF_minor_version = 1;
  171455. cinfo->density_unit = 0;
  171456. cinfo->X_density = 1;
  171457. cinfo->Y_density = 1;
  171458. cinfo->saw_Adobe_marker = FALSE;
  171459. cinfo->Adobe_transform = 0;
  171460. cinfo->marker->saw_SOI = TRUE;
  171461. return TRUE;
  171462. }
  171463. LOCAL(boolean)
  171464. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171465. /* Process a SOFn marker */
  171466. {
  171467. INT32 length;
  171468. int c, ci;
  171469. jpeg_component_info * compptr;
  171470. INPUT_VARS(cinfo);
  171471. cinfo->progressive_mode = is_prog;
  171472. cinfo->arith_code = is_arith;
  171473. INPUT_2BYTES(cinfo, length, return FALSE);
  171474. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171475. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171476. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171477. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171478. length -= 8;
  171479. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171480. (int) cinfo->image_width, (int) cinfo->image_height,
  171481. cinfo->num_components);
  171482. if (cinfo->marker->saw_SOF)
  171483. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171484. /* We don't support files in which the image height is initially specified */
  171485. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171486. /* might as well have a general sanity check. */
  171487. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171488. || cinfo->num_components <= 0)
  171489. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171490. if (length != (cinfo->num_components * 3))
  171491. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171492. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171493. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171494. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171495. cinfo->num_components * SIZEOF(jpeg_component_info));
  171496. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171497. ci++, compptr++) {
  171498. compptr->component_index = ci;
  171499. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171500. INPUT_BYTE(cinfo, c, return FALSE);
  171501. compptr->h_samp_factor = (c >> 4) & 15;
  171502. compptr->v_samp_factor = (c ) & 15;
  171503. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171504. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171505. compptr->component_id, compptr->h_samp_factor,
  171506. compptr->v_samp_factor, compptr->quant_tbl_no);
  171507. }
  171508. cinfo->marker->saw_SOF = TRUE;
  171509. INPUT_SYNC(cinfo);
  171510. return TRUE;
  171511. }
  171512. LOCAL(boolean)
  171513. get_sos (j_decompress_ptr cinfo)
  171514. /* Process a SOS marker */
  171515. {
  171516. INT32 length;
  171517. int i, ci, n, c, cc;
  171518. jpeg_component_info * compptr;
  171519. INPUT_VARS(cinfo);
  171520. if (! cinfo->marker->saw_SOF)
  171521. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171522. INPUT_2BYTES(cinfo, length, return FALSE);
  171523. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171524. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171525. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171526. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171527. cinfo->comps_in_scan = n;
  171528. /* Collect the component-spec parameters */
  171529. for (i = 0; i < n; i++) {
  171530. INPUT_BYTE(cinfo, cc, return FALSE);
  171531. INPUT_BYTE(cinfo, c, return FALSE);
  171532. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171533. ci++, compptr++) {
  171534. if (cc == compptr->component_id)
  171535. goto id_found;
  171536. }
  171537. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171538. id_found:
  171539. cinfo->cur_comp_info[i] = compptr;
  171540. compptr->dc_tbl_no = (c >> 4) & 15;
  171541. compptr->ac_tbl_no = (c ) & 15;
  171542. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171543. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171544. }
  171545. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171546. INPUT_BYTE(cinfo, c, return FALSE);
  171547. cinfo->Ss = c;
  171548. INPUT_BYTE(cinfo, c, return FALSE);
  171549. cinfo->Se = c;
  171550. INPUT_BYTE(cinfo, c, return FALSE);
  171551. cinfo->Ah = (c >> 4) & 15;
  171552. cinfo->Al = (c ) & 15;
  171553. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171554. cinfo->Ah, cinfo->Al);
  171555. /* Prepare to scan data & restart markers */
  171556. cinfo->marker->next_restart_num = 0;
  171557. /* Count another SOS marker */
  171558. cinfo->input_scan_number++;
  171559. INPUT_SYNC(cinfo);
  171560. return TRUE;
  171561. }
  171562. #ifdef D_ARITH_CODING_SUPPORTED
  171563. LOCAL(boolean)
  171564. get_dac (j_decompress_ptr cinfo)
  171565. /* Process a DAC marker */
  171566. {
  171567. INT32 length;
  171568. int index, val;
  171569. INPUT_VARS(cinfo);
  171570. INPUT_2BYTES(cinfo, length, return FALSE);
  171571. length -= 2;
  171572. while (length > 0) {
  171573. INPUT_BYTE(cinfo, index, return FALSE);
  171574. INPUT_BYTE(cinfo, val, return FALSE);
  171575. length -= 2;
  171576. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171577. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171578. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171579. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171580. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171581. } else { /* define DC table */
  171582. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171583. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171584. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171585. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171586. }
  171587. }
  171588. if (length != 0)
  171589. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171590. INPUT_SYNC(cinfo);
  171591. return TRUE;
  171592. }
  171593. #else /* ! D_ARITH_CODING_SUPPORTED */
  171594. #define get_dac(cinfo) skip_variable(cinfo)
  171595. #endif /* D_ARITH_CODING_SUPPORTED */
  171596. LOCAL(boolean)
  171597. get_dht (j_decompress_ptr cinfo)
  171598. /* Process a DHT marker */
  171599. {
  171600. INT32 length;
  171601. UINT8 bits[17];
  171602. UINT8 huffval[256];
  171603. int i, index, count;
  171604. JHUFF_TBL **htblptr;
  171605. INPUT_VARS(cinfo);
  171606. INPUT_2BYTES(cinfo, length, return FALSE);
  171607. length -= 2;
  171608. while (length > 16) {
  171609. INPUT_BYTE(cinfo, index, return FALSE);
  171610. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171611. bits[0] = 0;
  171612. count = 0;
  171613. for (i = 1; i <= 16; i++) {
  171614. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171615. count += bits[i];
  171616. }
  171617. length -= 1 + 16;
  171618. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171619. bits[1], bits[2], bits[3], bits[4],
  171620. bits[5], bits[6], bits[7], bits[8]);
  171621. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171622. bits[9], bits[10], bits[11], bits[12],
  171623. bits[13], bits[14], bits[15], bits[16]);
  171624. /* Here we just do minimal validation of the counts to avoid walking
  171625. * off the end of our table space. jdhuff.c will check more carefully.
  171626. */
  171627. if (count > 256 || ((INT32) count) > length)
  171628. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171629. for (i = 0; i < count; i++)
  171630. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171631. length -= count;
  171632. if (index & 0x10) { /* AC table definition */
  171633. index -= 0x10;
  171634. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171635. } else { /* DC table definition */
  171636. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171637. }
  171638. if (index < 0 || index >= NUM_HUFF_TBLS)
  171639. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171640. if (*htblptr == NULL)
  171641. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171642. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171643. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171644. }
  171645. if (length != 0)
  171646. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171647. INPUT_SYNC(cinfo);
  171648. return TRUE;
  171649. }
  171650. LOCAL(boolean)
  171651. get_dqt (j_decompress_ptr cinfo)
  171652. /* Process a DQT marker */
  171653. {
  171654. INT32 length;
  171655. int n, i, prec;
  171656. unsigned int tmp;
  171657. JQUANT_TBL *quant_ptr;
  171658. INPUT_VARS(cinfo);
  171659. INPUT_2BYTES(cinfo, length, return FALSE);
  171660. length -= 2;
  171661. while (length > 0) {
  171662. INPUT_BYTE(cinfo, n, return FALSE);
  171663. prec = n >> 4;
  171664. n &= 0x0F;
  171665. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171666. if (n >= NUM_QUANT_TBLS)
  171667. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171668. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171669. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171670. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171671. for (i = 0; i < DCTSIZE2; i++) {
  171672. if (prec)
  171673. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171674. else
  171675. INPUT_BYTE(cinfo, tmp, return FALSE);
  171676. /* We convert the zigzag-order table to natural array order. */
  171677. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171678. }
  171679. if (cinfo->err->trace_level >= 2) {
  171680. for (i = 0; i < DCTSIZE2; i += 8) {
  171681. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171682. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171683. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171684. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171685. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171686. }
  171687. }
  171688. length -= DCTSIZE2+1;
  171689. if (prec) length -= DCTSIZE2;
  171690. }
  171691. if (length != 0)
  171692. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171693. INPUT_SYNC(cinfo);
  171694. return TRUE;
  171695. }
  171696. LOCAL(boolean)
  171697. get_dri (j_decompress_ptr cinfo)
  171698. /* Process a DRI marker */
  171699. {
  171700. INT32 length;
  171701. unsigned int tmp;
  171702. INPUT_VARS(cinfo);
  171703. INPUT_2BYTES(cinfo, length, return FALSE);
  171704. if (length != 4)
  171705. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171706. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171707. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171708. cinfo->restart_interval = tmp;
  171709. INPUT_SYNC(cinfo);
  171710. return TRUE;
  171711. }
  171712. /*
  171713. * Routines for processing APPn and COM markers.
  171714. * These are either saved in memory or discarded, per application request.
  171715. * APP0 and APP14 are specially checked to see if they are
  171716. * JFIF and Adobe markers, respectively.
  171717. */
  171718. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171719. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171720. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171721. LOCAL(void)
  171722. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171723. unsigned int datalen, INT32 remaining)
  171724. /* Examine first few bytes from an APP0.
  171725. * Take appropriate action if it is a JFIF marker.
  171726. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171727. */
  171728. {
  171729. INT32 totallen = (INT32) datalen + remaining;
  171730. if (datalen >= APP0_DATA_LEN &&
  171731. GETJOCTET(data[0]) == 0x4A &&
  171732. GETJOCTET(data[1]) == 0x46 &&
  171733. GETJOCTET(data[2]) == 0x49 &&
  171734. GETJOCTET(data[3]) == 0x46 &&
  171735. GETJOCTET(data[4]) == 0) {
  171736. /* Found JFIF APP0 marker: save info */
  171737. cinfo->saw_JFIF_marker = TRUE;
  171738. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171739. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171740. cinfo->density_unit = GETJOCTET(data[7]);
  171741. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171742. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171743. /* Check version.
  171744. * Major version must be 1, anything else signals an incompatible change.
  171745. * (We used to treat this as an error, but now it's a nonfatal warning,
  171746. * because some bozo at Hijaak couldn't read the spec.)
  171747. * Minor version should be 0..2, but process anyway if newer.
  171748. */
  171749. if (cinfo->JFIF_major_version != 1)
  171750. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171751. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171752. /* Generate trace messages */
  171753. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171754. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171755. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171756. /* Validate thumbnail dimensions and issue appropriate messages */
  171757. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171758. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171759. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171760. totallen -= APP0_DATA_LEN;
  171761. if (totallen !=
  171762. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171763. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171764. } else if (datalen >= 6 &&
  171765. GETJOCTET(data[0]) == 0x4A &&
  171766. GETJOCTET(data[1]) == 0x46 &&
  171767. GETJOCTET(data[2]) == 0x58 &&
  171768. GETJOCTET(data[3]) == 0x58 &&
  171769. GETJOCTET(data[4]) == 0) {
  171770. /* Found JFIF "JFXX" extension APP0 marker */
  171771. /* The library doesn't actually do anything with these,
  171772. * but we try to produce a helpful trace message.
  171773. */
  171774. switch (GETJOCTET(data[5])) {
  171775. case 0x10:
  171776. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171777. break;
  171778. case 0x11:
  171779. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171780. break;
  171781. case 0x13:
  171782. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171783. break;
  171784. default:
  171785. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171786. GETJOCTET(data[5]), (int) totallen);
  171787. break;
  171788. }
  171789. } else {
  171790. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171791. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171792. }
  171793. }
  171794. LOCAL(void)
  171795. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171796. unsigned int datalen, INT32 remaining)
  171797. /* Examine first few bytes from an APP14.
  171798. * Take appropriate action if it is an Adobe marker.
  171799. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171800. */
  171801. {
  171802. unsigned int version, flags0, flags1, transform;
  171803. if (datalen >= APP14_DATA_LEN &&
  171804. GETJOCTET(data[0]) == 0x41 &&
  171805. GETJOCTET(data[1]) == 0x64 &&
  171806. GETJOCTET(data[2]) == 0x6F &&
  171807. GETJOCTET(data[3]) == 0x62 &&
  171808. GETJOCTET(data[4]) == 0x65) {
  171809. /* Found Adobe APP14 marker */
  171810. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171811. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171812. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171813. transform = GETJOCTET(data[11]);
  171814. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171815. cinfo->saw_Adobe_marker = TRUE;
  171816. cinfo->Adobe_transform = (UINT8) transform;
  171817. } else {
  171818. /* Start of APP14 does not match "Adobe", or too short */
  171819. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171820. }
  171821. }
  171822. METHODDEF(boolean)
  171823. get_interesting_appn (j_decompress_ptr cinfo)
  171824. /* Process an APP0 or APP14 marker without saving it */
  171825. {
  171826. INT32 length;
  171827. JOCTET b[APPN_DATA_LEN];
  171828. unsigned int i, numtoread;
  171829. INPUT_VARS(cinfo);
  171830. INPUT_2BYTES(cinfo, length, return FALSE);
  171831. length -= 2;
  171832. /* get the interesting part of the marker data */
  171833. if (length >= APPN_DATA_LEN)
  171834. numtoread = APPN_DATA_LEN;
  171835. else if (length > 0)
  171836. numtoread = (unsigned int) length;
  171837. else
  171838. numtoread = 0;
  171839. for (i = 0; i < numtoread; i++)
  171840. INPUT_BYTE(cinfo, b[i], return FALSE);
  171841. length -= numtoread;
  171842. /* process it */
  171843. switch (cinfo->unread_marker) {
  171844. case M_APP0:
  171845. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171846. break;
  171847. case M_APP14:
  171848. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171849. break;
  171850. default:
  171851. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171852. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171853. break;
  171854. }
  171855. /* skip any remaining data -- could be lots */
  171856. INPUT_SYNC(cinfo);
  171857. if (length > 0)
  171858. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171859. return TRUE;
  171860. }
  171861. #ifdef SAVE_MARKERS_SUPPORTED
  171862. METHODDEF(boolean)
  171863. save_marker (j_decompress_ptr cinfo)
  171864. /* Save an APPn or COM marker into the marker list */
  171865. {
  171866. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171867. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171868. unsigned int bytes_read, data_length;
  171869. JOCTET FAR * data;
  171870. INT32 length = 0;
  171871. INPUT_VARS(cinfo);
  171872. if (cur_marker == NULL) {
  171873. /* begin reading a marker */
  171874. INPUT_2BYTES(cinfo, length, return FALSE);
  171875. length -= 2;
  171876. if (length >= 0) { /* watch out for bogus length word */
  171877. /* figure out how much we want to save */
  171878. unsigned int limit;
  171879. if (cinfo->unread_marker == (int) M_COM)
  171880. limit = marker->length_limit_COM;
  171881. else
  171882. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171883. if ((unsigned int) length < limit)
  171884. limit = (unsigned int) length;
  171885. /* allocate and initialize the marker item */
  171886. cur_marker = (jpeg_saved_marker_ptr)
  171887. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171888. SIZEOF(struct jpeg_marker_struct) + limit);
  171889. cur_marker->next = NULL;
  171890. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171891. cur_marker->original_length = (unsigned int) length;
  171892. cur_marker->data_length = limit;
  171893. /* data area is just beyond the jpeg_marker_struct */
  171894. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171895. marker->cur_marker = cur_marker;
  171896. marker->bytes_read = 0;
  171897. bytes_read = 0;
  171898. data_length = limit;
  171899. } else {
  171900. /* deal with bogus length word */
  171901. bytes_read = data_length = 0;
  171902. data = NULL;
  171903. }
  171904. } else {
  171905. /* resume reading a marker */
  171906. bytes_read = marker->bytes_read;
  171907. data_length = cur_marker->data_length;
  171908. data = cur_marker->data + bytes_read;
  171909. }
  171910. while (bytes_read < data_length) {
  171911. INPUT_SYNC(cinfo); /* move the restart point to here */
  171912. marker->bytes_read = bytes_read;
  171913. /* If there's not at least one byte in buffer, suspend */
  171914. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171915. /* Copy bytes with reasonable rapidity */
  171916. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171917. *data++ = *next_input_byte++;
  171918. bytes_in_buffer--;
  171919. bytes_read++;
  171920. }
  171921. }
  171922. /* Done reading what we want to read */
  171923. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171924. /* Add new marker to end of list */
  171925. if (cinfo->marker_list == NULL) {
  171926. cinfo->marker_list = cur_marker;
  171927. } else {
  171928. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171929. while (prev->next != NULL)
  171930. prev = prev->next;
  171931. prev->next = cur_marker;
  171932. }
  171933. /* Reset pointer & calc remaining data length */
  171934. data = cur_marker->data;
  171935. length = cur_marker->original_length - data_length;
  171936. }
  171937. /* Reset to initial state for next marker */
  171938. marker->cur_marker = NULL;
  171939. /* Process the marker if interesting; else just make a generic trace msg */
  171940. switch (cinfo->unread_marker) {
  171941. case M_APP0:
  171942. examine_app0(cinfo, data, data_length, length);
  171943. break;
  171944. case M_APP14:
  171945. examine_app14(cinfo, data, data_length, length);
  171946. break;
  171947. default:
  171948. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171949. (int) (data_length + length));
  171950. break;
  171951. }
  171952. /* skip any remaining data -- could be lots */
  171953. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171954. if (length > 0)
  171955. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171956. return TRUE;
  171957. }
  171958. #endif /* SAVE_MARKERS_SUPPORTED */
  171959. METHODDEF(boolean)
  171960. skip_variable (j_decompress_ptr cinfo)
  171961. /* Skip over an unknown or uninteresting variable-length marker */
  171962. {
  171963. INT32 length;
  171964. INPUT_VARS(cinfo);
  171965. INPUT_2BYTES(cinfo, length, return FALSE);
  171966. length -= 2;
  171967. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171968. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171969. if (length > 0)
  171970. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171971. return TRUE;
  171972. }
  171973. /*
  171974. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171975. * Returns FALSE if had to suspend before reaching a marker;
  171976. * in that case cinfo->unread_marker is unchanged.
  171977. *
  171978. * Note that the result might not be a valid marker code,
  171979. * but it will never be 0 or FF.
  171980. */
  171981. LOCAL(boolean)
  171982. next_marker (j_decompress_ptr cinfo)
  171983. {
  171984. int c;
  171985. INPUT_VARS(cinfo);
  171986. for (;;) {
  171987. INPUT_BYTE(cinfo, c, return FALSE);
  171988. /* Skip any non-FF bytes.
  171989. * This may look a bit inefficient, but it will not occur in a valid file.
  171990. * We sync after each discarded byte so that a suspending data source
  171991. * can discard the byte from its buffer.
  171992. */
  171993. while (c != 0xFF) {
  171994. cinfo->marker->discarded_bytes++;
  171995. INPUT_SYNC(cinfo);
  171996. INPUT_BYTE(cinfo, c, return FALSE);
  171997. }
  171998. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171999. * pad bytes, so don't count them in discarded_bytes. We assume there
  172000. * will not be so many consecutive FF bytes as to overflow a suspending
  172001. * data source's input buffer.
  172002. */
  172003. do {
  172004. INPUT_BYTE(cinfo, c, return FALSE);
  172005. } while (c == 0xFF);
  172006. if (c != 0)
  172007. break; /* found a valid marker, exit loop */
  172008. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  172009. * Discard it and loop back to try again.
  172010. */
  172011. cinfo->marker->discarded_bytes += 2;
  172012. INPUT_SYNC(cinfo);
  172013. }
  172014. if (cinfo->marker->discarded_bytes != 0) {
  172015. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  172016. cinfo->marker->discarded_bytes = 0;
  172017. }
  172018. cinfo->unread_marker = c;
  172019. INPUT_SYNC(cinfo);
  172020. return TRUE;
  172021. }
  172022. LOCAL(boolean)
  172023. first_marker (j_decompress_ptr cinfo)
  172024. /* Like next_marker, but used to obtain the initial SOI marker. */
  172025. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  172026. * we might well scan an entire input file before realizing it ain't JPEG.
  172027. * If an application wants to process non-JFIF files, it must seek to the
  172028. * SOI before calling the JPEG library.
  172029. */
  172030. {
  172031. int c, c2;
  172032. INPUT_VARS(cinfo);
  172033. INPUT_BYTE(cinfo, c, return FALSE);
  172034. INPUT_BYTE(cinfo, c2, return FALSE);
  172035. if (c != 0xFF || c2 != (int) M_SOI)
  172036. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172037. cinfo->unread_marker = c2;
  172038. INPUT_SYNC(cinfo);
  172039. return TRUE;
  172040. }
  172041. /*
  172042. * Read markers until SOS or EOI.
  172043. *
  172044. * Returns same codes as are defined for jpeg_consume_input:
  172045. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172046. */
  172047. METHODDEF(int)
  172048. read_markers (j_decompress_ptr cinfo)
  172049. {
  172050. /* Outer loop repeats once for each marker. */
  172051. for (;;) {
  172052. /* Collect the marker proper, unless we already did. */
  172053. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172054. if (cinfo->unread_marker == 0) {
  172055. if (! cinfo->marker->saw_SOI) {
  172056. if (! first_marker(cinfo))
  172057. return JPEG_SUSPENDED;
  172058. } else {
  172059. if (! next_marker(cinfo))
  172060. return JPEG_SUSPENDED;
  172061. }
  172062. }
  172063. /* At this point cinfo->unread_marker contains the marker code and the
  172064. * input point is just past the marker proper, but before any parameters.
  172065. * A suspension will cause us to return with this state still true.
  172066. */
  172067. switch (cinfo->unread_marker) {
  172068. case M_SOI:
  172069. if (! get_soi(cinfo))
  172070. return JPEG_SUSPENDED;
  172071. break;
  172072. case M_SOF0: /* Baseline */
  172073. case M_SOF1: /* Extended sequential, Huffman */
  172074. if (! get_sof(cinfo, FALSE, FALSE))
  172075. return JPEG_SUSPENDED;
  172076. break;
  172077. case M_SOF2: /* Progressive, Huffman */
  172078. if (! get_sof(cinfo, TRUE, FALSE))
  172079. return JPEG_SUSPENDED;
  172080. break;
  172081. case M_SOF9: /* Extended sequential, arithmetic */
  172082. if (! get_sof(cinfo, FALSE, TRUE))
  172083. return JPEG_SUSPENDED;
  172084. break;
  172085. case M_SOF10: /* Progressive, arithmetic */
  172086. if (! get_sof(cinfo, TRUE, TRUE))
  172087. return JPEG_SUSPENDED;
  172088. break;
  172089. /* Currently unsupported SOFn types */
  172090. case M_SOF3: /* Lossless, Huffman */
  172091. case M_SOF5: /* Differential sequential, Huffman */
  172092. case M_SOF6: /* Differential progressive, Huffman */
  172093. case M_SOF7: /* Differential lossless, Huffman */
  172094. case M_JPG: /* Reserved for JPEG extensions */
  172095. case M_SOF11: /* Lossless, arithmetic */
  172096. case M_SOF13: /* Differential sequential, arithmetic */
  172097. case M_SOF14: /* Differential progressive, arithmetic */
  172098. case M_SOF15: /* Differential lossless, arithmetic */
  172099. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172100. break;
  172101. case M_SOS:
  172102. if (! get_sos(cinfo))
  172103. return JPEG_SUSPENDED;
  172104. cinfo->unread_marker = 0; /* processed the marker */
  172105. return JPEG_REACHED_SOS;
  172106. case M_EOI:
  172107. TRACEMS(cinfo, 1, JTRC_EOI);
  172108. cinfo->unread_marker = 0; /* processed the marker */
  172109. return JPEG_REACHED_EOI;
  172110. case M_DAC:
  172111. if (! get_dac(cinfo))
  172112. return JPEG_SUSPENDED;
  172113. break;
  172114. case M_DHT:
  172115. if (! get_dht(cinfo))
  172116. return JPEG_SUSPENDED;
  172117. break;
  172118. case M_DQT:
  172119. if (! get_dqt(cinfo))
  172120. return JPEG_SUSPENDED;
  172121. break;
  172122. case M_DRI:
  172123. if (! get_dri(cinfo))
  172124. return JPEG_SUSPENDED;
  172125. break;
  172126. case M_APP0:
  172127. case M_APP1:
  172128. case M_APP2:
  172129. case M_APP3:
  172130. case M_APP4:
  172131. case M_APP5:
  172132. case M_APP6:
  172133. case M_APP7:
  172134. case M_APP8:
  172135. case M_APP9:
  172136. case M_APP10:
  172137. case M_APP11:
  172138. case M_APP12:
  172139. case M_APP13:
  172140. case M_APP14:
  172141. case M_APP15:
  172142. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172143. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172144. return JPEG_SUSPENDED;
  172145. break;
  172146. case M_COM:
  172147. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172148. return JPEG_SUSPENDED;
  172149. break;
  172150. case M_RST0: /* these are all parameterless */
  172151. case M_RST1:
  172152. case M_RST2:
  172153. case M_RST3:
  172154. case M_RST4:
  172155. case M_RST5:
  172156. case M_RST6:
  172157. case M_RST7:
  172158. case M_TEM:
  172159. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172160. break;
  172161. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172162. if (! skip_variable(cinfo))
  172163. return JPEG_SUSPENDED;
  172164. break;
  172165. default: /* must be DHP, EXP, JPGn, or RESn */
  172166. /* For now, we treat the reserved markers as fatal errors since they are
  172167. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172168. * Once the JPEG 3 version-number marker is well defined, this code
  172169. * ought to change!
  172170. */
  172171. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172172. break;
  172173. }
  172174. /* Successfully processed marker, so reset state variable */
  172175. cinfo->unread_marker = 0;
  172176. } /* end loop */
  172177. }
  172178. /*
  172179. * Read a restart marker, which is expected to appear next in the datastream;
  172180. * if the marker is not there, take appropriate recovery action.
  172181. * Returns FALSE if suspension is required.
  172182. *
  172183. * This is called by the entropy decoder after it has read an appropriate
  172184. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172185. * has already read a marker from the data source. Under normal conditions
  172186. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172187. * it holds a marker which the decoder will be unable to read past.
  172188. */
  172189. METHODDEF(boolean)
  172190. read_restart_marker (j_decompress_ptr cinfo)
  172191. {
  172192. /* Obtain a marker unless we already did. */
  172193. /* Note that next_marker will complain if it skips any data. */
  172194. if (cinfo->unread_marker == 0) {
  172195. if (! next_marker(cinfo))
  172196. return FALSE;
  172197. }
  172198. if (cinfo->unread_marker ==
  172199. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172200. /* Normal case --- swallow the marker and let entropy decoder continue */
  172201. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172202. cinfo->unread_marker = 0;
  172203. } else {
  172204. /* Uh-oh, the restart markers have been messed up. */
  172205. /* Let the data source manager determine how to resync. */
  172206. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172207. cinfo->marker->next_restart_num))
  172208. return FALSE;
  172209. }
  172210. /* Update next-restart state */
  172211. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172212. return TRUE;
  172213. }
  172214. /*
  172215. * This is the default resync_to_restart method for data source managers
  172216. * to use if they don't have any better approach. Some data source managers
  172217. * may be able to back up, or may have additional knowledge about the data
  172218. * which permits a more intelligent recovery strategy; such managers would
  172219. * presumably supply their own resync method.
  172220. *
  172221. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172222. * the restart marker it was expecting. (This code is *not* used unless
  172223. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172224. * the marker code actually found (might be anything, except 0 or FF).
  172225. * The desired restart marker number (0..7) is passed as a parameter.
  172226. * This routine is supposed to apply whatever error recovery strategy seems
  172227. * appropriate in order to position the input stream to the next data segment.
  172228. * Note that cinfo->unread_marker is treated as a marker appearing before
  172229. * the current data-source input point; usually it should be reset to zero
  172230. * before returning.
  172231. * Returns FALSE if suspension is required.
  172232. *
  172233. * This implementation is substantially constrained by wanting to treat the
  172234. * input as a data stream; this means we can't back up. Therefore, we have
  172235. * only the following actions to work with:
  172236. * 1. Simply discard the marker and let the entropy decoder resume at next
  172237. * byte of file.
  172238. * 2. Read forward until we find another marker, discarding intervening
  172239. * data. (In theory we could look ahead within the current bufferload,
  172240. * without having to discard data if we don't find the desired marker.
  172241. * This idea is not implemented here, in part because it makes behavior
  172242. * dependent on buffer size and chance buffer-boundary positions.)
  172243. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172244. * This will cause the entropy decoder to process an empty data segment,
  172245. * inserting dummy zeroes, and then we will reprocess the marker.
  172246. *
  172247. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172248. * appropriate if the found marker is a future restart marker (indicating
  172249. * that we have missed the desired restart marker, probably because it got
  172250. * corrupted).
  172251. * We apply #2 or #3 if the found marker is a restart marker no more than
  172252. * two counts behind or ahead of the expected one. We also apply #2 if the
  172253. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172254. * If the found marker is a restart marker more than 2 counts away, we do #1
  172255. * (too much risk that the marker is erroneous; with luck we will be able to
  172256. * resync at some future point).
  172257. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172258. * overrunning the end of a scan. An implementation limited to single-scan
  172259. * files might find it better to apply #2 for markers other than EOI, since
  172260. * any other marker would have to be bogus data in that case.
  172261. */
  172262. GLOBAL(boolean)
  172263. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172264. {
  172265. int marker = cinfo->unread_marker;
  172266. int action = 1;
  172267. /* Always put up a warning. */
  172268. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172269. /* Outer loop handles repeated decision after scanning forward. */
  172270. for (;;) {
  172271. if (marker < (int) M_SOF0)
  172272. action = 2; /* invalid marker */
  172273. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172274. action = 3; /* valid non-restart marker */
  172275. else {
  172276. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172277. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172278. action = 3; /* one of the next two expected restarts */
  172279. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172280. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172281. action = 2; /* a prior restart, so advance */
  172282. else
  172283. action = 1; /* desired restart or too far away */
  172284. }
  172285. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172286. switch (action) {
  172287. case 1:
  172288. /* Discard marker and let entropy decoder resume processing. */
  172289. cinfo->unread_marker = 0;
  172290. return TRUE;
  172291. case 2:
  172292. /* Scan to the next marker, and repeat the decision loop. */
  172293. if (! next_marker(cinfo))
  172294. return FALSE;
  172295. marker = cinfo->unread_marker;
  172296. break;
  172297. case 3:
  172298. /* Return without advancing past this marker. */
  172299. /* Entropy decoder will be forced to process an empty segment. */
  172300. return TRUE;
  172301. }
  172302. } /* end loop */
  172303. }
  172304. /*
  172305. * Reset marker processing state to begin a fresh datastream.
  172306. */
  172307. METHODDEF(void)
  172308. reset_marker_reader (j_decompress_ptr cinfo)
  172309. {
  172310. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172311. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172312. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172313. cinfo->unread_marker = 0; /* no pending marker */
  172314. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172315. marker->pub.saw_SOF = FALSE;
  172316. marker->pub.discarded_bytes = 0;
  172317. marker->cur_marker = NULL;
  172318. }
  172319. /*
  172320. * Initialize the marker reader module.
  172321. * This is called only once, when the decompression object is created.
  172322. */
  172323. GLOBAL(void)
  172324. jinit_marker_reader (j_decompress_ptr cinfo)
  172325. {
  172326. my_marker_ptr2 marker;
  172327. int i;
  172328. /* Create subobject in permanent pool */
  172329. marker = (my_marker_ptr2)
  172330. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172331. SIZEOF(my_marker_reader));
  172332. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172333. /* Initialize public method pointers */
  172334. marker->pub.reset_marker_reader = reset_marker_reader;
  172335. marker->pub.read_markers = read_markers;
  172336. marker->pub.read_restart_marker = read_restart_marker;
  172337. /* Initialize COM/APPn processing.
  172338. * By default, we examine and then discard APP0 and APP14,
  172339. * but simply discard COM and all other APPn.
  172340. */
  172341. marker->process_COM = skip_variable;
  172342. marker->length_limit_COM = 0;
  172343. for (i = 0; i < 16; i++) {
  172344. marker->process_APPn[i] = skip_variable;
  172345. marker->length_limit_APPn[i] = 0;
  172346. }
  172347. marker->process_APPn[0] = get_interesting_appn;
  172348. marker->process_APPn[14] = get_interesting_appn;
  172349. /* Reset marker processing state */
  172350. reset_marker_reader(cinfo);
  172351. }
  172352. /*
  172353. * Control saving of COM and APPn markers into marker_list.
  172354. */
  172355. #ifdef SAVE_MARKERS_SUPPORTED
  172356. GLOBAL(void)
  172357. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172358. unsigned int length_limit)
  172359. {
  172360. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172361. long maxlength;
  172362. jpeg_marker_parser_method processor;
  172363. /* Length limit mustn't be larger than what we can allocate
  172364. * (should only be a concern in a 16-bit environment).
  172365. */
  172366. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172367. if (((long) length_limit) > maxlength)
  172368. length_limit = (unsigned int) maxlength;
  172369. /* Choose processor routine to use.
  172370. * APP0/APP14 have special requirements.
  172371. */
  172372. if (length_limit) {
  172373. processor = save_marker;
  172374. /* If saving APP0/APP14, save at least enough for our internal use. */
  172375. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172376. length_limit = APP0_DATA_LEN;
  172377. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172378. length_limit = APP14_DATA_LEN;
  172379. } else {
  172380. processor = skip_variable;
  172381. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172382. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172383. processor = get_interesting_appn;
  172384. }
  172385. if (marker_code == (int) M_COM) {
  172386. marker->process_COM = processor;
  172387. marker->length_limit_COM = length_limit;
  172388. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172389. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172390. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172391. } else
  172392. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172393. }
  172394. #endif /* SAVE_MARKERS_SUPPORTED */
  172395. /*
  172396. * Install a special processing method for COM or APPn markers.
  172397. */
  172398. GLOBAL(void)
  172399. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172400. jpeg_marker_parser_method routine)
  172401. {
  172402. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172403. if (marker_code == (int) M_COM)
  172404. marker->process_COM = routine;
  172405. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172406. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172407. else
  172408. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172409. }
  172410. /*** End of inlined file: jdmarker.c ***/
  172411. /*** Start of inlined file: jdmaster.c ***/
  172412. #define JPEG_INTERNALS
  172413. /* Private state */
  172414. typedef struct {
  172415. struct jpeg_decomp_master pub; /* public fields */
  172416. int pass_number; /* # of passes completed */
  172417. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172418. /* Saved references to initialized quantizer modules,
  172419. * in case we need to switch modes.
  172420. */
  172421. struct jpeg_color_quantizer * quantizer_1pass;
  172422. struct jpeg_color_quantizer * quantizer_2pass;
  172423. } my_decomp_master;
  172424. typedef my_decomp_master * my_master_ptr6;
  172425. /*
  172426. * Determine whether merged upsample/color conversion should be used.
  172427. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172428. */
  172429. LOCAL(boolean)
  172430. use_merged_upsample (j_decompress_ptr cinfo)
  172431. {
  172432. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172433. /* Merging is the equivalent of plain box-filter upsampling */
  172434. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172435. return FALSE;
  172436. /* jdmerge.c only supports YCC=>RGB color conversion */
  172437. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172438. cinfo->out_color_space != JCS_RGB ||
  172439. cinfo->out_color_components != RGB_PIXELSIZE)
  172440. return FALSE;
  172441. /* and it only handles 2h1v or 2h2v sampling ratios */
  172442. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172443. cinfo->comp_info[1].h_samp_factor != 1 ||
  172444. cinfo->comp_info[2].h_samp_factor != 1 ||
  172445. cinfo->comp_info[0].v_samp_factor > 2 ||
  172446. cinfo->comp_info[1].v_samp_factor != 1 ||
  172447. cinfo->comp_info[2].v_samp_factor != 1)
  172448. return FALSE;
  172449. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172450. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172451. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172452. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172453. return FALSE;
  172454. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172455. return TRUE; /* by golly, it'll work... */
  172456. #else
  172457. return FALSE;
  172458. #endif
  172459. }
  172460. /*
  172461. * Compute output image dimensions and related values.
  172462. * NOTE: this is exported for possible use by application.
  172463. * Hence it mustn't do anything that can't be done twice.
  172464. * Also note that it may be called before the master module is initialized!
  172465. */
  172466. GLOBAL(void)
  172467. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172468. /* Do computations that are needed before master selection phase */
  172469. {
  172470. #ifdef IDCT_SCALING_SUPPORTED
  172471. int ci;
  172472. jpeg_component_info *compptr;
  172473. #endif
  172474. /* Prevent application from calling me at wrong times */
  172475. if (cinfo->global_state != DSTATE_READY)
  172476. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172477. #ifdef IDCT_SCALING_SUPPORTED
  172478. /* Compute actual output image dimensions and DCT scaling choices. */
  172479. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172480. /* Provide 1/8 scaling */
  172481. cinfo->output_width = (JDIMENSION)
  172482. jdiv_round_up((long) cinfo->image_width, 8L);
  172483. cinfo->output_height = (JDIMENSION)
  172484. jdiv_round_up((long) cinfo->image_height, 8L);
  172485. cinfo->min_DCT_scaled_size = 1;
  172486. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172487. /* Provide 1/4 scaling */
  172488. cinfo->output_width = (JDIMENSION)
  172489. jdiv_round_up((long) cinfo->image_width, 4L);
  172490. cinfo->output_height = (JDIMENSION)
  172491. jdiv_round_up((long) cinfo->image_height, 4L);
  172492. cinfo->min_DCT_scaled_size = 2;
  172493. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172494. /* Provide 1/2 scaling */
  172495. cinfo->output_width = (JDIMENSION)
  172496. jdiv_round_up((long) cinfo->image_width, 2L);
  172497. cinfo->output_height = (JDIMENSION)
  172498. jdiv_round_up((long) cinfo->image_height, 2L);
  172499. cinfo->min_DCT_scaled_size = 4;
  172500. } else {
  172501. /* Provide 1/1 scaling */
  172502. cinfo->output_width = cinfo->image_width;
  172503. cinfo->output_height = cinfo->image_height;
  172504. cinfo->min_DCT_scaled_size = DCTSIZE;
  172505. }
  172506. /* In selecting the actual DCT scaling for each component, we try to
  172507. * scale up the chroma components via IDCT scaling rather than upsampling.
  172508. * This saves time if the upsampler gets to use 1:1 scaling.
  172509. * Note this code assumes that the supported DCT scalings are powers of 2.
  172510. */
  172511. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172512. ci++, compptr++) {
  172513. int ssize = cinfo->min_DCT_scaled_size;
  172514. while (ssize < DCTSIZE &&
  172515. (compptr->h_samp_factor * ssize * 2 <=
  172516. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172517. (compptr->v_samp_factor * ssize * 2 <=
  172518. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172519. ssize = ssize * 2;
  172520. }
  172521. compptr->DCT_scaled_size = ssize;
  172522. }
  172523. /* Recompute downsampled dimensions of components;
  172524. * application needs to know these if using raw downsampled data.
  172525. */
  172526. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172527. ci++, compptr++) {
  172528. /* Size in samples, after IDCT scaling */
  172529. compptr->downsampled_width = (JDIMENSION)
  172530. jdiv_round_up((long) cinfo->image_width *
  172531. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172532. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172533. compptr->downsampled_height = (JDIMENSION)
  172534. jdiv_round_up((long) cinfo->image_height *
  172535. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172536. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172537. }
  172538. #else /* !IDCT_SCALING_SUPPORTED */
  172539. /* Hardwire it to "no scaling" */
  172540. cinfo->output_width = cinfo->image_width;
  172541. cinfo->output_height = cinfo->image_height;
  172542. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172543. * and has computed unscaled downsampled_width and downsampled_height.
  172544. */
  172545. #endif /* IDCT_SCALING_SUPPORTED */
  172546. /* Report number of components in selected colorspace. */
  172547. /* Probably this should be in the color conversion module... */
  172548. switch (cinfo->out_color_space) {
  172549. case JCS_GRAYSCALE:
  172550. cinfo->out_color_components = 1;
  172551. break;
  172552. case JCS_RGB:
  172553. #if RGB_PIXELSIZE != 3
  172554. cinfo->out_color_components = RGB_PIXELSIZE;
  172555. break;
  172556. #endif /* else share code with YCbCr */
  172557. case JCS_YCbCr:
  172558. cinfo->out_color_components = 3;
  172559. break;
  172560. case JCS_CMYK:
  172561. case JCS_YCCK:
  172562. cinfo->out_color_components = 4;
  172563. break;
  172564. default: /* else must be same colorspace as in file */
  172565. cinfo->out_color_components = cinfo->num_components;
  172566. break;
  172567. }
  172568. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172569. cinfo->out_color_components);
  172570. /* See if upsampler will want to emit more than one row at a time */
  172571. if (use_merged_upsample(cinfo))
  172572. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172573. else
  172574. cinfo->rec_outbuf_height = 1;
  172575. }
  172576. /*
  172577. * Several decompression processes need to range-limit values to the range
  172578. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172579. * due to noise introduced by quantization, roundoff error, etc. These
  172580. * processes are inner loops and need to be as fast as possible. On most
  172581. * machines, particularly CPUs with pipelines or instruction prefetch,
  172582. * a (subscript-check-less) C table lookup
  172583. * x = sample_range_limit[x];
  172584. * is faster than explicit tests
  172585. * if (x < 0) x = 0;
  172586. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172587. * These processes all use a common table prepared by the routine below.
  172588. *
  172589. * For most steps we can mathematically guarantee that the initial value
  172590. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172591. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172592. * limiting step (just after the IDCT), a wildly out-of-range value is
  172593. * possible if the input data is corrupt. To avoid any chance of indexing
  172594. * off the end of memory and getting a bad-pointer trap, we perform the
  172595. * post-IDCT limiting thus:
  172596. * x = range_limit[x & MASK];
  172597. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172598. * samples. Under normal circumstances this is more than enough range and
  172599. * a correct output will be generated; with bogus input data the mask will
  172600. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172601. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172602. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172603. * So the post-IDCT limiting table ends up looking like this:
  172604. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172605. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172606. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172607. * 0,1,...,CENTERJSAMPLE-1
  172608. * Negative inputs select values from the upper half of the table after
  172609. * masking.
  172610. *
  172611. * We can save some space by overlapping the start of the post-IDCT table
  172612. * with the simpler range limiting table. The post-IDCT table begins at
  172613. * sample_range_limit + CENTERJSAMPLE.
  172614. *
  172615. * Note that the table is allocated in near data space on PCs; it's small
  172616. * enough and used often enough to justify this.
  172617. */
  172618. LOCAL(void)
  172619. prepare_range_limit_table (j_decompress_ptr cinfo)
  172620. /* Allocate and fill in the sample_range_limit table */
  172621. {
  172622. JSAMPLE * table;
  172623. int i;
  172624. table = (JSAMPLE *)
  172625. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172626. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172627. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172628. cinfo->sample_range_limit = table;
  172629. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172630. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172631. /* Main part of "simple" table: limit[x] = x */
  172632. for (i = 0; i <= MAXJSAMPLE; i++)
  172633. table[i] = (JSAMPLE) i;
  172634. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172635. /* End of simple table, rest of first half of post-IDCT table */
  172636. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172637. table[i] = MAXJSAMPLE;
  172638. /* Second half of post-IDCT table */
  172639. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172640. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172641. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172642. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172643. }
  172644. /*
  172645. * Master selection of decompression modules.
  172646. * This is done once at jpeg_start_decompress time. We determine
  172647. * which modules will be used and give them appropriate initialization calls.
  172648. * We also initialize the decompressor input side to begin consuming data.
  172649. *
  172650. * Since jpeg_read_header has finished, we know what is in the SOF
  172651. * and (first) SOS markers. We also have all the application parameter
  172652. * settings.
  172653. */
  172654. LOCAL(void)
  172655. master_selection (j_decompress_ptr cinfo)
  172656. {
  172657. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172658. boolean use_c_buffer;
  172659. long samplesperrow;
  172660. JDIMENSION jd_samplesperrow;
  172661. /* Initialize dimensions and other stuff */
  172662. jpeg_calc_output_dimensions(cinfo);
  172663. prepare_range_limit_table(cinfo);
  172664. /* Width of an output scanline must be representable as JDIMENSION. */
  172665. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172666. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172667. if ((long) jd_samplesperrow != samplesperrow)
  172668. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172669. /* Initialize my private state */
  172670. master->pass_number = 0;
  172671. master->using_merged_upsample = use_merged_upsample(cinfo);
  172672. /* Color quantizer selection */
  172673. master->quantizer_1pass = NULL;
  172674. master->quantizer_2pass = NULL;
  172675. /* No mode changes if not using buffered-image mode. */
  172676. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172677. cinfo->enable_1pass_quant = FALSE;
  172678. cinfo->enable_external_quant = FALSE;
  172679. cinfo->enable_2pass_quant = FALSE;
  172680. }
  172681. if (cinfo->quantize_colors) {
  172682. if (cinfo->raw_data_out)
  172683. ERREXIT(cinfo, JERR_NOTIMPL);
  172684. /* 2-pass quantizer only works in 3-component color space. */
  172685. if (cinfo->out_color_components != 3) {
  172686. cinfo->enable_1pass_quant = TRUE;
  172687. cinfo->enable_external_quant = FALSE;
  172688. cinfo->enable_2pass_quant = FALSE;
  172689. cinfo->colormap = NULL;
  172690. } else if (cinfo->colormap != NULL) {
  172691. cinfo->enable_external_quant = TRUE;
  172692. } else if (cinfo->two_pass_quantize) {
  172693. cinfo->enable_2pass_quant = TRUE;
  172694. } else {
  172695. cinfo->enable_1pass_quant = TRUE;
  172696. }
  172697. if (cinfo->enable_1pass_quant) {
  172698. #ifdef QUANT_1PASS_SUPPORTED
  172699. jinit_1pass_quantizer(cinfo);
  172700. master->quantizer_1pass = cinfo->cquantize;
  172701. #else
  172702. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172703. #endif
  172704. }
  172705. /* We use the 2-pass code to map to external colormaps. */
  172706. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172707. #ifdef QUANT_2PASS_SUPPORTED
  172708. jinit_2pass_quantizer(cinfo);
  172709. master->quantizer_2pass = cinfo->cquantize;
  172710. #else
  172711. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172712. #endif
  172713. }
  172714. /* If both quantizers are initialized, the 2-pass one is left active;
  172715. * this is necessary for starting with quantization to an external map.
  172716. */
  172717. }
  172718. /* Post-processing: in particular, color conversion first */
  172719. if (! cinfo->raw_data_out) {
  172720. if (master->using_merged_upsample) {
  172721. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172722. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172723. #else
  172724. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172725. #endif
  172726. } else {
  172727. jinit_color_deconverter(cinfo);
  172728. jinit_upsampler(cinfo);
  172729. }
  172730. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172731. }
  172732. /* Inverse DCT */
  172733. jinit_inverse_dct(cinfo);
  172734. /* Entropy decoding: either Huffman or arithmetic coding. */
  172735. if (cinfo->arith_code) {
  172736. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172737. } else {
  172738. if (cinfo->progressive_mode) {
  172739. #ifdef D_PROGRESSIVE_SUPPORTED
  172740. jinit_phuff_decoder(cinfo);
  172741. #else
  172742. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172743. #endif
  172744. } else
  172745. jinit_huff_decoder(cinfo);
  172746. }
  172747. /* Initialize principal buffer controllers. */
  172748. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172749. jinit_d_coef_controller(cinfo, use_c_buffer);
  172750. if (! cinfo->raw_data_out)
  172751. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172752. /* We can now tell the memory manager to allocate virtual arrays. */
  172753. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172754. /* Initialize input side of decompressor to consume first scan. */
  172755. (*cinfo->inputctl->start_input_pass) (cinfo);
  172756. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172757. /* If jpeg_start_decompress will read the whole file, initialize
  172758. * progress monitoring appropriately. The input step is counted
  172759. * as one pass.
  172760. */
  172761. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172762. cinfo->inputctl->has_multiple_scans) {
  172763. int nscans;
  172764. /* Estimate number of scans to set pass_limit. */
  172765. if (cinfo->progressive_mode) {
  172766. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172767. nscans = 2 + 3 * cinfo->num_components;
  172768. } else {
  172769. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172770. nscans = cinfo->num_components;
  172771. }
  172772. cinfo->progress->pass_counter = 0L;
  172773. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172774. cinfo->progress->completed_passes = 0;
  172775. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172776. /* Count the input pass as done */
  172777. master->pass_number++;
  172778. }
  172779. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172780. }
  172781. /*
  172782. * Per-pass setup.
  172783. * This is called at the beginning of each output pass. We determine which
  172784. * modules will be active during this pass and give them appropriate
  172785. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172786. * is a "real" output pass or a dummy pass for color quantization.
  172787. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172788. */
  172789. METHODDEF(void)
  172790. prepare_for_output_pass (j_decompress_ptr cinfo)
  172791. {
  172792. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172793. if (master->pub.is_dummy_pass) {
  172794. #ifdef QUANT_2PASS_SUPPORTED
  172795. /* Final pass of 2-pass quantization */
  172796. master->pub.is_dummy_pass = FALSE;
  172797. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172798. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172799. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172800. #else
  172801. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172802. #endif /* QUANT_2PASS_SUPPORTED */
  172803. } else {
  172804. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172805. /* Select new quantization method */
  172806. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172807. cinfo->cquantize = master->quantizer_2pass;
  172808. master->pub.is_dummy_pass = TRUE;
  172809. } else if (cinfo->enable_1pass_quant) {
  172810. cinfo->cquantize = master->quantizer_1pass;
  172811. } else {
  172812. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172813. }
  172814. }
  172815. (*cinfo->idct->start_pass) (cinfo);
  172816. (*cinfo->coef->start_output_pass) (cinfo);
  172817. if (! cinfo->raw_data_out) {
  172818. if (! master->using_merged_upsample)
  172819. (*cinfo->cconvert->start_pass) (cinfo);
  172820. (*cinfo->upsample->start_pass) (cinfo);
  172821. if (cinfo->quantize_colors)
  172822. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172823. (*cinfo->post->start_pass) (cinfo,
  172824. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172825. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172826. }
  172827. }
  172828. /* Set up progress monitor's pass info if present */
  172829. if (cinfo->progress != NULL) {
  172830. cinfo->progress->completed_passes = master->pass_number;
  172831. cinfo->progress->total_passes = master->pass_number +
  172832. (master->pub.is_dummy_pass ? 2 : 1);
  172833. /* In buffered-image mode, we assume one more output pass if EOI not
  172834. * yet reached, but no more passes if EOI has been reached.
  172835. */
  172836. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172837. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172838. }
  172839. }
  172840. }
  172841. /*
  172842. * Finish up at end of an output pass.
  172843. */
  172844. METHODDEF(void)
  172845. finish_output_pass (j_decompress_ptr cinfo)
  172846. {
  172847. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172848. if (cinfo->quantize_colors)
  172849. (*cinfo->cquantize->finish_pass) (cinfo);
  172850. master->pass_number++;
  172851. }
  172852. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172853. /*
  172854. * Switch to a new external colormap between output passes.
  172855. */
  172856. GLOBAL(void)
  172857. jpeg_new_colormap (j_decompress_ptr cinfo)
  172858. {
  172859. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172860. /* Prevent application from calling me at wrong times */
  172861. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172862. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172863. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172864. cinfo->colormap != NULL) {
  172865. /* Select 2-pass quantizer for external colormap use */
  172866. cinfo->cquantize = master->quantizer_2pass;
  172867. /* Notify quantizer of colormap change */
  172868. (*cinfo->cquantize->new_color_map) (cinfo);
  172869. master->pub.is_dummy_pass = FALSE; /* just in case */
  172870. } else
  172871. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172872. }
  172873. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172874. /*
  172875. * Initialize master decompression control and select active modules.
  172876. * This is performed at the start of jpeg_start_decompress.
  172877. */
  172878. GLOBAL(void)
  172879. jinit_master_decompress (j_decompress_ptr cinfo)
  172880. {
  172881. my_master_ptr6 master;
  172882. master = (my_master_ptr6)
  172883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172884. SIZEOF(my_decomp_master));
  172885. cinfo->master = (struct jpeg_decomp_master *) master;
  172886. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172887. master->pub.finish_output_pass = finish_output_pass;
  172888. master->pub.is_dummy_pass = FALSE;
  172889. master_selection(cinfo);
  172890. }
  172891. /*** End of inlined file: jdmaster.c ***/
  172892. #undef FIX
  172893. /*** Start of inlined file: jdmerge.c ***/
  172894. #define JPEG_INTERNALS
  172895. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172896. /* Private subobject */
  172897. typedef struct {
  172898. struct jpeg_upsampler pub; /* public fields */
  172899. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172900. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172901. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172902. JSAMPARRAY output_buf));
  172903. /* Private state for YCC->RGB conversion */
  172904. int * Cr_r_tab; /* => table for Cr to R conversion */
  172905. int * Cb_b_tab; /* => table for Cb to B conversion */
  172906. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172907. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172908. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172909. * We need a "spare" row buffer to hold the second output row if the
  172910. * application provides just a one-row buffer; we also use the spare
  172911. * to discard the dummy last row if the image height is odd.
  172912. */
  172913. JSAMPROW spare_row;
  172914. boolean spare_full; /* T if spare buffer is occupied */
  172915. JDIMENSION out_row_width; /* samples per output row */
  172916. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172917. } my_upsampler;
  172918. typedef my_upsampler * my_upsample_ptr;
  172919. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172920. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172921. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172922. /*
  172923. * Initialize tables for YCC->RGB colorspace conversion.
  172924. * This is taken directly from jdcolor.c; see that file for more info.
  172925. */
  172926. LOCAL(void)
  172927. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172928. {
  172929. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172930. int i;
  172931. INT32 x;
  172932. SHIFT_TEMPS
  172933. upsample->Cr_r_tab = (int *)
  172934. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172935. (MAXJSAMPLE+1) * SIZEOF(int));
  172936. upsample->Cb_b_tab = (int *)
  172937. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172938. (MAXJSAMPLE+1) * SIZEOF(int));
  172939. upsample->Cr_g_tab = (INT32 *)
  172940. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172941. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172942. upsample->Cb_g_tab = (INT32 *)
  172943. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172944. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172945. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172946. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172947. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172948. /* Cr=>R value is nearest int to 1.40200 * x */
  172949. upsample->Cr_r_tab[i] = (int)
  172950. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172951. /* Cb=>B value is nearest int to 1.77200 * x */
  172952. upsample->Cb_b_tab[i] = (int)
  172953. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172954. /* Cr=>G value is scaled-up -0.71414 * x */
  172955. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172956. /* Cb=>G value is scaled-up -0.34414 * x */
  172957. /* We also add in ONE_HALF so that need not do it in inner loop */
  172958. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172959. }
  172960. }
  172961. /*
  172962. * Initialize for an upsampling pass.
  172963. */
  172964. METHODDEF(void)
  172965. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172966. {
  172967. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172968. /* Mark the spare buffer empty */
  172969. upsample->spare_full = FALSE;
  172970. /* Initialize total-height counter for detecting bottom of image */
  172971. upsample->rows_to_go = cinfo->output_height;
  172972. }
  172973. /*
  172974. * Control routine to do upsampling (and color conversion).
  172975. *
  172976. * The control routine just handles the row buffering considerations.
  172977. */
  172978. METHODDEF(void)
  172979. merged_2v_upsample (j_decompress_ptr cinfo,
  172980. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172981. JDIMENSION,
  172982. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172983. JDIMENSION out_rows_avail)
  172984. /* 2:1 vertical sampling case: may need a spare row. */
  172985. {
  172986. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172987. JSAMPROW work_ptrs[2];
  172988. JDIMENSION num_rows; /* number of rows returned to caller */
  172989. if (upsample->spare_full) {
  172990. /* If we have a spare row saved from a previous cycle, just return it. */
  172991. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172992. 1, upsample->out_row_width);
  172993. num_rows = 1;
  172994. upsample->spare_full = FALSE;
  172995. } else {
  172996. /* Figure number of rows to return to caller. */
  172997. num_rows = 2;
  172998. /* Not more than the distance to the end of the image. */
  172999. if (num_rows > upsample->rows_to_go)
  173000. num_rows = upsample->rows_to_go;
  173001. /* And not more than what the client can accept: */
  173002. out_rows_avail -= *out_row_ctr;
  173003. if (num_rows > out_rows_avail)
  173004. num_rows = out_rows_avail;
  173005. /* Create output pointer array for upsampler. */
  173006. work_ptrs[0] = output_buf[*out_row_ctr];
  173007. if (num_rows > 1) {
  173008. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  173009. } else {
  173010. work_ptrs[1] = upsample->spare_row;
  173011. upsample->spare_full = TRUE;
  173012. }
  173013. /* Now do the upsampling. */
  173014. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  173015. }
  173016. /* Adjust counts */
  173017. *out_row_ctr += num_rows;
  173018. upsample->rows_to_go -= num_rows;
  173019. /* When the buffer is emptied, declare this input row group consumed */
  173020. if (! upsample->spare_full)
  173021. (*in_row_group_ctr)++;
  173022. }
  173023. METHODDEF(void)
  173024. merged_1v_upsample (j_decompress_ptr cinfo,
  173025. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173026. JDIMENSION,
  173027. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173028. JDIMENSION)
  173029. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173030. {
  173031. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173032. /* Just do the upsampling. */
  173033. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173034. output_buf + *out_row_ctr);
  173035. /* Adjust counts */
  173036. (*out_row_ctr)++;
  173037. (*in_row_group_ctr)++;
  173038. }
  173039. /*
  173040. * These are the routines invoked by the control routines to do
  173041. * the actual upsampling/conversion. One row group is processed per call.
  173042. *
  173043. * Note: since we may be writing directly into application-supplied buffers,
  173044. * we have to be honest about the output width; we can't assume the buffer
  173045. * has been rounded up to an even width.
  173046. */
  173047. /*
  173048. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173049. */
  173050. METHODDEF(void)
  173051. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173052. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173053. JSAMPARRAY output_buf)
  173054. {
  173055. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173056. register int y, cred, cgreen, cblue;
  173057. int cb, cr;
  173058. register JSAMPROW outptr;
  173059. JSAMPROW inptr0, inptr1, inptr2;
  173060. JDIMENSION col;
  173061. /* copy these pointers into registers if possible */
  173062. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173063. int * Crrtab = upsample->Cr_r_tab;
  173064. int * Cbbtab = upsample->Cb_b_tab;
  173065. INT32 * Crgtab = upsample->Cr_g_tab;
  173066. INT32 * Cbgtab = upsample->Cb_g_tab;
  173067. SHIFT_TEMPS
  173068. inptr0 = input_buf[0][in_row_group_ctr];
  173069. inptr1 = input_buf[1][in_row_group_ctr];
  173070. inptr2 = input_buf[2][in_row_group_ctr];
  173071. outptr = output_buf[0];
  173072. /* Loop for each pair of output pixels */
  173073. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173074. /* Do the chroma part of the calculation */
  173075. cb = GETJSAMPLE(*inptr1++);
  173076. cr = GETJSAMPLE(*inptr2++);
  173077. cred = Crrtab[cr];
  173078. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173079. cblue = Cbbtab[cb];
  173080. /* Fetch 2 Y values and emit 2 pixels */
  173081. y = GETJSAMPLE(*inptr0++);
  173082. outptr[RGB_RED] = range_limit[y + cred];
  173083. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173084. outptr[RGB_BLUE] = range_limit[y + cblue];
  173085. outptr += RGB_PIXELSIZE;
  173086. y = GETJSAMPLE(*inptr0++);
  173087. outptr[RGB_RED] = range_limit[y + cred];
  173088. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173089. outptr[RGB_BLUE] = range_limit[y + cblue];
  173090. outptr += RGB_PIXELSIZE;
  173091. }
  173092. /* If image width is odd, do the last output column separately */
  173093. if (cinfo->output_width & 1) {
  173094. cb = GETJSAMPLE(*inptr1);
  173095. cr = GETJSAMPLE(*inptr2);
  173096. cred = Crrtab[cr];
  173097. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173098. cblue = Cbbtab[cb];
  173099. y = GETJSAMPLE(*inptr0);
  173100. outptr[RGB_RED] = range_limit[y + cred];
  173101. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173102. outptr[RGB_BLUE] = range_limit[y + cblue];
  173103. }
  173104. }
  173105. /*
  173106. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173107. */
  173108. METHODDEF(void)
  173109. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173110. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173111. JSAMPARRAY output_buf)
  173112. {
  173113. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173114. register int y, cred, cgreen, cblue;
  173115. int cb, cr;
  173116. register JSAMPROW outptr0, outptr1;
  173117. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173118. JDIMENSION col;
  173119. /* copy these pointers into registers if possible */
  173120. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173121. int * Crrtab = upsample->Cr_r_tab;
  173122. int * Cbbtab = upsample->Cb_b_tab;
  173123. INT32 * Crgtab = upsample->Cr_g_tab;
  173124. INT32 * Cbgtab = upsample->Cb_g_tab;
  173125. SHIFT_TEMPS
  173126. inptr00 = input_buf[0][in_row_group_ctr*2];
  173127. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173128. inptr1 = input_buf[1][in_row_group_ctr];
  173129. inptr2 = input_buf[2][in_row_group_ctr];
  173130. outptr0 = output_buf[0];
  173131. outptr1 = output_buf[1];
  173132. /* Loop for each group of output pixels */
  173133. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173134. /* Do the chroma part of the calculation */
  173135. cb = GETJSAMPLE(*inptr1++);
  173136. cr = GETJSAMPLE(*inptr2++);
  173137. cred = Crrtab[cr];
  173138. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173139. cblue = Cbbtab[cb];
  173140. /* Fetch 4 Y values and emit 4 pixels */
  173141. y = GETJSAMPLE(*inptr00++);
  173142. outptr0[RGB_RED] = range_limit[y + cred];
  173143. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173144. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173145. outptr0 += RGB_PIXELSIZE;
  173146. y = GETJSAMPLE(*inptr00++);
  173147. outptr0[RGB_RED] = range_limit[y + cred];
  173148. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173149. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173150. outptr0 += RGB_PIXELSIZE;
  173151. y = GETJSAMPLE(*inptr01++);
  173152. outptr1[RGB_RED] = range_limit[y + cred];
  173153. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173154. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173155. outptr1 += RGB_PIXELSIZE;
  173156. y = GETJSAMPLE(*inptr01++);
  173157. outptr1[RGB_RED] = range_limit[y + cred];
  173158. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173159. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173160. outptr1 += RGB_PIXELSIZE;
  173161. }
  173162. /* If image width is odd, do the last output column separately */
  173163. if (cinfo->output_width & 1) {
  173164. cb = GETJSAMPLE(*inptr1);
  173165. cr = GETJSAMPLE(*inptr2);
  173166. cred = Crrtab[cr];
  173167. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173168. cblue = Cbbtab[cb];
  173169. y = GETJSAMPLE(*inptr00);
  173170. outptr0[RGB_RED] = range_limit[y + cred];
  173171. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173172. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173173. y = GETJSAMPLE(*inptr01);
  173174. outptr1[RGB_RED] = range_limit[y + cred];
  173175. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173176. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173177. }
  173178. }
  173179. /*
  173180. * Module initialization routine for merged upsampling/color conversion.
  173181. *
  173182. * NB: this is called under the conditions determined by use_merged_upsample()
  173183. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173184. * of this module; no safety checks are made here.
  173185. */
  173186. GLOBAL(void)
  173187. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173188. {
  173189. my_upsample_ptr upsample;
  173190. upsample = (my_upsample_ptr)
  173191. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173192. SIZEOF(my_upsampler));
  173193. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173194. upsample->pub.start_pass = start_pass_merged_upsample;
  173195. upsample->pub.need_context_rows = FALSE;
  173196. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173197. if (cinfo->max_v_samp_factor == 2) {
  173198. upsample->pub.upsample = merged_2v_upsample;
  173199. upsample->upmethod = h2v2_merged_upsample;
  173200. /* Allocate a spare row buffer */
  173201. upsample->spare_row = (JSAMPROW)
  173202. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173203. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173204. } else {
  173205. upsample->pub.upsample = merged_1v_upsample;
  173206. upsample->upmethod = h2v1_merged_upsample;
  173207. /* No spare row needed */
  173208. upsample->spare_row = NULL;
  173209. }
  173210. build_ycc_rgb_table2(cinfo);
  173211. }
  173212. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173213. /*** End of inlined file: jdmerge.c ***/
  173214. #undef ASSIGN_STATE
  173215. /*** Start of inlined file: jdphuff.c ***/
  173216. #define JPEG_INTERNALS
  173217. #ifdef D_PROGRESSIVE_SUPPORTED
  173218. /*
  173219. * Expanded entropy decoder object for progressive Huffman decoding.
  173220. *
  173221. * The savable_state subrecord contains fields that change within an MCU,
  173222. * but must not be updated permanently until we complete the MCU.
  173223. */
  173224. typedef struct {
  173225. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173226. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173227. } savable_state3;
  173228. /* This macro is to work around compilers with missing or broken
  173229. * structure assignment. You'll need to fix this code if you have
  173230. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173231. */
  173232. #ifndef NO_STRUCT_ASSIGN
  173233. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173234. #else
  173235. #if MAX_COMPS_IN_SCAN == 4
  173236. #define ASSIGN_STATE(dest,src) \
  173237. ((dest).EOBRUN = (src).EOBRUN, \
  173238. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173239. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173240. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173241. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173242. #endif
  173243. #endif
  173244. typedef struct {
  173245. struct jpeg_entropy_decoder pub; /* public fields */
  173246. /* These fields are loaded into local variables at start of each MCU.
  173247. * In case of suspension, we exit WITHOUT updating them.
  173248. */
  173249. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173250. savable_state3 saved; /* Other state at start of MCU */
  173251. /* These fields are NOT loaded into local working state. */
  173252. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173253. /* Pointers to derived tables (these workspaces have image lifespan) */
  173254. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173255. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173256. } phuff_entropy_decoder;
  173257. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173258. /* Forward declarations */
  173259. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173260. JBLOCKROW *MCU_data));
  173261. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173262. JBLOCKROW *MCU_data));
  173263. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173264. JBLOCKROW *MCU_data));
  173265. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173266. JBLOCKROW *MCU_data));
  173267. /*
  173268. * Initialize for a Huffman-compressed scan.
  173269. */
  173270. METHODDEF(void)
  173271. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173272. {
  173273. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173274. boolean is_DC_band, bad;
  173275. int ci, coefi, tbl;
  173276. int *coef_bit_ptr;
  173277. jpeg_component_info * compptr;
  173278. is_DC_band = (cinfo->Ss == 0);
  173279. /* Validate scan parameters */
  173280. bad = FALSE;
  173281. if (is_DC_band) {
  173282. if (cinfo->Se != 0)
  173283. bad = TRUE;
  173284. } else {
  173285. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173286. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173287. bad = TRUE;
  173288. /* AC scans may have only one component */
  173289. if (cinfo->comps_in_scan != 1)
  173290. bad = TRUE;
  173291. }
  173292. if (cinfo->Ah != 0) {
  173293. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173294. if (cinfo->Al != cinfo->Ah-1)
  173295. bad = TRUE;
  173296. }
  173297. if (cinfo->Al > 13) /* need not check for < 0 */
  173298. bad = TRUE;
  173299. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173300. * but the spec doesn't say so, and we try to be liberal about what we
  173301. * accept. Note: large Al values could result in out-of-range DC
  173302. * coefficients during early scans, leading to bizarre displays due to
  173303. * overflows in the IDCT math. But we won't crash.
  173304. */
  173305. if (bad)
  173306. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173307. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173308. /* Update progression status, and verify that scan order is legal.
  173309. * Note that inter-scan inconsistencies are treated as warnings
  173310. * not fatal errors ... not clear if this is right way to behave.
  173311. */
  173312. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173313. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173314. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173315. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173316. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173317. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173318. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173319. if (cinfo->Ah != expected)
  173320. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173321. coef_bit_ptr[coefi] = cinfo->Al;
  173322. }
  173323. }
  173324. /* Select MCU decoding routine */
  173325. if (cinfo->Ah == 0) {
  173326. if (is_DC_band)
  173327. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173328. else
  173329. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173330. } else {
  173331. if (is_DC_band)
  173332. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173333. else
  173334. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173335. }
  173336. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173337. compptr = cinfo->cur_comp_info[ci];
  173338. /* Make sure requested tables are present, and compute derived tables.
  173339. * We may build same derived table more than once, but it's not expensive.
  173340. */
  173341. if (is_DC_band) {
  173342. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173343. tbl = compptr->dc_tbl_no;
  173344. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173345. & entropy->derived_tbls[tbl]);
  173346. }
  173347. } else {
  173348. tbl = compptr->ac_tbl_no;
  173349. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173350. & entropy->derived_tbls[tbl]);
  173351. /* remember the single active table */
  173352. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173353. }
  173354. /* Initialize DC predictions to 0 */
  173355. entropy->saved.last_dc_val[ci] = 0;
  173356. }
  173357. /* Initialize bitread state variables */
  173358. entropy->bitstate.bits_left = 0;
  173359. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173360. entropy->pub.insufficient_data = FALSE;
  173361. /* Initialize private state variables */
  173362. entropy->saved.EOBRUN = 0;
  173363. /* Initialize restart counter */
  173364. entropy->restarts_to_go = cinfo->restart_interval;
  173365. }
  173366. /*
  173367. * Check for a restart marker & resynchronize decoder.
  173368. * Returns FALSE if must suspend.
  173369. */
  173370. LOCAL(boolean)
  173371. process_restartp (j_decompress_ptr cinfo)
  173372. {
  173373. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173374. int ci;
  173375. /* Throw away any unused bits remaining in bit buffer; */
  173376. /* include any full bytes in next_marker's count of discarded bytes */
  173377. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173378. entropy->bitstate.bits_left = 0;
  173379. /* Advance past the RSTn marker */
  173380. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173381. return FALSE;
  173382. /* Re-initialize DC predictions to 0 */
  173383. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173384. entropy->saved.last_dc_val[ci] = 0;
  173385. /* Re-init EOB run count, too */
  173386. entropy->saved.EOBRUN = 0;
  173387. /* Reset restart counter */
  173388. entropy->restarts_to_go = cinfo->restart_interval;
  173389. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173390. * against a marker. In that case we will end up treating the next data
  173391. * segment as empty, and we can avoid producing bogus output pixels by
  173392. * leaving the flag set.
  173393. */
  173394. if (cinfo->unread_marker == 0)
  173395. entropy->pub.insufficient_data = FALSE;
  173396. return TRUE;
  173397. }
  173398. /*
  173399. * Huffman MCU decoding.
  173400. * Each of these routines decodes and returns one MCU's worth of
  173401. * Huffman-compressed coefficients.
  173402. * The coefficients are reordered from zigzag order into natural array order,
  173403. * but are not dequantized.
  173404. *
  173405. * The i'th block of the MCU is stored into the block pointed to by
  173406. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173407. *
  173408. * We return FALSE if data source requested suspension. In that case no
  173409. * changes have been made to permanent state. (Exception: some output
  173410. * coefficients may already have been assigned. This is harmless for
  173411. * spectral selection, since we'll just re-assign them on the next call.
  173412. * Successive approximation AC refinement has to be more careful, however.)
  173413. */
  173414. /*
  173415. * MCU decoding for DC initial scan (either spectral selection,
  173416. * or first pass of successive approximation).
  173417. */
  173418. METHODDEF(boolean)
  173419. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173420. {
  173421. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173422. int Al = cinfo->Al;
  173423. register int s, r;
  173424. int blkn, ci;
  173425. JBLOCKROW block;
  173426. BITREAD_STATE_VARS;
  173427. savable_state3 state;
  173428. d_derived_tbl * tbl;
  173429. jpeg_component_info * compptr;
  173430. /* Process restart marker if needed; may have to suspend */
  173431. if (cinfo->restart_interval) {
  173432. if (entropy->restarts_to_go == 0)
  173433. if (! process_restartp(cinfo))
  173434. return FALSE;
  173435. }
  173436. /* If we've run out of data, just leave the MCU set to zeroes.
  173437. * This way, we return uniform gray for the remainder of the segment.
  173438. */
  173439. if (! entropy->pub.insufficient_data) {
  173440. /* Load up working state */
  173441. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173442. ASSIGN_STATE(state, entropy->saved);
  173443. /* Outer loop handles each block in the MCU */
  173444. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173445. block = MCU_data[blkn];
  173446. ci = cinfo->MCU_membership[blkn];
  173447. compptr = cinfo->cur_comp_info[ci];
  173448. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173449. /* Decode a single block's worth of coefficients */
  173450. /* Section F.2.2.1: decode the DC coefficient difference */
  173451. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173452. if (s) {
  173453. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173454. r = GET_BITS(s);
  173455. s = HUFF_EXTEND(r, s);
  173456. }
  173457. /* Convert DC difference to actual value, update last_dc_val */
  173458. s += state.last_dc_val[ci];
  173459. state.last_dc_val[ci] = s;
  173460. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173461. (*block)[0] = (JCOEF) (s << Al);
  173462. }
  173463. /* Completed MCU, so update state */
  173464. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173465. ASSIGN_STATE(entropy->saved, state);
  173466. }
  173467. /* Account for restart interval (no-op if not using restarts) */
  173468. entropy->restarts_to_go--;
  173469. return TRUE;
  173470. }
  173471. /*
  173472. * MCU decoding for AC initial scan (either spectral selection,
  173473. * or first pass of successive approximation).
  173474. */
  173475. METHODDEF(boolean)
  173476. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173477. {
  173478. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173479. int Se = cinfo->Se;
  173480. int Al = cinfo->Al;
  173481. register int s, k, r;
  173482. unsigned int EOBRUN;
  173483. JBLOCKROW block;
  173484. BITREAD_STATE_VARS;
  173485. d_derived_tbl * tbl;
  173486. /* Process restart marker if needed; may have to suspend */
  173487. if (cinfo->restart_interval) {
  173488. if (entropy->restarts_to_go == 0)
  173489. if (! process_restartp(cinfo))
  173490. return FALSE;
  173491. }
  173492. /* If we've run out of data, just leave the MCU set to zeroes.
  173493. * This way, we return uniform gray for the remainder of the segment.
  173494. */
  173495. if (! entropy->pub.insufficient_data) {
  173496. /* Load up working state.
  173497. * We can avoid loading/saving bitread state if in an EOB run.
  173498. */
  173499. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173500. /* There is always only one block per MCU */
  173501. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173502. EOBRUN--; /* ...process it now (we do nothing) */
  173503. else {
  173504. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173505. block = MCU_data[0];
  173506. tbl = entropy->ac_derived_tbl;
  173507. for (k = cinfo->Ss; k <= Se; k++) {
  173508. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173509. r = s >> 4;
  173510. s &= 15;
  173511. if (s) {
  173512. k += r;
  173513. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173514. r = GET_BITS(s);
  173515. s = HUFF_EXTEND(r, s);
  173516. /* Scale and output coefficient in natural (dezigzagged) order */
  173517. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173518. } else {
  173519. if (r == 15) { /* ZRL */
  173520. k += 15; /* skip 15 zeroes in band */
  173521. } else { /* EOBr, run length is 2^r + appended bits */
  173522. EOBRUN = 1 << r;
  173523. if (r) { /* EOBr, r > 0 */
  173524. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173525. r = GET_BITS(r);
  173526. EOBRUN += r;
  173527. }
  173528. EOBRUN--; /* this band is processed at this moment */
  173529. break; /* force end-of-band */
  173530. }
  173531. }
  173532. }
  173533. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173534. }
  173535. /* Completed MCU, so update state */
  173536. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173537. }
  173538. /* Account for restart interval (no-op if not using restarts) */
  173539. entropy->restarts_to_go--;
  173540. return TRUE;
  173541. }
  173542. /*
  173543. * MCU decoding for DC successive approximation refinement scan.
  173544. * Note: we assume such scans can be multi-component, although the spec
  173545. * is not very clear on the point.
  173546. */
  173547. METHODDEF(boolean)
  173548. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173549. {
  173550. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173551. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173552. int blkn;
  173553. JBLOCKROW block;
  173554. BITREAD_STATE_VARS;
  173555. /* Process restart marker if needed; may have to suspend */
  173556. if (cinfo->restart_interval) {
  173557. if (entropy->restarts_to_go == 0)
  173558. if (! process_restartp(cinfo))
  173559. return FALSE;
  173560. }
  173561. /* Not worth the cycles to check insufficient_data here,
  173562. * since we will not change the data anyway if we read zeroes.
  173563. */
  173564. /* Load up working state */
  173565. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173566. /* Outer loop handles each block in the MCU */
  173567. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173568. block = MCU_data[blkn];
  173569. /* Encoded data is simply the next bit of the two's-complement DC value */
  173570. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173571. if (GET_BITS(1))
  173572. (*block)[0] |= p1;
  173573. /* Note: since we use |=, repeating the assignment later is safe */
  173574. }
  173575. /* Completed MCU, so update state */
  173576. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173577. /* Account for restart interval (no-op if not using restarts) */
  173578. entropy->restarts_to_go--;
  173579. return TRUE;
  173580. }
  173581. /*
  173582. * MCU decoding for AC successive approximation refinement scan.
  173583. */
  173584. METHODDEF(boolean)
  173585. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173586. {
  173587. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173588. int Se = cinfo->Se;
  173589. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173590. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173591. register int s, k, r;
  173592. unsigned int EOBRUN;
  173593. JBLOCKROW block;
  173594. JCOEFPTR thiscoef;
  173595. BITREAD_STATE_VARS;
  173596. d_derived_tbl * tbl;
  173597. int num_newnz;
  173598. int newnz_pos[DCTSIZE2];
  173599. /* Process restart marker if needed; may have to suspend */
  173600. if (cinfo->restart_interval) {
  173601. if (entropy->restarts_to_go == 0)
  173602. if (! process_restartp(cinfo))
  173603. return FALSE;
  173604. }
  173605. /* If we've run out of data, don't modify the MCU.
  173606. */
  173607. if (! entropy->pub.insufficient_data) {
  173608. /* Load up working state */
  173609. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173610. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173611. /* There is always only one block per MCU */
  173612. block = MCU_data[0];
  173613. tbl = entropy->ac_derived_tbl;
  173614. /* If we are forced to suspend, we must undo the assignments to any newly
  173615. * nonzero coefficients in the block, because otherwise we'd get confused
  173616. * next time about which coefficients were already nonzero.
  173617. * But we need not undo addition of bits to already-nonzero coefficients;
  173618. * instead, we can test the current bit to see if we already did it.
  173619. */
  173620. num_newnz = 0;
  173621. /* initialize coefficient loop counter to start of band */
  173622. k = cinfo->Ss;
  173623. if (EOBRUN == 0) {
  173624. for (; k <= Se; k++) {
  173625. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173626. r = s >> 4;
  173627. s &= 15;
  173628. if (s) {
  173629. if (s != 1) /* size of new coef should always be 1 */
  173630. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173631. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173632. if (GET_BITS(1))
  173633. s = p1; /* newly nonzero coef is positive */
  173634. else
  173635. s = m1; /* newly nonzero coef is negative */
  173636. } else {
  173637. if (r != 15) {
  173638. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173639. if (r) {
  173640. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173641. r = GET_BITS(r);
  173642. EOBRUN += r;
  173643. }
  173644. break; /* rest of block is handled by EOB logic */
  173645. }
  173646. /* note s = 0 for processing ZRL */
  173647. }
  173648. /* Advance over already-nonzero coefs and r still-zero coefs,
  173649. * appending correction bits to the nonzeroes. A correction bit is 1
  173650. * if the absolute value of the coefficient must be increased.
  173651. */
  173652. do {
  173653. thiscoef = *block + jpeg_natural_order[k];
  173654. if (*thiscoef != 0) {
  173655. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173656. if (GET_BITS(1)) {
  173657. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173658. if (*thiscoef >= 0)
  173659. *thiscoef += p1;
  173660. else
  173661. *thiscoef += m1;
  173662. }
  173663. }
  173664. } else {
  173665. if (--r < 0)
  173666. break; /* reached target zero coefficient */
  173667. }
  173668. k++;
  173669. } while (k <= Se);
  173670. if (s) {
  173671. int pos = jpeg_natural_order[k];
  173672. /* Output newly nonzero coefficient */
  173673. (*block)[pos] = (JCOEF) s;
  173674. /* Remember its position in case we have to suspend */
  173675. newnz_pos[num_newnz++] = pos;
  173676. }
  173677. }
  173678. }
  173679. if (EOBRUN > 0) {
  173680. /* Scan any remaining coefficient positions after the end-of-band
  173681. * (the last newly nonzero coefficient, if any). Append a correction
  173682. * bit to each already-nonzero coefficient. A correction bit is 1
  173683. * if the absolute value of the coefficient must be increased.
  173684. */
  173685. for (; k <= Se; k++) {
  173686. thiscoef = *block + jpeg_natural_order[k];
  173687. if (*thiscoef != 0) {
  173688. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173689. if (GET_BITS(1)) {
  173690. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173691. if (*thiscoef >= 0)
  173692. *thiscoef += p1;
  173693. else
  173694. *thiscoef += m1;
  173695. }
  173696. }
  173697. }
  173698. }
  173699. /* Count one block completed in EOB run */
  173700. EOBRUN--;
  173701. }
  173702. /* Completed MCU, so update state */
  173703. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173704. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173705. }
  173706. /* Account for restart interval (no-op if not using restarts) */
  173707. entropy->restarts_to_go--;
  173708. return TRUE;
  173709. undoit:
  173710. /* Re-zero any output coefficients that we made newly nonzero */
  173711. while (num_newnz > 0)
  173712. (*block)[newnz_pos[--num_newnz]] = 0;
  173713. return FALSE;
  173714. }
  173715. /*
  173716. * Module initialization routine for progressive Huffman entropy decoding.
  173717. */
  173718. GLOBAL(void)
  173719. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173720. {
  173721. phuff_entropy_ptr2 entropy;
  173722. int *coef_bit_ptr;
  173723. int ci, i;
  173724. entropy = (phuff_entropy_ptr2)
  173725. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173726. SIZEOF(phuff_entropy_decoder));
  173727. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173728. entropy->pub.start_pass = start_pass_phuff_decoder;
  173729. /* Mark derived tables unallocated */
  173730. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173731. entropy->derived_tbls[i] = NULL;
  173732. }
  173733. /* Create progression status table */
  173734. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173735. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173736. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173737. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173738. for (ci = 0; ci < cinfo->num_components; ci++)
  173739. for (i = 0; i < DCTSIZE2; i++)
  173740. *coef_bit_ptr++ = -1;
  173741. }
  173742. #endif /* D_PROGRESSIVE_SUPPORTED */
  173743. /*** End of inlined file: jdphuff.c ***/
  173744. /*** Start of inlined file: jdpostct.c ***/
  173745. #define JPEG_INTERNALS
  173746. /* Private buffer controller object */
  173747. typedef struct {
  173748. struct jpeg_d_post_controller pub; /* public fields */
  173749. /* Color quantization source buffer: this holds output data from
  173750. * the upsample/color conversion step to be passed to the quantizer.
  173751. * For two-pass color quantization, we need a full-image buffer;
  173752. * for one-pass operation, a strip buffer is sufficient.
  173753. */
  173754. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173755. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173756. JDIMENSION strip_height; /* buffer size in rows */
  173757. /* for two-pass mode only: */
  173758. JDIMENSION starting_row; /* row # of first row in current strip */
  173759. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173760. } my_post_controller;
  173761. typedef my_post_controller * my_post_ptr;
  173762. /* Forward declarations */
  173763. METHODDEF(void) post_process_1pass
  173764. JPP((j_decompress_ptr cinfo,
  173765. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173766. JDIMENSION in_row_groups_avail,
  173767. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173768. JDIMENSION out_rows_avail));
  173769. #ifdef QUANT_2PASS_SUPPORTED
  173770. METHODDEF(void) post_process_prepass
  173771. JPP((j_decompress_ptr cinfo,
  173772. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173773. JDIMENSION in_row_groups_avail,
  173774. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173775. JDIMENSION out_rows_avail));
  173776. METHODDEF(void) post_process_2pass
  173777. JPP((j_decompress_ptr cinfo,
  173778. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173779. JDIMENSION in_row_groups_avail,
  173780. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173781. JDIMENSION out_rows_avail));
  173782. #endif
  173783. /*
  173784. * Initialize for a processing pass.
  173785. */
  173786. METHODDEF(void)
  173787. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173788. {
  173789. my_post_ptr post = (my_post_ptr) cinfo->post;
  173790. switch (pass_mode) {
  173791. case JBUF_PASS_THRU:
  173792. if (cinfo->quantize_colors) {
  173793. /* Single-pass processing with color quantization. */
  173794. post->pub.post_process_data = post_process_1pass;
  173795. /* We could be doing buffered-image output before starting a 2-pass
  173796. * color quantization; in that case, jinit_d_post_controller did not
  173797. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173798. */
  173799. if (post->buffer == NULL) {
  173800. post->buffer = (*cinfo->mem->access_virt_sarray)
  173801. ((j_common_ptr) cinfo, post->whole_image,
  173802. (JDIMENSION) 0, post->strip_height, TRUE);
  173803. }
  173804. } else {
  173805. /* For single-pass processing without color quantization,
  173806. * I have no work to do; just call the upsampler directly.
  173807. */
  173808. post->pub.post_process_data = cinfo->upsample->upsample;
  173809. }
  173810. break;
  173811. #ifdef QUANT_2PASS_SUPPORTED
  173812. case JBUF_SAVE_AND_PASS:
  173813. /* First pass of 2-pass quantization */
  173814. if (post->whole_image == NULL)
  173815. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173816. post->pub.post_process_data = post_process_prepass;
  173817. break;
  173818. case JBUF_CRANK_DEST:
  173819. /* Second pass of 2-pass quantization */
  173820. if (post->whole_image == NULL)
  173821. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173822. post->pub.post_process_data = post_process_2pass;
  173823. break;
  173824. #endif /* QUANT_2PASS_SUPPORTED */
  173825. default:
  173826. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173827. break;
  173828. }
  173829. post->starting_row = post->next_row = 0;
  173830. }
  173831. /*
  173832. * Process some data in the one-pass (strip buffer) case.
  173833. * This is used for color precision reduction as well as one-pass quantization.
  173834. */
  173835. METHODDEF(void)
  173836. post_process_1pass (j_decompress_ptr cinfo,
  173837. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173838. JDIMENSION in_row_groups_avail,
  173839. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173840. JDIMENSION out_rows_avail)
  173841. {
  173842. my_post_ptr post = (my_post_ptr) cinfo->post;
  173843. JDIMENSION num_rows, max_rows;
  173844. /* Fill the buffer, but not more than what we can dump out in one go. */
  173845. /* Note we rely on the upsampler to detect bottom of image. */
  173846. max_rows = out_rows_avail - *out_row_ctr;
  173847. if (max_rows > post->strip_height)
  173848. max_rows = post->strip_height;
  173849. num_rows = 0;
  173850. (*cinfo->upsample->upsample) (cinfo,
  173851. input_buf, in_row_group_ctr, in_row_groups_avail,
  173852. post->buffer, &num_rows, max_rows);
  173853. /* Quantize and emit data. */
  173854. (*cinfo->cquantize->color_quantize) (cinfo,
  173855. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173856. *out_row_ctr += num_rows;
  173857. }
  173858. #ifdef QUANT_2PASS_SUPPORTED
  173859. /*
  173860. * Process some data in the first pass of 2-pass quantization.
  173861. */
  173862. METHODDEF(void)
  173863. post_process_prepass (j_decompress_ptr cinfo,
  173864. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173865. JDIMENSION in_row_groups_avail,
  173866. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173867. JDIMENSION)
  173868. {
  173869. my_post_ptr post = (my_post_ptr) cinfo->post;
  173870. JDIMENSION old_next_row, num_rows;
  173871. /* Reposition virtual buffer if at start of strip. */
  173872. if (post->next_row == 0) {
  173873. post->buffer = (*cinfo->mem->access_virt_sarray)
  173874. ((j_common_ptr) cinfo, post->whole_image,
  173875. post->starting_row, post->strip_height, TRUE);
  173876. }
  173877. /* Upsample some data (up to a strip height's worth). */
  173878. old_next_row = post->next_row;
  173879. (*cinfo->upsample->upsample) (cinfo,
  173880. input_buf, in_row_group_ctr, in_row_groups_avail,
  173881. post->buffer, &post->next_row, post->strip_height);
  173882. /* Allow quantizer to scan new data. No data is emitted, */
  173883. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173884. if (post->next_row > old_next_row) {
  173885. num_rows = post->next_row - old_next_row;
  173886. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173887. (JSAMPARRAY) NULL, (int) num_rows);
  173888. *out_row_ctr += num_rows;
  173889. }
  173890. /* Advance if we filled the strip. */
  173891. if (post->next_row >= post->strip_height) {
  173892. post->starting_row += post->strip_height;
  173893. post->next_row = 0;
  173894. }
  173895. }
  173896. /*
  173897. * Process some data in the second pass of 2-pass quantization.
  173898. */
  173899. METHODDEF(void)
  173900. post_process_2pass (j_decompress_ptr cinfo,
  173901. JSAMPIMAGE, JDIMENSION *,
  173902. JDIMENSION,
  173903. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173904. JDIMENSION out_rows_avail)
  173905. {
  173906. my_post_ptr post = (my_post_ptr) cinfo->post;
  173907. JDIMENSION num_rows, max_rows;
  173908. /* Reposition virtual buffer if at start of strip. */
  173909. if (post->next_row == 0) {
  173910. post->buffer = (*cinfo->mem->access_virt_sarray)
  173911. ((j_common_ptr) cinfo, post->whole_image,
  173912. post->starting_row, post->strip_height, FALSE);
  173913. }
  173914. /* Determine number of rows to emit. */
  173915. num_rows = post->strip_height - post->next_row; /* available in strip */
  173916. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173917. if (num_rows > max_rows)
  173918. num_rows = max_rows;
  173919. /* We have to check bottom of image here, can't depend on upsampler. */
  173920. max_rows = cinfo->output_height - post->starting_row;
  173921. if (num_rows > max_rows)
  173922. num_rows = max_rows;
  173923. /* Quantize and emit data. */
  173924. (*cinfo->cquantize->color_quantize) (cinfo,
  173925. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173926. (int) num_rows);
  173927. *out_row_ctr += num_rows;
  173928. /* Advance if we filled the strip. */
  173929. post->next_row += num_rows;
  173930. if (post->next_row >= post->strip_height) {
  173931. post->starting_row += post->strip_height;
  173932. post->next_row = 0;
  173933. }
  173934. }
  173935. #endif /* QUANT_2PASS_SUPPORTED */
  173936. /*
  173937. * Initialize postprocessing controller.
  173938. */
  173939. GLOBAL(void)
  173940. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173941. {
  173942. my_post_ptr post;
  173943. post = (my_post_ptr)
  173944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173945. SIZEOF(my_post_controller));
  173946. cinfo->post = (struct jpeg_d_post_controller *) post;
  173947. post->pub.start_pass = start_pass_dpost;
  173948. post->whole_image = NULL; /* flag for no virtual arrays */
  173949. post->buffer = NULL; /* flag for no strip buffer */
  173950. /* Create the quantization buffer, if needed */
  173951. if (cinfo->quantize_colors) {
  173952. /* The buffer strip height is max_v_samp_factor, which is typically
  173953. * an efficient number of rows for upsampling to return.
  173954. * (In the presence of output rescaling, we might want to be smarter?)
  173955. */
  173956. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173957. if (need_full_buffer) {
  173958. /* Two-pass color quantization: need full-image storage. */
  173959. /* We round up the number of rows to a multiple of the strip height. */
  173960. #ifdef QUANT_2PASS_SUPPORTED
  173961. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173962. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173963. cinfo->output_width * cinfo->out_color_components,
  173964. (JDIMENSION) jround_up((long) cinfo->output_height,
  173965. (long) post->strip_height),
  173966. post->strip_height);
  173967. #else
  173968. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173969. #endif /* QUANT_2PASS_SUPPORTED */
  173970. } else {
  173971. /* One-pass color quantization: just make a strip buffer. */
  173972. post->buffer = (*cinfo->mem->alloc_sarray)
  173973. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173974. cinfo->output_width * cinfo->out_color_components,
  173975. post->strip_height);
  173976. }
  173977. }
  173978. }
  173979. /*** End of inlined file: jdpostct.c ***/
  173980. #undef FIX
  173981. /*** Start of inlined file: jdsample.c ***/
  173982. #define JPEG_INTERNALS
  173983. /* Pointer to routine to upsample a single component */
  173984. typedef JMETHOD(void, upsample1_ptr,
  173985. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173986. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173987. /* Private subobject */
  173988. typedef struct {
  173989. struct jpeg_upsampler pub; /* public fields */
  173990. /* Color conversion buffer. When using separate upsampling and color
  173991. * conversion steps, this buffer holds one upsampled row group until it
  173992. * has been color converted and output.
  173993. * Note: we do not allocate any storage for component(s) which are full-size,
  173994. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173995. * simply set to point to the input data array, thereby avoiding copying.
  173996. */
  173997. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173998. /* Per-component upsampling method pointers */
  173999. upsample1_ptr methods[MAX_COMPONENTS];
  174000. int next_row_out; /* counts rows emitted from color_buf */
  174001. JDIMENSION rows_to_go; /* counts rows remaining in image */
  174002. /* Height of an input row group for each component. */
  174003. int rowgroup_height[MAX_COMPONENTS];
  174004. /* These arrays save pixel expansion factors so that int_expand need not
  174005. * recompute them each time. They are unused for other upsampling methods.
  174006. */
  174007. UINT8 h_expand[MAX_COMPONENTS];
  174008. UINT8 v_expand[MAX_COMPONENTS];
  174009. } my_upsampler2;
  174010. typedef my_upsampler2 * my_upsample_ptr2;
  174011. /*
  174012. * Initialize for an upsampling pass.
  174013. */
  174014. METHODDEF(void)
  174015. start_pass_upsample (j_decompress_ptr cinfo)
  174016. {
  174017. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174018. /* Mark the conversion buffer empty */
  174019. upsample->next_row_out = cinfo->max_v_samp_factor;
  174020. /* Initialize total-height counter for detecting bottom of image */
  174021. upsample->rows_to_go = cinfo->output_height;
  174022. }
  174023. /*
  174024. * Control routine to do upsampling (and color conversion).
  174025. *
  174026. * In this version we upsample each component independently.
  174027. * We upsample one row group into the conversion buffer, then apply
  174028. * color conversion a row at a time.
  174029. */
  174030. METHODDEF(void)
  174031. sep_upsample (j_decompress_ptr cinfo,
  174032. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174033. JDIMENSION,
  174034. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174035. JDIMENSION out_rows_avail)
  174036. {
  174037. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174038. int ci;
  174039. jpeg_component_info * compptr;
  174040. JDIMENSION num_rows;
  174041. /* Fill the conversion buffer, if it's empty */
  174042. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174043. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174044. ci++, compptr++) {
  174045. /* Invoke per-component upsample method. Notice we pass a POINTER
  174046. * to color_buf[ci], so that fullsize_upsample can change it.
  174047. */
  174048. (*upsample->methods[ci]) (cinfo, compptr,
  174049. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174050. upsample->color_buf + ci);
  174051. }
  174052. upsample->next_row_out = 0;
  174053. }
  174054. /* Color-convert and emit rows */
  174055. /* How many we have in the buffer: */
  174056. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174057. /* Not more than the distance to the end of the image. Need this test
  174058. * in case the image height is not a multiple of max_v_samp_factor:
  174059. */
  174060. if (num_rows > upsample->rows_to_go)
  174061. num_rows = upsample->rows_to_go;
  174062. /* And not more than what the client can accept: */
  174063. out_rows_avail -= *out_row_ctr;
  174064. if (num_rows > out_rows_avail)
  174065. num_rows = out_rows_avail;
  174066. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174067. (JDIMENSION) upsample->next_row_out,
  174068. output_buf + *out_row_ctr,
  174069. (int) num_rows);
  174070. /* Adjust counts */
  174071. *out_row_ctr += num_rows;
  174072. upsample->rows_to_go -= num_rows;
  174073. upsample->next_row_out += num_rows;
  174074. /* When the buffer is emptied, declare this input row group consumed */
  174075. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174076. (*in_row_group_ctr)++;
  174077. }
  174078. /*
  174079. * These are the routines invoked by sep_upsample to upsample pixel values
  174080. * of a single component. One row group is processed per call.
  174081. */
  174082. /*
  174083. * For full-size components, we just make color_buf[ci] point at the
  174084. * input buffer, and thus avoid copying any data. Note that this is
  174085. * safe only because sep_upsample doesn't declare the input row group
  174086. * "consumed" until we are done color converting and emitting it.
  174087. */
  174088. METHODDEF(void)
  174089. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174090. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174091. {
  174092. *output_data_ptr = input_data;
  174093. }
  174094. /*
  174095. * This is a no-op version used for "uninteresting" components.
  174096. * These components will not be referenced by color conversion.
  174097. */
  174098. METHODDEF(void)
  174099. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174100. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174101. {
  174102. *output_data_ptr = NULL; /* safety check */
  174103. }
  174104. /*
  174105. * This version handles any integral sampling ratios.
  174106. * This is not used for typical JPEG files, so it need not be fast.
  174107. * Nor, for that matter, is it particularly accurate: the algorithm is
  174108. * simple replication of the input pixel onto the corresponding output
  174109. * pixels. The hi-falutin sampling literature refers to this as a
  174110. * "box filter". A box filter tends to introduce visible artifacts,
  174111. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174112. * you would be well advised to improve this code.
  174113. */
  174114. METHODDEF(void)
  174115. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174116. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174117. {
  174118. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174119. JSAMPARRAY output_data = *output_data_ptr;
  174120. register JSAMPROW inptr, outptr;
  174121. register JSAMPLE invalue;
  174122. register int h;
  174123. JSAMPROW outend;
  174124. int h_expand, v_expand;
  174125. int inrow, outrow;
  174126. h_expand = upsample->h_expand[compptr->component_index];
  174127. v_expand = upsample->v_expand[compptr->component_index];
  174128. inrow = outrow = 0;
  174129. while (outrow < cinfo->max_v_samp_factor) {
  174130. /* Generate one output row with proper horizontal expansion */
  174131. inptr = input_data[inrow];
  174132. outptr = output_data[outrow];
  174133. outend = outptr + cinfo->output_width;
  174134. while (outptr < outend) {
  174135. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174136. for (h = h_expand; h > 0; h--) {
  174137. *outptr++ = invalue;
  174138. }
  174139. }
  174140. /* Generate any additional output rows by duplicating the first one */
  174141. if (v_expand > 1) {
  174142. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174143. v_expand-1, cinfo->output_width);
  174144. }
  174145. inrow++;
  174146. outrow += v_expand;
  174147. }
  174148. }
  174149. /*
  174150. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174151. * It's still a box filter.
  174152. */
  174153. METHODDEF(void)
  174154. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174155. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174156. {
  174157. JSAMPARRAY output_data = *output_data_ptr;
  174158. register JSAMPROW inptr, outptr;
  174159. register JSAMPLE invalue;
  174160. JSAMPROW outend;
  174161. int inrow;
  174162. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174163. inptr = input_data[inrow];
  174164. outptr = output_data[inrow];
  174165. outend = outptr + cinfo->output_width;
  174166. while (outptr < outend) {
  174167. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174168. *outptr++ = invalue;
  174169. *outptr++ = invalue;
  174170. }
  174171. }
  174172. }
  174173. /*
  174174. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174175. * It's still a box filter.
  174176. */
  174177. METHODDEF(void)
  174178. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174179. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174180. {
  174181. JSAMPARRAY output_data = *output_data_ptr;
  174182. register JSAMPROW inptr, outptr;
  174183. register JSAMPLE invalue;
  174184. JSAMPROW outend;
  174185. int inrow, outrow;
  174186. inrow = outrow = 0;
  174187. while (outrow < cinfo->max_v_samp_factor) {
  174188. inptr = input_data[inrow];
  174189. outptr = output_data[outrow];
  174190. outend = outptr + cinfo->output_width;
  174191. while (outptr < outend) {
  174192. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174193. *outptr++ = invalue;
  174194. *outptr++ = invalue;
  174195. }
  174196. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174197. 1, cinfo->output_width);
  174198. inrow++;
  174199. outrow += 2;
  174200. }
  174201. }
  174202. /*
  174203. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174204. *
  174205. * The upsampling algorithm is linear interpolation between pixel centers,
  174206. * also known as a "triangle filter". This is a good compromise between
  174207. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174208. * of the way between input pixel centers.
  174209. *
  174210. * A note about the "bias" calculations: when rounding fractional values to
  174211. * integer, we do not want to always round 0.5 up to the next integer.
  174212. * If we did that, we'd introduce a noticeable bias towards larger values.
  174213. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174214. * alternate pixel locations (a simple ordered dither pattern).
  174215. */
  174216. METHODDEF(void)
  174217. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174218. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174219. {
  174220. JSAMPARRAY output_data = *output_data_ptr;
  174221. register JSAMPROW inptr, outptr;
  174222. register int invalue;
  174223. register JDIMENSION colctr;
  174224. int inrow;
  174225. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174226. inptr = input_data[inrow];
  174227. outptr = output_data[inrow];
  174228. /* Special case for first column */
  174229. invalue = GETJSAMPLE(*inptr++);
  174230. *outptr++ = (JSAMPLE) invalue;
  174231. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174232. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174233. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174234. invalue = GETJSAMPLE(*inptr++) * 3;
  174235. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174236. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174237. }
  174238. /* Special case for last column */
  174239. invalue = GETJSAMPLE(*inptr);
  174240. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174241. *outptr++ = (JSAMPLE) invalue;
  174242. }
  174243. }
  174244. /*
  174245. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174246. * Again a triangle filter; see comments for h2v1 case, above.
  174247. *
  174248. * It is OK for us to reference the adjacent input rows because we demanded
  174249. * context from the main buffer controller (see initialization code).
  174250. */
  174251. METHODDEF(void)
  174252. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174253. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174254. {
  174255. JSAMPARRAY output_data = *output_data_ptr;
  174256. register JSAMPROW inptr0, inptr1, outptr;
  174257. #if BITS_IN_JSAMPLE == 8
  174258. register int thiscolsum, lastcolsum, nextcolsum;
  174259. #else
  174260. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174261. #endif
  174262. register JDIMENSION colctr;
  174263. int inrow, outrow, v;
  174264. inrow = outrow = 0;
  174265. while (outrow < cinfo->max_v_samp_factor) {
  174266. for (v = 0; v < 2; v++) {
  174267. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174268. inptr0 = input_data[inrow];
  174269. if (v == 0) /* next nearest is row above */
  174270. inptr1 = input_data[inrow-1];
  174271. else /* next nearest is row below */
  174272. inptr1 = input_data[inrow+1];
  174273. outptr = output_data[outrow++];
  174274. /* Special case for first column */
  174275. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174276. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174277. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174278. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174279. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174280. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174281. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174282. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174283. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174284. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174285. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174286. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174287. }
  174288. /* Special case for last column */
  174289. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174290. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174291. }
  174292. inrow++;
  174293. }
  174294. }
  174295. /*
  174296. * Module initialization routine for upsampling.
  174297. */
  174298. GLOBAL(void)
  174299. jinit_upsampler (j_decompress_ptr cinfo)
  174300. {
  174301. my_upsample_ptr2 upsample;
  174302. int ci;
  174303. jpeg_component_info * compptr;
  174304. boolean need_buffer, do_fancy;
  174305. int h_in_group, v_in_group, h_out_group, v_out_group;
  174306. upsample = (my_upsample_ptr2)
  174307. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174308. SIZEOF(my_upsampler2));
  174309. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174310. upsample->pub.start_pass = start_pass_upsample;
  174311. upsample->pub.upsample = sep_upsample;
  174312. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174313. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174314. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174315. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174316. * so don't ask for it.
  174317. */
  174318. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174319. /* Verify we can handle the sampling factors, select per-component methods,
  174320. * and create storage as needed.
  174321. */
  174322. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174323. ci++, compptr++) {
  174324. /* Compute size of an "input group" after IDCT scaling. This many samples
  174325. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174326. */
  174327. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174328. cinfo->min_DCT_scaled_size;
  174329. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174330. cinfo->min_DCT_scaled_size;
  174331. h_out_group = cinfo->max_h_samp_factor;
  174332. v_out_group = cinfo->max_v_samp_factor;
  174333. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174334. need_buffer = TRUE;
  174335. if (! compptr->component_needed) {
  174336. /* Don't bother to upsample an uninteresting component. */
  174337. upsample->methods[ci] = noop_upsample;
  174338. need_buffer = FALSE;
  174339. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174340. /* Fullsize components can be processed without any work. */
  174341. upsample->methods[ci] = fullsize_upsample;
  174342. need_buffer = FALSE;
  174343. } else if (h_in_group * 2 == h_out_group &&
  174344. v_in_group == v_out_group) {
  174345. /* Special cases for 2h1v upsampling */
  174346. if (do_fancy && compptr->downsampled_width > 2)
  174347. upsample->methods[ci] = h2v1_fancy_upsample;
  174348. else
  174349. upsample->methods[ci] = h2v1_upsample;
  174350. } else if (h_in_group * 2 == h_out_group &&
  174351. v_in_group * 2 == v_out_group) {
  174352. /* Special cases for 2h2v upsampling */
  174353. if (do_fancy && compptr->downsampled_width > 2) {
  174354. upsample->methods[ci] = h2v2_fancy_upsample;
  174355. upsample->pub.need_context_rows = TRUE;
  174356. } else
  174357. upsample->methods[ci] = h2v2_upsample;
  174358. } else if ((h_out_group % h_in_group) == 0 &&
  174359. (v_out_group % v_in_group) == 0) {
  174360. /* Generic integral-factors upsampling method */
  174361. upsample->methods[ci] = int_upsample;
  174362. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174363. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174364. } else
  174365. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174366. if (need_buffer) {
  174367. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174368. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174369. (JDIMENSION) jround_up((long) cinfo->output_width,
  174370. (long) cinfo->max_h_samp_factor),
  174371. (JDIMENSION) cinfo->max_v_samp_factor);
  174372. }
  174373. }
  174374. }
  174375. /*** End of inlined file: jdsample.c ***/
  174376. /*** Start of inlined file: jdtrans.c ***/
  174377. #define JPEG_INTERNALS
  174378. /* Forward declarations */
  174379. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174380. /*
  174381. * Read the coefficient arrays from a JPEG file.
  174382. * jpeg_read_header must be completed before calling this.
  174383. *
  174384. * The entire image is read into a set of virtual coefficient-block arrays,
  174385. * one per component. The return value is a pointer to the array of
  174386. * virtual-array descriptors. These can be manipulated directly via the
  174387. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174388. * To release the memory occupied by the virtual arrays, call
  174389. * jpeg_finish_decompress() when done with the data.
  174390. *
  174391. * An alternative usage is to simply obtain access to the coefficient arrays
  174392. * during a buffered-image-mode decompression operation. This is allowed
  174393. * after any jpeg_finish_output() call. The arrays can be accessed until
  174394. * jpeg_finish_decompress() is called. (Note that any call to the library
  174395. * may reposition the arrays, so don't rely on access_virt_barray() results
  174396. * to stay valid across library calls.)
  174397. *
  174398. * Returns NULL if suspended. This case need be checked only if
  174399. * a suspending data source is used.
  174400. */
  174401. GLOBAL(jvirt_barray_ptr *)
  174402. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174403. {
  174404. if (cinfo->global_state == DSTATE_READY) {
  174405. /* First call: initialize active modules */
  174406. transdecode_master_selection(cinfo);
  174407. cinfo->global_state = DSTATE_RDCOEFS;
  174408. }
  174409. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174410. /* Absorb whole file into the coef buffer */
  174411. for (;;) {
  174412. int retcode;
  174413. /* Call progress monitor hook if present */
  174414. if (cinfo->progress != NULL)
  174415. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174416. /* Absorb some more input */
  174417. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174418. if (retcode == JPEG_SUSPENDED)
  174419. return NULL;
  174420. if (retcode == JPEG_REACHED_EOI)
  174421. break;
  174422. /* Advance progress counter if appropriate */
  174423. if (cinfo->progress != NULL &&
  174424. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174425. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174426. /* startup underestimated number of scans; ratchet up one scan */
  174427. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174428. }
  174429. }
  174430. }
  174431. /* Set state so that jpeg_finish_decompress does the right thing */
  174432. cinfo->global_state = DSTATE_STOPPING;
  174433. }
  174434. /* At this point we should be in state DSTATE_STOPPING if being used
  174435. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174436. * to the coefficients during a full buffered-image-mode decompression.
  174437. */
  174438. if ((cinfo->global_state == DSTATE_STOPPING ||
  174439. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174440. return cinfo->coef->coef_arrays;
  174441. }
  174442. /* Oops, improper usage */
  174443. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174444. return NULL; /* keep compiler happy */
  174445. }
  174446. /*
  174447. * Master selection of decompression modules for transcoding.
  174448. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174449. */
  174450. LOCAL(void)
  174451. transdecode_master_selection (j_decompress_ptr cinfo)
  174452. {
  174453. /* This is effectively a buffered-image operation. */
  174454. cinfo->buffered_image = TRUE;
  174455. /* Entropy decoding: either Huffman or arithmetic coding. */
  174456. if (cinfo->arith_code) {
  174457. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174458. } else {
  174459. if (cinfo->progressive_mode) {
  174460. #ifdef D_PROGRESSIVE_SUPPORTED
  174461. jinit_phuff_decoder(cinfo);
  174462. #else
  174463. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174464. #endif
  174465. } else
  174466. jinit_huff_decoder(cinfo);
  174467. }
  174468. /* Always get a full-image coefficient buffer. */
  174469. jinit_d_coef_controller(cinfo, TRUE);
  174470. /* We can now tell the memory manager to allocate virtual arrays. */
  174471. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174472. /* Initialize input side of decompressor to consume first scan. */
  174473. (*cinfo->inputctl->start_input_pass) (cinfo);
  174474. /* Initialize progress monitoring. */
  174475. if (cinfo->progress != NULL) {
  174476. int nscans;
  174477. /* Estimate number of scans to set pass_limit. */
  174478. if (cinfo->progressive_mode) {
  174479. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174480. nscans = 2 + 3 * cinfo->num_components;
  174481. } else if (cinfo->inputctl->has_multiple_scans) {
  174482. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174483. nscans = cinfo->num_components;
  174484. } else {
  174485. nscans = 1;
  174486. }
  174487. cinfo->progress->pass_counter = 0L;
  174488. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174489. cinfo->progress->completed_passes = 0;
  174490. cinfo->progress->total_passes = 1;
  174491. }
  174492. }
  174493. /*** End of inlined file: jdtrans.c ***/
  174494. /*** Start of inlined file: jfdctflt.c ***/
  174495. #define JPEG_INTERNALS
  174496. #ifdef DCT_FLOAT_SUPPORTED
  174497. /*
  174498. * This module is specialized to the case DCTSIZE = 8.
  174499. */
  174500. #if DCTSIZE != 8
  174501. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174502. #endif
  174503. /*
  174504. * Perform the forward DCT on one block of samples.
  174505. */
  174506. GLOBAL(void)
  174507. jpeg_fdct_float (FAST_FLOAT * data)
  174508. {
  174509. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174510. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174511. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174512. FAST_FLOAT *dataptr;
  174513. int ctr;
  174514. /* Pass 1: process rows. */
  174515. dataptr = data;
  174516. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174517. tmp0 = dataptr[0] + dataptr[7];
  174518. tmp7 = dataptr[0] - dataptr[7];
  174519. tmp1 = dataptr[1] + dataptr[6];
  174520. tmp6 = dataptr[1] - dataptr[6];
  174521. tmp2 = dataptr[2] + dataptr[5];
  174522. tmp5 = dataptr[2] - dataptr[5];
  174523. tmp3 = dataptr[3] + dataptr[4];
  174524. tmp4 = dataptr[3] - dataptr[4];
  174525. /* Even part */
  174526. tmp10 = tmp0 + tmp3; /* phase 2 */
  174527. tmp13 = tmp0 - tmp3;
  174528. tmp11 = tmp1 + tmp2;
  174529. tmp12 = tmp1 - tmp2;
  174530. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174531. dataptr[4] = tmp10 - tmp11;
  174532. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174533. dataptr[2] = tmp13 + z1; /* phase 5 */
  174534. dataptr[6] = tmp13 - z1;
  174535. /* Odd part */
  174536. tmp10 = tmp4 + tmp5; /* phase 2 */
  174537. tmp11 = tmp5 + tmp6;
  174538. tmp12 = tmp6 + tmp7;
  174539. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174540. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174541. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174542. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174543. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174544. z11 = tmp7 + z3; /* phase 5 */
  174545. z13 = tmp7 - z3;
  174546. dataptr[5] = z13 + z2; /* phase 6 */
  174547. dataptr[3] = z13 - z2;
  174548. dataptr[1] = z11 + z4;
  174549. dataptr[7] = z11 - z4;
  174550. dataptr += DCTSIZE; /* advance pointer to next row */
  174551. }
  174552. /* Pass 2: process columns. */
  174553. dataptr = data;
  174554. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174555. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174556. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174557. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174558. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174559. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174560. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174561. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174562. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174563. /* Even part */
  174564. tmp10 = tmp0 + tmp3; /* phase 2 */
  174565. tmp13 = tmp0 - tmp3;
  174566. tmp11 = tmp1 + tmp2;
  174567. tmp12 = tmp1 - tmp2;
  174568. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174569. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174570. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174571. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174572. dataptr[DCTSIZE*6] = tmp13 - z1;
  174573. /* Odd part */
  174574. tmp10 = tmp4 + tmp5; /* phase 2 */
  174575. tmp11 = tmp5 + tmp6;
  174576. tmp12 = tmp6 + tmp7;
  174577. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174578. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174579. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174580. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174581. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174582. z11 = tmp7 + z3; /* phase 5 */
  174583. z13 = tmp7 - z3;
  174584. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174585. dataptr[DCTSIZE*3] = z13 - z2;
  174586. dataptr[DCTSIZE*1] = z11 + z4;
  174587. dataptr[DCTSIZE*7] = z11 - z4;
  174588. dataptr++; /* advance pointer to next column */
  174589. }
  174590. }
  174591. #endif /* DCT_FLOAT_SUPPORTED */
  174592. /*** End of inlined file: jfdctflt.c ***/
  174593. /*** Start of inlined file: jfdctint.c ***/
  174594. #define JPEG_INTERNALS
  174595. #ifdef DCT_ISLOW_SUPPORTED
  174596. /*
  174597. * This module is specialized to the case DCTSIZE = 8.
  174598. */
  174599. #if DCTSIZE != 8
  174600. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174601. #endif
  174602. /*
  174603. * The poop on this scaling stuff is as follows:
  174604. *
  174605. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174606. * larger than the true DCT outputs. The final outputs are therefore
  174607. * a factor of N larger than desired; since N=8 this can be cured by
  174608. * a simple right shift at the end of the algorithm. The advantage of
  174609. * this arrangement is that we save two multiplications per 1-D DCT,
  174610. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174611. * In the IJG code, this factor of 8 is removed by the quantization step
  174612. * (in jcdctmgr.c), NOT in this module.
  174613. *
  174614. * We have to do addition and subtraction of the integer inputs, which
  174615. * is no problem, and multiplication by fractional constants, which is
  174616. * a problem to do in integer arithmetic. We multiply all the constants
  174617. * by CONST_SCALE and convert them to integer constants (thus retaining
  174618. * CONST_BITS bits of precision in the constants). After doing a
  174619. * multiplication we have to divide the product by CONST_SCALE, with proper
  174620. * rounding, to produce the correct output. This division can be done
  174621. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174622. * as long as possible so that partial sums can be added together with
  174623. * full fractional precision.
  174624. *
  174625. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174626. * they are represented to better-than-integral precision. These outputs
  174627. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174628. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174629. * array is INT32 anyway.)
  174630. *
  174631. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174632. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174633. * shows that the values given below are the most effective.
  174634. */
  174635. #if BITS_IN_JSAMPLE == 8
  174636. #define CONST_BITS 13
  174637. #define PASS1_BITS 2
  174638. #else
  174639. #define CONST_BITS 13
  174640. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174641. #endif
  174642. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174643. * causing a lot of useless floating-point operations at run time.
  174644. * To get around this we use the following pre-calculated constants.
  174645. * If you change CONST_BITS you may want to add appropriate values.
  174646. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174647. */
  174648. #if CONST_BITS == 13
  174649. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174650. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174651. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174652. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174653. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174654. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174655. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174656. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174657. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174658. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174659. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174660. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174661. #else
  174662. #define FIX_0_298631336 FIX(0.298631336)
  174663. #define FIX_0_390180644 FIX(0.390180644)
  174664. #define FIX_0_541196100 FIX(0.541196100)
  174665. #define FIX_0_765366865 FIX(0.765366865)
  174666. #define FIX_0_899976223 FIX(0.899976223)
  174667. #define FIX_1_175875602 FIX(1.175875602)
  174668. #define FIX_1_501321110 FIX(1.501321110)
  174669. #define FIX_1_847759065 FIX(1.847759065)
  174670. #define FIX_1_961570560 FIX(1.961570560)
  174671. #define FIX_2_053119869 FIX(2.053119869)
  174672. #define FIX_2_562915447 FIX(2.562915447)
  174673. #define FIX_3_072711026 FIX(3.072711026)
  174674. #endif
  174675. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174676. * For 8-bit samples with the recommended scaling, all the variable
  174677. * and constant values involved are no more than 16 bits wide, so a
  174678. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174679. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174680. */
  174681. #if BITS_IN_JSAMPLE == 8
  174682. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174683. #else
  174684. #define MULTIPLY(var,const) ((var) * (const))
  174685. #endif
  174686. /*
  174687. * Perform the forward DCT on one block of samples.
  174688. */
  174689. GLOBAL(void)
  174690. jpeg_fdct_islow (DCTELEM * data)
  174691. {
  174692. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174693. INT32 tmp10, tmp11, tmp12, tmp13;
  174694. INT32 z1, z2, z3, z4, z5;
  174695. DCTELEM *dataptr;
  174696. int ctr;
  174697. SHIFT_TEMPS
  174698. /* Pass 1: process rows. */
  174699. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174700. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174701. dataptr = data;
  174702. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174703. tmp0 = dataptr[0] + dataptr[7];
  174704. tmp7 = dataptr[0] - dataptr[7];
  174705. tmp1 = dataptr[1] + dataptr[6];
  174706. tmp6 = dataptr[1] - dataptr[6];
  174707. tmp2 = dataptr[2] + dataptr[5];
  174708. tmp5 = dataptr[2] - dataptr[5];
  174709. tmp3 = dataptr[3] + dataptr[4];
  174710. tmp4 = dataptr[3] - dataptr[4];
  174711. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174712. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174713. */
  174714. tmp10 = tmp0 + tmp3;
  174715. tmp13 = tmp0 - tmp3;
  174716. tmp11 = tmp1 + tmp2;
  174717. tmp12 = tmp1 - tmp2;
  174718. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174719. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174720. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174721. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174722. CONST_BITS-PASS1_BITS);
  174723. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174724. CONST_BITS-PASS1_BITS);
  174725. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174726. * cK represents cos(K*pi/16).
  174727. * i0..i3 in the paper are tmp4..tmp7 here.
  174728. */
  174729. z1 = tmp4 + tmp7;
  174730. z2 = tmp5 + tmp6;
  174731. z3 = tmp4 + tmp6;
  174732. z4 = tmp5 + tmp7;
  174733. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174734. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174735. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174736. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174737. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174738. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174739. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174740. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174741. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174742. z3 += z5;
  174743. z4 += z5;
  174744. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174745. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174746. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174747. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174748. dataptr += DCTSIZE; /* advance pointer to next row */
  174749. }
  174750. /* Pass 2: process columns.
  174751. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174752. * by an overall factor of 8.
  174753. */
  174754. dataptr = data;
  174755. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174756. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174757. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174758. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174759. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174760. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174761. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174762. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174763. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174764. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174765. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174766. */
  174767. tmp10 = tmp0 + tmp3;
  174768. tmp13 = tmp0 - tmp3;
  174769. tmp11 = tmp1 + tmp2;
  174770. tmp12 = tmp1 - tmp2;
  174771. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174772. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174773. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174774. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174775. CONST_BITS+PASS1_BITS);
  174776. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174777. CONST_BITS+PASS1_BITS);
  174778. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174779. * cK represents cos(K*pi/16).
  174780. * i0..i3 in the paper are tmp4..tmp7 here.
  174781. */
  174782. z1 = tmp4 + tmp7;
  174783. z2 = tmp5 + tmp6;
  174784. z3 = tmp4 + tmp6;
  174785. z4 = tmp5 + tmp7;
  174786. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174787. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174788. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174789. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174790. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174791. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174792. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174793. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174794. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174795. z3 += z5;
  174796. z4 += z5;
  174797. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174798. CONST_BITS+PASS1_BITS);
  174799. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174800. CONST_BITS+PASS1_BITS);
  174801. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174802. CONST_BITS+PASS1_BITS);
  174803. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174804. CONST_BITS+PASS1_BITS);
  174805. dataptr++; /* advance pointer to next column */
  174806. }
  174807. }
  174808. #endif /* DCT_ISLOW_SUPPORTED */
  174809. /*** End of inlined file: jfdctint.c ***/
  174810. #undef CONST_BITS
  174811. #undef MULTIPLY
  174812. #undef FIX_0_541196100
  174813. /*** Start of inlined file: jfdctfst.c ***/
  174814. #define JPEG_INTERNALS
  174815. #ifdef DCT_IFAST_SUPPORTED
  174816. /*
  174817. * This module is specialized to the case DCTSIZE = 8.
  174818. */
  174819. #if DCTSIZE != 8
  174820. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174821. #endif
  174822. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174823. * see jfdctint.c for more details. However, we choose to descale
  174824. * (right shift) multiplication products as soon as they are formed,
  174825. * rather than carrying additional fractional bits into subsequent additions.
  174826. * This compromises accuracy slightly, but it lets us save a few shifts.
  174827. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174828. * everywhere except in the multiplications proper; this saves a good deal
  174829. * of work on 16-bit-int machines.
  174830. *
  174831. * Again to save a few shifts, the intermediate results between pass 1 and
  174832. * pass 2 are not upscaled, but are represented only to integral precision.
  174833. *
  174834. * A final compromise is to represent the multiplicative constants to only
  174835. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174836. * machines, and may also reduce the cost of multiplication (since there
  174837. * are fewer one-bits in the constants).
  174838. */
  174839. #define CONST_BITS 8
  174840. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174841. * causing a lot of useless floating-point operations at run time.
  174842. * To get around this we use the following pre-calculated constants.
  174843. * If you change CONST_BITS you may want to add appropriate values.
  174844. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174845. */
  174846. #if CONST_BITS == 8
  174847. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174848. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174849. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174850. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174851. #else
  174852. #define FIX_0_382683433 FIX(0.382683433)
  174853. #define FIX_0_541196100 FIX(0.541196100)
  174854. #define FIX_0_707106781 FIX(0.707106781)
  174855. #define FIX_1_306562965 FIX(1.306562965)
  174856. #endif
  174857. /* We can gain a little more speed, with a further compromise in accuracy,
  174858. * by omitting the addition in a descaling shift. This yields an incorrectly
  174859. * rounded result half the time...
  174860. */
  174861. #ifndef USE_ACCURATE_ROUNDING
  174862. #undef DESCALE
  174863. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174864. #endif
  174865. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174866. * descale to yield a DCTELEM result.
  174867. */
  174868. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174869. /*
  174870. * Perform the forward DCT on one block of samples.
  174871. */
  174872. GLOBAL(void)
  174873. jpeg_fdct_ifast (DCTELEM * data)
  174874. {
  174875. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174876. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174877. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174878. DCTELEM *dataptr;
  174879. int ctr;
  174880. SHIFT_TEMPS
  174881. /* Pass 1: process rows. */
  174882. dataptr = data;
  174883. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174884. tmp0 = dataptr[0] + dataptr[7];
  174885. tmp7 = dataptr[0] - dataptr[7];
  174886. tmp1 = dataptr[1] + dataptr[6];
  174887. tmp6 = dataptr[1] - dataptr[6];
  174888. tmp2 = dataptr[2] + dataptr[5];
  174889. tmp5 = dataptr[2] - dataptr[5];
  174890. tmp3 = dataptr[3] + dataptr[4];
  174891. tmp4 = dataptr[3] - dataptr[4];
  174892. /* Even part */
  174893. tmp10 = tmp0 + tmp3; /* phase 2 */
  174894. tmp13 = tmp0 - tmp3;
  174895. tmp11 = tmp1 + tmp2;
  174896. tmp12 = tmp1 - tmp2;
  174897. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174898. dataptr[4] = tmp10 - tmp11;
  174899. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174900. dataptr[2] = tmp13 + z1; /* phase 5 */
  174901. dataptr[6] = tmp13 - z1;
  174902. /* Odd part */
  174903. tmp10 = tmp4 + tmp5; /* phase 2 */
  174904. tmp11 = tmp5 + tmp6;
  174905. tmp12 = tmp6 + tmp7;
  174906. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174907. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174908. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174909. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174910. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174911. z11 = tmp7 + z3; /* phase 5 */
  174912. z13 = tmp7 - z3;
  174913. dataptr[5] = z13 + z2; /* phase 6 */
  174914. dataptr[3] = z13 - z2;
  174915. dataptr[1] = z11 + z4;
  174916. dataptr[7] = z11 - z4;
  174917. dataptr += DCTSIZE; /* advance pointer to next row */
  174918. }
  174919. /* Pass 2: process columns. */
  174920. dataptr = data;
  174921. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174922. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174923. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174924. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174925. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174926. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174927. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174928. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174929. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174930. /* Even part */
  174931. tmp10 = tmp0 + tmp3; /* phase 2 */
  174932. tmp13 = tmp0 - tmp3;
  174933. tmp11 = tmp1 + tmp2;
  174934. tmp12 = tmp1 - tmp2;
  174935. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174936. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174937. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174938. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174939. dataptr[DCTSIZE*6] = tmp13 - z1;
  174940. /* Odd part */
  174941. tmp10 = tmp4 + tmp5; /* phase 2 */
  174942. tmp11 = tmp5 + tmp6;
  174943. tmp12 = tmp6 + tmp7;
  174944. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174945. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174946. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174947. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174948. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174949. z11 = tmp7 + z3; /* phase 5 */
  174950. z13 = tmp7 - z3;
  174951. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174952. dataptr[DCTSIZE*3] = z13 - z2;
  174953. dataptr[DCTSIZE*1] = z11 + z4;
  174954. dataptr[DCTSIZE*7] = z11 - z4;
  174955. dataptr++; /* advance pointer to next column */
  174956. }
  174957. }
  174958. #endif /* DCT_IFAST_SUPPORTED */
  174959. /*** End of inlined file: jfdctfst.c ***/
  174960. #undef FIX_0_541196100
  174961. /*** Start of inlined file: jidctflt.c ***/
  174962. #define JPEG_INTERNALS
  174963. #ifdef DCT_FLOAT_SUPPORTED
  174964. /*
  174965. * This module is specialized to the case DCTSIZE = 8.
  174966. */
  174967. #if DCTSIZE != 8
  174968. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174969. #endif
  174970. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174971. * entry; produce a float result.
  174972. */
  174973. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174974. /*
  174975. * Perform dequantization and inverse DCT on one block of coefficients.
  174976. */
  174977. GLOBAL(void)
  174978. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174979. JCOEFPTR coef_block,
  174980. JSAMPARRAY output_buf, JDIMENSION output_col)
  174981. {
  174982. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174983. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174984. FAST_FLOAT z5, z10, z11, z12, z13;
  174985. JCOEFPTR inptr;
  174986. FLOAT_MULT_TYPE * quantptr;
  174987. FAST_FLOAT * wsptr;
  174988. JSAMPROW outptr;
  174989. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174990. int ctr;
  174991. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174992. SHIFT_TEMPS
  174993. /* Pass 1: process columns from input, store into work array. */
  174994. inptr = coef_block;
  174995. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174996. wsptr = workspace;
  174997. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174998. /* Due to quantization, we will usually find that many of the input
  174999. * coefficients are zero, especially the AC terms. We can exploit this
  175000. * by short-circuiting the IDCT calculation for any column in which all
  175001. * the AC terms are zero. In that case each output is equal to the
  175002. * DC coefficient (with scale factor as needed).
  175003. * With typical images and quantization tables, half or more of the
  175004. * column DCT calculations can be simplified this way.
  175005. */
  175006. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175007. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175008. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175009. inptr[DCTSIZE*7] == 0) {
  175010. /* AC terms all zero */
  175011. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175012. wsptr[DCTSIZE*0] = dcval;
  175013. wsptr[DCTSIZE*1] = dcval;
  175014. wsptr[DCTSIZE*2] = dcval;
  175015. wsptr[DCTSIZE*3] = dcval;
  175016. wsptr[DCTSIZE*4] = dcval;
  175017. wsptr[DCTSIZE*5] = dcval;
  175018. wsptr[DCTSIZE*6] = dcval;
  175019. wsptr[DCTSIZE*7] = dcval;
  175020. inptr++; /* advance pointers to next column */
  175021. quantptr++;
  175022. wsptr++;
  175023. continue;
  175024. }
  175025. /* Even part */
  175026. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175027. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175028. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175029. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175030. tmp10 = tmp0 + tmp2; /* phase 3 */
  175031. tmp11 = tmp0 - tmp2;
  175032. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175033. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175034. tmp0 = tmp10 + tmp13; /* phase 2 */
  175035. tmp3 = tmp10 - tmp13;
  175036. tmp1 = tmp11 + tmp12;
  175037. tmp2 = tmp11 - tmp12;
  175038. /* Odd part */
  175039. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175040. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175041. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175042. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175043. z13 = tmp6 + tmp5; /* phase 6 */
  175044. z10 = tmp6 - tmp5;
  175045. z11 = tmp4 + tmp7;
  175046. z12 = tmp4 - tmp7;
  175047. tmp7 = z11 + z13; /* phase 5 */
  175048. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175049. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175050. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175051. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175052. tmp6 = tmp12 - tmp7; /* phase 2 */
  175053. tmp5 = tmp11 - tmp6;
  175054. tmp4 = tmp10 + tmp5;
  175055. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175056. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175057. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175058. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175059. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175060. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175061. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175062. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175063. inptr++; /* advance pointers to next column */
  175064. quantptr++;
  175065. wsptr++;
  175066. }
  175067. /* Pass 2: process rows from work array, store into output array. */
  175068. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175069. wsptr = workspace;
  175070. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175071. outptr = output_buf[ctr] + output_col;
  175072. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175073. * However, the column calculation has created many nonzero AC terms, so
  175074. * the simplification applies less often (typically 5% to 10% of the time).
  175075. * And testing floats for zero is relatively expensive, so we don't bother.
  175076. */
  175077. /* Even part */
  175078. tmp10 = wsptr[0] + wsptr[4];
  175079. tmp11 = wsptr[0] - wsptr[4];
  175080. tmp13 = wsptr[2] + wsptr[6];
  175081. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175082. tmp0 = tmp10 + tmp13;
  175083. tmp3 = tmp10 - tmp13;
  175084. tmp1 = tmp11 + tmp12;
  175085. tmp2 = tmp11 - tmp12;
  175086. /* Odd part */
  175087. z13 = wsptr[5] + wsptr[3];
  175088. z10 = wsptr[5] - wsptr[3];
  175089. z11 = wsptr[1] + wsptr[7];
  175090. z12 = wsptr[1] - wsptr[7];
  175091. tmp7 = z11 + z13;
  175092. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175093. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175094. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175095. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175096. tmp6 = tmp12 - tmp7;
  175097. tmp5 = tmp11 - tmp6;
  175098. tmp4 = tmp10 + tmp5;
  175099. /* Final output stage: scale down by a factor of 8 and range-limit */
  175100. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175101. & RANGE_MASK];
  175102. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175103. & RANGE_MASK];
  175104. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175105. & RANGE_MASK];
  175106. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175107. & RANGE_MASK];
  175108. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175109. & RANGE_MASK];
  175110. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175111. & RANGE_MASK];
  175112. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175113. & RANGE_MASK];
  175114. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175115. & RANGE_MASK];
  175116. wsptr += DCTSIZE; /* advance pointer to next row */
  175117. }
  175118. }
  175119. #endif /* DCT_FLOAT_SUPPORTED */
  175120. /*** End of inlined file: jidctflt.c ***/
  175121. #undef CONST_BITS
  175122. #undef FIX_1_847759065
  175123. #undef MULTIPLY
  175124. #undef DEQUANTIZE
  175125. #undef DESCALE
  175126. /*** Start of inlined file: jidctfst.c ***/
  175127. #define JPEG_INTERNALS
  175128. #ifdef DCT_IFAST_SUPPORTED
  175129. /*
  175130. * This module is specialized to the case DCTSIZE = 8.
  175131. */
  175132. #if DCTSIZE != 8
  175133. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175134. #endif
  175135. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175136. * see jidctint.c for more details. However, we choose to descale
  175137. * (right shift) multiplication products as soon as they are formed,
  175138. * rather than carrying additional fractional bits into subsequent additions.
  175139. * This compromises accuracy slightly, but it lets us save a few shifts.
  175140. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175141. * everywhere except in the multiplications proper; this saves a good deal
  175142. * of work on 16-bit-int machines.
  175143. *
  175144. * The dequantized coefficients are not integers because the AA&N scaling
  175145. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175146. * so that the first and second IDCT rounds have the same input scaling.
  175147. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175148. * avoid a descaling shift; this compromises accuracy rather drastically
  175149. * for small quantization table entries, but it saves a lot of shifts.
  175150. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175151. * so we use a much larger scaling factor to preserve accuracy.
  175152. *
  175153. * A final compromise is to represent the multiplicative constants to only
  175154. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175155. * machines, and may also reduce the cost of multiplication (since there
  175156. * are fewer one-bits in the constants).
  175157. */
  175158. #if BITS_IN_JSAMPLE == 8
  175159. #define CONST_BITS 8
  175160. #define PASS1_BITS 2
  175161. #else
  175162. #define CONST_BITS 8
  175163. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175164. #endif
  175165. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175166. * causing a lot of useless floating-point operations at run time.
  175167. * To get around this we use the following pre-calculated constants.
  175168. * If you change CONST_BITS you may want to add appropriate values.
  175169. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175170. */
  175171. #if CONST_BITS == 8
  175172. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175173. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175174. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175175. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175176. #else
  175177. #define FIX_1_082392200 FIX(1.082392200)
  175178. #define FIX_1_414213562 FIX(1.414213562)
  175179. #define FIX_1_847759065 FIX(1.847759065)
  175180. #define FIX_2_613125930 FIX(2.613125930)
  175181. #endif
  175182. /* We can gain a little more speed, with a further compromise in accuracy,
  175183. * by omitting the addition in a descaling shift. This yields an incorrectly
  175184. * rounded result half the time...
  175185. */
  175186. #ifndef USE_ACCURATE_ROUNDING
  175187. #undef DESCALE
  175188. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175189. #endif
  175190. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175191. * descale to yield a DCTELEM result.
  175192. */
  175193. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175194. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175195. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175196. * multiplication will do. For 12-bit data, the multiplier table is
  175197. * declared INT32, so a 32-bit multiply will be used.
  175198. */
  175199. #if BITS_IN_JSAMPLE == 8
  175200. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175201. #else
  175202. #define DEQUANTIZE(coef,quantval) \
  175203. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175204. #endif
  175205. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175206. * We assume that int right shift is unsigned if INT32 right shift is.
  175207. */
  175208. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175209. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175210. #if BITS_IN_JSAMPLE == 8
  175211. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175212. #else
  175213. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175214. #endif
  175215. #define IRIGHT_SHIFT(x,shft) \
  175216. ((ishift_temp = (x)) < 0 ? \
  175217. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175218. (ishift_temp >> (shft)))
  175219. #else
  175220. #define ISHIFT_TEMPS
  175221. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175222. #endif
  175223. #ifdef USE_ACCURATE_ROUNDING
  175224. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175225. #else
  175226. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175227. #endif
  175228. /*
  175229. * Perform dequantization and inverse DCT on one block of coefficients.
  175230. */
  175231. GLOBAL(void)
  175232. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175233. JCOEFPTR coef_block,
  175234. JSAMPARRAY output_buf, JDIMENSION output_col)
  175235. {
  175236. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175237. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175238. DCTELEM z5, z10, z11, z12, z13;
  175239. JCOEFPTR inptr;
  175240. IFAST_MULT_TYPE * quantptr;
  175241. int * wsptr;
  175242. JSAMPROW outptr;
  175243. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175244. int ctr;
  175245. int workspace[DCTSIZE2]; /* buffers data between passes */
  175246. SHIFT_TEMPS /* for DESCALE */
  175247. ISHIFT_TEMPS /* for IDESCALE */
  175248. /* Pass 1: process columns from input, store into work array. */
  175249. inptr = coef_block;
  175250. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175251. wsptr = workspace;
  175252. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175253. /* Due to quantization, we will usually find that many of the input
  175254. * coefficients are zero, especially the AC terms. We can exploit this
  175255. * by short-circuiting the IDCT calculation for any column in which all
  175256. * the AC terms are zero. In that case each output is equal to the
  175257. * DC coefficient (with scale factor as needed).
  175258. * With typical images and quantization tables, half or more of the
  175259. * column DCT calculations can be simplified this way.
  175260. */
  175261. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175262. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175263. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175264. inptr[DCTSIZE*7] == 0) {
  175265. /* AC terms all zero */
  175266. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175267. wsptr[DCTSIZE*0] = dcval;
  175268. wsptr[DCTSIZE*1] = dcval;
  175269. wsptr[DCTSIZE*2] = dcval;
  175270. wsptr[DCTSIZE*3] = dcval;
  175271. wsptr[DCTSIZE*4] = dcval;
  175272. wsptr[DCTSIZE*5] = dcval;
  175273. wsptr[DCTSIZE*6] = dcval;
  175274. wsptr[DCTSIZE*7] = dcval;
  175275. inptr++; /* advance pointers to next column */
  175276. quantptr++;
  175277. wsptr++;
  175278. continue;
  175279. }
  175280. /* Even part */
  175281. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175282. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175283. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175284. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175285. tmp10 = tmp0 + tmp2; /* phase 3 */
  175286. tmp11 = tmp0 - tmp2;
  175287. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175288. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175289. tmp0 = tmp10 + tmp13; /* phase 2 */
  175290. tmp3 = tmp10 - tmp13;
  175291. tmp1 = tmp11 + tmp12;
  175292. tmp2 = tmp11 - tmp12;
  175293. /* Odd part */
  175294. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175295. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175296. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175297. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175298. z13 = tmp6 + tmp5; /* phase 6 */
  175299. z10 = tmp6 - tmp5;
  175300. z11 = tmp4 + tmp7;
  175301. z12 = tmp4 - tmp7;
  175302. tmp7 = z11 + z13; /* phase 5 */
  175303. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175304. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175305. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175306. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175307. tmp6 = tmp12 - tmp7; /* phase 2 */
  175308. tmp5 = tmp11 - tmp6;
  175309. tmp4 = tmp10 + tmp5;
  175310. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175311. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175312. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175313. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175314. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175315. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175316. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175317. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175318. inptr++; /* advance pointers to next column */
  175319. quantptr++;
  175320. wsptr++;
  175321. }
  175322. /* Pass 2: process rows from work array, store into output array. */
  175323. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175324. /* and also undo the PASS1_BITS scaling. */
  175325. wsptr = workspace;
  175326. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175327. outptr = output_buf[ctr] + output_col;
  175328. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175329. * However, the column calculation has created many nonzero AC terms, so
  175330. * the simplification applies less often (typically 5% to 10% of the time).
  175331. * On machines with very fast multiplication, it's possible that the
  175332. * test takes more time than it's worth. In that case this section
  175333. * may be commented out.
  175334. */
  175335. #ifndef NO_ZERO_ROW_TEST
  175336. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175337. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175338. /* AC terms all zero */
  175339. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175340. & RANGE_MASK];
  175341. outptr[0] = dcval;
  175342. outptr[1] = dcval;
  175343. outptr[2] = dcval;
  175344. outptr[3] = dcval;
  175345. outptr[4] = dcval;
  175346. outptr[5] = dcval;
  175347. outptr[6] = dcval;
  175348. outptr[7] = dcval;
  175349. wsptr += DCTSIZE; /* advance pointer to next row */
  175350. continue;
  175351. }
  175352. #endif
  175353. /* Even part */
  175354. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175355. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175356. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175357. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175358. - tmp13;
  175359. tmp0 = tmp10 + tmp13;
  175360. tmp3 = tmp10 - tmp13;
  175361. tmp1 = tmp11 + tmp12;
  175362. tmp2 = tmp11 - tmp12;
  175363. /* Odd part */
  175364. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175365. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175366. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175367. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175368. tmp7 = z11 + z13; /* phase 5 */
  175369. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175370. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175371. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175372. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175373. tmp6 = tmp12 - tmp7; /* phase 2 */
  175374. tmp5 = tmp11 - tmp6;
  175375. tmp4 = tmp10 + tmp5;
  175376. /* Final output stage: scale down by a factor of 8 and range-limit */
  175377. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175378. & RANGE_MASK];
  175379. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175380. & RANGE_MASK];
  175381. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175382. & RANGE_MASK];
  175383. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175384. & RANGE_MASK];
  175385. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175386. & RANGE_MASK];
  175387. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175388. & RANGE_MASK];
  175389. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175390. & RANGE_MASK];
  175391. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175392. & RANGE_MASK];
  175393. wsptr += DCTSIZE; /* advance pointer to next row */
  175394. }
  175395. }
  175396. #endif /* DCT_IFAST_SUPPORTED */
  175397. /*** End of inlined file: jidctfst.c ***/
  175398. #undef CONST_BITS
  175399. #undef FIX_1_847759065
  175400. #undef MULTIPLY
  175401. #undef DEQUANTIZE
  175402. /*** Start of inlined file: jidctint.c ***/
  175403. #define JPEG_INTERNALS
  175404. #ifdef DCT_ISLOW_SUPPORTED
  175405. /*
  175406. * This module is specialized to the case DCTSIZE = 8.
  175407. */
  175408. #if DCTSIZE != 8
  175409. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175410. #endif
  175411. /*
  175412. * The poop on this scaling stuff is as follows:
  175413. *
  175414. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175415. * larger than the true IDCT outputs. The final outputs are therefore
  175416. * a factor of N larger than desired; since N=8 this can be cured by
  175417. * a simple right shift at the end of the algorithm. The advantage of
  175418. * this arrangement is that we save two multiplications per 1-D IDCT,
  175419. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175420. *
  175421. * We have to do addition and subtraction of the integer inputs, which
  175422. * is no problem, and multiplication by fractional constants, which is
  175423. * a problem to do in integer arithmetic. We multiply all the constants
  175424. * by CONST_SCALE and convert them to integer constants (thus retaining
  175425. * CONST_BITS bits of precision in the constants). After doing a
  175426. * multiplication we have to divide the product by CONST_SCALE, with proper
  175427. * rounding, to produce the correct output. This division can be done
  175428. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175429. * as long as possible so that partial sums can be added together with
  175430. * full fractional precision.
  175431. *
  175432. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175433. * they are represented to better-than-integral precision. These outputs
  175434. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175435. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175436. * intermediate INT32 array would be needed.)
  175437. *
  175438. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175439. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175440. * shows that the values given below are the most effective.
  175441. */
  175442. #if BITS_IN_JSAMPLE == 8
  175443. #define CONST_BITS 13
  175444. #define PASS1_BITS 2
  175445. #else
  175446. #define CONST_BITS 13
  175447. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175448. #endif
  175449. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175450. * causing a lot of useless floating-point operations at run time.
  175451. * To get around this we use the following pre-calculated constants.
  175452. * If you change CONST_BITS you may want to add appropriate values.
  175453. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175454. */
  175455. #if CONST_BITS == 13
  175456. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175457. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175458. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175459. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175460. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175461. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175462. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175463. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175464. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175465. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175466. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175467. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175468. #else
  175469. #define FIX_0_298631336 FIX(0.298631336)
  175470. #define FIX_0_390180644 FIX(0.390180644)
  175471. #define FIX_0_541196100 FIX(0.541196100)
  175472. #define FIX_0_765366865 FIX(0.765366865)
  175473. #define FIX_0_899976223 FIX(0.899976223)
  175474. #define FIX_1_175875602 FIX(1.175875602)
  175475. #define FIX_1_501321110 FIX(1.501321110)
  175476. #define FIX_1_847759065 FIX(1.847759065)
  175477. #define FIX_1_961570560 FIX(1.961570560)
  175478. #define FIX_2_053119869 FIX(2.053119869)
  175479. #define FIX_2_562915447 FIX(2.562915447)
  175480. #define FIX_3_072711026 FIX(3.072711026)
  175481. #endif
  175482. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175483. * For 8-bit samples with the recommended scaling, all the variable
  175484. * and constant values involved are no more than 16 bits wide, so a
  175485. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175486. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175487. */
  175488. #if BITS_IN_JSAMPLE == 8
  175489. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175490. #else
  175491. #define MULTIPLY(var,const) ((var) * (const))
  175492. #endif
  175493. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175494. * entry; produce an int result. In this module, both inputs and result
  175495. * are 16 bits or less, so either int or short multiply will work.
  175496. */
  175497. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175498. /*
  175499. * Perform dequantization and inverse DCT on one block of coefficients.
  175500. */
  175501. GLOBAL(void)
  175502. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175503. JCOEFPTR coef_block,
  175504. JSAMPARRAY output_buf, JDIMENSION output_col)
  175505. {
  175506. INT32 tmp0, tmp1, tmp2, tmp3;
  175507. INT32 tmp10, tmp11, tmp12, tmp13;
  175508. INT32 z1, z2, z3, z4, z5;
  175509. JCOEFPTR inptr;
  175510. ISLOW_MULT_TYPE * quantptr;
  175511. int * wsptr;
  175512. JSAMPROW outptr;
  175513. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175514. int ctr;
  175515. int workspace[DCTSIZE2]; /* buffers data between passes */
  175516. SHIFT_TEMPS
  175517. /* Pass 1: process columns from input, store into work array. */
  175518. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175519. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175520. inptr = coef_block;
  175521. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175522. wsptr = workspace;
  175523. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175524. /* Due to quantization, we will usually find that many of the input
  175525. * coefficients are zero, especially the AC terms. We can exploit this
  175526. * by short-circuiting the IDCT calculation for any column in which all
  175527. * the AC terms are zero. In that case each output is equal to the
  175528. * DC coefficient (with scale factor as needed).
  175529. * With typical images and quantization tables, half or more of the
  175530. * column DCT calculations can be simplified this way.
  175531. */
  175532. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175533. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175534. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175535. inptr[DCTSIZE*7] == 0) {
  175536. /* AC terms all zero */
  175537. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175538. wsptr[DCTSIZE*0] = dcval;
  175539. wsptr[DCTSIZE*1] = dcval;
  175540. wsptr[DCTSIZE*2] = dcval;
  175541. wsptr[DCTSIZE*3] = dcval;
  175542. wsptr[DCTSIZE*4] = dcval;
  175543. wsptr[DCTSIZE*5] = dcval;
  175544. wsptr[DCTSIZE*6] = dcval;
  175545. wsptr[DCTSIZE*7] = dcval;
  175546. inptr++; /* advance pointers to next column */
  175547. quantptr++;
  175548. wsptr++;
  175549. continue;
  175550. }
  175551. /* Even part: reverse the even part of the forward DCT. */
  175552. /* The rotator is sqrt(2)*c(-6). */
  175553. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175554. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175555. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175556. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175557. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175558. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175559. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175560. tmp0 = (z2 + z3) << CONST_BITS;
  175561. tmp1 = (z2 - z3) << CONST_BITS;
  175562. tmp10 = tmp0 + tmp3;
  175563. tmp13 = tmp0 - tmp3;
  175564. tmp11 = tmp1 + tmp2;
  175565. tmp12 = tmp1 - tmp2;
  175566. /* Odd part per figure 8; the matrix is unitary and hence its
  175567. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175568. */
  175569. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175570. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175571. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175572. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175573. z1 = tmp0 + tmp3;
  175574. z2 = tmp1 + tmp2;
  175575. z3 = tmp0 + tmp2;
  175576. z4 = tmp1 + tmp3;
  175577. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175578. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175579. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175580. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175581. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175582. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175583. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175584. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175585. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175586. z3 += z5;
  175587. z4 += z5;
  175588. tmp0 += z1 + z3;
  175589. tmp1 += z2 + z4;
  175590. tmp2 += z2 + z3;
  175591. tmp3 += z1 + z4;
  175592. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175593. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175594. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175595. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175596. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175597. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175598. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175599. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175600. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175601. inptr++; /* advance pointers to next column */
  175602. quantptr++;
  175603. wsptr++;
  175604. }
  175605. /* Pass 2: process rows from work array, store into output array. */
  175606. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175607. /* and also undo the PASS1_BITS scaling. */
  175608. wsptr = workspace;
  175609. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175610. outptr = output_buf[ctr] + output_col;
  175611. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175612. * However, the column calculation has created many nonzero AC terms, so
  175613. * the simplification applies less often (typically 5% to 10% of the time).
  175614. * On machines with very fast multiplication, it's possible that the
  175615. * test takes more time than it's worth. In that case this section
  175616. * may be commented out.
  175617. */
  175618. #ifndef NO_ZERO_ROW_TEST
  175619. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175620. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175621. /* AC terms all zero */
  175622. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175623. & RANGE_MASK];
  175624. outptr[0] = dcval;
  175625. outptr[1] = dcval;
  175626. outptr[2] = dcval;
  175627. outptr[3] = dcval;
  175628. outptr[4] = dcval;
  175629. outptr[5] = dcval;
  175630. outptr[6] = dcval;
  175631. outptr[7] = dcval;
  175632. wsptr += DCTSIZE; /* advance pointer to next row */
  175633. continue;
  175634. }
  175635. #endif
  175636. /* Even part: reverse the even part of the forward DCT. */
  175637. /* The rotator is sqrt(2)*c(-6). */
  175638. z2 = (INT32) wsptr[2];
  175639. z3 = (INT32) wsptr[6];
  175640. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175641. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175642. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175643. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175644. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175645. tmp10 = tmp0 + tmp3;
  175646. tmp13 = tmp0 - tmp3;
  175647. tmp11 = tmp1 + tmp2;
  175648. tmp12 = tmp1 - tmp2;
  175649. /* Odd part per figure 8; the matrix is unitary and hence its
  175650. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175651. */
  175652. tmp0 = (INT32) wsptr[7];
  175653. tmp1 = (INT32) wsptr[5];
  175654. tmp2 = (INT32) wsptr[3];
  175655. tmp3 = (INT32) wsptr[1];
  175656. z1 = tmp0 + tmp3;
  175657. z2 = tmp1 + tmp2;
  175658. z3 = tmp0 + tmp2;
  175659. z4 = tmp1 + tmp3;
  175660. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175661. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175662. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175663. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175664. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175665. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175666. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175667. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175668. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175669. z3 += z5;
  175670. z4 += z5;
  175671. tmp0 += z1 + z3;
  175672. tmp1 += z2 + z4;
  175673. tmp2 += z2 + z3;
  175674. tmp3 += z1 + z4;
  175675. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175676. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175677. CONST_BITS+PASS1_BITS+3)
  175678. & RANGE_MASK];
  175679. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175680. CONST_BITS+PASS1_BITS+3)
  175681. & RANGE_MASK];
  175682. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175683. CONST_BITS+PASS1_BITS+3)
  175684. & RANGE_MASK];
  175685. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175686. CONST_BITS+PASS1_BITS+3)
  175687. & RANGE_MASK];
  175688. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175689. CONST_BITS+PASS1_BITS+3)
  175690. & RANGE_MASK];
  175691. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175692. CONST_BITS+PASS1_BITS+3)
  175693. & RANGE_MASK];
  175694. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175695. CONST_BITS+PASS1_BITS+3)
  175696. & RANGE_MASK];
  175697. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175698. CONST_BITS+PASS1_BITS+3)
  175699. & RANGE_MASK];
  175700. wsptr += DCTSIZE; /* advance pointer to next row */
  175701. }
  175702. }
  175703. #endif /* DCT_ISLOW_SUPPORTED */
  175704. /*** End of inlined file: jidctint.c ***/
  175705. /*** Start of inlined file: jidctred.c ***/
  175706. #define JPEG_INTERNALS
  175707. #ifdef IDCT_SCALING_SUPPORTED
  175708. /*
  175709. * This module is specialized to the case DCTSIZE = 8.
  175710. */
  175711. #if DCTSIZE != 8
  175712. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175713. #endif
  175714. /* Scaling is the same as in jidctint.c. */
  175715. #if BITS_IN_JSAMPLE == 8
  175716. #define CONST_BITS 13
  175717. #define PASS1_BITS 2
  175718. #else
  175719. #define CONST_BITS 13
  175720. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175721. #endif
  175722. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175723. * causing a lot of useless floating-point operations at run time.
  175724. * To get around this we use the following pre-calculated constants.
  175725. * If you change CONST_BITS you may want to add appropriate values.
  175726. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175727. */
  175728. #if CONST_BITS == 13
  175729. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175730. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175731. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175732. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175733. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175734. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175735. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175736. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175737. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175738. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175739. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175740. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175741. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175742. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175743. #else
  175744. #define FIX_0_211164243 FIX(0.211164243)
  175745. #define FIX_0_509795579 FIX(0.509795579)
  175746. #define FIX_0_601344887 FIX(0.601344887)
  175747. #define FIX_0_720959822 FIX(0.720959822)
  175748. #define FIX_0_765366865 FIX(0.765366865)
  175749. #define FIX_0_850430095 FIX(0.850430095)
  175750. #define FIX_0_899976223 FIX(0.899976223)
  175751. #define FIX_1_061594337 FIX(1.061594337)
  175752. #define FIX_1_272758580 FIX(1.272758580)
  175753. #define FIX_1_451774981 FIX(1.451774981)
  175754. #define FIX_1_847759065 FIX(1.847759065)
  175755. #define FIX_2_172734803 FIX(2.172734803)
  175756. #define FIX_2_562915447 FIX(2.562915447)
  175757. #define FIX_3_624509785 FIX(3.624509785)
  175758. #endif
  175759. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175760. * For 8-bit samples with the recommended scaling, all the variable
  175761. * and constant values involved are no more than 16 bits wide, so a
  175762. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175763. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175764. */
  175765. #if BITS_IN_JSAMPLE == 8
  175766. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175767. #else
  175768. #define MULTIPLY(var,const) ((var) * (const))
  175769. #endif
  175770. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175771. * entry; produce an int result. In this module, both inputs and result
  175772. * are 16 bits or less, so either int or short multiply will work.
  175773. */
  175774. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175775. /*
  175776. * Perform dequantization and inverse DCT on one block of coefficients,
  175777. * producing a reduced-size 4x4 output block.
  175778. */
  175779. GLOBAL(void)
  175780. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175781. JCOEFPTR coef_block,
  175782. JSAMPARRAY output_buf, JDIMENSION output_col)
  175783. {
  175784. INT32 tmp0, tmp2, tmp10, tmp12;
  175785. INT32 z1, z2, z3, z4;
  175786. JCOEFPTR inptr;
  175787. ISLOW_MULT_TYPE * quantptr;
  175788. int * wsptr;
  175789. JSAMPROW outptr;
  175790. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175791. int ctr;
  175792. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175793. SHIFT_TEMPS
  175794. /* Pass 1: process columns from input, store into work array. */
  175795. inptr = coef_block;
  175796. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175797. wsptr = workspace;
  175798. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175799. /* Don't bother to process column 4, because second pass won't use it */
  175800. if (ctr == DCTSIZE-4)
  175801. continue;
  175802. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175803. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175804. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175805. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175806. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175807. wsptr[DCTSIZE*0] = dcval;
  175808. wsptr[DCTSIZE*1] = dcval;
  175809. wsptr[DCTSIZE*2] = dcval;
  175810. wsptr[DCTSIZE*3] = dcval;
  175811. continue;
  175812. }
  175813. /* Even part */
  175814. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175815. tmp0 <<= (CONST_BITS+1);
  175816. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175817. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175818. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175819. tmp10 = tmp0 + tmp2;
  175820. tmp12 = tmp0 - tmp2;
  175821. /* Odd part */
  175822. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175823. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175824. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175825. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175826. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175827. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175828. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175829. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175830. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175831. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175832. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175833. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175834. /* Final output stage */
  175835. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175836. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175837. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175838. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175839. }
  175840. /* Pass 2: process 4 rows from work array, store into output array. */
  175841. wsptr = workspace;
  175842. for (ctr = 0; ctr < 4; ctr++) {
  175843. outptr = output_buf[ctr] + output_col;
  175844. /* It's not clear whether a zero row test is worthwhile here ... */
  175845. #ifndef NO_ZERO_ROW_TEST
  175846. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175847. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175848. /* AC terms all zero */
  175849. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175850. & RANGE_MASK];
  175851. outptr[0] = dcval;
  175852. outptr[1] = dcval;
  175853. outptr[2] = dcval;
  175854. outptr[3] = dcval;
  175855. wsptr += DCTSIZE; /* advance pointer to next row */
  175856. continue;
  175857. }
  175858. #endif
  175859. /* Even part */
  175860. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175861. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175862. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175863. tmp10 = tmp0 + tmp2;
  175864. tmp12 = tmp0 - tmp2;
  175865. /* Odd part */
  175866. z1 = (INT32) wsptr[7];
  175867. z2 = (INT32) wsptr[5];
  175868. z3 = (INT32) wsptr[3];
  175869. z4 = (INT32) wsptr[1];
  175870. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175871. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175872. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175873. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175874. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175875. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175876. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175877. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175878. /* Final output stage */
  175879. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175880. CONST_BITS+PASS1_BITS+3+1)
  175881. & RANGE_MASK];
  175882. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175883. CONST_BITS+PASS1_BITS+3+1)
  175884. & RANGE_MASK];
  175885. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175886. CONST_BITS+PASS1_BITS+3+1)
  175887. & RANGE_MASK];
  175888. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175889. CONST_BITS+PASS1_BITS+3+1)
  175890. & RANGE_MASK];
  175891. wsptr += DCTSIZE; /* advance pointer to next row */
  175892. }
  175893. }
  175894. /*
  175895. * Perform dequantization and inverse DCT on one block of coefficients,
  175896. * producing a reduced-size 2x2 output block.
  175897. */
  175898. GLOBAL(void)
  175899. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175900. JCOEFPTR coef_block,
  175901. JSAMPARRAY output_buf, JDIMENSION output_col)
  175902. {
  175903. INT32 tmp0, tmp10, z1;
  175904. JCOEFPTR inptr;
  175905. ISLOW_MULT_TYPE * quantptr;
  175906. int * wsptr;
  175907. JSAMPROW outptr;
  175908. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175909. int ctr;
  175910. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175911. SHIFT_TEMPS
  175912. /* Pass 1: process columns from input, store into work array. */
  175913. inptr = coef_block;
  175914. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175915. wsptr = workspace;
  175916. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175917. /* Don't bother to process columns 2,4,6 */
  175918. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175919. continue;
  175920. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175921. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175922. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175923. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175924. wsptr[DCTSIZE*0] = dcval;
  175925. wsptr[DCTSIZE*1] = dcval;
  175926. continue;
  175927. }
  175928. /* Even part */
  175929. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175930. tmp10 = z1 << (CONST_BITS+2);
  175931. /* Odd part */
  175932. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175933. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175934. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175935. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175936. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175937. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175938. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175939. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175940. /* Final output stage */
  175941. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175942. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175943. }
  175944. /* Pass 2: process 2 rows from work array, store into output array. */
  175945. wsptr = workspace;
  175946. for (ctr = 0; ctr < 2; ctr++) {
  175947. outptr = output_buf[ctr] + output_col;
  175948. /* It's not clear whether a zero row test is worthwhile here ... */
  175949. #ifndef NO_ZERO_ROW_TEST
  175950. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175951. /* AC terms all zero */
  175952. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175953. & RANGE_MASK];
  175954. outptr[0] = dcval;
  175955. outptr[1] = dcval;
  175956. wsptr += DCTSIZE; /* advance pointer to next row */
  175957. continue;
  175958. }
  175959. #endif
  175960. /* Even part */
  175961. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175962. /* Odd part */
  175963. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175964. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175965. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175966. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175967. /* Final output stage */
  175968. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175969. CONST_BITS+PASS1_BITS+3+2)
  175970. & RANGE_MASK];
  175971. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175972. CONST_BITS+PASS1_BITS+3+2)
  175973. & RANGE_MASK];
  175974. wsptr += DCTSIZE; /* advance pointer to next row */
  175975. }
  175976. }
  175977. /*
  175978. * Perform dequantization and inverse DCT on one block of coefficients,
  175979. * producing a reduced-size 1x1 output block.
  175980. */
  175981. GLOBAL(void)
  175982. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175983. JCOEFPTR coef_block,
  175984. JSAMPARRAY output_buf, JDIMENSION output_col)
  175985. {
  175986. int dcval;
  175987. ISLOW_MULT_TYPE * quantptr;
  175988. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175989. SHIFT_TEMPS
  175990. /* We hardly need an inverse DCT routine for this: just take the
  175991. * average pixel value, which is one-eighth of the DC coefficient.
  175992. */
  175993. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175994. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175995. dcval = (int) DESCALE((INT32) dcval, 3);
  175996. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175997. }
  175998. #endif /* IDCT_SCALING_SUPPORTED */
  175999. /*** End of inlined file: jidctred.c ***/
  176000. /*** Start of inlined file: jmemmgr.c ***/
  176001. #define JPEG_INTERNALS
  176002. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  176003. /*** Start of inlined file: jmemsys.h ***/
  176004. #ifndef __jmemsys_h__
  176005. #define __jmemsys_h__
  176006. /* Short forms of external names for systems with brain-damaged linkers. */
  176007. #ifdef NEED_SHORT_EXTERNAL_NAMES
  176008. #define jpeg_get_small jGetSmall
  176009. #define jpeg_free_small jFreeSmall
  176010. #define jpeg_get_large jGetLarge
  176011. #define jpeg_free_large jFreeLarge
  176012. #define jpeg_mem_available jMemAvail
  176013. #define jpeg_open_backing_store jOpenBackStore
  176014. #define jpeg_mem_init jMemInit
  176015. #define jpeg_mem_term jMemTerm
  176016. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176017. /*
  176018. * These two functions are used to allocate and release small chunks of
  176019. * memory. (Typically the total amount requested through jpeg_get_small is
  176020. * no more than 20K or so; this will be requested in chunks of a few K each.)
  176021. * Behavior should be the same as for the standard library functions malloc
  176022. * and free; in particular, jpeg_get_small must return NULL on failure.
  176023. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  176024. * size of the object being freed, just in case it's needed.
  176025. * On an 80x86 machine using small-data memory model, these manage near heap.
  176026. */
  176027. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176028. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176029. size_t sizeofobject));
  176030. /*
  176031. * These two functions are used to allocate and release large chunks of
  176032. * memory (up to the total free space designated by jpeg_mem_available).
  176033. * The interface is the same as above, except that on an 80x86 machine,
  176034. * far pointers are used. On most other machines these are identical to
  176035. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176036. * in case a different allocation strategy is desirable for large chunks.
  176037. */
  176038. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176039. size_t sizeofobject));
  176040. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176041. size_t sizeofobject));
  176042. /*
  176043. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176044. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176045. * matter, but that case should never come into play). This macro is needed
  176046. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176047. * On those machines, we expect that jconfig.h will provide a proper value.
  176048. * On machines with 32-bit flat address spaces, any large constant may be used.
  176049. *
  176050. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176051. * size_t and will be a multiple of sizeof(align_type).
  176052. */
  176053. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176054. #define MAX_ALLOC_CHUNK 1000000000L
  176055. #endif
  176056. /*
  176057. * This routine computes the total space still available for allocation by
  176058. * jpeg_get_large. If more space than this is needed, backing store will be
  176059. * used. NOTE: any memory already allocated must not be counted.
  176060. *
  176061. * There is a minimum space requirement, corresponding to the minimum
  176062. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176063. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176064. * all working storage in memory, is also passed in case it is useful.
  176065. * Finally, the total space already allocated is passed. If no better
  176066. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176067. * is often a suitable calculation.
  176068. *
  176069. * It is OK for jpeg_mem_available to underestimate the space available
  176070. * (that'll just lead to more backing-store access than is really necessary).
  176071. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176072. * a slop factor from the true available space. 5% should be enough.
  176073. *
  176074. * On machines with lots of virtual memory, any large constant may be returned.
  176075. * Conversely, zero may be returned to always use the minimum amount of memory.
  176076. */
  176077. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176078. long min_bytes_needed,
  176079. long max_bytes_needed,
  176080. long already_allocated));
  176081. /*
  176082. * This structure holds whatever state is needed to access a single
  176083. * backing-store object. The read/write/close method pointers are called
  176084. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176085. * are private to the system-dependent backing store routines.
  176086. */
  176087. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176088. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176089. typedef unsigned short XMSH; /* type of extended-memory handles */
  176090. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176091. typedef union {
  176092. short file_handle; /* DOS file handle if it's a temp file */
  176093. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176094. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176095. } handle_union;
  176096. #endif /* USE_MSDOS_MEMMGR */
  176097. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176098. #include <Files.h>
  176099. #endif /* USE_MAC_MEMMGR */
  176100. //typedef struct backing_store_struct * backing_store_ptr;
  176101. typedef struct backing_store_struct {
  176102. /* Methods for reading/writing/closing this backing-store object */
  176103. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176104. struct backing_store_struct *info,
  176105. void FAR * buffer_address,
  176106. long file_offset, long byte_count));
  176107. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176108. struct backing_store_struct *info,
  176109. void FAR * buffer_address,
  176110. long file_offset, long byte_count));
  176111. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176112. struct backing_store_struct *info));
  176113. /* Private fields for system-dependent backing-store management */
  176114. #ifdef USE_MSDOS_MEMMGR
  176115. /* For the MS-DOS manager (jmemdos.c), we need: */
  176116. handle_union handle; /* reference to backing-store storage object */
  176117. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176118. #else
  176119. #ifdef USE_MAC_MEMMGR
  176120. /* For the Mac manager (jmemmac.c), we need: */
  176121. short temp_file; /* file reference number to temp file */
  176122. FSSpec tempSpec; /* the FSSpec for the temp file */
  176123. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176124. #else
  176125. /* For a typical implementation with temp files, we need: */
  176126. FILE * temp_file; /* stdio reference to temp file */
  176127. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176128. #endif
  176129. #endif
  176130. } backing_store_info;
  176131. /*
  176132. * Initial opening of a backing-store object. This must fill in the
  176133. * read/write/close pointers in the object. The read/write routines
  176134. * may take an error exit if the specified maximum file size is exceeded.
  176135. * (If jpeg_mem_available always returns a large value, this routine can
  176136. * just take an error exit.)
  176137. */
  176138. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176139. struct backing_store_struct *info,
  176140. long total_bytes_needed));
  176141. /*
  176142. * These routines take care of any system-dependent initialization and
  176143. * cleanup required. jpeg_mem_init will be called before anything is
  176144. * allocated (and, therefore, nothing in cinfo is of use except the error
  176145. * manager pointer). It should return a suitable default value for
  176146. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176147. * application. (Note that max_memory_to_use is only important if
  176148. * jpeg_mem_available chooses to consult it ... no one else will.)
  176149. * jpeg_mem_term may assume that all requested memory has been freed and that
  176150. * all opened backing-store objects have been closed.
  176151. */
  176152. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176153. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176154. #endif
  176155. /*** End of inlined file: jmemsys.h ***/
  176156. /* import the system-dependent declarations */
  176157. #ifndef NO_GETENV
  176158. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176159. extern char * getenv JPP((const char * name));
  176160. #endif
  176161. #endif
  176162. /*
  176163. * Some important notes:
  176164. * The allocation routines provided here must never return NULL.
  176165. * They should exit to error_exit if unsuccessful.
  176166. *
  176167. * It's not a good idea to try to merge the sarray and barray routines,
  176168. * even though they are textually almost the same, because samples are
  176169. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176170. * in machines where byte pointers have a different representation from
  176171. * word pointers, the resulting machine code could not be the same.
  176172. */
  176173. /*
  176174. * Many machines require storage alignment: longs must start on 4-byte
  176175. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176176. * always returns pointers that are multiples of the worst-case alignment
  176177. * requirement, and we had better do so too.
  176178. * There isn't any really portable way to determine the worst-case alignment
  176179. * requirement. This module assumes that the alignment requirement is
  176180. * multiples of sizeof(ALIGN_TYPE).
  176181. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176182. * workstations (where doubles really do need 8-byte alignment) and will work
  176183. * fine on nearly everything. If your machine has lesser alignment needs,
  176184. * you can save a few bytes by making ALIGN_TYPE smaller.
  176185. * The only place I know of where this will NOT work is certain Macintosh
  176186. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176187. * Doing 10-byte alignment is counterproductive because longwords won't be
  176188. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176189. * such a compiler.
  176190. */
  176191. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176192. #define ALIGN_TYPE double
  176193. #endif
  176194. /*
  176195. * We allocate objects from "pools", where each pool is gotten with a single
  176196. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176197. * overhead within a pool, except for alignment padding. Each pool has a
  176198. * header with a link to the next pool of the same class.
  176199. * Small and large pool headers are identical except that the latter's
  176200. * link pointer must be FAR on 80x86 machines.
  176201. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176202. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176203. * of the alignment requirement of ALIGN_TYPE.
  176204. */
  176205. typedef union small_pool_struct * small_pool_ptr;
  176206. typedef union small_pool_struct {
  176207. struct {
  176208. small_pool_ptr next; /* next in list of pools */
  176209. size_t bytes_used; /* how many bytes already used within pool */
  176210. size_t bytes_left; /* bytes still available in this pool */
  176211. } hdr;
  176212. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176213. } small_pool_hdr;
  176214. typedef union large_pool_struct FAR * large_pool_ptr;
  176215. typedef union large_pool_struct {
  176216. struct {
  176217. large_pool_ptr next; /* next in list of pools */
  176218. size_t bytes_used; /* how many bytes already used within pool */
  176219. size_t bytes_left; /* bytes still available in this pool */
  176220. } hdr;
  176221. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176222. } large_pool_hdr;
  176223. /*
  176224. * Here is the full definition of a memory manager object.
  176225. */
  176226. typedef struct {
  176227. struct jpeg_memory_mgr pub; /* public fields */
  176228. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176229. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176230. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176231. /* Since we only have one lifetime class of virtual arrays, only one
  176232. * linked list is necessary (for each datatype). Note that the virtual
  176233. * array control blocks being linked together are actually stored somewhere
  176234. * in the small-pool list.
  176235. */
  176236. jvirt_sarray_ptr virt_sarray_list;
  176237. jvirt_barray_ptr virt_barray_list;
  176238. /* This counts total space obtained from jpeg_get_small/large */
  176239. long total_space_allocated;
  176240. /* alloc_sarray and alloc_barray set this value for use by virtual
  176241. * array routines.
  176242. */
  176243. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176244. } my_memory_mgr;
  176245. typedef my_memory_mgr * my_mem_ptr;
  176246. /*
  176247. * The control blocks for virtual arrays.
  176248. * Note that these blocks are allocated in the "small" pool area.
  176249. * System-dependent info for the associated backing store (if any) is hidden
  176250. * inside the backing_store_info struct.
  176251. */
  176252. struct jvirt_sarray_control {
  176253. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176254. JDIMENSION rows_in_array; /* total virtual array height */
  176255. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176256. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176257. JDIMENSION rows_in_mem; /* height of memory buffer */
  176258. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176259. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176260. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176261. boolean pre_zero; /* pre-zero mode requested? */
  176262. boolean dirty; /* do current buffer contents need written? */
  176263. boolean b_s_open; /* is backing-store data valid? */
  176264. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176265. backing_store_info b_s_info; /* System-dependent control info */
  176266. };
  176267. struct jvirt_barray_control {
  176268. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176269. JDIMENSION rows_in_array; /* total virtual array height */
  176270. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176271. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176272. JDIMENSION rows_in_mem; /* height of memory buffer */
  176273. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176274. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176275. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176276. boolean pre_zero; /* pre-zero mode requested? */
  176277. boolean dirty; /* do current buffer contents need written? */
  176278. boolean b_s_open; /* is backing-store data valid? */
  176279. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176280. backing_store_info b_s_info; /* System-dependent control info */
  176281. };
  176282. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176283. LOCAL(void)
  176284. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176285. {
  176286. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176287. small_pool_ptr shdr_ptr;
  176288. large_pool_ptr lhdr_ptr;
  176289. /* Since this is only a debugging stub, we can cheat a little by using
  176290. * fprintf directly rather than going through the trace message code.
  176291. * This is helpful because message parm array can't handle longs.
  176292. */
  176293. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176294. pool_id, mem->total_space_allocated);
  176295. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176296. lhdr_ptr = lhdr_ptr->hdr.next) {
  176297. fprintf(stderr, " Large chunk used %ld\n",
  176298. (long) lhdr_ptr->hdr.bytes_used);
  176299. }
  176300. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176301. shdr_ptr = shdr_ptr->hdr.next) {
  176302. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176303. (long) shdr_ptr->hdr.bytes_used,
  176304. (long) shdr_ptr->hdr.bytes_left);
  176305. }
  176306. }
  176307. #endif /* MEM_STATS */
  176308. LOCAL(void)
  176309. out_of_memory (j_common_ptr cinfo, int which)
  176310. /* Report an out-of-memory error and stop execution */
  176311. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176312. {
  176313. #ifdef MEM_STATS
  176314. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176315. #endif
  176316. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176317. }
  176318. /*
  176319. * Allocation of "small" objects.
  176320. *
  176321. * For these, we use pooled storage. When a new pool must be created,
  176322. * we try to get enough space for the current request plus a "slop" factor,
  176323. * where the slop will be the amount of leftover space in the new pool.
  176324. * The speed vs. space tradeoff is largely determined by the slop values.
  176325. * A different slop value is provided for each pool class (lifetime),
  176326. * and we also distinguish the first pool of a class from later ones.
  176327. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176328. * machines, but may be too small if longs are 64 bits or more.
  176329. */
  176330. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176331. {
  176332. 1600, /* first PERMANENT pool */
  176333. 16000 /* first IMAGE pool */
  176334. };
  176335. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176336. {
  176337. 0, /* additional PERMANENT pools */
  176338. 5000 /* additional IMAGE pools */
  176339. };
  176340. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176341. METHODDEF(void *)
  176342. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176343. /* Allocate a "small" object */
  176344. {
  176345. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176346. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176347. char * data_ptr;
  176348. size_t odd_bytes, min_request, slop;
  176349. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176350. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176351. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176352. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176353. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176354. if (odd_bytes > 0)
  176355. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176356. /* See if space is available in any existing pool */
  176357. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176358. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176359. prev_hdr_ptr = NULL;
  176360. hdr_ptr = mem->small_list[pool_id];
  176361. while (hdr_ptr != NULL) {
  176362. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176363. break; /* found pool with enough space */
  176364. prev_hdr_ptr = hdr_ptr;
  176365. hdr_ptr = hdr_ptr->hdr.next;
  176366. }
  176367. /* Time to make a new pool? */
  176368. if (hdr_ptr == NULL) {
  176369. /* min_request is what we need now, slop is what will be leftover */
  176370. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176371. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176372. slop = first_pool_slop[pool_id];
  176373. else
  176374. slop = extra_pool_slop[pool_id];
  176375. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176376. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176377. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176378. /* Try to get space, if fail reduce slop and try again */
  176379. for (;;) {
  176380. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176381. if (hdr_ptr != NULL)
  176382. break;
  176383. slop /= 2;
  176384. if (slop < MIN_SLOP) /* give up when it gets real small */
  176385. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176386. }
  176387. mem->total_space_allocated += min_request + slop;
  176388. /* Success, initialize the new pool header and add to end of list */
  176389. hdr_ptr->hdr.next = NULL;
  176390. hdr_ptr->hdr.bytes_used = 0;
  176391. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176392. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176393. mem->small_list[pool_id] = hdr_ptr;
  176394. else
  176395. prev_hdr_ptr->hdr.next = hdr_ptr;
  176396. }
  176397. /* OK, allocate the object from the current pool */
  176398. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176399. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176400. hdr_ptr->hdr.bytes_used += sizeofobject;
  176401. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176402. return (void *) data_ptr;
  176403. }
  176404. /*
  176405. * Allocation of "large" objects.
  176406. *
  176407. * The external semantics of these are the same as "small" objects,
  176408. * except that FAR pointers are used on 80x86. However the pool
  176409. * management heuristics are quite different. We assume that each
  176410. * request is large enough that it may as well be passed directly to
  176411. * jpeg_get_large; the pool management just links everything together
  176412. * so that we can free it all on demand.
  176413. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176414. * structures. The routines that create these structures (see below)
  176415. * deliberately bunch rows together to ensure a large request size.
  176416. */
  176417. METHODDEF(void FAR *)
  176418. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176419. /* Allocate a "large" object */
  176420. {
  176421. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176422. large_pool_ptr hdr_ptr;
  176423. size_t odd_bytes;
  176424. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176425. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176426. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176427. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176428. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176429. if (odd_bytes > 0)
  176430. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176431. /* Always make a new pool */
  176432. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176433. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176434. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176435. SIZEOF(large_pool_hdr));
  176436. if (hdr_ptr == NULL)
  176437. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176438. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176439. /* Success, initialize the new pool header and add to list */
  176440. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176441. /* We maintain space counts in each pool header for statistical purposes,
  176442. * even though they are not needed for allocation.
  176443. */
  176444. hdr_ptr->hdr.bytes_used = sizeofobject;
  176445. hdr_ptr->hdr.bytes_left = 0;
  176446. mem->large_list[pool_id] = hdr_ptr;
  176447. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176448. }
  176449. /*
  176450. * Creation of 2-D sample arrays.
  176451. * The pointers are in near heap, the samples themselves in FAR heap.
  176452. *
  176453. * To minimize allocation overhead and to allow I/O of large contiguous
  176454. * blocks, we allocate the sample rows in groups of as many rows as possible
  176455. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176456. * NB: the virtual array control routines, later in this file, know about
  176457. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176458. * object so that it can be saved away if this sarray is the workspace for
  176459. * a virtual array.
  176460. */
  176461. METHODDEF(JSAMPARRAY)
  176462. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176463. JDIMENSION samplesperrow, JDIMENSION numrows)
  176464. /* Allocate a 2-D sample array */
  176465. {
  176466. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176467. JSAMPARRAY result;
  176468. JSAMPROW workspace;
  176469. JDIMENSION rowsperchunk, currow, i;
  176470. long ltemp;
  176471. /* Calculate max # of rows allowed in one allocation chunk */
  176472. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176473. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176474. if (ltemp <= 0)
  176475. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176476. if (ltemp < (long) numrows)
  176477. rowsperchunk = (JDIMENSION) ltemp;
  176478. else
  176479. rowsperchunk = numrows;
  176480. mem->last_rowsperchunk = rowsperchunk;
  176481. /* Get space for row pointers (small object) */
  176482. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176483. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176484. /* Get the rows themselves (large objects) */
  176485. currow = 0;
  176486. while (currow < numrows) {
  176487. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176488. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176489. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176490. * SIZEOF(JSAMPLE)));
  176491. for (i = rowsperchunk; i > 0; i--) {
  176492. result[currow++] = workspace;
  176493. workspace += samplesperrow;
  176494. }
  176495. }
  176496. return result;
  176497. }
  176498. /*
  176499. * Creation of 2-D coefficient-block arrays.
  176500. * This is essentially the same as the code for sample arrays, above.
  176501. */
  176502. METHODDEF(JBLOCKARRAY)
  176503. alloc_barray (j_common_ptr cinfo, int pool_id,
  176504. JDIMENSION blocksperrow, JDIMENSION numrows)
  176505. /* Allocate a 2-D coefficient-block array */
  176506. {
  176507. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176508. JBLOCKARRAY result;
  176509. JBLOCKROW workspace;
  176510. JDIMENSION rowsperchunk, currow, i;
  176511. long ltemp;
  176512. /* Calculate max # of rows allowed in one allocation chunk */
  176513. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176514. ((long) blocksperrow * SIZEOF(JBLOCK));
  176515. if (ltemp <= 0)
  176516. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176517. if (ltemp < (long) numrows)
  176518. rowsperchunk = (JDIMENSION) ltemp;
  176519. else
  176520. rowsperchunk = numrows;
  176521. mem->last_rowsperchunk = rowsperchunk;
  176522. /* Get space for row pointers (small object) */
  176523. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176524. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176525. /* Get the rows themselves (large objects) */
  176526. currow = 0;
  176527. while (currow < numrows) {
  176528. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176529. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176530. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176531. * SIZEOF(JBLOCK)));
  176532. for (i = rowsperchunk; i > 0; i--) {
  176533. result[currow++] = workspace;
  176534. workspace += blocksperrow;
  176535. }
  176536. }
  176537. return result;
  176538. }
  176539. /*
  176540. * About virtual array management:
  176541. *
  176542. * The above "normal" array routines are only used to allocate strip buffers
  176543. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176544. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176545. * time, but the memory manager must save the whole array for repeated
  176546. * accesses. The intended implementation is that there is a strip buffer in
  176547. * memory (as high as is possible given the desired memory limit), plus a
  176548. * backing file that holds the rest of the array.
  176549. *
  176550. * The request_virt_array routines are told the total size of the image and
  176551. * the maximum number of rows that will be accessed at once. The in-memory
  176552. * buffer must be at least as large as the maxaccess value.
  176553. *
  176554. * The request routines create control blocks but not the in-memory buffers.
  176555. * That is postponed until realize_virt_arrays is called. At that time the
  176556. * total amount of space needed is known (approximately, anyway), so free
  176557. * memory can be divided up fairly.
  176558. *
  176559. * The access_virt_array routines are responsible for making a specific strip
  176560. * area accessible (after reading or writing the backing file, if necessary).
  176561. * Note that the access routines are told whether the caller intends to modify
  176562. * the accessed strip; during a read-only pass this saves having to rewrite
  176563. * data to disk. The access routines are also responsible for pre-zeroing
  176564. * any newly accessed rows, if pre-zeroing was requested.
  176565. *
  176566. * In current usage, the access requests are usually for nonoverlapping
  176567. * strips; that is, successive access start_row numbers differ by exactly
  176568. * num_rows = maxaccess. This means we can get good performance with simple
  176569. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176570. * of the access height; then there will never be accesses across bufferload
  176571. * boundaries. The code will still work with overlapping access requests,
  176572. * but it doesn't handle bufferload overlaps very efficiently.
  176573. */
  176574. METHODDEF(jvirt_sarray_ptr)
  176575. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176576. JDIMENSION samplesperrow, JDIMENSION numrows,
  176577. JDIMENSION maxaccess)
  176578. /* Request a virtual 2-D sample array */
  176579. {
  176580. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176581. jvirt_sarray_ptr result;
  176582. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176583. if (pool_id != JPOOL_IMAGE)
  176584. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176585. /* get control block */
  176586. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176587. SIZEOF(struct jvirt_sarray_control));
  176588. result->mem_buffer = NULL; /* marks array not yet realized */
  176589. result->rows_in_array = numrows;
  176590. result->samplesperrow = samplesperrow;
  176591. result->maxaccess = maxaccess;
  176592. result->pre_zero = pre_zero;
  176593. result->b_s_open = FALSE; /* no associated backing-store object */
  176594. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176595. mem->virt_sarray_list = result;
  176596. return result;
  176597. }
  176598. METHODDEF(jvirt_barray_ptr)
  176599. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176600. JDIMENSION blocksperrow, JDIMENSION numrows,
  176601. JDIMENSION maxaccess)
  176602. /* Request a virtual 2-D coefficient-block array */
  176603. {
  176604. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176605. jvirt_barray_ptr result;
  176606. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176607. if (pool_id != JPOOL_IMAGE)
  176608. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176609. /* get control block */
  176610. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176611. SIZEOF(struct jvirt_barray_control));
  176612. result->mem_buffer = NULL; /* marks array not yet realized */
  176613. result->rows_in_array = numrows;
  176614. result->blocksperrow = blocksperrow;
  176615. result->maxaccess = maxaccess;
  176616. result->pre_zero = pre_zero;
  176617. result->b_s_open = FALSE; /* no associated backing-store object */
  176618. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176619. mem->virt_barray_list = result;
  176620. return result;
  176621. }
  176622. METHODDEF(void)
  176623. realize_virt_arrays (j_common_ptr cinfo)
  176624. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176625. {
  176626. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176627. long space_per_minheight, maximum_space, avail_mem;
  176628. long minheights, max_minheights;
  176629. jvirt_sarray_ptr sptr;
  176630. jvirt_barray_ptr bptr;
  176631. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176632. * and the maximum space needed (full image height in each buffer).
  176633. * These may be of use to the system-dependent jpeg_mem_available routine.
  176634. */
  176635. space_per_minheight = 0;
  176636. maximum_space = 0;
  176637. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176638. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176639. space_per_minheight += (long) sptr->maxaccess *
  176640. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176641. maximum_space += (long) sptr->rows_in_array *
  176642. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176643. }
  176644. }
  176645. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176646. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176647. space_per_minheight += (long) bptr->maxaccess *
  176648. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176649. maximum_space += (long) bptr->rows_in_array *
  176650. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176651. }
  176652. }
  176653. if (space_per_minheight <= 0)
  176654. return; /* no unrealized arrays, no work */
  176655. /* Determine amount of memory to actually use; this is system-dependent. */
  176656. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176657. mem->total_space_allocated);
  176658. /* If the maximum space needed is available, make all the buffers full
  176659. * height; otherwise parcel it out with the same number of minheights
  176660. * in each buffer.
  176661. */
  176662. if (avail_mem >= maximum_space)
  176663. max_minheights = 1000000000L;
  176664. else {
  176665. max_minheights = avail_mem / space_per_minheight;
  176666. /* If there doesn't seem to be enough space, try to get the minimum
  176667. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176668. */
  176669. if (max_minheights <= 0)
  176670. max_minheights = 1;
  176671. }
  176672. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176673. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176674. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176675. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176676. if (minheights <= max_minheights) {
  176677. /* This buffer fits in memory */
  176678. sptr->rows_in_mem = sptr->rows_in_array;
  176679. } else {
  176680. /* It doesn't fit in memory, create backing store. */
  176681. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176682. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176683. (long) sptr->rows_in_array *
  176684. (long) sptr->samplesperrow *
  176685. (long) SIZEOF(JSAMPLE));
  176686. sptr->b_s_open = TRUE;
  176687. }
  176688. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176689. sptr->samplesperrow, sptr->rows_in_mem);
  176690. sptr->rowsperchunk = mem->last_rowsperchunk;
  176691. sptr->cur_start_row = 0;
  176692. sptr->first_undef_row = 0;
  176693. sptr->dirty = FALSE;
  176694. }
  176695. }
  176696. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176697. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176698. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176699. if (minheights <= max_minheights) {
  176700. /* This buffer fits in memory */
  176701. bptr->rows_in_mem = bptr->rows_in_array;
  176702. } else {
  176703. /* It doesn't fit in memory, create backing store. */
  176704. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176705. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176706. (long) bptr->rows_in_array *
  176707. (long) bptr->blocksperrow *
  176708. (long) SIZEOF(JBLOCK));
  176709. bptr->b_s_open = TRUE;
  176710. }
  176711. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176712. bptr->blocksperrow, bptr->rows_in_mem);
  176713. bptr->rowsperchunk = mem->last_rowsperchunk;
  176714. bptr->cur_start_row = 0;
  176715. bptr->first_undef_row = 0;
  176716. bptr->dirty = FALSE;
  176717. }
  176718. }
  176719. }
  176720. LOCAL(void)
  176721. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176722. /* Do backing store read or write of a virtual sample array */
  176723. {
  176724. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176725. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176726. file_offset = ptr->cur_start_row * bytesperrow;
  176727. /* Loop to read or write each allocation chunk in mem_buffer */
  176728. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176729. /* One chunk, but check for short chunk at end of buffer */
  176730. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176731. /* Transfer no more than is currently defined */
  176732. thisrow = (long) ptr->cur_start_row + i;
  176733. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176734. /* Transfer no more than fits in file */
  176735. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176736. if (rows <= 0) /* this chunk might be past end of file! */
  176737. break;
  176738. byte_count = rows * bytesperrow;
  176739. if (writing)
  176740. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176741. (void FAR *) ptr->mem_buffer[i],
  176742. file_offset, byte_count);
  176743. else
  176744. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176745. (void FAR *) ptr->mem_buffer[i],
  176746. file_offset, byte_count);
  176747. file_offset += byte_count;
  176748. }
  176749. }
  176750. LOCAL(void)
  176751. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176752. /* Do backing store read or write of a virtual coefficient-block array */
  176753. {
  176754. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176755. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176756. file_offset = ptr->cur_start_row * bytesperrow;
  176757. /* Loop to read or write each allocation chunk in mem_buffer */
  176758. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176759. /* One chunk, but check for short chunk at end of buffer */
  176760. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176761. /* Transfer no more than is currently defined */
  176762. thisrow = (long) ptr->cur_start_row + i;
  176763. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176764. /* Transfer no more than fits in file */
  176765. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176766. if (rows <= 0) /* this chunk might be past end of file! */
  176767. break;
  176768. byte_count = rows * bytesperrow;
  176769. if (writing)
  176770. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176771. (void FAR *) ptr->mem_buffer[i],
  176772. file_offset, byte_count);
  176773. else
  176774. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176775. (void FAR *) ptr->mem_buffer[i],
  176776. file_offset, byte_count);
  176777. file_offset += byte_count;
  176778. }
  176779. }
  176780. METHODDEF(JSAMPARRAY)
  176781. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176782. JDIMENSION start_row, JDIMENSION num_rows,
  176783. boolean writable)
  176784. /* Access the part of a virtual sample array starting at start_row */
  176785. /* and extending for num_rows rows. writable is true if */
  176786. /* caller intends to modify the accessed area. */
  176787. {
  176788. JDIMENSION end_row = start_row + num_rows;
  176789. JDIMENSION undef_row;
  176790. /* debugging check */
  176791. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176792. ptr->mem_buffer == NULL)
  176793. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176794. /* Make the desired part of the virtual array accessible */
  176795. if (start_row < ptr->cur_start_row ||
  176796. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176797. if (! ptr->b_s_open)
  176798. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176799. /* Flush old buffer contents if necessary */
  176800. if (ptr->dirty) {
  176801. do_sarray_io(cinfo, ptr, TRUE);
  176802. ptr->dirty = FALSE;
  176803. }
  176804. /* Decide what part of virtual array to access.
  176805. * Algorithm: if target address > current window, assume forward scan,
  176806. * load starting at target address. If target address < current window,
  176807. * assume backward scan, load so that target area is top of window.
  176808. * Note that when switching from forward write to forward read, will have
  176809. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176810. */
  176811. if (start_row > ptr->cur_start_row) {
  176812. ptr->cur_start_row = start_row;
  176813. } else {
  176814. /* use long arithmetic here to avoid overflow & unsigned problems */
  176815. long ltemp;
  176816. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176817. if (ltemp < 0)
  176818. ltemp = 0; /* don't fall off front end of file */
  176819. ptr->cur_start_row = (JDIMENSION) ltemp;
  176820. }
  176821. /* Read in the selected part of the array.
  176822. * During the initial write pass, we will do no actual read
  176823. * because the selected part is all undefined.
  176824. */
  176825. do_sarray_io(cinfo, ptr, FALSE);
  176826. }
  176827. /* Ensure the accessed part of the array is defined; prezero if needed.
  176828. * To improve locality of access, we only prezero the part of the array
  176829. * that the caller is about to access, not the entire in-memory array.
  176830. */
  176831. if (ptr->first_undef_row < end_row) {
  176832. if (ptr->first_undef_row < start_row) {
  176833. if (writable) /* writer skipped over a section of array */
  176834. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176835. undef_row = start_row; /* but reader is allowed to read ahead */
  176836. } else {
  176837. undef_row = ptr->first_undef_row;
  176838. }
  176839. if (writable)
  176840. ptr->first_undef_row = end_row;
  176841. if (ptr->pre_zero) {
  176842. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176843. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176844. end_row -= ptr->cur_start_row;
  176845. while (undef_row < end_row) {
  176846. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176847. undef_row++;
  176848. }
  176849. } else {
  176850. if (! writable) /* reader looking at undefined data */
  176851. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176852. }
  176853. }
  176854. /* Flag the buffer dirty if caller will write in it */
  176855. if (writable)
  176856. ptr->dirty = TRUE;
  176857. /* Return address of proper part of the buffer */
  176858. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176859. }
  176860. METHODDEF(JBLOCKARRAY)
  176861. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176862. JDIMENSION start_row, JDIMENSION num_rows,
  176863. boolean writable)
  176864. /* Access the part of a virtual block array starting at start_row */
  176865. /* and extending for num_rows rows. writable is true if */
  176866. /* caller intends to modify the accessed area. */
  176867. {
  176868. JDIMENSION end_row = start_row + num_rows;
  176869. JDIMENSION undef_row;
  176870. /* debugging check */
  176871. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176872. ptr->mem_buffer == NULL)
  176873. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176874. /* Make the desired part of the virtual array accessible */
  176875. if (start_row < ptr->cur_start_row ||
  176876. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176877. if (! ptr->b_s_open)
  176878. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176879. /* Flush old buffer contents if necessary */
  176880. if (ptr->dirty) {
  176881. do_barray_io(cinfo, ptr, TRUE);
  176882. ptr->dirty = FALSE;
  176883. }
  176884. /* Decide what part of virtual array to access.
  176885. * Algorithm: if target address > current window, assume forward scan,
  176886. * load starting at target address. If target address < current window,
  176887. * assume backward scan, load so that target area is top of window.
  176888. * Note that when switching from forward write to forward read, will have
  176889. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176890. */
  176891. if (start_row > ptr->cur_start_row) {
  176892. ptr->cur_start_row = start_row;
  176893. } else {
  176894. /* use long arithmetic here to avoid overflow & unsigned problems */
  176895. long ltemp;
  176896. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176897. if (ltemp < 0)
  176898. ltemp = 0; /* don't fall off front end of file */
  176899. ptr->cur_start_row = (JDIMENSION) ltemp;
  176900. }
  176901. /* Read in the selected part of the array.
  176902. * During the initial write pass, we will do no actual read
  176903. * because the selected part is all undefined.
  176904. */
  176905. do_barray_io(cinfo, ptr, FALSE);
  176906. }
  176907. /* Ensure the accessed part of the array is defined; prezero if needed.
  176908. * To improve locality of access, we only prezero the part of the array
  176909. * that the caller is about to access, not the entire in-memory array.
  176910. */
  176911. if (ptr->first_undef_row < end_row) {
  176912. if (ptr->first_undef_row < start_row) {
  176913. if (writable) /* writer skipped over a section of array */
  176914. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176915. undef_row = start_row; /* but reader is allowed to read ahead */
  176916. } else {
  176917. undef_row = ptr->first_undef_row;
  176918. }
  176919. if (writable)
  176920. ptr->first_undef_row = end_row;
  176921. if (ptr->pre_zero) {
  176922. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176923. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176924. end_row -= ptr->cur_start_row;
  176925. while (undef_row < end_row) {
  176926. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176927. undef_row++;
  176928. }
  176929. } else {
  176930. if (! writable) /* reader looking at undefined data */
  176931. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176932. }
  176933. }
  176934. /* Flag the buffer dirty if caller will write in it */
  176935. if (writable)
  176936. ptr->dirty = TRUE;
  176937. /* Return address of proper part of the buffer */
  176938. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176939. }
  176940. /*
  176941. * Release all objects belonging to a specified pool.
  176942. */
  176943. METHODDEF(void)
  176944. free_pool (j_common_ptr cinfo, int pool_id)
  176945. {
  176946. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176947. small_pool_ptr shdr_ptr;
  176948. large_pool_ptr lhdr_ptr;
  176949. size_t space_freed;
  176950. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176951. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176952. #ifdef MEM_STATS
  176953. if (cinfo->err->trace_level > 1)
  176954. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176955. #endif
  176956. /* If freeing IMAGE pool, close any virtual arrays first */
  176957. if (pool_id == JPOOL_IMAGE) {
  176958. jvirt_sarray_ptr sptr;
  176959. jvirt_barray_ptr bptr;
  176960. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176961. if (sptr->b_s_open) { /* there may be no backing store */
  176962. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176963. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176964. }
  176965. }
  176966. mem->virt_sarray_list = NULL;
  176967. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176968. if (bptr->b_s_open) { /* there may be no backing store */
  176969. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176970. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176971. }
  176972. }
  176973. mem->virt_barray_list = NULL;
  176974. }
  176975. /* Release large objects */
  176976. lhdr_ptr = mem->large_list[pool_id];
  176977. mem->large_list[pool_id] = NULL;
  176978. while (lhdr_ptr != NULL) {
  176979. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176980. space_freed = lhdr_ptr->hdr.bytes_used +
  176981. lhdr_ptr->hdr.bytes_left +
  176982. SIZEOF(large_pool_hdr);
  176983. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176984. mem->total_space_allocated -= space_freed;
  176985. lhdr_ptr = next_lhdr_ptr;
  176986. }
  176987. /* Release small objects */
  176988. shdr_ptr = mem->small_list[pool_id];
  176989. mem->small_list[pool_id] = NULL;
  176990. while (shdr_ptr != NULL) {
  176991. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176992. space_freed = shdr_ptr->hdr.bytes_used +
  176993. shdr_ptr->hdr.bytes_left +
  176994. SIZEOF(small_pool_hdr);
  176995. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176996. mem->total_space_allocated -= space_freed;
  176997. shdr_ptr = next_shdr_ptr;
  176998. }
  176999. }
  177000. /*
  177001. * Close up shop entirely.
  177002. * Note that this cannot be called unless cinfo->mem is non-NULL.
  177003. */
  177004. METHODDEF(void)
  177005. self_destruct (j_common_ptr cinfo)
  177006. {
  177007. int pool;
  177008. /* Close all backing store, release all memory.
  177009. * Releasing pools in reverse order might help avoid fragmentation
  177010. * with some (brain-damaged) malloc libraries.
  177011. */
  177012. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177013. free_pool(cinfo, pool);
  177014. }
  177015. /* Release the memory manager control block too. */
  177016. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  177017. cinfo->mem = NULL; /* ensures I will be called only once */
  177018. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177019. }
  177020. /*
  177021. * Memory manager initialization.
  177022. * When this is called, only the error manager pointer is valid in cinfo!
  177023. */
  177024. GLOBAL(void)
  177025. jinit_memory_mgr (j_common_ptr cinfo)
  177026. {
  177027. my_mem_ptr mem;
  177028. long max_to_use;
  177029. int pool;
  177030. size_t test_mac;
  177031. cinfo->mem = NULL; /* for safety if init fails */
  177032. /* Check for configuration errors.
  177033. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177034. * doesn't reflect any real hardware alignment requirement.
  177035. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177036. * in common if and only if X is a power of 2, ie has only one one-bit.
  177037. * Some compilers may give an "unreachable code" warning here; ignore it.
  177038. */
  177039. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177040. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177041. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177042. * a multiple of SIZEOF(ALIGN_TYPE).
  177043. * Again, an "unreachable code" warning may be ignored here.
  177044. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177045. */
  177046. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177047. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177048. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177049. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177050. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177051. /* Attempt to allocate memory manager's control block */
  177052. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177053. if (mem == NULL) {
  177054. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177055. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177056. }
  177057. /* OK, fill in the method pointers */
  177058. mem->pub.alloc_small = alloc_small;
  177059. mem->pub.alloc_large = alloc_large;
  177060. mem->pub.alloc_sarray = alloc_sarray;
  177061. mem->pub.alloc_barray = alloc_barray;
  177062. mem->pub.request_virt_sarray = request_virt_sarray;
  177063. mem->pub.request_virt_barray = request_virt_barray;
  177064. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177065. mem->pub.access_virt_sarray = access_virt_sarray;
  177066. mem->pub.access_virt_barray = access_virt_barray;
  177067. mem->pub.free_pool = free_pool;
  177068. mem->pub.self_destruct = self_destruct;
  177069. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177070. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177071. /* Initialize working state */
  177072. mem->pub.max_memory_to_use = max_to_use;
  177073. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177074. mem->small_list[pool] = NULL;
  177075. mem->large_list[pool] = NULL;
  177076. }
  177077. mem->virt_sarray_list = NULL;
  177078. mem->virt_barray_list = NULL;
  177079. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177080. /* Declare ourselves open for business */
  177081. cinfo->mem = & mem->pub;
  177082. /* Check for an environment variable JPEGMEM; if found, override the
  177083. * default max_memory setting from jpeg_mem_init. Note that the
  177084. * surrounding application may again override this value.
  177085. * If your system doesn't support getenv(), define NO_GETENV to disable
  177086. * this feature.
  177087. */
  177088. #ifndef NO_GETENV
  177089. { char * memenv;
  177090. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177091. char ch = 'x';
  177092. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177093. if (ch == 'm' || ch == 'M')
  177094. max_to_use *= 1000L;
  177095. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177096. }
  177097. }
  177098. }
  177099. #endif
  177100. }
  177101. /*** End of inlined file: jmemmgr.c ***/
  177102. /*** Start of inlined file: jmemnobs.c ***/
  177103. #define JPEG_INTERNALS
  177104. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177105. extern void * malloc JPP((size_t size));
  177106. extern void free JPP((void *ptr));
  177107. #endif
  177108. /*
  177109. * Memory allocation and freeing are controlled by the regular library
  177110. * routines malloc() and free().
  177111. */
  177112. GLOBAL(void *)
  177113. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177114. {
  177115. return (void *) malloc(sizeofobject);
  177116. }
  177117. GLOBAL(void)
  177118. jpeg_free_small (j_common_ptr , void * object, size_t)
  177119. {
  177120. free(object);
  177121. }
  177122. /*
  177123. * "Large" objects are treated the same as "small" ones.
  177124. * NB: although we include FAR keywords in the routine declarations,
  177125. * this file won't actually work in 80x86 small/medium model; at least,
  177126. * you probably won't be able to process useful-size images in only 64KB.
  177127. */
  177128. GLOBAL(void FAR *)
  177129. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177130. {
  177131. return (void FAR *) malloc(sizeofobject);
  177132. }
  177133. GLOBAL(void)
  177134. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177135. {
  177136. free(object);
  177137. }
  177138. /*
  177139. * This routine computes the total memory space available for allocation.
  177140. * Here we always say, "we got all you want bud!"
  177141. */
  177142. GLOBAL(long)
  177143. jpeg_mem_available (j_common_ptr, long,
  177144. long max_bytes_needed, long)
  177145. {
  177146. return max_bytes_needed;
  177147. }
  177148. /*
  177149. * Backing store (temporary file) management.
  177150. * Since jpeg_mem_available always promised the moon,
  177151. * this should never be called and we can just error out.
  177152. */
  177153. GLOBAL(void)
  177154. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177155. long )
  177156. {
  177157. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177158. }
  177159. /*
  177160. * These routines take care of any system-dependent initialization and
  177161. * cleanup required. Here, there isn't any.
  177162. */
  177163. GLOBAL(long)
  177164. jpeg_mem_init (j_common_ptr)
  177165. {
  177166. return 0; /* just set max_memory_to_use to 0 */
  177167. }
  177168. GLOBAL(void)
  177169. jpeg_mem_term (j_common_ptr)
  177170. {
  177171. /* no work */
  177172. }
  177173. /*** End of inlined file: jmemnobs.c ***/
  177174. /*** Start of inlined file: jquant1.c ***/
  177175. #define JPEG_INTERNALS
  177176. #ifdef QUANT_1PASS_SUPPORTED
  177177. /*
  177178. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177179. * high quality, colormapped output capability. A 2-pass quantizer usually
  177180. * gives better visual quality; however, for quantized grayscale output this
  177181. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177182. * quantizer, though you can turn it off if you really want to.
  177183. *
  177184. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177185. * image. We use a map consisting of all combinations of Ncolors[i] color
  177186. * values for the i'th component. The Ncolors[] values are chosen so that
  177187. * their product, the total number of colors, is no more than that requested.
  177188. * (In most cases, the product will be somewhat less.)
  177189. *
  177190. * Since the colormap is orthogonal, the representative value for each color
  177191. * component can be determined without considering the other components;
  177192. * then these indexes can be combined into a colormap index by a standard
  177193. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177194. * can be precalculated and stored in the lookup table colorindex[].
  177195. * colorindex[i][j] maps pixel value j in component i to the nearest
  177196. * representative value (grid plane) for that component; this index is
  177197. * multiplied by the array stride for component i, so that the
  177198. * index of the colormap entry closest to a given pixel value is just
  177199. * sum( colorindex[component-number][pixel-component-value] )
  177200. * Aside from being fast, this scheme allows for variable spacing between
  177201. * representative values with no additional lookup cost.
  177202. *
  177203. * If gamma correction has been applied in color conversion, it might be wise
  177204. * to adjust the color grid spacing so that the representative colors are
  177205. * equidistant in linear space. At this writing, gamma correction is not
  177206. * implemented by jdcolor, so nothing is done here.
  177207. */
  177208. /* Declarations for ordered dithering.
  177209. *
  177210. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177211. * dithering is described in many references, for instance Dale Schumacher's
  177212. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177213. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177214. * "dither" value to the input pixel and then round the result to the nearest
  177215. * output value. The dither value is equivalent to (0.5 - threshold) times
  177216. * the distance between output values. For ordered dithering, we assume that
  177217. * the output colors are equally spaced; if not, results will probably be
  177218. * worse, since the dither may be too much or too little at a given point.
  177219. *
  177220. * The normal calculation would be to form pixel value + dither, range-limit
  177221. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177222. * We can skip the separate range-limiting step by extending the colorindex
  177223. * table in both directions.
  177224. */
  177225. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177226. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177227. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177228. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177229. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177230. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177231. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177232. /* Bayer's order-4 dither array. Generated by the code given in
  177233. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177234. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177235. */
  177236. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177237. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177238. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177239. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177240. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177241. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177242. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177243. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177244. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177245. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177246. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177247. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177248. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177249. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177250. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177251. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177252. };
  177253. /* Declarations for Floyd-Steinberg dithering.
  177254. *
  177255. * Errors are accumulated into the array fserrors[], at a resolution of
  177256. * 1/16th of a pixel count. The error at a given pixel is propagated
  177257. * to its not-yet-processed neighbors using the standard F-S fractions,
  177258. * ... (here) 7/16
  177259. * 3/16 5/16 1/16
  177260. * We work left-to-right on even rows, right-to-left on odd rows.
  177261. *
  177262. * We can get away with a single array (holding one row's worth of errors)
  177263. * by using it to store the current row's errors at pixel columns not yet
  177264. * processed, but the next row's errors at columns already processed. We
  177265. * need only a few extra variables to hold the errors immediately around the
  177266. * current column. (If we are lucky, those variables are in registers, but
  177267. * even if not, they're probably cheaper to access than array elements are.)
  177268. *
  177269. * The fserrors[] array is indexed [component#][position].
  177270. * We provide (#columns + 2) entries per component; the extra entry at each
  177271. * end saves us from special-casing the first and last pixels.
  177272. *
  177273. * Note: on a wide image, we might not have enough room in a PC's near data
  177274. * segment to hold the error array; so it is allocated with alloc_large.
  177275. */
  177276. #if BITS_IN_JSAMPLE == 8
  177277. typedef INT16 FSERROR; /* 16 bits should be enough */
  177278. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177279. #else
  177280. typedef INT32 FSERROR; /* may need more than 16 bits */
  177281. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177282. #endif
  177283. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177284. /* Private subobject */
  177285. #define MAX_Q_COMPS 4 /* max components I can handle */
  177286. typedef struct {
  177287. struct jpeg_color_quantizer pub; /* public fields */
  177288. /* Initially allocated colormap is saved here */
  177289. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177290. int sv_actual; /* number of entries in use */
  177291. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177292. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177293. * premultiplied as described above. Since colormap indexes must fit into
  177294. * JSAMPLEs, the entries of this array will too.
  177295. */
  177296. boolean is_padded; /* is the colorindex padded for odither? */
  177297. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177298. /* Variables for ordered dithering */
  177299. int row_index; /* cur row's vertical index in dither matrix */
  177300. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177301. /* Variables for Floyd-Steinberg dithering */
  177302. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177303. boolean on_odd_row; /* flag to remember which row we are on */
  177304. } my_cquantizer;
  177305. typedef my_cquantizer * my_cquantize_ptr;
  177306. /*
  177307. * Policy-making subroutines for create_colormap and create_colorindex.
  177308. * These routines determine the colormap to be used. The rest of the module
  177309. * only assumes that the colormap is orthogonal.
  177310. *
  177311. * * select_ncolors decides how to divvy up the available colors
  177312. * among the components.
  177313. * * output_value defines the set of representative values for a component.
  177314. * * largest_input_value defines the mapping from input values to
  177315. * representative values for a component.
  177316. * Note that the latter two routines may impose different policies for
  177317. * different components, though this is not currently done.
  177318. */
  177319. LOCAL(int)
  177320. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177321. /* Determine allocation of desired colors to components, */
  177322. /* and fill in Ncolors[] array to indicate choice. */
  177323. /* Return value is total number of colors (product of Ncolors[] values). */
  177324. {
  177325. int nc = cinfo->out_color_components; /* number of color components */
  177326. int max_colors = cinfo->desired_number_of_colors;
  177327. int total_colors, iroot, i, j;
  177328. boolean changed;
  177329. long temp;
  177330. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177331. /* We can allocate at least the nc'th root of max_colors per component. */
  177332. /* Compute floor(nc'th root of max_colors). */
  177333. iroot = 1;
  177334. do {
  177335. iroot++;
  177336. temp = iroot; /* set temp = iroot ** nc */
  177337. for (i = 1; i < nc; i++)
  177338. temp *= iroot;
  177339. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177340. iroot--; /* now iroot = floor(root) */
  177341. /* Must have at least 2 color values per component */
  177342. if (iroot < 2)
  177343. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177344. /* Initialize to iroot color values for each component */
  177345. total_colors = 1;
  177346. for (i = 0; i < nc; i++) {
  177347. Ncolors[i] = iroot;
  177348. total_colors *= iroot;
  177349. }
  177350. /* We may be able to increment the count for one or more components without
  177351. * exceeding max_colors, though we know not all can be incremented.
  177352. * Sometimes, the first component can be incremented more than once!
  177353. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177354. * In RGB colorspace, try to increment G first, then R, then B.
  177355. */
  177356. do {
  177357. changed = FALSE;
  177358. for (i = 0; i < nc; i++) {
  177359. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177360. /* calculate new total_colors if Ncolors[j] is incremented */
  177361. temp = total_colors / Ncolors[j];
  177362. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177363. if (temp > (long) max_colors)
  177364. break; /* won't fit, done with this pass */
  177365. Ncolors[j]++; /* OK, apply the increment */
  177366. total_colors = (int) temp;
  177367. changed = TRUE;
  177368. }
  177369. } while (changed);
  177370. return total_colors;
  177371. }
  177372. LOCAL(int)
  177373. output_value (j_decompress_ptr, int, int j, int maxj)
  177374. /* Return j'th output value, where j will range from 0 to maxj */
  177375. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177376. {
  177377. /* We always provide values 0 and MAXJSAMPLE for each component;
  177378. * any additional values are equally spaced between these limits.
  177379. * (Forcing the upper and lower values to the limits ensures that
  177380. * dithering can't produce a color outside the selected gamut.)
  177381. */
  177382. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177383. }
  177384. LOCAL(int)
  177385. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177386. /* Return largest input value that should map to j'th output value */
  177387. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177388. {
  177389. /* Breakpoints are halfway between values returned by output_value */
  177390. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177391. }
  177392. /*
  177393. * Create the colormap.
  177394. */
  177395. LOCAL(void)
  177396. create_colormap (j_decompress_ptr cinfo)
  177397. {
  177398. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177399. JSAMPARRAY colormap; /* Created colormap */
  177400. int total_colors; /* Number of distinct output colors */
  177401. int i,j,k, nci, blksize, blkdist, ptr, val;
  177402. /* Select number of colors for each component */
  177403. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177404. /* Report selected color counts */
  177405. if (cinfo->out_color_components == 3)
  177406. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177407. total_colors, cquantize->Ncolors[0],
  177408. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177409. else
  177410. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177411. /* Allocate and fill in the colormap. */
  177412. /* The colors are ordered in the map in standard row-major order, */
  177413. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177414. colormap = (*cinfo->mem->alloc_sarray)
  177415. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177416. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177417. /* blksize is number of adjacent repeated entries for a component */
  177418. /* blkdist is distance between groups of identical entries for a component */
  177419. blkdist = total_colors;
  177420. for (i = 0; i < cinfo->out_color_components; i++) {
  177421. /* fill in colormap entries for i'th color component */
  177422. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177423. blksize = blkdist / nci;
  177424. for (j = 0; j < nci; j++) {
  177425. /* Compute j'th output value (out of nci) for component */
  177426. val = output_value(cinfo, i, j, nci-1);
  177427. /* Fill in all colormap entries that have this value of this component */
  177428. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177429. /* fill in blksize entries beginning at ptr */
  177430. for (k = 0; k < blksize; k++)
  177431. colormap[i][ptr+k] = (JSAMPLE) val;
  177432. }
  177433. }
  177434. blkdist = blksize; /* blksize of this color is blkdist of next */
  177435. }
  177436. /* Save the colormap in private storage,
  177437. * where it will survive color quantization mode changes.
  177438. */
  177439. cquantize->sv_colormap = colormap;
  177440. cquantize->sv_actual = total_colors;
  177441. }
  177442. /*
  177443. * Create the color index table.
  177444. */
  177445. LOCAL(void)
  177446. create_colorindex (j_decompress_ptr cinfo)
  177447. {
  177448. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177449. JSAMPROW indexptr;
  177450. int i,j,k, nci, blksize, val, pad;
  177451. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177452. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177453. * This is not necessary in the other dithering modes. However, we
  177454. * flag whether it was done in case user changes dithering mode.
  177455. */
  177456. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177457. pad = MAXJSAMPLE*2;
  177458. cquantize->is_padded = TRUE;
  177459. } else {
  177460. pad = 0;
  177461. cquantize->is_padded = FALSE;
  177462. }
  177463. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177464. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177465. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177466. (JDIMENSION) cinfo->out_color_components);
  177467. /* blksize is number of adjacent repeated entries for a component */
  177468. blksize = cquantize->sv_actual;
  177469. for (i = 0; i < cinfo->out_color_components; i++) {
  177470. /* fill in colorindex entries for i'th color component */
  177471. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177472. blksize = blksize / nci;
  177473. /* adjust colorindex pointers to provide padding at negative indexes. */
  177474. if (pad)
  177475. cquantize->colorindex[i] += MAXJSAMPLE;
  177476. /* in loop, val = index of current output value, */
  177477. /* and k = largest j that maps to current val */
  177478. indexptr = cquantize->colorindex[i];
  177479. val = 0;
  177480. k = largest_input_value(cinfo, i, 0, nci-1);
  177481. for (j = 0; j <= MAXJSAMPLE; j++) {
  177482. while (j > k) /* advance val if past boundary */
  177483. k = largest_input_value(cinfo, i, ++val, nci-1);
  177484. /* premultiply so that no multiplication needed in main processing */
  177485. indexptr[j] = (JSAMPLE) (val * blksize);
  177486. }
  177487. /* Pad at both ends if necessary */
  177488. if (pad)
  177489. for (j = 1; j <= MAXJSAMPLE; j++) {
  177490. indexptr[-j] = indexptr[0];
  177491. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177492. }
  177493. }
  177494. }
  177495. /*
  177496. * Create an ordered-dither array for a component having ncolors
  177497. * distinct output values.
  177498. */
  177499. LOCAL(ODITHER_MATRIX_PTR)
  177500. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177501. {
  177502. ODITHER_MATRIX_PTR odither;
  177503. int j,k;
  177504. INT32 num,den;
  177505. odither = (ODITHER_MATRIX_PTR)
  177506. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177507. SIZEOF(ODITHER_MATRIX));
  177508. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177509. * Hence the dither value for the matrix cell with fill order f
  177510. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177511. * On 16-bit-int machine, be careful to avoid overflow.
  177512. */
  177513. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177514. for (j = 0; j < ODITHER_SIZE; j++) {
  177515. for (k = 0; k < ODITHER_SIZE; k++) {
  177516. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177517. * MAXJSAMPLE;
  177518. /* Ensure round towards zero despite C's lack of consistency
  177519. * about rounding negative values in integer division...
  177520. */
  177521. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177522. }
  177523. }
  177524. return odither;
  177525. }
  177526. /*
  177527. * Create the ordered-dither tables.
  177528. * Components having the same number of representative colors may
  177529. * share a dither table.
  177530. */
  177531. LOCAL(void)
  177532. create_odither_tables (j_decompress_ptr cinfo)
  177533. {
  177534. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177535. ODITHER_MATRIX_PTR odither;
  177536. int i, j, nci;
  177537. for (i = 0; i < cinfo->out_color_components; i++) {
  177538. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177539. odither = NULL; /* search for matching prior component */
  177540. for (j = 0; j < i; j++) {
  177541. if (nci == cquantize->Ncolors[j]) {
  177542. odither = cquantize->odither[j];
  177543. break;
  177544. }
  177545. }
  177546. if (odither == NULL) /* need a new table? */
  177547. odither = make_odither_array(cinfo, nci);
  177548. cquantize->odither[i] = odither;
  177549. }
  177550. }
  177551. /*
  177552. * Map some rows of pixels to the output colormapped representation.
  177553. */
  177554. METHODDEF(void)
  177555. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177556. JSAMPARRAY output_buf, int num_rows)
  177557. /* General case, no dithering */
  177558. {
  177559. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177560. JSAMPARRAY colorindex = cquantize->colorindex;
  177561. register int pixcode, ci;
  177562. register JSAMPROW ptrin, ptrout;
  177563. int row;
  177564. JDIMENSION col;
  177565. JDIMENSION width = cinfo->output_width;
  177566. register int nc = cinfo->out_color_components;
  177567. for (row = 0; row < num_rows; row++) {
  177568. ptrin = input_buf[row];
  177569. ptrout = output_buf[row];
  177570. for (col = width; col > 0; col--) {
  177571. pixcode = 0;
  177572. for (ci = 0; ci < nc; ci++) {
  177573. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177574. }
  177575. *ptrout++ = (JSAMPLE) pixcode;
  177576. }
  177577. }
  177578. }
  177579. METHODDEF(void)
  177580. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177581. JSAMPARRAY output_buf, int num_rows)
  177582. /* Fast path for out_color_components==3, no dithering */
  177583. {
  177584. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177585. register int pixcode;
  177586. register JSAMPROW ptrin, ptrout;
  177587. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177588. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177589. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177590. int row;
  177591. JDIMENSION col;
  177592. JDIMENSION width = cinfo->output_width;
  177593. for (row = 0; row < num_rows; row++) {
  177594. ptrin = input_buf[row];
  177595. ptrout = output_buf[row];
  177596. for (col = width; col > 0; col--) {
  177597. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177598. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177599. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177600. *ptrout++ = (JSAMPLE) pixcode;
  177601. }
  177602. }
  177603. }
  177604. METHODDEF(void)
  177605. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177606. JSAMPARRAY output_buf, int num_rows)
  177607. /* General case, with ordered dithering */
  177608. {
  177609. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177610. register JSAMPROW input_ptr;
  177611. register JSAMPROW output_ptr;
  177612. JSAMPROW colorindex_ci;
  177613. int * dither; /* points to active row of dither matrix */
  177614. int row_index, col_index; /* current indexes into dither matrix */
  177615. int nc = cinfo->out_color_components;
  177616. int ci;
  177617. int row;
  177618. JDIMENSION col;
  177619. JDIMENSION width = cinfo->output_width;
  177620. for (row = 0; row < num_rows; row++) {
  177621. /* Initialize output values to 0 so can process components separately */
  177622. jzero_far((void FAR *) output_buf[row],
  177623. (size_t) (width * SIZEOF(JSAMPLE)));
  177624. row_index = cquantize->row_index;
  177625. for (ci = 0; ci < nc; ci++) {
  177626. input_ptr = input_buf[row] + ci;
  177627. output_ptr = output_buf[row];
  177628. colorindex_ci = cquantize->colorindex[ci];
  177629. dither = cquantize->odither[ci][row_index];
  177630. col_index = 0;
  177631. for (col = width; col > 0; col--) {
  177632. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177633. * select output value, accumulate into output code for this pixel.
  177634. * Range-limiting need not be done explicitly, as we have extended
  177635. * the colorindex table to produce the right answers for out-of-range
  177636. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177637. * required amount of padding.
  177638. */
  177639. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177640. input_ptr += nc;
  177641. output_ptr++;
  177642. col_index = (col_index + 1) & ODITHER_MASK;
  177643. }
  177644. }
  177645. /* Advance row index for next row */
  177646. row_index = (row_index + 1) & ODITHER_MASK;
  177647. cquantize->row_index = row_index;
  177648. }
  177649. }
  177650. METHODDEF(void)
  177651. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177652. JSAMPARRAY output_buf, int num_rows)
  177653. /* Fast path for out_color_components==3, with ordered dithering */
  177654. {
  177655. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177656. register int pixcode;
  177657. register JSAMPROW input_ptr;
  177658. register JSAMPROW output_ptr;
  177659. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177660. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177661. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177662. int * dither0; /* points to active row of dither matrix */
  177663. int * dither1;
  177664. int * dither2;
  177665. int row_index, col_index; /* current indexes into dither matrix */
  177666. int row;
  177667. JDIMENSION col;
  177668. JDIMENSION width = cinfo->output_width;
  177669. for (row = 0; row < num_rows; row++) {
  177670. row_index = cquantize->row_index;
  177671. input_ptr = input_buf[row];
  177672. output_ptr = output_buf[row];
  177673. dither0 = cquantize->odither[0][row_index];
  177674. dither1 = cquantize->odither[1][row_index];
  177675. dither2 = cquantize->odither[2][row_index];
  177676. col_index = 0;
  177677. for (col = width; col > 0; col--) {
  177678. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177679. dither0[col_index]]);
  177680. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177681. dither1[col_index]]);
  177682. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177683. dither2[col_index]]);
  177684. *output_ptr++ = (JSAMPLE) pixcode;
  177685. col_index = (col_index + 1) & ODITHER_MASK;
  177686. }
  177687. row_index = (row_index + 1) & ODITHER_MASK;
  177688. cquantize->row_index = row_index;
  177689. }
  177690. }
  177691. METHODDEF(void)
  177692. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177693. JSAMPARRAY output_buf, int num_rows)
  177694. /* General case, with Floyd-Steinberg dithering */
  177695. {
  177696. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177697. register LOCFSERROR cur; /* current error or pixel value */
  177698. LOCFSERROR belowerr; /* error for pixel below cur */
  177699. LOCFSERROR bpreverr; /* error for below/prev col */
  177700. LOCFSERROR bnexterr; /* error for below/next col */
  177701. LOCFSERROR delta;
  177702. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177703. register JSAMPROW input_ptr;
  177704. register JSAMPROW output_ptr;
  177705. JSAMPROW colorindex_ci;
  177706. JSAMPROW colormap_ci;
  177707. int pixcode;
  177708. int nc = cinfo->out_color_components;
  177709. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177710. int dirnc; /* dir * nc */
  177711. int ci;
  177712. int row;
  177713. JDIMENSION col;
  177714. JDIMENSION width = cinfo->output_width;
  177715. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177716. SHIFT_TEMPS
  177717. for (row = 0; row < num_rows; row++) {
  177718. /* Initialize output values to 0 so can process components separately */
  177719. jzero_far((void FAR *) output_buf[row],
  177720. (size_t) (width * SIZEOF(JSAMPLE)));
  177721. for (ci = 0; ci < nc; ci++) {
  177722. input_ptr = input_buf[row] + ci;
  177723. output_ptr = output_buf[row];
  177724. if (cquantize->on_odd_row) {
  177725. /* work right to left in this row */
  177726. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177727. output_ptr += width-1;
  177728. dir = -1;
  177729. dirnc = -nc;
  177730. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177731. } else {
  177732. /* work left to right in this row */
  177733. dir = 1;
  177734. dirnc = nc;
  177735. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177736. }
  177737. colorindex_ci = cquantize->colorindex[ci];
  177738. colormap_ci = cquantize->sv_colormap[ci];
  177739. /* Preset error values: no error propagated to first pixel from left */
  177740. cur = 0;
  177741. /* and no error propagated to row below yet */
  177742. belowerr = bpreverr = 0;
  177743. for (col = width; col > 0; col--) {
  177744. /* cur holds the error propagated from the previous pixel on the
  177745. * current line. Add the error propagated from the previous line
  177746. * to form the complete error correction term for this pixel, and
  177747. * round the error term (which is expressed * 16) to an integer.
  177748. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177749. * for either sign of the error value.
  177750. * Note: errorptr points to *previous* column's array entry.
  177751. */
  177752. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177753. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177754. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177755. * of the range_limit array.
  177756. */
  177757. cur += GETJSAMPLE(*input_ptr);
  177758. cur = GETJSAMPLE(range_limit[cur]);
  177759. /* Select output value, accumulate into output code for this pixel */
  177760. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177761. *output_ptr += (JSAMPLE) pixcode;
  177762. /* Compute actual representation error at this pixel */
  177763. /* Note: we can do this even though we don't have the final */
  177764. /* pixel code, because the colormap is orthogonal. */
  177765. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177766. /* Compute error fractions to be propagated to adjacent pixels.
  177767. * Add these into the running sums, and simultaneously shift the
  177768. * next-line error sums left by 1 column.
  177769. */
  177770. bnexterr = cur;
  177771. delta = cur * 2;
  177772. cur += delta; /* form error * 3 */
  177773. errorptr[0] = (FSERROR) (bpreverr + cur);
  177774. cur += delta; /* form error * 5 */
  177775. bpreverr = belowerr + cur;
  177776. belowerr = bnexterr;
  177777. cur += delta; /* form error * 7 */
  177778. /* At this point cur contains the 7/16 error value to be propagated
  177779. * to the next pixel on the current line, and all the errors for the
  177780. * next line have been shifted over. We are therefore ready to move on.
  177781. */
  177782. input_ptr += dirnc; /* advance input ptr to next column */
  177783. output_ptr += dir; /* advance output ptr to next column */
  177784. errorptr += dir; /* advance errorptr to current column */
  177785. }
  177786. /* Post-loop cleanup: we must unload the final error value into the
  177787. * final fserrors[] entry. Note we need not unload belowerr because
  177788. * it is for the dummy column before or after the actual array.
  177789. */
  177790. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177791. }
  177792. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177793. }
  177794. }
  177795. /*
  177796. * Allocate workspace for Floyd-Steinberg errors.
  177797. */
  177798. LOCAL(void)
  177799. alloc_fs_workspace (j_decompress_ptr cinfo)
  177800. {
  177801. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177802. size_t arraysize;
  177803. int i;
  177804. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177805. for (i = 0; i < cinfo->out_color_components; i++) {
  177806. cquantize->fserrors[i] = (FSERRPTR)
  177807. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177808. }
  177809. }
  177810. /*
  177811. * Initialize for one-pass color quantization.
  177812. */
  177813. METHODDEF(void)
  177814. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177815. {
  177816. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177817. size_t arraysize;
  177818. int i;
  177819. /* Install my colormap. */
  177820. cinfo->colormap = cquantize->sv_colormap;
  177821. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177822. /* Initialize for desired dithering mode. */
  177823. switch (cinfo->dither_mode) {
  177824. case JDITHER_NONE:
  177825. if (cinfo->out_color_components == 3)
  177826. cquantize->pub.color_quantize = color_quantize3;
  177827. else
  177828. cquantize->pub.color_quantize = color_quantize;
  177829. break;
  177830. case JDITHER_ORDERED:
  177831. if (cinfo->out_color_components == 3)
  177832. cquantize->pub.color_quantize = quantize3_ord_dither;
  177833. else
  177834. cquantize->pub.color_quantize = quantize_ord_dither;
  177835. cquantize->row_index = 0; /* initialize state for ordered dither */
  177836. /* If user changed to ordered dither from another mode,
  177837. * we must recreate the color index table with padding.
  177838. * This will cost extra space, but probably isn't very likely.
  177839. */
  177840. if (! cquantize->is_padded)
  177841. create_colorindex(cinfo);
  177842. /* Create ordered-dither tables if we didn't already. */
  177843. if (cquantize->odither[0] == NULL)
  177844. create_odither_tables(cinfo);
  177845. break;
  177846. case JDITHER_FS:
  177847. cquantize->pub.color_quantize = quantize_fs_dither;
  177848. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177849. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177850. if (cquantize->fserrors[0] == NULL)
  177851. alloc_fs_workspace(cinfo);
  177852. /* Initialize the propagated errors to zero. */
  177853. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177854. for (i = 0; i < cinfo->out_color_components; i++)
  177855. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177856. break;
  177857. default:
  177858. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177859. break;
  177860. }
  177861. }
  177862. /*
  177863. * Finish up at the end of the pass.
  177864. */
  177865. METHODDEF(void)
  177866. finish_pass_1_quant (j_decompress_ptr)
  177867. {
  177868. /* no work in 1-pass case */
  177869. }
  177870. /*
  177871. * Switch to a new external colormap between output passes.
  177872. * Shouldn't get to this module!
  177873. */
  177874. METHODDEF(void)
  177875. new_color_map_1_quant (j_decompress_ptr cinfo)
  177876. {
  177877. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177878. }
  177879. /*
  177880. * Module initialization routine for 1-pass color quantization.
  177881. */
  177882. GLOBAL(void)
  177883. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177884. {
  177885. my_cquantize_ptr cquantize;
  177886. cquantize = (my_cquantize_ptr)
  177887. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177888. SIZEOF(my_cquantizer));
  177889. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177890. cquantize->pub.start_pass = start_pass_1_quant;
  177891. cquantize->pub.finish_pass = finish_pass_1_quant;
  177892. cquantize->pub.new_color_map = new_color_map_1_quant;
  177893. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177894. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177895. /* Make sure my internal arrays won't overflow */
  177896. if (cinfo->out_color_components > MAX_Q_COMPS)
  177897. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177898. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177899. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177900. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177901. /* Create the colormap and color index table. */
  177902. create_colormap(cinfo);
  177903. create_colorindex(cinfo);
  177904. /* Allocate Floyd-Steinberg workspace now if requested.
  177905. * We do this now since it is FAR storage and may affect the memory
  177906. * manager's space calculations. If the user changes to FS dither
  177907. * mode in a later pass, we will allocate the space then, and will
  177908. * possibly overrun the max_memory_to_use setting.
  177909. */
  177910. if (cinfo->dither_mode == JDITHER_FS)
  177911. alloc_fs_workspace(cinfo);
  177912. }
  177913. #endif /* QUANT_1PASS_SUPPORTED */
  177914. /*** End of inlined file: jquant1.c ***/
  177915. /*** Start of inlined file: jquant2.c ***/
  177916. #define JPEG_INTERNALS
  177917. #ifdef QUANT_2PASS_SUPPORTED
  177918. /*
  177919. * This module implements the well-known Heckbert paradigm for color
  177920. * quantization. Most of the ideas used here can be traced back to
  177921. * Heckbert's seminal paper
  177922. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177923. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177924. *
  177925. * In the first pass over the image, we accumulate a histogram showing the
  177926. * usage count of each possible color. To keep the histogram to a reasonable
  177927. * size, we reduce the precision of the input; typical practice is to retain
  177928. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177929. * in the same histogram cell.
  177930. *
  177931. * Next, the color-selection step begins with a box representing the whole
  177932. * color space, and repeatedly splits the "largest" remaining box until we
  177933. * have as many boxes as desired colors. Then the mean color in each
  177934. * remaining box becomes one of the possible output colors.
  177935. *
  177936. * The second pass over the image maps each input pixel to the closest output
  177937. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177938. * This mapping is logically trivial, but making it go fast enough requires
  177939. * considerable care.
  177940. *
  177941. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177942. * the "largest" box and deciding where to cut it. The particular policies
  177943. * used here have proved out well in experimental comparisons, but better ones
  177944. * may yet be found.
  177945. *
  177946. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177947. * space, processing the raw upsampled data without a color conversion step.
  177948. * This allowed the color conversion math to be done only once per colormap
  177949. * entry, not once per pixel. However, that optimization precluded other
  177950. * useful optimizations (such as merging color conversion with upsampling)
  177951. * and it also interfered with desired capabilities such as quantizing to an
  177952. * externally-supplied colormap. We have therefore abandoned that approach.
  177953. * The present code works in the post-conversion color space, typically RGB.
  177954. *
  177955. * To improve the visual quality of the results, we actually work in scaled
  177956. * RGB space, giving G distances more weight than R, and R in turn more than
  177957. * B. To do everything in integer math, we must use integer scale factors.
  177958. * The 2/3/1 scale factors used here correspond loosely to the relative
  177959. * weights of the colors in the NTSC grayscale equation.
  177960. * If you want to use this code to quantize a non-RGB color space, you'll
  177961. * probably need to change these scale factors.
  177962. */
  177963. #define R_SCALE 2 /* scale R distances by this much */
  177964. #define G_SCALE 3 /* scale G distances by this much */
  177965. #define B_SCALE 1 /* and B by this much */
  177966. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177967. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177968. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177969. * you'll get compile errors until you extend this logic. In that case
  177970. * you'll probably want to tweak the histogram sizes too.
  177971. */
  177972. #if RGB_RED == 0
  177973. #define C0_SCALE R_SCALE
  177974. #endif
  177975. #if RGB_BLUE == 0
  177976. #define C0_SCALE B_SCALE
  177977. #endif
  177978. #if RGB_GREEN == 1
  177979. #define C1_SCALE G_SCALE
  177980. #endif
  177981. #if RGB_RED == 2
  177982. #define C2_SCALE R_SCALE
  177983. #endif
  177984. #if RGB_BLUE == 2
  177985. #define C2_SCALE B_SCALE
  177986. #endif
  177987. /*
  177988. * First we have the histogram data structure and routines for creating it.
  177989. *
  177990. * The number of bits of precision can be adjusted by changing these symbols.
  177991. * We recommend keeping 6 bits for G and 5 each for R and B.
  177992. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177993. * better results; if you are short of memory, 5 bits all around will save
  177994. * some space but degrade the results.
  177995. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177996. * (preferably unsigned long) for each cell. In practice this is overkill;
  177997. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177998. * and clamping those that do overflow to the maximum value will give close-
  177999. * enough results. This reduces the recommended histogram size from 256Kb
  178000. * to 128Kb, which is a useful savings on PC-class machines.
  178001. * (In the second pass the histogram space is re-used for pixel mapping data;
  178002. * in that capacity, each cell must be able to store zero to the number of
  178003. * desired colors. 16 bits/cell is plenty for that too.)
  178004. * Since the JPEG code is intended to run in small memory model on 80x86
  178005. * machines, we can't just allocate the histogram in one chunk. Instead
  178006. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  178007. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  178008. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  178009. * on 80x86 machines, the pointer row is in near memory but the actual
  178010. * arrays are in far memory (same arrangement as we use for image arrays).
  178011. */
  178012. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  178013. /* These will do the right thing for either R,G,B or B,G,R color order,
  178014. * but you may not like the results for other color orders.
  178015. */
  178016. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  178017. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  178018. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  178019. /* Number of elements along histogram axes. */
  178020. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  178021. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  178022. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  178023. /* These are the amounts to shift an input value to get a histogram index. */
  178024. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  178025. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  178026. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  178027. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178028. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178029. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178030. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178031. typedef hist2d * hist3d; /* type for top-level pointer */
  178032. /* Declarations for Floyd-Steinberg dithering.
  178033. *
  178034. * Errors are accumulated into the array fserrors[], at a resolution of
  178035. * 1/16th of a pixel count. The error at a given pixel is propagated
  178036. * to its not-yet-processed neighbors using the standard F-S fractions,
  178037. * ... (here) 7/16
  178038. * 3/16 5/16 1/16
  178039. * We work left-to-right on even rows, right-to-left on odd rows.
  178040. *
  178041. * We can get away with a single array (holding one row's worth of errors)
  178042. * by using it to store the current row's errors at pixel columns not yet
  178043. * processed, but the next row's errors at columns already processed. We
  178044. * need only a few extra variables to hold the errors immediately around the
  178045. * current column. (If we are lucky, those variables are in registers, but
  178046. * even if not, they're probably cheaper to access than array elements are.)
  178047. *
  178048. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178049. * each end saves us from special-casing the first and last pixels.
  178050. * Each entry is three values long, one value for each color component.
  178051. *
  178052. * Note: on a wide image, we might not have enough room in a PC's near data
  178053. * segment to hold the error array; so it is allocated with alloc_large.
  178054. */
  178055. #if BITS_IN_JSAMPLE == 8
  178056. typedef INT16 FSERROR; /* 16 bits should be enough */
  178057. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178058. #else
  178059. typedef INT32 FSERROR; /* may need more than 16 bits */
  178060. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178061. #endif
  178062. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178063. /* Private subobject */
  178064. typedef struct {
  178065. struct jpeg_color_quantizer pub; /* public fields */
  178066. /* Space for the eventually created colormap is stashed here */
  178067. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178068. int desired; /* desired # of colors = size of colormap */
  178069. /* Variables for accumulating image statistics */
  178070. hist3d histogram; /* pointer to the histogram */
  178071. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178072. /* Variables for Floyd-Steinberg dithering */
  178073. FSERRPTR fserrors; /* accumulated errors */
  178074. boolean on_odd_row; /* flag to remember which row we are on */
  178075. int * error_limiter; /* table for clamping the applied error */
  178076. } my_cquantizer2;
  178077. typedef my_cquantizer2 * my_cquantize_ptr2;
  178078. /*
  178079. * Prescan some rows of pixels.
  178080. * In this module the prescan simply updates the histogram, which has been
  178081. * initialized to zeroes by start_pass.
  178082. * An output_buf parameter is required by the method signature, but no data
  178083. * is actually output (in fact the buffer controller is probably passing a
  178084. * NULL pointer).
  178085. */
  178086. METHODDEF(void)
  178087. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178088. JSAMPARRAY, int num_rows)
  178089. {
  178090. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178091. register JSAMPROW ptr;
  178092. register histptr histp;
  178093. register hist3d histogram = cquantize->histogram;
  178094. int row;
  178095. JDIMENSION col;
  178096. JDIMENSION width = cinfo->output_width;
  178097. for (row = 0; row < num_rows; row++) {
  178098. ptr = input_buf[row];
  178099. for (col = width; col > 0; col--) {
  178100. /* get pixel value and index into the histogram */
  178101. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178102. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178103. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178104. /* increment, check for overflow and undo increment if so. */
  178105. if (++(*histp) <= 0)
  178106. (*histp)--;
  178107. ptr += 3;
  178108. }
  178109. }
  178110. }
  178111. /*
  178112. * Next we have the really interesting routines: selection of a colormap
  178113. * given the completed histogram.
  178114. * These routines work with a list of "boxes", each representing a rectangular
  178115. * subset of the input color space (to histogram precision).
  178116. */
  178117. typedef struct {
  178118. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178119. int c0min, c0max;
  178120. int c1min, c1max;
  178121. int c2min, c2max;
  178122. /* The volume (actually 2-norm) of the box */
  178123. INT32 volume;
  178124. /* The number of nonzero histogram cells within this box */
  178125. long colorcount;
  178126. } box;
  178127. typedef box * boxptr;
  178128. LOCAL(boxptr)
  178129. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178130. /* Find the splittable box with the largest color population */
  178131. /* Returns NULL if no splittable boxes remain */
  178132. {
  178133. register boxptr boxp;
  178134. register int i;
  178135. register long maxc = 0;
  178136. boxptr which = NULL;
  178137. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178138. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178139. which = boxp;
  178140. maxc = boxp->colorcount;
  178141. }
  178142. }
  178143. return which;
  178144. }
  178145. LOCAL(boxptr)
  178146. find_biggest_volume (boxptr boxlist, int numboxes)
  178147. /* Find the splittable box with the largest (scaled) volume */
  178148. /* Returns NULL if no splittable boxes remain */
  178149. {
  178150. register boxptr boxp;
  178151. register int i;
  178152. register INT32 maxv = 0;
  178153. boxptr which = NULL;
  178154. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178155. if (boxp->volume > maxv) {
  178156. which = boxp;
  178157. maxv = boxp->volume;
  178158. }
  178159. }
  178160. return which;
  178161. }
  178162. LOCAL(void)
  178163. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178164. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178165. /* and recompute its volume and population */
  178166. {
  178167. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178168. hist3d histogram = cquantize->histogram;
  178169. histptr histp;
  178170. int c0,c1,c2;
  178171. int c0min,c0max,c1min,c1max,c2min,c2max;
  178172. INT32 dist0,dist1,dist2;
  178173. long ccount;
  178174. c0min = boxp->c0min; c0max = boxp->c0max;
  178175. c1min = boxp->c1min; c1max = boxp->c1max;
  178176. c2min = boxp->c2min; c2max = boxp->c2max;
  178177. if (c0max > c0min)
  178178. for (c0 = c0min; c0 <= c0max; c0++)
  178179. for (c1 = c1min; c1 <= c1max; c1++) {
  178180. histp = & histogram[c0][c1][c2min];
  178181. for (c2 = c2min; c2 <= c2max; c2++)
  178182. if (*histp++ != 0) {
  178183. boxp->c0min = c0min = c0;
  178184. goto have_c0min;
  178185. }
  178186. }
  178187. have_c0min:
  178188. if (c0max > c0min)
  178189. for (c0 = c0max; c0 >= c0min; c0--)
  178190. for (c1 = c1min; c1 <= c1max; c1++) {
  178191. histp = & histogram[c0][c1][c2min];
  178192. for (c2 = c2min; c2 <= c2max; c2++)
  178193. if (*histp++ != 0) {
  178194. boxp->c0max = c0max = c0;
  178195. goto have_c0max;
  178196. }
  178197. }
  178198. have_c0max:
  178199. if (c1max > c1min)
  178200. for (c1 = c1min; c1 <= c1max; c1++)
  178201. for (c0 = c0min; c0 <= c0max; c0++) {
  178202. histp = & histogram[c0][c1][c2min];
  178203. for (c2 = c2min; c2 <= c2max; c2++)
  178204. if (*histp++ != 0) {
  178205. boxp->c1min = c1min = c1;
  178206. goto have_c1min;
  178207. }
  178208. }
  178209. have_c1min:
  178210. if (c1max > c1min)
  178211. for (c1 = c1max; c1 >= c1min; c1--)
  178212. for (c0 = c0min; c0 <= c0max; c0++) {
  178213. histp = & histogram[c0][c1][c2min];
  178214. for (c2 = c2min; c2 <= c2max; c2++)
  178215. if (*histp++ != 0) {
  178216. boxp->c1max = c1max = c1;
  178217. goto have_c1max;
  178218. }
  178219. }
  178220. have_c1max:
  178221. if (c2max > c2min)
  178222. for (c2 = c2min; c2 <= c2max; c2++)
  178223. for (c0 = c0min; c0 <= c0max; c0++) {
  178224. histp = & histogram[c0][c1min][c2];
  178225. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178226. if (*histp != 0) {
  178227. boxp->c2min = c2min = c2;
  178228. goto have_c2min;
  178229. }
  178230. }
  178231. have_c2min:
  178232. if (c2max > c2min)
  178233. for (c2 = c2max; c2 >= c2min; c2--)
  178234. for (c0 = c0min; c0 <= c0max; c0++) {
  178235. histp = & histogram[c0][c1min][c2];
  178236. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178237. if (*histp != 0) {
  178238. boxp->c2max = c2max = c2;
  178239. goto have_c2max;
  178240. }
  178241. }
  178242. have_c2max:
  178243. /* Update box volume.
  178244. * We use 2-norm rather than real volume here; this biases the method
  178245. * against making long narrow boxes, and it has the side benefit that
  178246. * a box is splittable iff norm > 0.
  178247. * Since the differences are expressed in histogram-cell units,
  178248. * we have to shift back to JSAMPLE units to get consistent distances;
  178249. * after which, we scale according to the selected distance scale factors.
  178250. */
  178251. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178252. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178253. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178254. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178255. /* Now scan remaining volume of box and compute population */
  178256. ccount = 0;
  178257. for (c0 = c0min; c0 <= c0max; c0++)
  178258. for (c1 = c1min; c1 <= c1max; c1++) {
  178259. histp = & histogram[c0][c1][c2min];
  178260. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178261. if (*histp != 0) {
  178262. ccount++;
  178263. }
  178264. }
  178265. boxp->colorcount = ccount;
  178266. }
  178267. LOCAL(int)
  178268. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178269. int desired_colors)
  178270. /* Repeatedly select and split the largest box until we have enough boxes */
  178271. {
  178272. int n,lb;
  178273. int c0,c1,c2,cmax;
  178274. register boxptr b1,b2;
  178275. while (numboxes < desired_colors) {
  178276. /* Select box to split.
  178277. * Current algorithm: by population for first half, then by volume.
  178278. */
  178279. if (numboxes*2 <= desired_colors) {
  178280. b1 = find_biggest_color_pop(boxlist, numboxes);
  178281. } else {
  178282. b1 = find_biggest_volume(boxlist, numboxes);
  178283. }
  178284. if (b1 == NULL) /* no splittable boxes left! */
  178285. break;
  178286. b2 = &boxlist[numboxes]; /* where new box will go */
  178287. /* Copy the color bounds to the new box. */
  178288. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178289. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178290. /* Choose which axis to split the box on.
  178291. * Current algorithm: longest scaled axis.
  178292. * See notes in update_box about scaling distances.
  178293. */
  178294. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178295. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178296. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178297. /* We want to break any ties in favor of green, then red, blue last.
  178298. * This code does the right thing for R,G,B or B,G,R color orders only.
  178299. */
  178300. #if RGB_RED == 0
  178301. cmax = c1; n = 1;
  178302. if (c0 > cmax) { cmax = c0; n = 0; }
  178303. if (c2 > cmax) { n = 2; }
  178304. #else
  178305. cmax = c1; n = 1;
  178306. if (c2 > cmax) { cmax = c2; n = 2; }
  178307. if (c0 > cmax) { n = 0; }
  178308. #endif
  178309. /* Choose split point along selected axis, and update box bounds.
  178310. * Current algorithm: split at halfway point.
  178311. * (Since the box has been shrunk to minimum volume,
  178312. * any split will produce two nonempty subboxes.)
  178313. * Note that lb value is max for lower box, so must be < old max.
  178314. */
  178315. switch (n) {
  178316. case 0:
  178317. lb = (b1->c0max + b1->c0min) / 2;
  178318. b1->c0max = lb;
  178319. b2->c0min = lb+1;
  178320. break;
  178321. case 1:
  178322. lb = (b1->c1max + b1->c1min) / 2;
  178323. b1->c1max = lb;
  178324. b2->c1min = lb+1;
  178325. break;
  178326. case 2:
  178327. lb = (b1->c2max + b1->c2min) / 2;
  178328. b1->c2max = lb;
  178329. b2->c2min = lb+1;
  178330. break;
  178331. }
  178332. /* Update stats for boxes */
  178333. update_box(cinfo, b1);
  178334. update_box(cinfo, b2);
  178335. numboxes++;
  178336. }
  178337. return numboxes;
  178338. }
  178339. LOCAL(void)
  178340. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178341. /* Compute representative color for a box, put it in colormap[icolor] */
  178342. {
  178343. /* Current algorithm: mean weighted by pixels (not colors) */
  178344. /* Note it is important to get the rounding correct! */
  178345. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178346. hist3d histogram = cquantize->histogram;
  178347. histptr histp;
  178348. int c0,c1,c2;
  178349. int c0min,c0max,c1min,c1max,c2min,c2max;
  178350. long count;
  178351. long total = 0;
  178352. long c0total = 0;
  178353. long c1total = 0;
  178354. long c2total = 0;
  178355. c0min = boxp->c0min; c0max = boxp->c0max;
  178356. c1min = boxp->c1min; c1max = boxp->c1max;
  178357. c2min = boxp->c2min; c2max = boxp->c2max;
  178358. for (c0 = c0min; c0 <= c0max; c0++)
  178359. for (c1 = c1min; c1 <= c1max; c1++) {
  178360. histp = & histogram[c0][c1][c2min];
  178361. for (c2 = c2min; c2 <= c2max; c2++) {
  178362. if ((count = *histp++) != 0) {
  178363. total += count;
  178364. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178365. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178366. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178367. }
  178368. }
  178369. }
  178370. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178371. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178372. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178373. }
  178374. LOCAL(void)
  178375. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178376. /* Master routine for color selection */
  178377. {
  178378. boxptr boxlist;
  178379. int numboxes;
  178380. int i;
  178381. /* Allocate workspace for box list */
  178382. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178383. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178384. /* Initialize one box containing whole space */
  178385. numboxes = 1;
  178386. boxlist[0].c0min = 0;
  178387. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178388. boxlist[0].c1min = 0;
  178389. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178390. boxlist[0].c2min = 0;
  178391. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178392. /* Shrink it to actually-used volume and set its statistics */
  178393. update_box(cinfo, & boxlist[0]);
  178394. /* Perform median-cut to produce final box list */
  178395. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178396. /* Compute the representative color for each box, fill colormap */
  178397. for (i = 0; i < numboxes; i++)
  178398. compute_color(cinfo, & boxlist[i], i);
  178399. cinfo->actual_number_of_colors = numboxes;
  178400. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178401. }
  178402. /*
  178403. * These routines are concerned with the time-critical task of mapping input
  178404. * colors to the nearest color in the selected colormap.
  178405. *
  178406. * We re-use the histogram space as an "inverse color map", essentially a
  178407. * cache for the results of nearest-color searches. All colors within a
  178408. * histogram cell will be mapped to the same colormap entry, namely the one
  178409. * closest to the cell's center. This may not be quite the closest entry to
  178410. * the actual input color, but it's almost as good. A zero in the cache
  178411. * indicates we haven't found the nearest color for that cell yet; the array
  178412. * is cleared to zeroes before starting the mapping pass. When we find the
  178413. * nearest color for a cell, its colormap index plus one is recorded in the
  178414. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178415. * when they need to use an unfilled entry in the cache.
  178416. *
  178417. * Our method of efficiently finding nearest colors is based on the "locally
  178418. * sorted search" idea described by Heckbert and on the incremental distance
  178419. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178420. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178421. * the distances from a given colormap entry to each cell of the histogram can
  178422. * be computed quickly using an incremental method: the differences between
  178423. * distances to adjacent cells themselves differ by a constant. This allows a
  178424. * fairly fast implementation of the "brute force" approach of computing the
  178425. * distance from every colormap entry to every histogram cell. Unfortunately,
  178426. * it needs a work array to hold the best-distance-so-far for each histogram
  178427. * cell (because the inner loop has to be over cells, not colormap entries).
  178428. * The work array elements have to be INT32s, so the work array would need
  178429. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178430. *
  178431. * To get around these problems, we apply Thomas' method to compute the
  178432. * nearest colors for only the cells within a small subbox of the histogram.
  178433. * The work array need be only as big as the subbox, so the memory usage
  178434. * problem is solved. Furthermore, we need not fill subboxes that are never
  178435. * referenced in pass2; many images use only part of the color gamut, so a
  178436. * fair amount of work is saved. An additional advantage of this
  178437. * approach is that we can apply Heckbert's locality criterion to quickly
  178438. * eliminate colormap entries that are far away from the subbox; typically
  178439. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178440. * and we need not compute their distances to individual cells in the subbox.
  178441. * The speed of this approach is heavily influenced by the subbox size: too
  178442. * small means too much overhead, too big loses because Heckbert's criterion
  178443. * can't eliminate as many colormap entries. Empirically the best subbox
  178444. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178445. *
  178446. * Thomas' article also describes a refined method which is asymptotically
  178447. * faster than the brute-force method, but it is also far more complex and
  178448. * cannot efficiently be applied to small subboxes. It is therefore not
  178449. * useful for programs intended to be portable to DOS machines. On machines
  178450. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178451. * refined method might be faster than the present code --- but then again,
  178452. * it might not be any faster, and it's certainly more complicated.
  178453. */
  178454. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178455. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178456. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178457. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178458. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178459. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178460. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178461. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178462. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178463. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178464. /*
  178465. * The next three routines implement inverse colormap filling. They could
  178466. * all be folded into one big routine, but splitting them up this way saves
  178467. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178468. * and may allow some compilers to produce better code by registerizing more
  178469. * inner-loop variables.
  178470. */
  178471. LOCAL(int)
  178472. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178473. JSAMPLE colorlist[])
  178474. /* Locate the colormap entries close enough to an update box to be candidates
  178475. * for the nearest entry to some cell(s) in the update box. The update box
  178476. * is specified by the center coordinates of its first cell. The number of
  178477. * candidate colormap entries is returned, and their colormap indexes are
  178478. * placed in colorlist[].
  178479. * This routine uses Heckbert's "locally sorted search" criterion to select
  178480. * the colors that need further consideration.
  178481. */
  178482. {
  178483. int numcolors = cinfo->actual_number_of_colors;
  178484. int maxc0, maxc1, maxc2;
  178485. int centerc0, centerc1, centerc2;
  178486. int i, x, ncolors;
  178487. INT32 minmaxdist, min_dist, max_dist, tdist;
  178488. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178489. /* Compute true coordinates of update box's upper corner and center.
  178490. * Actually we compute the coordinates of the center of the upper-corner
  178491. * histogram cell, which are the upper bounds of the volume we care about.
  178492. * Note that since ">>" rounds down, the "center" values may be closer to
  178493. * min than to max; hence comparisons to them must be "<=", not "<".
  178494. */
  178495. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178496. centerc0 = (minc0 + maxc0) >> 1;
  178497. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178498. centerc1 = (minc1 + maxc1) >> 1;
  178499. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178500. centerc2 = (minc2 + maxc2) >> 1;
  178501. /* For each color in colormap, find:
  178502. * 1. its minimum squared-distance to any point in the update box
  178503. * (zero if color is within update box);
  178504. * 2. its maximum squared-distance to any point in the update box.
  178505. * Both of these can be found by considering only the corners of the box.
  178506. * We save the minimum distance for each color in mindist[];
  178507. * only the smallest maximum distance is of interest.
  178508. */
  178509. minmaxdist = 0x7FFFFFFFL;
  178510. for (i = 0; i < numcolors; i++) {
  178511. /* We compute the squared-c0-distance term, then add in the other two. */
  178512. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178513. if (x < minc0) {
  178514. tdist = (x - minc0) * C0_SCALE;
  178515. min_dist = tdist*tdist;
  178516. tdist = (x - maxc0) * C0_SCALE;
  178517. max_dist = tdist*tdist;
  178518. } else if (x > maxc0) {
  178519. tdist = (x - maxc0) * C0_SCALE;
  178520. min_dist = tdist*tdist;
  178521. tdist = (x - minc0) * C0_SCALE;
  178522. max_dist = tdist*tdist;
  178523. } else {
  178524. /* within cell range so no contribution to min_dist */
  178525. min_dist = 0;
  178526. if (x <= centerc0) {
  178527. tdist = (x - maxc0) * C0_SCALE;
  178528. max_dist = tdist*tdist;
  178529. } else {
  178530. tdist = (x - minc0) * C0_SCALE;
  178531. max_dist = tdist*tdist;
  178532. }
  178533. }
  178534. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178535. if (x < minc1) {
  178536. tdist = (x - minc1) * C1_SCALE;
  178537. min_dist += tdist*tdist;
  178538. tdist = (x - maxc1) * C1_SCALE;
  178539. max_dist += tdist*tdist;
  178540. } else if (x > maxc1) {
  178541. tdist = (x - maxc1) * C1_SCALE;
  178542. min_dist += tdist*tdist;
  178543. tdist = (x - minc1) * C1_SCALE;
  178544. max_dist += tdist*tdist;
  178545. } else {
  178546. /* within cell range so no contribution to min_dist */
  178547. if (x <= centerc1) {
  178548. tdist = (x - maxc1) * C1_SCALE;
  178549. max_dist += tdist*tdist;
  178550. } else {
  178551. tdist = (x - minc1) * C1_SCALE;
  178552. max_dist += tdist*tdist;
  178553. }
  178554. }
  178555. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178556. if (x < minc2) {
  178557. tdist = (x - minc2) * C2_SCALE;
  178558. min_dist += tdist*tdist;
  178559. tdist = (x - maxc2) * C2_SCALE;
  178560. max_dist += tdist*tdist;
  178561. } else if (x > maxc2) {
  178562. tdist = (x - maxc2) * C2_SCALE;
  178563. min_dist += tdist*tdist;
  178564. tdist = (x - minc2) * C2_SCALE;
  178565. max_dist += tdist*tdist;
  178566. } else {
  178567. /* within cell range so no contribution to min_dist */
  178568. if (x <= centerc2) {
  178569. tdist = (x - maxc2) * C2_SCALE;
  178570. max_dist += tdist*tdist;
  178571. } else {
  178572. tdist = (x - minc2) * C2_SCALE;
  178573. max_dist += tdist*tdist;
  178574. }
  178575. }
  178576. mindist[i] = min_dist; /* save away the results */
  178577. if (max_dist < minmaxdist)
  178578. minmaxdist = max_dist;
  178579. }
  178580. /* Now we know that no cell in the update box is more than minmaxdist
  178581. * away from some colormap entry. Therefore, only colors that are
  178582. * within minmaxdist of some part of the box need be considered.
  178583. */
  178584. ncolors = 0;
  178585. for (i = 0; i < numcolors; i++) {
  178586. if (mindist[i] <= minmaxdist)
  178587. colorlist[ncolors++] = (JSAMPLE) i;
  178588. }
  178589. return ncolors;
  178590. }
  178591. LOCAL(void)
  178592. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178593. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178594. /* Find the closest colormap entry for each cell in the update box,
  178595. * given the list of candidate colors prepared by find_nearby_colors.
  178596. * Return the indexes of the closest entries in the bestcolor[] array.
  178597. * This routine uses Thomas' incremental distance calculation method to
  178598. * find the distance from a colormap entry to successive cells in the box.
  178599. */
  178600. {
  178601. int ic0, ic1, ic2;
  178602. int i, icolor;
  178603. register INT32 * bptr; /* pointer into bestdist[] array */
  178604. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178605. INT32 dist0, dist1; /* initial distance values */
  178606. register INT32 dist2; /* current distance in inner loop */
  178607. INT32 xx0, xx1; /* distance increments */
  178608. register INT32 xx2;
  178609. INT32 inc0, inc1, inc2; /* initial values for increments */
  178610. /* This array holds the distance to the nearest-so-far color for each cell */
  178611. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178612. /* Initialize best-distance for each cell of the update box */
  178613. bptr = bestdist;
  178614. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178615. *bptr++ = 0x7FFFFFFFL;
  178616. /* For each color selected by find_nearby_colors,
  178617. * compute its distance to the center of each cell in the box.
  178618. * If that's less than best-so-far, update best distance and color number.
  178619. */
  178620. /* Nominal steps between cell centers ("x" in Thomas article) */
  178621. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178622. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178623. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178624. for (i = 0; i < numcolors; i++) {
  178625. icolor = GETJSAMPLE(colorlist[i]);
  178626. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178627. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178628. dist0 = inc0*inc0;
  178629. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178630. dist0 += inc1*inc1;
  178631. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178632. dist0 += inc2*inc2;
  178633. /* Form the initial difference increments */
  178634. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178635. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178636. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178637. /* Now loop over all cells in box, updating distance per Thomas method */
  178638. bptr = bestdist;
  178639. cptr = bestcolor;
  178640. xx0 = inc0;
  178641. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178642. dist1 = dist0;
  178643. xx1 = inc1;
  178644. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178645. dist2 = dist1;
  178646. xx2 = inc2;
  178647. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178648. if (dist2 < *bptr) {
  178649. *bptr = dist2;
  178650. *cptr = (JSAMPLE) icolor;
  178651. }
  178652. dist2 += xx2;
  178653. xx2 += 2 * STEP_C2 * STEP_C2;
  178654. bptr++;
  178655. cptr++;
  178656. }
  178657. dist1 += xx1;
  178658. xx1 += 2 * STEP_C1 * STEP_C1;
  178659. }
  178660. dist0 += xx0;
  178661. xx0 += 2 * STEP_C0 * STEP_C0;
  178662. }
  178663. }
  178664. }
  178665. LOCAL(void)
  178666. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178667. /* Fill the inverse-colormap entries in the update box that contains */
  178668. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178669. /* we can fill as many others as we wish.) */
  178670. {
  178671. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178672. hist3d histogram = cquantize->histogram;
  178673. int minc0, minc1, minc2; /* lower left corner of update box */
  178674. int ic0, ic1, ic2;
  178675. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178676. register histptr cachep; /* pointer into main cache array */
  178677. /* This array lists the candidate colormap indexes. */
  178678. JSAMPLE colorlist[MAXNUMCOLORS];
  178679. int numcolors; /* number of candidate colors */
  178680. /* This array holds the actually closest colormap index for each cell. */
  178681. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178682. /* Convert cell coordinates to update box ID */
  178683. c0 >>= BOX_C0_LOG;
  178684. c1 >>= BOX_C1_LOG;
  178685. c2 >>= BOX_C2_LOG;
  178686. /* Compute true coordinates of update box's origin corner.
  178687. * Actually we compute the coordinates of the center of the corner
  178688. * histogram cell, which are the lower bounds of the volume we care about.
  178689. */
  178690. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178691. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178692. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178693. /* Determine which colormap entries are close enough to be candidates
  178694. * for the nearest entry to some cell in the update box.
  178695. */
  178696. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178697. /* Determine the actually nearest colors. */
  178698. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178699. bestcolor);
  178700. /* Save the best color numbers (plus 1) in the main cache array */
  178701. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178702. c1 <<= BOX_C1_LOG;
  178703. c2 <<= BOX_C2_LOG;
  178704. cptr = bestcolor;
  178705. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178706. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178707. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178708. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178709. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178710. }
  178711. }
  178712. }
  178713. }
  178714. /*
  178715. * Map some rows of pixels to the output colormapped representation.
  178716. */
  178717. METHODDEF(void)
  178718. pass2_no_dither (j_decompress_ptr cinfo,
  178719. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178720. /* This version performs no dithering */
  178721. {
  178722. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178723. hist3d histogram = cquantize->histogram;
  178724. register JSAMPROW inptr, outptr;
  178725. register histptr cachep;
  178726. register int c0, c1, c2;
  178727. int row;
  178728. JDIMENSION col;
  178729. JDIMENSION width = cinfo->output_width;
  178730. for (row = 0; row < num_rows; row++) {
  178731. inptr = input_buf[row];
  178732. outptr = output_buf[row];
  178733. for (col = width; col > 0; col--) {
  178734. /* get pixel value and index into the cache */
  178735. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178736. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178737. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178738. cachep = & histogram[c0][c1][c2];
  178739. /* If we have not seen this color before, find nearest colormap entry */
  178740. /* and update the cache */
  178741. if (*cachep == 0)
  178742. fill_inverse_cmap(cinfo, c0,c1,c2);
  178743. /* Now emit the colormap index for this cell */
  178744. *outptr++ = (JSAMPLE) (*cachep - 1);
  178745. }
  178746. }
  178747. }
  178748. METHODDEF(void)
  178749. pass2_fs_dither (j_decompress_ptr cinfo,
  178750. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178751. /* This version performs Floyd-Steinberg dithering */
  178752. {
  178753. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178754. hist3d histogram = cquantize->histogram;
  178755. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178756. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178757. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178758. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178759. JSAMPROW inptr; /* => current input pixel */
  178760. JSAMPROW outptr; /* => current output pixel */
  178761. histptr cachep;
  178762. int dir; /* +1 or -1 depending on direction */
  178763. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178764. int row;
  178765. JDIMENSION col;
  178766. JDIMENSION width = cinfo->output_width;
  178767. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178768. int *error_limit = cquantize->error_limiter;
  178769. JSAMPROW colormap0 = cinfo->colormap[0];
  178770. JSAMPROW colormap1 = cinfo->colormap[1];
  178771. JSAMPROW colormap2 = cinfo->colormap[2];
  178772. SHIFT_TEMPS
  178773. for (row = 0; row < num_rows; row++) {
  178774. inptr = input_buf[row];
  178775. outptr = output_buf[row];
  178776. if (cquantize->on_odd_row) {
  178777. /* work right to left in this row */
  178778. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178779. outptr += width-1;
  178780. dir = -1;
  178781. dir3 = -3;
  178782. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178783. cquantize->on_odd_row = FALSE; /* flip for next time */
  178784. } else {
  178785. /* work left to right in this row */
  178786. dir = 1;
  178787. dir3 = 3;
  178788. errorptr = cquantize->fserrors; /* => entry before first real column */
  178789. cquantize->on_odd_row = TRUE; /* flip for next time */
  178790. }
  178791. /* Preset error values: no error propagated to first pixel from left */
  178792. cur0 = cur1 = cur2 = 0;
  178793. /* and no error propagated to row below yet */
  178794. belowerr0 = belowerr1 = belowerr2 = 0;
  178795. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178796. for (col = width; col > 0; col--) {
  178797. /* curN holds the error propagated from the previous pixel on the
  178798. * current line. Add the error propagated from the previous line
  178799. * to form the complete error correction term for this pixel, and
  178800. * round the error term (which is expressed * 16) to an integer.
  178801. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178802. * for either sign of the error value.
  178803. * Note: errorptr points to *previous* column's array entry.
  178804. */
  178805. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178806. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178807. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178808. /* Limit the error using transfer function set by init_error_limit.
  178809. * See comments with init_error_limit for rationale.
  178810. */
  178811. cur0 = error_limit[cur0];
  178812. cur1 = error_limit[cur1];
  178813. cur2 = error_limit[cur2];
  178814. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178815. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178816. * this sets the required size of the range_limit array.
  178817. */
  178818. cur0 += GETJSAMPLE(inptr[0]);
  178819. cur1 += GETJSAMPLE(inptr[1]);
  178820. cur2 += GETJSAMPLE(inptr[2]);
  178821. cur0 = GETJSAMPLE(range_limit[cur0]);
  178822. cur1 = GETJSAMPLE(range_limit[cur1]);
  178823. cur2 = GETJSAMPLE(range_limit[cur2]);
  178824. /* Index into the cache with adjusted pixel value */
  178825. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178826. /* If we have not seen this color before, find nearest colormap */
  178827. /* entry and update the cache */
  178828. if (*cachep == 0)
  178829. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178830. /* Now emit the colormap index for this cell */
  178831. { register int pixcode = *cachep - 1;
  178832. *outptr = (JSAMPLE) pixcode;
  178833. /* Compute representation error for this pixel */
  178834. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178835. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178836. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178837. }
  178838. /* Compute error fractions to be propagated to adjacent pixels.
  178839. * Add these into the running sums, and simultaneously shift the
  178840. * next-line error sums left by 1 column.
  178841. */
  178842. { register LOCFSERROR bnexterr, delta;
  178843. bnexterr = cur0; /* Process component 0 */
  178844. delta = cur0 * 2;
  178845. cur0 += delta; /* form error * 3 */
  178846. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178847. cur0 += delta; /* form error * 5 */
  178848. bpreverr0 = belowerr0 + cur0;
  178849. belowerr0 = bnexterr;
  178850. cur0 += delta; /* form error * 7 */
  178851. bnexterr = cur1; /* Process component 1 */
  178852. delta = cur1 * 2;
  178853. cur1 += delta; /* form error * 3 */
  178854. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178855. cur1 += delta; /* form error * 5 */
  178856. bpreverr1 = belowerr1 + cur1;
  178857. belowerr1 = bnexterr;
  178858. cur1 += delta; /* form error * 7 */
  178859. bnexterr = cur2; /* Process component 2 */
  178860. delta = cur2 * 2;
  178861. cur2 += delta; /* form error * 3 */
  178862. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178863. cur2 += delta; /* form error * 5 */
  178864. bpreverr2 = belowerr2 + cur2;
  178865. belowerr2 = bnexterr;
  178866. cur2 += delta; /* form error * 7 */
  178867. }
  178868. /* At this point curN contains the 7/16 error value to be propagated
  178869. * to the next pixel on the current line, and all the errors for the
  178870. * next line have been shifted over. We are therefore ready to move on.
  178871. */
  178872. inptr += dir3; /* Advance pixel pointers to next column */
  178873. outptr += dir;
  178874. errorptr += dir3; /* advance errorptr to current column */
  178875. }
  178876. /* Post-loop cleanup: we must unload the final error values into the
  178877. * final fserrors[] entry. Note we need not unload belowerrN because
  178878. * it is for the dummy column before or after the actual array.
  178879. */
  178880. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178881. errorptr[1] = (FSERROR) bpreverr1;
  178882. errorptr[2] = (FSERROR) bpreverr2;
  178883. }
  178884. }
  178885. /*
  178886. * Initialize the error-limiting transfer function (lookup table).
  178887. * The raw F-S error computation can potentially compute error values of up to
  178888. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178889. * much less, otherwise obviously wrong pixels will be created. (Typical
  178890. * effects include weird fringes at color-area boundaries, isolated bright
  178891. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178892. * is to ensure that the "corners" of the color cube are allocated as output
  178893. * colors; then repeated errors in the same direction cannot cause cascading
  178894. * error buildup. However, that only prevents the error from getting
  178895. * completely out of hand; Aaron Giles reports that error limiting improves
  178896. * the results even with corner colors allocated.
  178897. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178898. * well, but the smoother transfer function used below is even better. Thanks
  178899. * to Aaron Giles for this idea.
  178900. */
  178901. LOCAL(void)
  178902. init_error_limit (j_decompress_ptr cinfo)
  178903. /* Allocate and fill in the error_limiter table */
  178904. {
  178905. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178906. int * table;
  178907. int in, out;
  178908. table = (int *) (*cinfo->mem->alloc_small)
  178909. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178910. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178911. cquantize->error_limiter = table;
  178912. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178913. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178914. out = 0;
  178915. for (in = 0; in < STEPSIZE; in++, out++) {
  178916. table[in] = out; table[-in] = -out;
  178917. }
  178918. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178919. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178920. table[in] = out; table[-in] = -out;
  178921. }
  178922. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178923. for (; in <= MAXJSAMPLE; in++) {
  178924. table[in] = out; table[-in] = -out;
  178925. }
  178926. #undef STEPSIZE
  178927. }
  178928. /*
  178929. * Finish up at the end of each pass.
  178930. */
  178931. METHODDEF(void)
  178932. finish_pass1 (j_decompress_ptr cinfo)
  178933. {
  178934. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178935. /* Select the representative colors and fill in cinfo->colormap */
  178936. cinfo->colormap = cquantize->sv_colormap;
  178937. select_colors(cinfo, cquantize->desired);
  178938. /* Force next pass to zero the color index table */
  178939. cquantize->needs_zeroed = TRUE;
  178940. }
  178941. METHODDEF(void)
  178942. finish_pass2 (j_decompress_ptr)
  178943. {
  178944. /* no work */
  178945. }
  178946. /*
  178947. * Initialize for each processing pass.
  178948. */
  178949. METHODDEF(void)
  178950. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178951. {
  178952. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178953. hist3d histogram = cquantize->histogram;
  178954. int i;
  178955. /* Only F-S dithering or no dithering is supported. */
  178956. /* If user asks for ordered dither, give him F-S. */
  178957. if (cinfo->dither_mode != JDITHER_NONE)
  178958. cinfo->dither_mode = JDITHER_FS;
  178959. if (is_pre_scan) {
  178960. /* Set up method pointers */
  178961. cquantize->pub.color_quantize = prescan_quantize;
  178962. cquantize->pub.finish_pass = finish_pass1;
  178963. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178964. } else {
  178965. /* Set up method pointers */
  178966. if (cinfo->dither_mode == JDITHER_FS)
  178967. cquantize->pub.color_quantize = pass2_fs_dither;
  178968. else
  178969. cquantize->pub.color_quantize = pass2_no_dither;
  178970. cquantize->pub.finish_pass = finish_pass2;
  178971. /* Make sure color count is acceptable */
  178972. i = cinfo->actual_number_of_colors;
  178973. if (i < 1)
  178974. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178975. if (i > MAXNUMCOLORS)
  178976. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178977. if (cinfo->dither_mode == JDITHER_FS) {
  178978. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178979. (3 * SIZEOF(FSERROR)));
  178980. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178981. if (cquantize->fserrors == NULL)
  178982. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178983. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178984. /* Initialize the propagated errors to zero. */
  178985. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178986. /* Make the error-limit table if we didn't already. */
  178987. if (cquantize->error_limiter == NULL)
  178988. init_error_limit(cinfo);
  178989. cquantize->on_odd_row = FALSE;
  178990. }
  178991. }
  178992. /* Zero the histogram or inverse color map, if necessary */
  178993. if (cquantize->needs_zeroed) {
  178994. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178995. jzero_far((void FAR *) histogram[i],
  178996. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178997. }
  178998. cquantize->needs_zeroed = FALSE;
  178999. }
  179000. }
  179001. /*
  179002. * Switch to a new external colormap between output passes.
  179003. */
  179004. METHODDEF(void)
  179005. new_color_map_2_quant (j_decompress_ptr cinfo)
  179006. {
  179007. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179008. /* Reset the inverse color map */
  179009. cquantize->needs_zeroed = TRUE;
  179010. }
  179011. /*
  179012. * Module initialization routine for 2-pass color quantization.
  179013. */
  179014. GLOBAL(void)
  179015. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  179016. {
  179017. my_cquantize_ptr2 cquantize;
  179018. int i;
  179019. cquantize = (my_cquantize_ptr2)
  179020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179021. SIZEOF(my_cquantizer2));
  179022. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  179023. cquantize->pub.start_pass = start_pass_2_quant;
  179024. cquantize->pub.new_color_map = new_color_map_2_quant;
  179025. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  179026. cquantize->error_limiter = NULL;
  179027. /* Make sure jdmaster didn't give me a case I can't handle */
  179028. if (cinfo->out_color_components != 3)
  179029. ERREXIT(cinfo, JERR_NOTIMPL);
  179030. /* Allocate the histogram/inverse colormap storage */
  179031. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179032. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179033. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179034. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179035. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179036. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179037. }
  179038. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179039. /* Allocate storage for the completed colormap, if required.
  179040. * We do this now since it is FAR storage and may affect
  179041. * the memory manager's space calculations.
  179042. */
  179043. if (cinfo->enable_2pass_quant) {
  179044. /* Make sure color count is acceptable */
  179045. int desired = cinfo->desired_number_of_colors;
  179046. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179047. if (desired < 8)
  179048. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179049. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179050. if (desired > MAXNUMCOLORS)
  179051. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179052. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179053. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179054. cquantize->desired = desired;
  179055. } else
  179056. cquantize->sv_colormap = NULL;
  179057. /* Only F-S dithering or no dithering is supported. */
  179058. /* If user asks for ordered dither, give him F-S. */
  179059. if (cinfo->dither_mode != JDITHER_NONE)
  179060. cinfo->dither_mode = JDITHER_FS;
  179061. /* Allocate Floyd-Steinberg workspace if necessary.
  179062. * This isn't really needed until pass 2, but again it is FAR storage.
  179063. * Although we will cope with a later change in dither_mode,
  179064. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179065. */
  179066. if (cinfo->dither_mode == JDITHER_FS) {
  179067. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179068. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179069. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179070. /* Might as well create the error-limiting table too. */
  179071. init_error_limit(cinfo);
  179072. }
  179073. }
  179074. #endif /* QUANT_2PASS_SUPPORTED */
  179075. /*** End of inlined file: jquant2.c ***/
  179076. /*** Start of inlined file: jutils.c ***/
  179077. #define JPEG_INTERNALS
  179078. /*
  179079. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179080. * of a DCT block read in natural order (left to right, top to bottom).
  179081. */
  179082. #if 0 /* This table is not actually needed in v6a */
  179083. const int jpeg_zigzag_order[DCTSIZE2] = {
  179084. 0, 1, 5, 6, 14, 15, 27, 28,
  179085. 2, 4, 7, 13, 16, 26, 29, 42,
  179086. 3, 8, 12, 17, 25, 30, 41, 43,
  179087. 9, 11, 18, 24, 31, 40, 44, 53,
  179088. 10, 19, 23, 32, 39, 45, 52, 54,
  179089. 20, 22, 33, 38, 46, 51, 55, 60,
  179090. 21, 34, 37, 47, 50, 56, 59, 61,
  179091. 35, 36, 48, 49, 57, 58, 62, 63
  179092. };
  179093. #endif
  179094. /*
  179095. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179096. * of zigzag order.
  179097. *
  179098. * When reading corrupted data, the Huffman decoders could attempt
  179099. * to reference an entry beyond the end of this array (if the decoded
  179100. * zero run length reaches past the end of the block). To prevent
  179101. * wild stores without adding an inner-loop test, we put some extra
  179102. * "63"s after the real entries. This will cause the extra coefficient
  179103. * to be stored in location 63 of the block, not somewhere random.
  179104. * The worst case would be a run-length of 15, which means we need 16
  179105. * fake entries.
  179106. */
  179107. const int jpeg_natural_order[DCTSIZE2+16] = {
  179108. 0, 1, 8, 16, 9, 2, 3, 10,
  179109. 17, 24, 32, 25, 18, 11, 4, 5,
  179110. 12, 19, 26, 33, 40, 48, 41, 34,
  179111. 27, 20, 13, 6, 7, 14, 21, 28,
  179112. 35, 42, 49, 56, 57, 50, 43, 36,
  179113. 29, 22, 15, 23, 30, 37, 44, 51,
  179114. 58, 59, 52, 45, 38, 31, 39, 46,
  179115. 53, 60, 61, 54, 47, 55, 62, 63,
  179116. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179117. 63, 63, 63, 63, 63, 63, 63, 63
  179118. };
  179119. /*
  179120. * Arithmetic utilities
  179121. */
  179122. GLOBAL(long)
  179123. jdiv_round_up (long a, long b)
  179124. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179125. /* Assumes a >= 0, b > 0 */
  179126. {
  179127. return (a + b - 1L) / b;
  179128. }
  179129. GLOBAL(long)
  179130. jround_up (long a, long b)
  179131. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179132. /* Assumes a >= 0, b > 0 */
  179133. {
  179134. a += b - 1L;
  179135. return a - (a % b);
  179136. }
  179137. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179138. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179139. * are FAR and we're assuming a small-pointer memory model. However, some
  179140. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179141. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179142. * Otherwise, the routines below do it the hard way. (The performance cost
  179143. * is not all that great, because these routines aren't very heavily used.)
  179144. */
  179145. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179146. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179147. #define FMEMZERO(target,size) MEMZERO(target,size)
  179148. #else /* 80x86 case, define if we can */
  179149. #ifdef USE_FMEM
  179150. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179151. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179152. #endif
  179153. #endif
  179154. GLOBAL(void)
  179155. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179156. JSAMPARRAY output_array, int dest_row,
  179157. int num_rows, JDIMENSION num_cols)
  179158. /* Copy some rows of samples from one place to another.
  179159. * num_rows rows are copied from input_array[source_row++]
  179160. * to output_array[dest_row++]; these areas may overlap for duplication.
  179161. * The source and destination arrays must be at least as wide as num_cols.
  179162. */
  179163. {
  179164. register JSAMPROW inptr, outptr;
  179165. #ifdef FMEMCOPY
  179166. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179167. #else
  179168. register JDIMENSION count;
  179169. #endif
  179170. register int row;
  179171. input_array += source_row;
  179172. output_array += dest_row;
  179173. for (row = num_rows; row > 0; row--) {
  179174. inptr = *input_array++;
  179175. outptr = *output_array++;
  179176. #ifdef FMEMCOPY
  179177. FMEMCOPY(outptr, inptr, count);
  179178. #else
  179179. for (count = num_cols; count > 0; count--)
  179180. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179181. #endif
  179182. }
  179183. }
  179184. GLOBAL(void)
  179185. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179186. JDIMENSION num_blocks)
  179187. /* Copy a row of coefficient blocks from one place to another. */
  179188. {
  179189. #ifdef FMEMCOPY
  179190. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179191. #else
  179192. register JCOEFPTR inptr, outptr;
  179193. register long count;
  179194. inptr = (JCOEFPTR) input_row;
  179195. outptr = (JCOEFPTR) output_row;
  179196. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179197. *outptr++ = *inptr++;
  179198. }
  179199. #endif
  179200. }
  179201. GLOBAL(void)
  179202. jzero_far (void FAR * target, size_t bytestozero)
  179203. /* Zero out a chunk of FAR memory. */
  179204. /* This might be sample-array data, block-array data, or alloc_large data. */
  179205. {
  179206. #ifdef FMEMZERO
  179207. FMEMZERO(target, bytestozero);
  179208. #else
  179209. register char FAR * ptr = (char FAR *) target;
  179210. register size_t count;
  179211. for (count = bytestozero; count > 0; count--) {
  179212. *ptr++ = 0;
  179213. }
  179214. #endif
  179215. }
  179216. /*** End of inlined file: jutils.c ***/
  179217. /*** Start of inlined file: transupp.c ***/
  179218. /* Although this file really shouldn't have access to the library internals,
  179219. * it's helpful to let it call jround_up() and jcopy_block_row().
  179220. */
  179221. #define JPEG_INTERNALS
  179222. /*** Start of inlined file: transupp.h ***/
  179223. /* If you happen not to want the image transform support, disable it here */
  179224. #ifndef TRANSFORMS_SUPPORTED
  179225. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179226. #endif
  179227. /* Short forms of external names for systems with brain-damaged linkers. */
  179228. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179229. #define jtransform_request_workspace jTrRequest
  179230. #define jtransform_adjust_parameters jTrAdjust
  179231. #define jtransform_execute_transformation jTrExec
  179232. #define jcopy_markers_setup jCMrkSetup
  179233. #define jcopy_markers_execute jCMrkExec
  179234. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179235. /*
  179236. * Codes for supported types of image transformations.
  179237. */
  179238. typedef enum {
  179239. JXFORM_NONE, /* no transformation */
  179240. JXFORM_FLIP_H, /* horizontal flip */
  179241. JXFORM_FLIP_V, /* vertical flip */
  179242. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179243. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179244. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179245. JXFORM_ROT_180, /* 180-degree rotation */
  179246. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179247. } JXFORM_CODE;
  179248. /*
  179249. * Although rotating and flipping data expressed as DCT coefficients is not
  179250. * hard, there is an asymmetry in the JPEG format specification for images
  179251. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179252. * image edges are padded out to the next iMCU boundary with junk data; but
  179253. * no padding is possible at the top and left edges. If we were to flip
  179254. * the whole image including the pad data, then pad garbage would become
  179255. * visible at the top and/or left, and real pixels would disappear into the
  179256. * pad margins --- perhaps permanently, since encoders & decoders may not
  179257. * bother to preserve DCT blocks that appear to be completely outside the
  179258. * nominal image area. So, we have to exclude any partial iMCUs from the
  179259. * basic transformation.
  179260. *
  179261. * Transpose is the only transformation that can handle partial iMCUs at the
  179262. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179263. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179264. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179265. * The other transforms are defined as combinations of these basic transforms
  179266. * and process edge blocks in a way that preserves the equivalence.
  179267. *
  179268. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179269. * this is not strictly lossless, but it usually gives the best-looking
  179270. * result for odd-size images. Note that when this option is active,
  179271. * the expected mathematical equivalences between the transforms may not hold.
  179272. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179273. * followed by -rot 180 -trim trims both edges.)
  179274. *
  179275. * We also offer a "force to grayscale" option, which simply discards the
  179276. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179277. * the luminance channel is preserved exactly. It's not the same kind of
  179278. * thing as the rotate/flip transformations, but it's convenient to handle it
  179279. * as part of this package, mainly because the transformation routines have to
  179280. * be aware of the option to know how many components to work on.
  179281. */
  179282. typedef struct {
  179283. /* Options: set by caller */
  179284. JXFORM_CODE transform; /* image transform operator */
  179285. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179286. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179287. /* Internal workspace: caller should not touch these */
  179288. int num_components; /* # of components in workspace */
  179289. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179290. } jpeg_transform_info;
  179291. #if TRANSFORMS_SUPPORTED
  179292. /* Request any required workspace */
  179293. EXTERN(void) jtransform_request_workspace
  179294. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179295. /* Adjust output image parameters */
  179296. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179297. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179298. jvirt_barray_ptr *src_coef_arrays,
  179299. jpeg_transform_info *info));
  179300. /* Execute the actual transformation, if any */
  179301. EXTERN(void) jtransform_execute_transformation
  179302. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179303. jvirt_barray_ptr *src_coef_arrays,
  179304. jpeg_transform_info *info));
  179305. #endif /* TRANSFORMS_SUPPORTED */
  179306. /*
  179307. * Support for copying optional markers from source to destination file.
  179308. */
  179309. typedef enum {
  179310. JCOPYOPT_NONE, /* copy no optional markers */
  179311. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179312. JCOPYOPT_ALL /* copy all optional markers */
  179313. } JCOPY_OPTION;
  179314. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179315. /* Setup decompression object to save desired markers in memory */
  179316. EXTERN(void) jcopy_markers_setup
  179317. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179318. /* Copy markers saved in the given source object to the destination object */
  179319. EXTERN(void) jcopy_markers_execute
  179320. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179321. JCOPY_OPTION option));
  179322. /*** End of inlined file: transupp.h ***/
  179323. /* My own external interface */
  179324. #if TRANSFORMS_SUPPORTED
  179325. /*
  179326. * Lossless image transformation routines. These routines work on DCT
  179327. * coefficient arrays and thus do not require any lossy decompression
  179328. * or recompression of the image.
  179329. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179330. *
  179331. * Horizontal flipping is done in-place, using a single top-to-bottom
  179332. * pass through the virtual source array. It will thus be much the
  179333. * fastest option for images larger than main memory.
  179334. *
  179335. * The other routines require a set of destination virtual arrays, so they
  179336. * need twice as much memory as jpegtran normally does. The destination
  179337. * arrays are always written in normal scan order (top to bottom) because
  179338. * the virtual array manager expects this. The source arrays will be scanned
  179339. * in the corresponding order, which means multiple passes through the source
  179340. * arrays for most of the transforms. That could result in much thrashing
  179341. * if the image is larger than main memory.
  179342. *
  179343. * Some notes about the operating environment of the individual transform
  179344. * routines:
  179345. * 1. Both the source and destination virtual arrays are allocated from the
  179346. * source JPEG object, and therefore should be manipulated by calling the
  179347. * source's memory manager.
  179348. * 2. The destination's component count should be used. It may be smaller
  179349. * than the source's when forcing to grayscale.
  179350. * 3. Likewise the destination's sampling factors should be used. When
  179351. * forcing to grayscale the destination's sampling factors will be all 1,
  179352. * and we may as well take that as the effective iMCU size.
  179353. * 4. When "trim" is in effect, the destination's dimensions will be the
  179354. * trimmed values but the source's will be untrimmed.
  179355. * 5. All the routines assume that the source and destination buffers are
  179356. * padded out to a full iMCU boundary. This is true, although for the
  179357. * source buffer it is an undocumented property of jdcoefct.c.
  179358. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179359. * dimensions and ignore the source's.
  179360. */
  179361. LOCAL(void)
  179362. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179363. jvirt_barray_ptr *src_coef_arrays)
  179364. /* Horizontal flip; done in-place, so no separate dest array is required */
  179365. {
  179366. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179367. int ci, k, offset_y;
  179368. JBLOCKARRAY buffer;
  179369. JCOEFPTR ptr1, ptr2;
  179370. JCOEF temp1, temp2;
  179371. jpeg_component_info *compptr;
  179372. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179373. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179374. * mirroring by changing the signs of odd-numbered columns.
  179375. * Partial iMCUs at the right edge are left untouched.
  179376. */
  179377. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179378. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179379. compptr = dstinfo->comp_info + ci;
  179380. comp_width = MCU_cols * compptr->h_samp_factor;
  179381. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179382. blk_y += compptr->v_samp_factor) {
  179383. buffer = (*srcinfo->mem->access_virt_barray)
  179384. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179385. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179386. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179387. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179388. ptr1 = buffer[offset_y][blk_x];
  179389. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179390. /* this unrolled loop doesn't need to know which row it's on... */
  179391. for (k = 0; k < DCTSIZE2; k += 2) {
  179392. temp1 = *ptr1; /* swap even column */
  179393. temp2 = *ptr2;
  179394. *ptr1++ = temp2;
  179395. *ptr2++ = temp1;
  179396. temp1 = *ptr1; /* swap odd column with sign change */
  179397. temp2 = *ptr2;
  179398. *ptr1++ = -temp2;
  179399. *ptr2++ = -temp1;
  179400. }
  179401. }
  179402. }
  179403. }
  179404. }
  179405. }
  179406. LOCAL(void)
  179407. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179408. jvirt_barray_ptr *src_coef_arrays,
  179409. jvirt_barray_ptr *dst_coef_arrays)
  179410. /* Vertical flip */
  179411. {
  179412. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179413. int ci, i, j, offset_y;
  179414. JBLOCKARRAY src_buffer, dst_buffer;
  179415. JBLOCKROW src_row_ptr, dst_row_ptr;
  179416. JCOEFPTR src_ptr, dst_ptr;
  179417. jpeg_component_info *compptr;
  179418. /* We output into a separate array because we can't touch different
  179419. * rows of the source virtual array simultaneously. Otherwise, this
  179420. * is a pretty straightforward analog of horizontal flip.
  179421. * Within a DCT block, vertical mirroring is done by changing the signs
  179422. * of odd-numbered rows.
  179423. * Partial iMCUs at the bottom edge are copied verbatim.
  179424. */
  179425. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179426. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179427. compptr = dstinfo->comp_info + ci;
  179428. comp_height = MCU_rows * compptr->v_samp_factor;
  179429. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179430. dst_blk_y += compptr->v_samp_factor) {
  179431. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179432. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179433. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179434. if (dst_blk_y < comp_height) {
  179435. /* Row is within the mirrorable area. */
  179436. src_buffer = (*srcinfo->mem->access_virt_barray)
  179437. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179438. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179439. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179440. } else {
  179441. /* Bottom-edge blocks will be copied verbatim. */
  179442. src_buffer = (*srcinfo->mem->access_virt_barray)
  179443. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179444. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179445. }
  179446. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179447. if (dst_blk_y < comp_height) {
  179448. /* Row is within the mirrorable area. */
  179449. dst_row_ptr = dst_buffer[offset_y];
  179450. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179451. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179452. dst_blk_x++) {
  179453. dst_ptr = dst_row_ptr[dst_blk_x];
  179454. src_ptr = src_row_ptr[dst_blk_x];
  179455. for (i = 0; i < DCTSIZE; i += 2) {
  179456. /* copy even row */
  179457. for (j = 0; j < DCTSIZE; j++)
  179458. *dst_ptr++ = *src_ptr++;
  179459. /* copy odd row with sign change */
  179460. for (j = 0; j < DCTSIZE; j++)
  179461. *dst_ptr++ = - *src_ptr++;
  179462. }
  179463. }
  179464. } else {
  179465. /* Just copy row verbatim. */
  179466. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179467. compptr->width_in_blocks);
  179468. }
  179469. }
  179470. }
  179471. }
  179472. }
  179473. LOCAL(void)
  179474. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179475. jvirt_barray_ptr *src_coef_arrays,
  179476. jvirt_barray_ptr *dst_coef_arrays)
  179477. /* Transpose source into destination */
  179478. {
  179479. JDIMENSION dst_blk_x, dst_blk_y;
  179480. int ci, i, j, offset_x, offset_y;
  179481. JBLOCKARRAY src_buffer, dst_buffer;
  179482. JCOEFPTR src_ptr, dst_ptr;
  179483. jpeg_component_info *compptr;
  179484. /* Transposing pixels within a block just requires transposing the
  179485. * DCT coefficients.
  179486. * Partial iMCUs at the edges require no special treatment; we simply
  179487. * process all the available DCT blocks for every component.
  179488. */
  179489. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179490. compptr = dstinfo->comp_info + ci;
  179491. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179492. dst_blk_y += compptr->v_samp_factor) {
  179493. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179494. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179495. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179496. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179497. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179498. dst_blk_x += compptr->h_samp_factor) {
  179499. src_buffer = (*srcinfo->mem->access_virt_barray)
  179500. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179501. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179502. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179503. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179504. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179505. for (i = 0; i < DCTSIZE; i++)
  179506. for (j = 0; j < DCTSIZE; j++)
  179507. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179508. }
  179509. }
  179510. }
  179511. }
  179512. }
  179513. }
  179514. LOCAL(void)
  179515. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179516. jvirt_barray_ptr *src_coef_arrays,
  179517. jvirt_barray_ptr *dst_coef_arrays)
  179518. /* 90 degree rotation is equivalent to
  179519. * 1. Transposing the image;
  179520. * 2. Horizontal mirroring.
  179521. * These two steps are merged into a single processing routine.
  179522. */
  179523. {
  179524. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179525. int ci, i, j, offset_x, offset_y;
  179526. JBLOCKARRAY src_buffer, dst_buffer;
  179527. JCOEFPTR src_ptr, dst_ptr;
  179528. jpeg_component_info *compptr;
  179529. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179530. * at the (output) right edge properly. They just get transposed and
  179531. * not mirrored.
  179532. */
  179533. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179534. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179535. compptr = dstinfo->comp_info + ci;
  179536. comp_width = MCU_cols * compptr->h_samp_factor;
  179537. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179538. dst_blk_y += compptr->v_samp_factor) {
  179539. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179540. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179541. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179542. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179543. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179544. dst_blk_x += compptr->h_samp_factor) {
  179545. src_buffer = (*srcinfo->mem->access_virt_barray)
  179546. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179547. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179548. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179549. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179550. if (dst_blk_x < comp_width) {
  179551. /* Block is within the mirrorable area. */
  179552. dst_ptr = dst_buffer[offset_y]
  179553. [comp_width - dst_blk_x - offset_x - 1];
  179554. for (i = 0; i < DCTSIZE; i++) {
  179555. for (j = 0; j < DCTSIZE; j++)
  179556. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179557. i++;
  179558. for (j = 0; j < DCTSIZE; j++)
  179559. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179560. }
  179561. } else {
  179562. /* Edge blocks are transposed but not mirrored. */
  179563. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179564. for (i = 0; i < DCTSIZE; i++)
  179565. for (j = 0; j < DCTSIZE; j++)
  179566. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179567. }
  179568. }
  179569. }
  179570. }
  179571. }
  179572. }
  179573. }
  179574. LOCAL(void)
  179575. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179576. jvirt_barray_ptr *src_coef_arrays,
  179577. jvirt_barray_ptr *dst_coef_arrays)
  179578. /* 270 degree rotation is equivalent to
  179579. * 1. Horizontal mirroring;
  179580. * 2. Transposing the image.
  179581. * These two steps are merged into a single processing routine.
  179582. */
  179583. {
  179584. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179585. int ci, i, j, offset_x, offset_y;
  179586. JBLOCKARRAY src_buffer, dst_buffer;
  179587. JCOEFPTR src_ptr, dst_ptr;
  179588. jpeg_component_info *compptr;
  179589. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179590. * at the (output) bottom edge properly. They just get transposed and
  179591. * not mirrored.
  179592. */
  179593. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179594. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179595. compptr = dstinfo->comp_info + ci;
  179596. comp_height = MCU_rows * compptr->v_samp_factor;
  179597. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179598. dst_blk_y += compptr->v_samp_factor) {
  179599. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179600. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179601. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179602. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179603. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179604. dst_blk_x += compptr->h_samp_factor) {
  179605. src_buffer = (*srcinfo->mem->access_virt_barray)
  179606. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179607. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179608. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179609. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179610. if (dst_blk_y < comp_height) {
  179611. /* Block is within the mirrorable area. */
  179612. src_ptr = src_buffer[offset_x]
  179613. [comp_height - dst_blk_y - offset_y - 1];
  179614. for (i = 0; i < DCTSIZE; i++) {
  179615. for (j = 0; j < DCTSIZE; j++) {
  179616. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179617. j++;
  179618. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179619. }
  179620. }
  179621. } else {
  179622. /* Edge blocks are transposed but not mirrored. */
  179623. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179624. for (i = 0; i < DCTSIZE; i++)
  179625. for (j = 0; j < DCTSIZE; j++)
  179626. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179627. }
  179628. }
  179629. }
  179630. }
  179631. }
  179632. }
  179633. }
  179634. LOCAL(void)
  179635. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179636. jvirt_barray_ptr *src_coef_arrays,
  179637. jvirt_barray_ptr *dst_coef_arrays)
  179638. /* 180 degree rotation is equivalent to
  179639. * 1. Vertical mirroring;
  179640. * 2. Horizontal mirroring.
  179641. * These two steps are merged into a single processing routine.
  179642. */
  179643. {
  179644. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179645. int ci, i, j, offset_y;
  179646. JBLOCKARRAY src_buffer, dst_buffer;
  179647. JBLOCKROW src_row_ptr, dst_row_ptr;
  179648. JCOEFPTR src_ptr, dst_ptr;
  179649. jpeg_component_info *compptr;
  179650. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179651. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179652. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179653. compptr = dstinfo->comp_info + ci;
  179654. comp_width = MCU_cols * compptr->h_samp_factor;
  179655. comp_height = MCU_rows * compptr->v_samp_factor;
  179656. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179657. dst_blk_y += compptr->v_samp_factor) {
  179658. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179659. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179660. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179661. if (dst_blk_y < comp_height) {
  179662. /* Row is within the vertically mirrorable area. */
  179663. src_buffer = (*srcinfo->mem->access_virt_barray)
  179664. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179665. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179666. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179667. } else {
  179668. /* Bottom-edge rows are only mirrored horizontally. */
  179669. src_buffer = (*srcinfo->mem->access_virt_barray)
  179670. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179671. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179672. }
  179673. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179674. if (dst_blk_y < comp_height) {
  179675. /* Row is within the mirrorable area. */
  179676. dst_row_ptr = dst_buffer[offset_y];
  179677. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179678. /* Process the blocks that can be mirrored both ways. */
  179679. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179680. dst_ptr = dst_row_ptr[dst_blk_x];
  179681. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179682. for (i = 0; i < DCTSIZE; i += 2) {
  179683. /* For even row, negate every odd column. */
  179684. for (j = 0; j < DCTSIZE; j += 2) {
  179685. *dst_ptr++ = *src_ptr++;
  179686. *dst_ptr++ = - *src_ptr++;
  179687. }
  179688. /* For odd row, negate every even column. */
  179689. for (j = 0; j < DCTSIZE; j += 2) {
  179690. *dst_ptr++ = - *src_ptr++;
  179691. *dst_ptr++ = *src_ptr++;
  179692. }
  179693. }
  179694. }
  179695. /* Any remaining right-edge blocks are only mirrored vertically. */
  179696. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179697. dst_ptr = dst_row_ptr[dst_blk_x];
  179698. src_ptr = src_row_ptr[dst_blk_x];
  179699. for (i = 0; i < DCTSIZE; i += 2) {
  179700. for (j = 0; j < DCTSIZE; j++)
  179701. *dst_ptr++ = *src_ptr++;
  179702. for (j = 0; j < DCTSIZE; j++)
  179703. *dst_ptr++ = - *src_ptr++;
  179704. }
  179705. }
  179706. } else {
  179707. /* Remaining rows are just mirrored horizontally. */
  179708. dst_row_ptr = dst_buffer[offset_y];
  179709. src_row_ptr = src_buffer[offset_y];
  179710. /* Process the blocks that can be mirrored. */
  179711. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179712. dst_ptr = dst_row_ptr[dst_blk_x];
  179713. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179714. for (i = 0; i < DCTSIZE2; i += 2) {
  179715. *dst_ptr++ = *src_ptr++;
  179716. *dst_ptr++ = - *src_ptr++;
  179717. }
  179718. }
  179719. /* Any remaining right-edge blocks are only copied. */
  179720. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179721. dst_ptr = dst_row_ptr[dst_blk_x];
  179722. src_ptr = src_row_ptr[dst_blk_x];
  179723. for (i = 0; i < DCTSIZE2; i++)
  179724. *dst_ptr++ = *src_ptr++;
  179725. }
  179726. }
  179727. }
  179728. }
  179729. }
  179730. }
  179731. LOCAL(void)
  179732. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179733. jvirt_barray_ptr *src_coef_arrays,
  179734. jvirt_barray_ptr *dst_coef_arrays)
  179735. /* Transverse transpose is equivalent to
  179736. * 1. 180 degree rotation;
  179737. * 2. Transposition;
  179738. * or
  179739. * 1. Horizontal mirroring;
  179740. * 2. Transposition;
  179741. * 3. Horizontal mirroring.
  179742. * These steps are merged into a single processing routine.
  179743. */
  179744. {
  179745. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179746. int ci, i, j, offset_x, offset_y;
  179747. JBLOCKARRAY src_buffer, dst_buffer;
  179748. JCOEFPTR src_ptr, dst_ptr;
  179749. jpeg_component_info *compptr;
  179750. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179751. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179752. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179753. compptr = dstinfo->comp_info + ci;
  179754. comp_width = MCU_cols * compptr->h_samp_factor;
  179755. comp_height = MCU_rows * compptr->v_samp_factor;
  179756. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179757. dst_blk_y += compptr->v_samp_factor) {
  179758. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179759. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179760. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179761. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179762. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179763. dst_blk_x += compptr->h_samp_factor) {
  179764. src_buffer = (*srcinfo->mem->access_virt_barray)
  179765. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179766. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179767. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179768. if (dst_blk_y < comp_height) {
  179769. src_ptr = src_buffer[offset_x]
  179770. [comp_height - dst_blk_y - offset_y - 1];
  179771. if (dst_blk_x < comp_width) {
  179772. /* Block is within the mirrorable area. */
  179773. dst_ptr = dst_buffer[offset_y]
  179774. [comp_width - dst_blk_x - offset_x - 1];
  179775. for (i = 0; i < DCTSIZE; i++) {
  179776. for (j = 0; j < DCTSIZE; j++) {
  179777. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179778. j++;
  179779. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179780. }
  179781. i++;
  179782. for (j = 0; j < DCTSIZE; j++) {
  179783. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179784. j++;
  179785. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179786. }
  179787. }
  179788. } else {
  179789. /* Right-edge blocks are mirrored in y only */
  179790. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179791. for (i = 0; i < DCTSIZE; i++) {
  179792. for (j = 0; j < DCTSIZE; j++) {
  179793. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179794. j++;
  179795. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179796. }
  179797. }
  179798. }
  179799. } else {
  179800. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179801. if (dst_blk_x < comp_width) {
  179802. /* Bottom-edge blocks are mirrored in x only */
  179803. dst_ptr = dst_buffer[offset_y]
  179804. [comp_width - dst_blk_x - offset_x - 1];
  179805. for (i = 0; i < DCTSIZE; i++) {
  179806. for (j = 0; j < DCTSIZE; j++)
  179807. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179808. i++;
  179809. for (j = 0; j < DCTSIZE; j++)
  179810. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179811. }
  179812. } else {
  179813. /* At lower right corner, just transpose, no mirroring */
  179814. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179815. for (i = 0; i < DCTSIZE; i++)
  179816. for (j = 0; j < DCTSIZE; j++)
  179817. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179818. }
  179819. }
  179820. }
  179821. }
  179822. }
  179823. }
  179824. }
  179825. }
  179826. /* Request any required workspace.
  179827. *
  179828. * We allocate the workspace virtual arrays from the source decompression
  179829. * object, so that all the arrays (both the original data and the workspace)
  179830. * will be taken into account while making memory management decisions.
  179831. * Hence, this routine must be called after jpeg_read_header (which reads
  179832. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179833. * the source's virtual arrays).
  179834. */
  179835. GLOBAL(void)
  179836. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179837. jpeg_transform_info *info)
  179838. {
  179839. jvirt_barray_ptr *coef_arrays = NULL;
  179840. jpeg_component_info *compptr;
  179841. int ci;
  179842. if (info->force_grayscale &&
  179843. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179844. srcinfo->num_components == 3) {
  179845. /* We'll only process the first component */
  179846. info->num_components = 1;
  179847. } else {
  179848. /* Process all the components */
  179849. info->num_components = srcinfo->num_components;
  179850. }
  179851. switch (info->transform) {
  179852. case JXFORM_NONE:
  179853. case JXFORM_FLIP_H:
  179854. /* Don't need a workspace array */
  179855. break;
  179856. case JXFORM_FLIP_V:
  179857. case JXFORM_ROT_180:
  179858. /* Need workspace arrays having same dimensions as source image.
  179859. * Note that we allocate arrays padded out to the next iMCU boundary,
  179860. * so that transform routines need not worry about missing edge blocks.
  179861. */
  179862. coef_arrays = (jvirt_barray_ptr *)
  179863. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179864. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179865. for (ci = 0; ci < info->num_components; ci++) {
  179866. compptr = srcinfo->comp_info + ci;
  179867. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179868. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179869. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179870. (long) compptr->h_samp_factor),
  179871. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179872. (long) compptr->v_samp_factor),
  179873. (JDIMENSION) compptr->v_samp_factor);
  179874. }
  179875. break;
  179876. case JXFORM_TRANSPOSE:
  179877. case JXFORM_TRANSVERSE:
  179878. case JXFORM_ROT_90:
  179879. case JXFORM_ROT_270:
  179880. /* Need workspace arrays having transposed dimensions.
  179881. * Note that we allocate arrays padded out to the next iMCU boundary,
  179882. * so that transform routines need not worry about missing edge blocks.
  179883. */
  179884. coef_arrays = (jvirt_barray_ptr *)
  179885. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179886. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179887. for (ci = 0; ci < info->num_components; ci++) {
  179888. compptr = srcinfo->comp_info + ci;
  179889. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179890. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179891. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179892. (long) compptr->v_samp_factor),
  179893. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179894. (long) compptr->h_samp_factor),
  179895. (JDIMENSION) compptr->h_samp_factor);
  179896. }
  179897. break;
  179898. }
  179899. info->workspace_coef_arrays = coef_arrays;
  179900. }
  179901. /* Transpose destination image parameters */
  179902. LOCAL(void)
  179903. transpose_critical_parameters (j_compress_ptr dstinfo)
  179904. {
  179905. int tblno, i, j, ci, itemp;
  179906. jpeg_component_info *compptr;
  179907. JQUANT_TBL *qtblptr;
  179908. JDIMENSION dtemp;
  179909. UINT16 qtemp;
  179910. /* Transpose basic image dimensions */
  179911. dtemp = dstinfo->image_width;
  179912. dstinfo->image_width = dstinfo->image_height;
  179913. dstinfo->image_height = dtemp;
  179914. /* Transpose sampling factors */
  179915. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179916. compptr = dstinfo->comp_info + ci;
  179917. itemp = compptr->h_samp_factor;
  179918. compptr->h_samp_factor = compptr->v_samp_factor;
  179919. compptr->v_samp_factor = itemp;
  179920. }
  179921. /* Transpose quantization tables */
  179922. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179923. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179924. if (qtblptr != NULL) {
  179925. for (i = 0; i < DCTSIZE; i++) {
  179926. for (j = 0; j < i; j++) {
  179927. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179928. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179929. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179930. }
  179931. }
  179932. }
  179933. }
  179934. }
  179935. /* Trim off any partial iMCUs on the indicated destination edge */
  179936. LOCAL(void)
  179937. trim_right_edge (j_compress_ptr dstinfo)
  179938. {
  179939. int ci, max_h_samp_factor;
  179940. JDIMENSION MCU_cols;
  179941. /* We have to compute max_h_samp_factor ourselves,
  179942. * because it hasn't been set yet in the destination
  179943. * (and we don't want to use the source's value).
  179944. */
  179945. max_h_samp_factor = 1;
  179946. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179947. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179948. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179949. }
  179950. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179951. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179952. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179953. }
  179954. LOCAL(void)
  179955. trim_bottom_edge (j_compress_ptr dstinfo)
  179956. {
  179957. int ci, max_v_samp_factor;
  179958. JDIMENSION MCU_rows;
  179959. /* We have to compute max_v_samp_factor ourselves,
  179960. * because it hasn't been set yet in the destination
  179961. * (and we don't want to use the source's value).
  179962. */
  179963. max_v_samp_factor = 1;
  179964. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179965. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179966. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179967. }
  179968. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179969. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179970. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179971. }
  179972. /* Adjust output image parameters as needed.
  179973. *
  179974. * This must be called after jpeg_copy_critical_parameters()
  179975. * and before jpeg_write_coefficients().
  179976. *
  179977. * The return value is the set of virtual coefficient arrays to be written
  179978. * (either the ones allocated by jtransform_request_workspace, or the
  179979. * original source data arrays). The caller will need to pass this value
  179980. * to jpeg_write_coefficients().
  179981. */
  179982. GLOBAL(jvirt_barray_ptr *)
  179983. jtransform_adjust_parameters (j_decompress_ptr,
  179984. j_compress_ptr dstinfo,
  179985. jvirt_barray_ptr *src_coef_arrays,
  179986. jpeg_transform_info *info)
  179987. {
  179988. /* If force-to-grayscale is requested, adjust destination parameters */
  179989. if (info->force_grayscale) {
  179990. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179991. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179992. * will get set to 1, which typically won't match the source.
  179993. * In fact we do this even if the source is already grayscale; that
  179994. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179995. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179996. */
  179997. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179998. dstinfo->num_components == 3) ||
  179999. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  180000. dstinfo->num_components == 1)) {
  180001. /* We have to preserve the source's quantization table number. */
  180002. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  180003. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  180004. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  180005. } else {
  180006. /* Sorry, can't do it */
  180007. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  180008. }
  180009. }
  180010. /* Correct the destination's image dimensions etc if necessary */
  180011. switch (info->transform) {
  180012. case JXFORM_NONE:
  180013. /* Nothing to do */
  180014. break;
  180015. case JXFORM_FLIP_H:
  180016. if (info->trim)
  180017. trim_right_edge(dstinfo);
  180018. break;
  180019. case JXFORM_FLIP_V:
  180020. if (info->trim)
  180021. trim_bottom_edge(dstinfo);
  180022. break;
  180023. case JXFORM_TRANSPOSE:
  180024. transpose_critical_parameters(dstinfo);
  180025. /* transpose does NOT have to trim anything */
  180026. break;
  180027. case JXFORM_TRANSVERSE:
  180028. transpose_critical_parameters(dstinfo);
  180029. if (info->trim) {
  180030. trim_right_edge(dstinfo);
  180031. trim_bottom_edge(dstinfo);
  180032. }
  180033. break;
  180034. case JXFORM_ROT_90:
  180035. transpose_critical_parameters(dstinfo);
  180036. if (info->trim)
  180037. trim_right_edge(dstinfo);
  180038. break;
  180039. case JXFORM_ROT_180:
  180040. if (info->trim) {
  180041. trim_right_edge(dstinfo);
  180042. trim_bottom_edge(dstinfo);
  180043. }
  180044. break;
  180045. case JXFORM_ROT_270:
  180046. transpose_critical_parameters(dstinfo);
  180047. if (info->trim)
  180048. trim_bottom_edge(dstinfo);
  180049. break;
  180050. }
  180051. /* Return the appropriate output data set */
  180052. if (info->workspace_coef_arrays != NULL)
  180053. return info->workspace_coef_arrays;
  180054. return src_coef_arrays;
  180055. }
  180056. /* Execute the actual transformation, if any.
  180057. *
  180058. * This must be called *after* jpeg_write_coefficients, because it depends
  180059. * on jpeg_write_coefficients to have computed subsidiary values such as
  180060. * the per-component width and height fields in the destination object.
  180061. *
  180062. * Note that some transformations will modify the source data arrays!
  180063. */
  180064. GLOBAL(void)
  180065. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180066. j_compress_ptr dstinfo,
  180067. jvirt_barray_ptr *src_coef_arrays,
  180068. jpeg_transform_info *info)
  180069. {
  180070. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180071. switch (info->transform) {
  180072. case JXFORM_NONE:
  180073. break;
  180074. case JXFORM_FLIP_H:
  180075. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180076. break;
  180077. case JXFORM_FLIP_V:
  180078. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180079. break;
  180080. case JXFORM_TRANSPOSE:
  180081. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180082. break;
  180083. case JXFORM_TRANSVERSE:
  180084. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180085. break;
  180086. case JXFORM_ROT_90:
  180087. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180088. break;
  180089. case JXFORM_ROT_180:
  180090. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180091. break;
  180092. case JXFORM_ROT_270:
  180093. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180094. break;
  180095. }
  180096. }
  180097. #endif /* TRANSFORMS_SUPPORTED */
  180098. /* Setup decompression object to save desired markers in memory.
  180099. * This must be called before jpeg_read_header() to have the desired effect.
  180100. */
  180101. GLOBAL(void)
  180102. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180103. {
  180104. #ifdef SAVE_MARKERS_SUPPORTED
  180105. int m;
  180106. /* Save comments except under NONE option */
  180107. if (option != JCOPYOPT_NONE) {
  180108. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180109. }
  180110. /* Save all types of APPn markers iff ALL option */
  180111. if (option == JCOPYOPT_ALL) {
  180112. for (m = 0; m < 16; m++)
  180113. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180114. }
  180115. #endif /* SAVE_MARKERS_SUPPORTED */
  180116. }
  180117. /* Copy markers saved in the given source object to the destination object.
  180118. * This should be called just after jpeg_start_compress() or
  180119. * jpeg_write_coefficients().
  180120. * Note that those routines will have written the SOI, and also the
  180121. * JFIF APP0 or Adobe APP14 markers if selected.
  180122. */
  180123. GLOBAL(void)
  180124. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180125. JCOPY_OPTION)
  180126. {
  180127. jpeg_saved_marker_ptr marker;
  180128. /* In the current implementation, we don't actually need to examine the
  180129. * option flag here; we just copy everything that got saved.
  180130. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180131. * if the encoder library already wrote one.
  180132. */
  180133. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180134. if (dstinfo->write_JFIF_header &&
  180135. marker->marker == JPEG_APP0 &&
  180136. marker->data_length >= 5 &&
  180137. GETJOCTET(marker->data[0]) == 0x4A &&
  180138. GETJOCTET(marker->data[1]) == 0x46 &&
  180139. GETJOCTET(marker->data[2]) == 0x49 &&
  180140. GETJOCTET(marker->data[3]) == 0x46 &&
  180141. GETJOCTET(marker->data[4]) == 0)
  180142. continue; /* reject duplicate JFIF */
  180143. if (dstinfo->write_Adobe_marker &&
  180144. marker->marker == JPEG_APP0+14 &&
  180145. marker->data_length >= 5 &&
  180146. GETJOCTET(marker->data[0]) == 0x41 &&
  180147. GETJOCTET(marker->data[1]) == 0x64 &&
  180148. GETJOCTET(marker->data[2]) == 0x6F &&
  180149. GETJOCTET(marker->data[3]) == 0x62 &&
  180150. GETJOCTET(marker->data[4]) == 0x65)
  180151. continue; /* reject duplicate Adobe */
  180152. #ifdef NEED_FAR_POINTERS
  180153. /* We could use jpeg_write_marker if the data weren't FAR... */
  180154. {
  180155. unsigned int i;
  180156. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180157. for (i = 0; i < marker->data_length; i++)
  180158. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180159. }
  180160. #else
  180161. jpeg_write_marker(dstinfo, marker->marker,
  180162. marker->data, marker->data_length);
  180163. #endif
  180164. }
  180165. }
  180166. /*** End of inlined file: transupp.c ***/
  180167. #else
  180168. #define JPEG_INTERNALS
  180169. #undef FAR
  180170. #include <jpeglib.h>
  180171. #endif
  180172. }
  180173. #undef max
  180174. #undef min
  180175. #if JUCE_MSVC
  180176. #pragma warning (pop)
  180177. #endif
  180178. BEGIN_JUCE_NAMESPACE
  180179. namespace JPEGHelpers
  180180. {
  180181. using namespace jpeglibNamespace;
  180182. #if ! JUCE_MSVC
  180183. using jpeglibNamespace::boolean;
  180184. #endif
  180185. struct JPEGDecodingFailure {};
  180186. static void fatalErrorHandler (j_common_ptr)
  180187. {
  180188. throw JPEGDecodingFailure();
  180189. }
  180190. static void silentErrorCallback1 (j_common_ptr) {}
  180191. static void silentErrorCallback2 (j_common_ptr, int) {}
  180192. static void silentErrorCallback3 (j_common_ptr, char*) {}
  180193. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180194. {
  180195. zerostruct (err);
  180196. err.error_exit = fatalErrorHandler;
  180197. err.emit_message = silentErrorCallback2;
  180198. err.output_message = silentErrorCallback1;
  180199. err.format_message = silentErrorCallback3;
  180200. err.reset_error_mgr = silentErrorCallback1;
  180201. }
  180202. static void dummyCallback1 (j_decompress_ptr)
  180203. {
  180204. }
  180205. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  180206. {
  180207. decompStruct->src->next_input_byte += num;
  180208. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180209. decompStruct->src->bytes_in_buffer -= num;
  180210. }
  180211. static boolean jpegFill (j_decompress_ptr)
  180212. {
  180213. return 0;
  180214. }
  180215. static const int jpegBufferSize = 512;
  180216. struct JuceJpegDest : public jpeg_destination_mgr
  180217. {
  180218. OutputStream* output;
  180219. char* buffer;
  180220. };
  180221. static void jpegWriteInit (j_compress_ptr)
  180222. {
  180223. }
  180224. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180225. {
  180226. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180227. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180228. dest->output->write (dest->buffer, (int) numToWrite);
  180229. }
  180230. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180231. {
  180232. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180233. const int numToWrite = jpegBufferSize;
  180234. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180235. dest->free_in_buffer = jpegBufferSize;
  180236. return dest->output->write (dest->buffer, numToWrite);
  180237. }
  180238. }
  180239. JPEGImageFormat::JPEGImageFormat()
  180240. : quality (-1.0f)
  180241. {
  180242. }
  180243. JPEGImageFormat::~JPEGImageFormat() {}
  180244. void JPEGImageFormat::setQuality (const float newQuality)
  180245. {
  180246. quality = newQuality;
  180247. }
  180248. const String JPEGImageFormat::getFormatName()
  180249. {
  180250. return "JPEG";
  180251. }
  180252. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180253. {
  180254. const int bytesNeeded = 10;
  180255. uint8 header [bytesNeeded];
  180256. if (in.read (header, bytesNeeded) == bytesNeeded)
  180257. {
  180258. return header[0] == 0xff
  180259. && header[1] == 0xd8
  180260. && header[2] == 0xff
  180261. && (header[3] == 0xe0 || header[3] == 0xe1);
  180262. }
  180263. return false;
  180264. }
  180265. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180266. const Image juce_loadWithCoreImage (InputStream& input);
  180267. #endif
  180268. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180269. {
  180270. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180271. return juce_loadWithCoreImage (in);
  180272. #else
  180273. using namespace jpeglibNamespace;
  180274. using namespace JPEGHelpers;
  180275. MemoryOutputStream mb;
  180276. mb.writeFromInputStream (in, -1);
  180277. Image image;
  180278. if (mb.getDataSize() > 16)
  180279. {
  180280. struct jpeg_decompress_struct jpegDecompStruct;
  180281. struct jpeg_error_mgr jerr;
  180282. setupSilentErrorHandler (jerr);
  180283. jpegDecompStruct.err = &jerr;
  180284. jpeg_create_decompress (&jpegDecompStruct);
  180285. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180286. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180287. jpegDecompStruct.src->init_source = dummyCallback1;
  180288. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180289. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180290. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180291. jpegDecompStruct.src->term_source = dummyCallback1;
  180292. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180293. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180294. try
  180295. {
  180296. jpeg_read_header (&jpegDecompStruct, TRUE);
  180297. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180298. const int width = jpegDecompStruct.output_width;
  180299. const int height = jpegDecompStruct.output_height;
  180300. jpegDecompStruct.out_color_space = JCS_RGB;
  180301. JSAMPARRAY buffer
  180302. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180303. JPOOL_IMAGE,
  180304. width * 3, 1);
  180305. if (jpeg_start_decompress (&jpegDecompStruct))
  180306. {
  180307. image = Image (Image::RGB, width, height, false);
  180308. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180309. const Image::BitmapData destData (image, true);
  180310. for (int y = 0; y < height; ++y)
  180311. {
  180312. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180313. const uint8* src = *buffer;
  180314. uint8* dest = destData.getLinePointer (y);
  180315. if (hasAlphaChan)
  180316. {
  180317. for (int i = width; --i >= 0;)
  180318. {
  180319. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180320. ((PixelARGB*) dest)->premultiply();
  180321. dest += destData.pixelStride;
  180322. src += 3;
  180323. }
  180324. }
  180325. else
  180326. {
  180327. for (int i = width; --i >= 0;)
  180328. {
  180329. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180330. dest += destData.pixelStride;
  180331. src += 3;
  180332. }
  180333. }
  180334. }
  180335. jpeg_finish_decompress (&jpegDecompStruct);
  180336. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180337. }
  180338. jpeg_destroy_decompress (&jpegDecompStruct);
  180339. }
  180340. catch (...)
  180341. {}
  180342. }
  180343. return image;
  180344. #endif
  180345. }
  180346. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180347. {
  180348. using namespace jpeglibNamespace;
  180349. using namespace JPEGHelpers;
  180350. if (image.hasAlphaChannel())
  180351. {
  180352. // this method could fill the background in white and still save the image..
  180353. jassertfalse;
  180354. return true;
  180355. }
  180356. struct jpeg_compress_struct jpegCompStruct;
  180357. struct jpeg_error_mgr jerr;
  180358. setupSilentErrorHandler (jerr);
  180359. jpegCompStruct.err = &jerr;
  180360. jpeg_create_compress (&jpegCompStruct);
  180361. JuceJpegDest dest;
  180362. jpegCompStruct.dest = &dest;
  180363. dest.output = &out;
  180364. HeapBlock <char> tempBuffer (jpegBufferSize);
  180365. dest.buffer = tempBuffer;
  180366. dest.next_output_byte = (JOCTET*) dest.buffer;
  180367. dest.free_in_buffer = jpegBufferSize;
  180368. dest.init_destination = jpegWriteInit;
  180369. dest.empty_output_buffer = jpegWriteFlush;
  180370. dest.term_destination = jpegWriteTerminate;
  180371. jpegCompStruct.image_width = image.getWidth();
  180372. jpegCompStruct.image_height = image.getHeight();
  180373. jpegCompStruct.input_components = 3;
  180374. jpegCompStruct.in_color_space = JCS_RGB;
  180375. jpegCompStruct.write_JFIF_header = 1;
  180376. jpegCompStruct.X_density = 72;
  180377. jpegCompStruct.Y_density = 72;
  180378. jpeg_set_defaults (&jpegCompStruct);
  180379. jpegCompStruct.dct_method = JDCT_FLOAT;
  180380. jpegCompStruct.optimize_coding = 1;
  180381. //jpegCompStruct.smoothing_factor = 10;
  180382. if (quality < 0.0f)
  180383. quality = 0.85f;
  180384. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180385. jpeg_start_compress (&jpegCompStruct, TRUE);
  180386. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180387. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180388. JPOOL_IMAGE, strideBytes, 1);
  180389. const Image::BitmapData srcData (image, false);
  180390. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180391. {
  180392. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180393. uint8* dst = *buffer;
  180394. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180395. {
  180396. *dst++ = ((const PixelRGB*) src)->getRed();
  180397. *dst++ = ((const PixelRGB*) src)->getGreen();
  180398. *dst++ = ((const PixelRGB*) src)->getBlue();
  180399. src += srcData.pixelStride;
  180400. }
  180401. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180402. }
  180403. jpeg_finish_compress (&jpegCompStruct);
  180404. jpeg_destroy_compress (&jpegCompStruct);
  180405. out.flush();
  180406. return true;
  180407. }
  180408. END_JUCE_NAMESPACE
  180409. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180410. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180411. #if JUCE_MSVC
  180412. #pragma warning (push)
  180413. #pragma warning (disable: 4390 4611)
  180414. #endif
  180415. namespace zlibNamespace
  180416. {
  180417. #if JUCE_INCLUDE_ZLIB_CODE
  180418. #undef OS_CODE
  180419. #undef fdopen
  180420. #undef OS_CODE
  180421. #else
  180422. #include <zlib.h>
  180423. #endif
  180424. }
  180425. namespace pnglibNamespace
  180426. {
  180427. using namespace zlibNamespace;
  180428. #if JUCE_INCLUDE_PNGLIB_CODE
  180429. #if _MSC_VER != 1310
  180430. using ::calloc; // (causes conflict in VS.NET 2003)
  180431. using ::malloc;
  180432. using ::free;
  180433. #endif
  180434. using ::abs;
  180435. #define PNG_INTERNAL
  180436. #define NO_DUMMY_DECL
  180437. #define PNG_SETJMP_NOT_SUPPORTED
  180438. /*** Start of inlined file: png.h ***/
  180439. /* png.h - header file for PNG reference library
  180440. *
  180441. * libpng version 1.2.21 - October 4, 2007
  180442. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180443. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180444. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180445. *
  180446. * Authors and maintainers:
  180447. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180448. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180449. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180450. * See also "Contributing Authors", below.
  180451. *
  180452. * Note about libpng version numbers:
  180453. *
  180454. * Due to various miscommunications, unforeseen code incompatibilities
  180455. * and occasional factors outside the authors' control, version numbering
  180456. * on the library has not always been consistent and straightforward.
  180457. * The following table summarizes matters since version 0.89c, which was
  180458. * the first widely used release:
  180459. *
  180460. * source png.h png.h shared-lib
  180461. * version string int version
  180462. * ------- ------ ----- ----------
  180463. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180464. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180465. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180466. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180467. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180468. * 0.97c 0.97 97 2.0.97
  180469. * 0.98 0.98 98 2.0.98
  180470. * 0.99 0.99 98 2.0.99
  180471. * 0.99a-m 0.99 99 2.0.99
  180472. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180473. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180474. * 1.0.1 png.h string is 10001 2.1.0
  180475. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180476. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180477. * 1.0.2a-b 10003 version, except as noted.
  180478. * 1.0.3 10003
  180479. * 1.0.3a-d 10004
  180480. * 1.0.4 10004
  180481. * 1.0.4a-f 10005
  180482. * 1.0.5 (+ 2 patches) 10005
  180483. * 1.0.5a-d 10006
  180484. * 1.0.5e-r 10100 (not source compatible)
  180485. * 1.0.5s-v 10006 (not binary compatible)
  180486. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180487. * 1.0.6d-f 10007 (still binary incompatible)
  180488. * 1.0.6g 10007
  180489. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180490. * 1.0.6i 10007 10.6i
  180491. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180492. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180493. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180494. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180495. * 1.0.7 1 10007 (still compatible)
  180496. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180497. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180498. * 1.0.8 1 10008 2.1.0.8
  180499. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180500. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180501. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180502. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180503. * 1.0.9 1 10009 2.1.0.9
  180504. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180505. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180506. * 1.0.10 1 10010 2.1.0.10
  180507. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180508. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180509. * 1.0.11 1 10011 2.1.0.11
  180510. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180511. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180512. * 1.0.12 2 10012 2.1.0.12
  180513. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180514. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180515. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180516. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180517. * 1.2.0 3 10200 3.1.2.0
  180518. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180519. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180520. * 1.2.1 3 10201 3.1.2.1
  180521. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180522. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180523. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180524. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180525. * 1.0.13 10 10013 10.so.0.1.0.13
  180526. * 1.2.2 12 10202 12.so.0.1.2.2
  180527. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180528. * 1.2.3 12 10203 12.so.0.1.2.3
  180529. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180530. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180531. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180532. * 1.0.14 10 10014 10.so.0.1.0.14
  180533. * 1.2.4 13 10204 12.so.0.1.2.4
  180534. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180535. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180536. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180537. * 1.0.15 10 10015 10.so.0.1.0.15
  180538. * 1.2.5 13 10205 12.so.0.1.2.5
  180539. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180540. * 1.0.16 10 10016 10.so.0.1.0.16
  180541. * 1.2.6 13 10206 12.so.0.1.2.6
  180542. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180543. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180544. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180545. * 1.0.17 10 10017 10.so.0.1.0.17
  180546. * 1.2.7 13 10207 12.so.0.1.2.7
  180547. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180548. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180549. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180550. * 1.0.18 10 10018 10.so.0.1.0.18
  180551. * 1.2.8 13 10208 12.so.0.1.2.8
  180552. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180553. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180554. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180555. * 1.2.9 13 10209 12.so.0.9[.0]
  180556. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180557. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180558. * 1.2.10 13 10210 12.so.0.10[.0]
  180559. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180560. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180561. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180562. * 1.0.19 10 10019 10.so.0.19[.0]
  180563. * 1.2.11 13 10211 12.so.0.11[.0]
  180564. * 1.0.20 10 10020 10.so.0.20[.0]
  180565. * 1.2.12 13 10212 12.so.0.12[.0]
  180566. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180567. * 1.0.21 10 10021 10.so.0.21[.0]
  180568. * 1.2.13 13 10213 12.so.0.13[.0]
  180569. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180570. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180571. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180572. * 1.0.22 10 10022 10.so.0.22[.0]
  180573. * 1.2.14 13 10214 12.so.0.14[.0]
  180574. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180575. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180576. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180577. * 1.0.23 10 10023 10.so.0.23[.0]
  180578. * 1.2.15 13 10215 12.so.0.15[.0]
  180579. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180580. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180581. * 1.0.24 10 10024 10.so.0.24[.0]
  180582. * 1.2.16 13 10216 12.so.0.16[.0]
  180583. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180584. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180585. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180586. * 1.0.25 10 10025 10.so.0.25[.0]
  180587. * 1.2.17 13 10217 12.so.0.17[.0]
  180588. * 1.0.26 10 10026 10.so.0.26[.0]
  180589. * 1.2.18 13 10218 12.so.0.18[.0]
  180590. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180591. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180592. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180593. * 1.0.27 10 10027 10.so.0.27[.0]
  180594. * 1.2.19 13 10219 12.so.0.19[.0]
  180595. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180596. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180597. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180598. * 1.0.28 10 10028 10.so.0.28[.0]
  180599. * 1.2.20 13 10220 12.so.0.20[.0]
  180600. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180601. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180602. * 1.0.29 10 10029 10.so.0.29[.0]
  180603. * 1.2.21 13 10221 12.so.0.21[.0]
  180604. *
  180605. * Henceforth the source version will match the shared-library major
  180606. * and minor numbers; the shared-library major version number will be
  180607. * used for changes in backward compatibility, as it is intended. The
  180608. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180609. * for applications, is an unsigned integer of the form xyyzz corresponding
  180610. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180611. * were given the previous public release number plus a letter, until
  180612. * version 1.0.6j; from then on they were given the upcoming public
  180613. * release number plus "betaNN" or "rcN".
  180614. *
  180615. * Binary incompatibility exists only when applications make direct access
  180616. * to the info_ptr or png_ptr members through png.h, and the compiled
  180617. * application is loaded with a different version of the library.
  180618. *
  180619. * DLLNUM will change each time there are forward or backward changes
  180620. * in binary compatibility (e.g., when a new feature is added).
  180621. *
  180622. * See libpng.txt or libpng.3 for more information. The PNG specification
  180623. * is available as a W3C Recommendation and as an ISO Specification,
  180624. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180625. */
  180626. /*
  180627. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180628. *
  180629. * If you modify libpng you may insert additional notices immediately following
  180630. * this sentence.
  180631. *
  180632. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180633. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180634. * distributed according to the same disclaimer and license as libpng-1.2.5
  180635. * with the following individual added to the list of Contributing Authors:
  180636. *
  180637. * Cosmin Truta
  180638. *
  180639. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180640. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180641. * distributed according to the same disclaimer and license as libpng-1.0.6
  180642. * with the following individuals added to the list of Contributing Authors:
  180643. *
  180644. * Simon-Pierre Cadieux
  180645. * Eric S. Raymond
  180646. * Gilles Vollant
  180647. *
  180648. * and with the following additions to the disclaimer:
  180649. *
  180650. * There is no warranty against interference with your enjoyment of the
  180651. * library or against infringement. There is no warranty that our
  180652. * efforts or the library will fulfill any of your particular purposes
  180653. * or needs. This library is provided with all faults, and the entire
  180654. * risk of satisfactory quality, performance, accuracy, and effort is with
  180655. * the user.
  180656. *
  180657. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180658. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180659. * distributed according to the same disclaimer and license as libpng-0.96,
  180660. * with the following individuals added to the list of Contributing Authors:
  180661. *
  180662. * Tom Lane
  180663. * Glenn Randers-Pehrson
  180664. * Willem van Schaik
  180665. *
  180666. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180667. * Copyright (c) 1996, 1997 Andreas Dilger
  180668. * Distributed according to the same disclaimer and license as libpng-0.88,
  180669. * with the following individuals added to the list of Contributing Authors:
  180670. *
  180671. * John Bowler
  180672. * Kevin Bracey
  180673. * Sam Bushell
  180674. * Magnus Holmgren
  180675. * Greg Roelofs
  180676. * Tom Tanner
  180677. *
  180678. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180679. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180680. *
  180681. * For the purposes of this copyright and license, "Contributing Authors"
  180682. * is defined as the following set of individuals:
  180683. *
  180684. * Andreas Dilger
  180685. * Dave Martindale
  180686. * Guy Eric Schalnat
  180687. * Paul Schmidt
  180688. * Tim Wegner
  180689. *
  180690. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180691. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180692. * including, without limitation, the warranties of merchantability and of
  180693. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180694. * assume no liability for direct, indirect, incidental, special, exemplary,
  180695. * or consequential damages, which may result from the use of the PNG
  180696. * Reference Library, even if advised of the possibility of such damage.
  180697. *
  180698. * Permission is hereby granted to use, copy, modify, and distribute this
  180699. * source code, or portions hereof, for any purpose, without fee, subject
  180700. * to the following restrictions:
  180701. *
  180702. * 1. The origin of this source code must not be misrepresented.
  180703. *
  180704. * 2. Altered versions must be plainly marked as such and
  180705. * must not be misrepresented as being the original source.
  180706. *
  180707. * 3. This Copyright notice may not be removed or altered from
  180708. * any source or altered source distribution.
  180709. *
  180710. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180711. * fee, and encourage the use of this source code as a component to
  180712. * supporting the PNG file format in commercial products. If you use this
  180713. * source code in a product, acknowledgment is not required but would be
  180714. * appreciated.
  180715. */
  180716. /*
  180717. * A "png_get_copyright" function is available, for convenient use in "about"
  180718. * boxes and the like:
  180719. *
  180720. * printf("%s",png_get_copyright(NULL));
  180721. *
  180722. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180723. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180724. */
  180725. /*
  180726. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180727. * certification mark of the Open Source Initiative.
  180728. */
  180729. /*
  180730. * The contributing authors would like to thank all those who helped
  180731. * with testing, bug fixes, and patience. This wouldn't have been
  180732. * possible without all of you.
  180733. *
  180734. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180735. */
  180736. /*
  180737. * Y2K compliance in libpng:
  180738. * =========================
  180739. *
  180740. * October 4, 2007
  180741. *
  180742. * Since the PNG Development group is an ad-hoc body, we can't make
  180743. * an official declaration.
  180744. *
  180745. * This is your unofficial assurance that libpng from version 0.71 and
  180746. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180747. * versions were also Y2K compliant.
  180748. *
  180749. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180750. * that will hold years up to 65535. The other two hold the date in text
  180751. * format, and will hold years up to 9999.
  180752. *
  180753. * The integer is
  180754. * "png_uint_16 year" in png_time_struct.
  180755. *
  180756. * The strings are
  180757. * "png_charp time_buffer" in png_struct and
  180758. * "near_time_buffer", which is a local character string in png.c.
  180759. *
  180760. * There are seven time-related functions:
  180761. * png.c: png_convert_to_rfc_1123() in png.c
  180762. * (formerly png_convert_to_rfc_1152() in error)
  180763. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180764. * png_convert_from_time_t() in pngwrite.c
  180765. * png_get_tIME() in pngget.c
  180766. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180767. * png_set_tIME() in pngset.c
  180768. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180769. *
  180770. * All handle dates properly in a Y2K environment. The
  180771. * png_convert_from_time_t() function calls gmtime() to convert from system
  180772. * clock time, which returns (year - 1900), which we properly convert to
  180773. * the full 4-digit year. There is a possibility that applications using
  180774. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180775. * function, or that they are incorrectly passing only a 2-digit year
  180776. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180777. * but this is not under our control. The libpng documentation has always
  180778. * stated that it works with 4-digit years, and the APIs have been
  180779. * documented as such.
  180780. *
  180781. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180782. * integer to hold the year, and can hold years as large as 65535.
  180783. *
  180784. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180785. * no date-related code.
  180786. *
  180787. * Glenn Randers-Pehrson
  180788. * libpng maintainer
  180789. * PNG Development Group
  180790. */
  180791. #ifndef PNG_H
  180792. #define PNG_H
  180793. /* This is not the place to learn how to use libpng. The file libpng.txt
  180794. * describes how to use libpng, and the file example.c summarizes it
  180795. * with some code on which to build. This file is useful for looking
  180796. * at the actual function definitions and structure components.
  180797. */
  180798. /* Version information for png.h - this should match the version in png.c */
  180799. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180800. #define PNG_HEADER_VERSION_STRING \
  180801. " libpng version 1.2.21 - October 4, 2007\n"
  180802. #define PNG_LIBPNG_VER_SONUM 0
  180803. #define PNG_LIBPNG_VER_DLLNUM 13
  180804. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180805. #define PNG_LIBPNG_VER_MAJOR 1
  180806. #define PNG_LIBPNG_VER_MINOR 2
  180807. #define PNG_LIBPNG_VER_RELEASE 21
  180808. /* This should match the numeric part of the final component of
  180809. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180810. #define PNG_LIBPNG_VER_BUILD 0
  180811. /* Release Status */
  180812. #define PNG_LIBPNG_BUILD_ALPHA 1
  180813. #define PNG_LIBPNG_BUILD_BETA 2
  180814. #define PNG_LIBPNG_BUILD_RC 3
  180815. #define PNG_LIBPNG_BUILD_STABLE 4
  180816. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180817. /* Release-Specific Flags */
  180818. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180819. PNG_LIBPNG_BUILD_STABLE only */
  180820. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180821. PNG_LIBPNG_BUILD_SPECIAL */
  180822. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180823. PNG_LIBPNG_BUILD_PRIVATE */
  180824. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180825. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180826. * We must not include leading zeros.
  180827. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180828. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180829. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180830. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180831. #ifndef PNG_VERSION_INFO_ONLY
  180832. /* include the compression library's header */
  180833. #endif
  180834. /* include all user configurable info, including optional assembler routines */
  180835. /*** Start of inlined file: pngconf.h ***/
  180836. /* pngconf.h - machine configurable file for libpng
  180837. *
  180838. * libpng version 1.2.21 - October 4, 2007
  180839. * For conditions of distribution and use, see copyright notice in png.h
  180840. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180841. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180842. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180843. */
  180844. /* Any machine specific code is near the front of this file, so if you
  180845. * are configuring libpng for a machine, you may want to read the section
  180846. * starting here down to where it starts to typedef png_color, png_text,
  180847. * and png_info.
  180848. */
  180849. #ifndef PNGCONF_H
  180850. #define PNGCONF_H
  180851. #define PNG_1_2_X
  180852. // These are some Juce config settings that should remove any unnecessary code bloat..
  180853. #define PNG_NO_STDIO 1
  180854. #define PNG_DEBUG 0
  180855. #define PNG_NO_WARNINGS 1
  180856. #define PNG_NO_ERROR_TEXT 1
  180857. #define PNG_NO_ERROR_NUMBERS 1
  180858. #define PNG_NO_USER_MEM 1
  180859. #define PNG_NO_READ_iCCP 1
  180860. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180861. #define PNG_NO_READ_USER_CHUNKS 1
  180862. #define PNG_NO_READ_iTXt 1
  180863. #define PNG_NO_READ_sCAL 1
  180864. #define PNG_NO_READ_sPLT 1
  180865. #define png_error(a, b) png_err(a)
  180866. #define png_warning(a, b)
  180867. #define png_chunk_error(a, b) png_err(a)
  180868. #define png_chunk_warning(a, b)
  180869. /*
  180870. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180871. * includes the resource compiler for Windows DLL configurations.
  180872. */
  180873. #ifdef PNG_USER_CONFIG
  180874. # ifndef PNG_USER_PRIVATEBUILD
  180875. # define PNG_USER_PRIVATEBUILD
  180876. # endif
  180877. #include "pngusr.h"
  180878. #endif
  180879. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180880. #ifdef PNG_CONFIGURE_LIBPNG
  180881. #ifdef HAVE_CONFIG_H
  180882. #include "config.h"
  180883. #endif
  180884. #endif
  180885. /*
  180886. * Added at libpng-1.2.8
  180887. *
  180888. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180889. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180890. * the DLL was built>
  180891. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180892. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180893. * distinguish your DLL from those of the official release. These
  180894. * correspond to the trailing letters that come after the version
  180895. * number and must match your private DLL name>
  180896. * e.g. // private DLL "libpng13gx.dll"
  180897. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180898. *
  180899. * The following macros are also at your disposal if you want to complete the
  180900. * DLL VERSIONINFO structure.
  180901. * - PNG_USER_VERSIONINFO_COMMENTS
  180902. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180903. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180904. */
  180905. #ifdef __STDC__
  180906. #ifdef SPECIALBUILD
  180907. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180908. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180909. #endif
  180910. #ifdef PRIVATEBUILD
  180911. # pragma message("PRIVATEBUILD is deprecated.\
  180912. Use PNG_USER_PRIVATEBUILD instead.")
  180913. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180914. #endif
  180915. #endif /* __STDC__ */
  180916. #ifndef PNG_VERSION_INFO_ONLY
  180917. /* End of material added to libpng-1.2.8 */
  180918. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180919. Restored at libpng-1.2.21 */
  180920. # define PNG_WARN_UNINITIALIZED_ROW 1
  180921. /* End of material added at libpng-1.2.19/1.2.21 */
  180922. /* This is the size of the compression buffer, and thus the size of
  180923. * an IDAT chunk. Make this whatever size you feel is best for your
  180924. * machine. One of these will be allocated per png_struct. When this
  180925. * is full, it writes the data to the disk, and does some other
  180926. * calculations. Making this an extremely small size will slow
  180927. * the library down, but you may want to experiment to determine
  180928. * where it becomes significant, if you are concerned with memory
  180929. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180930. * this describes the size of the buffer available to read the data in.
  180931. * Unless this gets smaller than the size of a row (compressed),
  180932. * it should not make much difference how big this is.
  180933. */
  180934. #ifndef PNG_ZBUF_SIZE
  180935. # define PNG_ZBUF_SIZE 8192
  180936. #endif
  180937. /* Enable if you want a write-only libpng */
  180938. #ifndef PNG_NO_READ_SUPPORTED
  180939. # define PNG_READ_SUPPORTED
  180940. #endif
  180941. /* Enable if you want a read-only libpng */
  180942. #ifndef PNG_NO_WRITE_SUPPORTED
  180943. # define PNG_WRITE_SUPPORTED
  180944. #endif
  180945. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180946. support PNGs that are embedded in MNG datastreams */
  180947. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180948. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180949. # define PNG_MNG_FEATURES_SUPPORTED
  180950. # endif
  180951. #endif
  180952. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180953. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180954. # define PNG_FLOATING_POINT_SUPPORTED
  180955. # endif
  180956. #endif
  180957. /* If you are running on a machine where you cannot allocate more
  180958. * than 64K of memory at once, uncomment this. While libpng will not
  180959. * normally need that much memory in a chunk (unless you load up a very
  180960. * large file), zlib needs to know how big of a chunk it can use, and
  180961. * libpng thus makes sure to check any memory allocation to verify it
  180962. * will fit into memory.
  180963. #define PNG_MAX_MALLOC_64K
  180964. */
  180965. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180966. # define PNG_MAX_MALLOC_64K
  180967. #endif
  180968. /* Special munging to support doing things the 'cygwin' way:
  180969. * 'Normal' png-on-win32 defines/defaults:
  180970. * PNG_BUILD_DLL -- building dll
  180971. * PNG_USE_DLL -- building an application, linking to dll
  180972. * (no define) -- building static library, or building an
  180973. * application and linking to the static lib
  180974. * 'Cygwin' defines/defaults:
  180975. * PNG_BUILD_DLL -- (ignored) building the dll
  180976. * (no define) -- (ignored) building an application, linking to the dll
  180977. * PNG_STATIC -- (ignored) building the static lib, or building an
  180978. * application that links to the static lib.
  180979. * ALL_STATIC -- (ignored) building various static libs, or building an
  180980. * application that links to the static libs.
  180981. * Thus,
  180982. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180983. * this bit of #ifdefs will define the 'correct' config variables based on
  180984. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180985. * unnecessary.
  180986. *
  180987. * Also, the precedence order is:
  180988. * ALL_STATIC (since we can't #undef something outside our namespace)
  180989. * PNG_BUILD_DLL
  180990. * PNG_STATIC
  180991. * (nothing) == PNG_USE_DLL
  180992. *
  180993. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180994. * of auto-import in binutils, we no longer need to worry about
  180995. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180996. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180997. * to __declspec() stuff. However, we DO need to worry about
  180998. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180999. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  181000. */
  181001. #if defined(__CYGWIN__)
  181002. # if defined(ALL_STATIC)
  181003. # if defined(PNG_BUILD_DLL)
  181004. # undef PNG_BUILD_DLL
  181005. # endif
  181006. # if defined(PNG_USE_DLL)
  181007. # undef PNG_USE_DLL
  181008. # endif
  181009. # if defined(PNG_DLL)
  181010. # undef PNG_DLL
  181011. # endif
  181012. # if !defined(PNG_STATIC)
  181013. # define PNG_STATIC
  181014. # endif
  181015. # else
  181016. # if defined (PNG_BUILD_DLL)
  181017. # if defined(PNG_STATIC)
  181018. # undef PNG_STATIC
  181019. # endif
  181020. # if defined(PNG_USE_DLL)
  181021. # undef PNG_USE_DLL
  181022. # endif
  181023. # if !defined(PNG_DLL)
  181024. # define PNG_DLL
  181025. # endif
  181026. # else
  181027. # if defined(PNG_STATIC)
  181028. # if defined(PNG_USE_DLL)
  181029. # undef PNG_USE_DLL
  181030. # endif
  181031. # if defined(PNG_DLL)
  181032. # undef PNG_DLL
  181033. # endif
  181034. # else
  181035. # if !defined(PNG_USE_DLL)
  181036. # define PNG_USE_DLL
  181037. # endif
  181038. # if !defined(PNG_DLL)
  181039. # define PNG_DLL
  181040. # endif
  181041. # endif
  181042. # endif
  181043. # endif
  181044. #endif
  181045. /* This protects us against compilers that run on a windowing system
  181046. * and thus don't have or would rather us not use the stdio types:
  181047. * stdin, stdout, and stderr. The only one currently used is stderr
  181048. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181049. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181050. * will also prevent these, plus will prevent the entire set of stdio
  181051. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181052. * unless (PNG_DEBUG > 0) has been #defined.
  181053. *
  181054. * #define PNG_NO_CONSOLE_IO
  181055. * #define PNG_NO_STDIO
  181056. */
  181057. #if defined(_WIN32_WCE)
  181058. # include <windows.h>
  181059. /* Console I/O functions are not supported on WindowsCE */
  181060. # define PNG_NO_CONSOLE_IO
  181061. # ifdef PNG_DEBUG
  181062. # undef PNG_DEBUG
  181063. # endif
  181064. #endif
  181065. #ifdef PNG_BUILD_DLL
  181066. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181067. # ifndef PNG_NO_CONSOLE_IO
  181068. # define PNG_NO_CONSOLE_IO
  181069. # endif
  181070. # endif
  181071. #endif
  181072. # ifdef PNG_NO_STDIO
  181073. # ifndef PNG_NO_CONSOLE_IO
  181074. # define PNG_NO_CONSOLE_IO
  181075. # endif
  181076. # ifdef PNG_DEBUG
  181077. # if (PNG_DEBUG > 0)
  181078. # include <stdio.h>
  181079. # endif
  181080. # endif
  181081. # else
  181082. # if !defined(_WIN32_WCE)
  181083. /* "stdio.h" functions are not supported on WindowsCE */
  181084. # include <stdio.h>
  181085. # endif
  181086. # endif
  181087. /* This macro protects us against machines that don't have function
  181088. * prototypes (ie K&R style headers). If your compiler does not handle
  181089. * function prototypes, define this macro and use the included ansi2knr.
  181090. * I've always been able to use _NO_PROTO as the indicator, but you may
  181091. * need to drag the empty declaration out in front of here, or change the
  181092. * ifdef to suit your own needs.
  181093. */
  181094. #ifndef PNGARG
  181095. #ifdef OF /* zlib prototype munger */
  181096. # define PNGARG(arglist) OF(arglist)
  181097. #else
  181098. #ifdef _NO_PROTO
  181099. # define PNGARG(arglist) ()
  181100. # ifndef PNG_TYPECAST_NULL
  181101. # define PNG_TYPECAST_NULL
  181102. # endif
  181103. #else
  181104. # define PNGARG(arglist) arglist
  181105. #endif /* _NO_PROTO */
  181106. #endif /* OF */
  181107. #endif /* PNGARG */
  181108. /* Try to determine if we are compiling on a Mac. Note that testing for
  181109. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181110. * on non-Mac platforms.
  181111. */
  181112. #ifndef MACOS
  181113. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181114. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181115. # define MACOS
  181116. # endif
  181117. #endif
  181118. /* enough people need this for various reasons to include it here */
  181119. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181120. # include <sys/types.h>
  181121. #endif
  181122. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181123. # define PNG_SETJMP_SUPPORTED
  181124. #endif
  181125. #ifdef PNG_SETJMP_SUPPORTED
  181126. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181127. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181128. */
  181129. # ifdef __linux__
  181130. # ifdef _BSD_SOURCE
  181131. # define PNG_SAVE_BSD_SOURCE
  181132. # undef _BSD_SOURCE
  181133. # endif
  181134. # ifdef _SETJMP_H
  181135. /* If you encounter a compiler error here, see the explanation
  181136. * near the end of INSTALL.
  181137. */
  181138. __png.h__ already includes setjmp.h;
  181139. __dont__ include it again.;
  181140. # endif
  181141. # endif /* __linux__ */
  181142. /* include setjmp.h for error handling */
  181143. # include <setjmp.h>
  181144. # ifdef __linux__
  181145. # ifdef PNG_SAVE_BSD_SOURCE
  181146. # define _BSD_SOURCE
  181147. # undef PNG_SAVE_BSD_SOURCE
  181148. # endif
  181149. # endif /* __linux__ */
  181150. #endif /* PNG_SETJMP_SUPPORTED */
  181151. #ifdef BSD
  181152. #if ! JUCE_MAC
  181153. # include <strings.h>
  181154. #endif
  181155. #else
  181156. # include <string.h>
  181157. #endif
  181158. /* Other defines for things like memory and the like can go here. */
  181159. #ifdef PNG_INTERNAL
  181160. #include <stdlib.h>
  181161. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181162. * aren't usually used outside the library (as far as I know), so it is
  181163. * debatable if they should be exported at all. In the future, when it is
  181164. * possible to have run-time registry of chunk-handling functions, some of
  181165. * these will be made available again.
  181166. #define PNG_EXTERN extern
  181167. */
  181168. #define PNG_EXTERN
  181169. /* Other defines specific to compilers can go here. Try to keep
  181170. * them inside an appropriate ifdef/endif pair for portability.
  181171. */
  181172. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181173. # if defined(MACOS)
  181174. /* We need to check that <math.h> hasn't already been included earlier
  181175. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181176. * <fp.h> if possible.
  181177. */
  181178. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181179. # include <fp.h>
  181180. # endif
  181181. # else
  181182. # include <math.h>
  181183. # endif
  181184. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181185. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181186. * MATH=68881
  181187. */
  181188. # include <m68881.h>
  181189. # endif
  181190. #endif
  181191. /* Codewarrior on NT has linking problems without this. */
  181192. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181193. # define PNG_ALWAYS_EXTERN
  181194. #endif
  181195. /* This provides the non-ANSI (far) memory allocation routines. */
  181196. #if defined(__TURBOC__) && defined(__MSDOS__)
  181197. # include <mem.h>
  181198. # include <alloc.h>
  181199. #endif
  181200. /* I have no idea why is this necessary... */
  181201. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181202. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181203. # include <malloc.h>
  181204. #endif
  181205. /* This controls how fine the dithering gets. As this allocates
  181206. * a largish chunk of memory (32K), those who are not as concerned
  181207. * with dithering quality can decrease some or all of these.
  181208. */
  181209. #ifndef PNG_DITHER_RED_BITS
  181210. # define PNG_DITHER_RED_BITS 5
  181211. #endif
  181212. #ifndef PNG_DITHER_GREEN_BITS
  181213. # define PNG_DITHER_GREEN_BITS 5
  181214. #endif
  181215. #ifndef PNG_DITHER_BLUE_BITS
  181216. # define PNG_DITHER_BLUE_BITS 5
  181217. #endif
  181218. /* This controls how fine the gamma correction becomes when you
  181219. * are only interested in 8 bits anyway. Increasing this value
  181220. * results in more memory being used, and more pow() functions
  181221. * being called to fill in the gamma tables. Don't set this value
  181222. * less then 8, and even that may not work (I haven't tested it).
  181223. */
  181224. #ifndef PNG_MAX_GAMMA_8
  181225. # define PNG_MAX_GAMMA_8 11
  181226. #endif
  181227. /* This controls how much a difference in gamma we can tolerate before
  181228. * we actually start doing gamma conversion.
  181229. */
  181230. #ifndef PNG_GAMMA_THRESHOLD
  181231. # define PNG_GAMMA_THRESHOLD 0.05
  181232. #endif
  181233. #endif /* PNG_INTERNAL */
  181234. /* The following uses const char * instead of char * for error
  181235. * and warning message functions, so some compilers won't complain.
  181236. * If you do not want to use const, define PNG_NO_CONST here.
  181237. */
  181238. #ifndef PNG_NO_CONST
  181239. # define PNG_CONST const
  181240. #else
  181241. # define PNG_CONST
  181242. #endif
  181243. /* The following defines give you the ability to remove code from the
  181244. * library that you will not be using. I wish I could figure out how to
  181245. * automate this, but I can't do that without making it seriously hard
  181246. * on the users. So if you are not using an ability, change the #define
  181247. * to and #undef, and that part of the library will not be compiled. If
  181248. * your linker can't find a function, you may want to make sure the
  181249. * ability is defined here. Some of these depend upon some others being
  181250. * defined. I haven't figured out all the interactions here, so you may
  181251. * have to experiment awhile to get everything to compile. If you are
  181252. * creating or using a shared library, you probably shouldn't touch this,
  181253. * as it will affect the size of the structures, and this will cause bad
  181254. * things to happen if the library and/or application ever change.
  181255. */
  181256. /* Any features you will not be using can be undef'ed here */
  181257. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181258. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181259. * on the compile line, then pick and choose which ones to define without
  181260. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181261. * if you only want to have a png-compliant reader/writer but don't need
  181262. * any of the extra transformations. This saves about 80 kbytes in a
  181263. * typical installation of the library. (PNG_NO_* form added in version
  181264. * 1.0.1c, for consistency)
  181265. */
  181266. /* The size of the png_text structure changed in libpng-1.0.6 when
  181267. * iTXt support was added. iTXt support was turned off by default through
  181268. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181269. * instead of calling png_set_text() and letting libpng malloc it. It
  181270. * was turned on by default in libpng-1.3.0.
  181271. */
  181272. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181273. # ifndef PNG_NO_iTXt_SUPPORTED
  181274. # define PNG_NO_iTXt_SUPPORTED
  181275. # endif
  181276. # ifndef PNG_NO_READ_iTXt
  181277. # define PNG_NO_READ_iTXt
  181278. # endif
  181279. # ifndef PNG_NO_WRITE_iTXt
  181280. # define PNG_NO_WRITE_iTXt
  181281. # endif
  181282. #endif
  181283. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181284. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181285. # define PNG_READ_iTXt
  181286. # endif
  181287. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181288. # define PNG_WRITE_iTXt
  181289. # endif
  181290. #endif
  181291. /* The following support, added after version 1.0.0, can be turned off here en
  181292. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181293. * with old applications that require the length of png_struct and png_info
  181294. * to remain unchanged.
  181295. */
  181296. #ifdef PNG_LEGACY_SUPPORTED
  181297. # define PNG_NO_FREE_ME
  181298. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181299. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181300. # define PNG_NO_READ_USER_CHUNKS
  181301. # define PNG_NO_READ_iCCP
  181302. # define PNG_NO_WRITE_iCCP
  181303. # define PNG_NO_READ_iTXt
  181304. # define PNG_NO_WRITE_iTXt
  181305. # define PNG_NO_READ_sCAL
  181306. # define PNG_NO_WRITE_sCAL
  181307. # define PNG_NO_READ_sPLT
  181308. # define PNG_NO_WRITE_sPLT
  181309. # define PNG_NO_INFO_IMAGE
  181310. # define PNG_NO_READ_RGB_TO_GRAY
  181311. # define PNG_NO_READ_USER_TRANSFORM
  181312. # define PNG_NO_WRITE_USER_TRANSFORM
  181313. # define PNG_NO_USER_MEM
  181314. # define PNG_NO_READ_EMPTY_PLTE
  181315. # define PNG_NO_MNG_FEATURES
  181316. # define PNG_NO_FIXED_POINT_SUPPORTED
  181317. #endif
  181318. /* Ignore attempt to turn off both floating and fixed point support */
  181319. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181320. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181321. # define PNG_FIXED_POINT_SUPPORTED
  181322. #endif
  181323. #ifndef PNG_NO_FREE_ME
  181324. # define PNG_FREE_ME_SUPPORTED
  181325. #endif
  181326. #if defined(PNG_READ_SUPPORTED)
  181327. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181328. !defined(PNG_NO_READ_TRANSFORMS)
  181329. # define PNG_READ_TRANSFORMS_SUPPORTED
  181330. #endif
  181331. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181332. # ifndef PNG_NO_READ_EXPAND
  181333. # define PNG_READ_EXPAND_SUPPORTED
  181334. # endif
  181335. # ifndef PNG_NO_READ_SHIFT
  181336. # define PNG_READ_SHIFT_SUPPORTED
  181337. # endif
  181338. # ifndef PNG_NO_READ_PACK
  181339. # define PNG_READ_PACK_SUPPORTED
  181340. # endif
  181341. # ifndef PNG_NO_READ_BGR
  181342. # define PNG_READ_BGR_SUPPORTED
  181343. # endif
  181344. # ifndef PNG_NO_READ_SWAP
  181345. # define PNG_READ_SWAP_SUPPORTED
  181346. # endif
  181347. # ifndef PNG_NO_READ_PACKSWAP
  181348. # define PNG_READ_PACKSWAP_SUPPORTED
  181349. # endif
  181350. # ifndef PNG_NO_READ_INVERT
  181351. # define PNG_READ_INVERT_SUPPORTED
  181352. # endif
  181353. # ifndef PNG_NO_READ_DITHER
  181354. # define PNG_READ_DITHER_SUPPORTED
  181355. # endif
  181356. # ifndef PNG_NO_READ_BACKGROUND
  181357. # define PNG_READ_BACKGROUND_SUPPORTED
  181358. # endif
  181359. # ifndef PNG_NO_READ_16_TO_8
  181360. # define PNG_READ_16_TO_8_SUPPORTED
  181361. # endif
  181362. # ifndef PNG_NO_READ_FILLER
  181363. # define PNG_READ_FILLER_SUPPORTED
  181364. # endif
  181365. # ifndef PNG_NO_READ_GAMMA
  181366. # define PNG_READ_GAMMA_SUPPORTED
  181367. # endif
  181368. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181369. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181370. # endif
  181371. # ifndef PNG_NO_READ_SWAP_ALPHA
  181372. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181373. # endif
  181374. # ifndef PNG_NO_READ_INVERT_ALPHA
  181375. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181376. # endif
  181377. # ifndef PNG_NO_READ_STRIP_ALPHA
  181378. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181379. # endif
  181380. # ifndef PNG_NO_READ_USER_TRANSFORM
  181381. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181382. # endif
  181383. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181384. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181385. # endif
  181386. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181387. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181388. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181389. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181390. #endif /* about interlacing capability! You'll */
  181391. /* still have interlacing unless you change the following line: */
  181392. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181393. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181394. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181395. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181396. # endif
  181397. #endif
  181398. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181399. /* Deprecated, will be removed from version 2.0.0.
  181400. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181401. #ifndef PNG_NO_READ_EMPTY_PLTE
  181402. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181403. #endif
  181404. #endif
  181405. #endif /* PNG_READ_SUPPORTED */
  181406. #if defined(PNG_WRITE_SUPPORTED)
  181407. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181408. !defined(PNG_NO_WRITE_TRANSFORMS)
  181409. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181410. #endif
  181411. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181412. # ifndef PNG_NO_WRITE_SHIFT
  181413. # define PNG_WRITE_SHIFT_SUPPORTED
  181414. # endif
  181415. # ifndef PNG_NO_WRITE_PACK
  181416. # define PNG_WRITE_PACK_SUPPORTED
  181417. # endif
  181418. # ifndef PNG_NO_WRITE_BGR
  181419. # define PNG_WRITE_BGR_SUPPORTED
  181420. # endif
  181421. # ifndef PNG_NO_WRITE_SWAP
  181422. # define PNG_WRITE_SWAP_SUPPORTED
  181423. # endif
  181424. # ifndef PNG_NO_WRITE_PACKSWAP
  181425. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181426. # endif
  181427. # ifndef PNG_NO_WRITE_INVERT
  181428. # define PNG_WRITE_INVERT_SUPPORTED
  181429. # endif
  181430. # ifndef PNG_NO_WRITE_FILLER
  181431. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181432. # endif
  181433. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181434. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181435. # endif
  181436. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181437. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181438. # endif
  181439. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181440. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181441. # endif
  181442. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181443. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181444. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181445. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181446. encoders, but can cause trouble
  181447. if left undefined */
  181448. #endif
  181449. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181450. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181451. defined(PNG_FLOATING_POINT_SUPPORTED)
  181452. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181453. #endif
  181454. #ifndef PNG_NO_WRITE_FLUSH
  181455. # define PNG_WRITE_FLUSH_SUPPORTED
  181456. #endif
  181457. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181458. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181459. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181460. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181461. #endif
  181462. #endif
  181463. #endif /* PNG_WRITE_SUPPORTED */
  181464. #ifndef PNG_1_0_X
  181465. # ifndef PNG_NO_ERROR_NUMBERS
  181466. # define PNG_ERROR_NUMBERS_SUPPORTED
  181467. # endif
  181468. #endif /* PNG_1_0_X */
  181469. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181470. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181471. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181472. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181473. # endif
  181474. #endif
  181475. #ifndef PNG_NO_STDIO
  181476. # define PNG_TIME_RFC1123_SUPPORTED
  181477. #endif
  181478. /* This adds extra functions in pngget.c for accessing data from the
  181479. * info pointer (added in version 0.99)
  181480. * png_get_image_width()
  181481. * png_get_image_height()
  181482. * png_get_bit_depth()
  181483. * png_get_color_type()
  181484. * png_get_compression_type()
  181485. * png_get_filter_type()
  181486. * png_get_interlace_type()
  181487. * png_get_pixel_aspect_ratio()
  181488. * png_get_pixels_per_meter()
  181489. * png_get_x_offset_pixels()
  181490. * png_get_y_offset_pixels()
  181491. * png_get_x_offset_microns()
  181492. * png_get_y_offset_microns()
  181493. */
  181494. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181495. # define PNG_EASY_ACCESS_SUPPORTED
  181496. #endif
  181497. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181498. * and removed from version 1.2.20. The following will be removed
  181499. * from libpng-1.4.0
  181500. */
  181501. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181502. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181503. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181504. # endif
  181505. #endif
  181506. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181507. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181508. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181509. # endif
  181510. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181511. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181512. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181513. # define PNG_NO_MMX_CODE
  181514. # endif
  181515. # endif
  181516. # if defined(__APPLE__)
  181517. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181518. # define PNG_NO_MMX_CODE
  181519. # endif
  181520. # endif
  181521. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181522. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181523. # define PNG_NO_MMX_CODE
  181524. # endif
  181525. # endif
  181526. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181527. # define PNG_MMX_CODE_SUPPORTED
  181528. # endif
  181529. #endif
  181530. /* end of obsolete code to be removed from libpng-1.4.0 */
  181531. #if !defined(PNG_1_0_X)
  181532. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181533. # define PNG_USER_MEM_SUPPORTED
  181534. #endif
  181535. #endif /* PNG_1_0_X */
  181536. /* Added at libpng-1.2.6 */
  181537. #if !defined(PNG_1_0_X)
  181538. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181539. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181540. # define PNG_SET_USER_LIMITS_SUPPORTED
  181541. #endif
  181542. #endif
  181543. #endif /* PNG_1_0_X */
  181544. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181545. * how large, set these limits to 0x7fffffffL
  181546. */
  181547. #ifndef PNG_USER_WIDTH_MAX
  181548. # define PNG_USER_WIDTH_MAX 1000000L
  181549. #endif
  181550. #ifndef PNG_USER_HEIGHT_MAX
  181551. # define PNG_USER_HEIGHT_MAX 1000000L
  181552. #endif
  181553. /* These are currently experimental features, define them if you want */
  181554. /* very little testing */
  181555. /*
  181556. #ifdef PNG_READ_SUPPORTED
  181557. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181558. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181559. # endif
  181560. #endif
  181561. */
  181562. /* This is only for PowerPC big-endian and 680x0 systems */
  181563. /* some testing */
  181564. /*
  181565. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181566. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181567. #endif
  181568. */
  181569. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181570. /*
  181571. #define PNG_NO_POINTER_INDEXING
  181572. */
  181573. /* These functions are turned off by default, as they will be phased out. */
  181574. /*
  181575. #define PNG_USELESS_TESTS_SUPPORTED
  181576. #define PNG_CORRECT_PALETTE_SUPPORTED
  181577. */
  181578. /* Any chunks you are not interested in, you can undef here. The
  181579. * ones that allocate memory may be expecially important (hIST,
  181580. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181581. * a bit smaller.
  181582. */
  181583. #if defined(PNG_READ_SUPPORTED) && \
  181584. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181585. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181586. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181587. #endif
  181588. #if defined(PNG_WRITE_SUPPORTED) && \
  181589. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181590. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181591. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181592. #endif
  181593. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181594. #ifdef PNG_NO_READ_TEXT
  181595. # define PNG_NO_READ_iTXt
  181596. # define PNG_NO_READ_tEXt
  181597. # define PNG_NO_READ_zTXt
  181598. #endif
  181599. #ifndef PNG_NO_READ_bKGD
  181600. # define PNG_READ_bKGD_SUPPORTED
  181601. # define PNG_bKGD_SUPPORTED
  181602. #endif
  181603. #ifndef PNG_NO_READ_cHRM
  181604. # define PNG_READ_cHRM_SUPPORTED
  181605. # define PNG_cHRM_SUPPORTED
  181606. #endif
  181607. #ifndef PNG_NO_READ_gAMA
  181608. # define PNG_READ_gAMA_SUPPORTED
  181609. # define PNG_gAMA_SUPPORTED
  181610. #endif
  181611. #ifndef PNG_NO_READ_hIST
  181612. # define PNG_READ_hIST_SUPPORTED
  181613. # define PNG_hIST_SUPPORTED
  181614. #endif
  181615. #ifndef PNG_NO_READ_iCCP
  181616. # define PNG_READ_iCCP_SUPPORTED
  181617. # define PNG_iCCP_SUPPORTED
  181618. #endif
  181619. #ifndef PNG_NO_READ_iTXt
  181620. # ifndef PNG_READ_iTXt_SUPPORTED
  181621. # define PNG_READ_iTXt_SUPPORTED
  181622. # endif
  181623. # ifndef PNG_iTXt_SUPPORTED
  181624. # define PNG_iTXt_SUPPORTED
  181625. # endif
  181626. #endif
  181627. #ifndef PNG_NO_READ_oFFs
  181628. # define PNG_READ_oFFs_SUPPORTED
  181629. # define PNG_oFFs_SUPPORTED
  181630. #endif
  181631. #ifndef PNG_NO_READ_pCAL
  181632. # define PNG_READ_pCAL_SUPPORTED
  181633. # define PNG_pCAL_SUPPORTED
  181634. #endif
  181635. #ifndef PNG_NO_READ_sCAL
  181636. # define PNG_READ_sCAL_SUPPORTED
  181637. # define PNG_sCAL_SUPPORTED
  181638. #endif
  181639. #ifndef PNG_NO_READ_pHYs
  181640. # define PNG_READ_pHYs_SUPPORTED
  181641. # define PNG_pHYs_SUPPORTED
  181642. #endif
  181643. #ifndef PNG_NO_READ_sBIT
  181644. # define PNG_READ_sBIT_SUPPORTED
  181645. # define PNG_sBIT_SUPPORTED
  181646. #endif
  181647. #ifndef PNG_NO_READ_sPLT
  181648. # define PNG_READ_sPLT_SUPPORTED
  181649. # define PNG_sPLT_SUPPORTED
  181650. #endif
  181651. #ifndef PNG_NO_READ_sRGB
  181652. # define PNG_READ_sRGB_SUPPORTED
  181653. # define PNG_sRGB_SUPPORTED
  181654. #endif
  181655. #ifndef PNG_NO_READ_tEXt
  181656. # define PNG_READ_tEXt_SUPPORTED
  181657. # define PNG_tEXt_SUPPORTED
  181658. #endif
  181659. #ifndef PNG_NO_READ_tIME
  181660. # define PNG_READ_tIME_SUPPORTED
  181661. # define PNG_tIME_SUPPORTED
  181662. #endif
  181663. #ifndef PNG_NO_READ_tRNS
  181664. # define PNG_READ_tRNS_SUPPORTED
  181665. # define PNG_tRNS_SUPPORTED
  181666. #endif
  181667. #ifndef PNG_NO_READ_zTXt
  181668. # define PNG_READ_zTXt_SUPPORTED
  181669. # define PNG_zTXt_SUPPORTED
  181670. #endif
  181671. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181672. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181673. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181674. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181675. # endif
  181676. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181677. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181678. # endif
  181679. #endif
  181680. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181681. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181682. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181683. # define PNG_USER_CHUNKS_SUPPORTED
  181684. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181685. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181686. # endif
  181687. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181688. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181689. # endif
  181690. #endif
  181691. #ifndef PNG_NO_READ_OPT_PLTE
  181692. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181693. #endif /* optional PLTE chunk in RGB and RGBA images */
  181694. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181695. defined(PNG_READ_zTXt_SUPPORTED)
  181696. # define PNG_READ_TEXT_SUPPORTED
  181697. # define PNG_TEXT_SUPPORTED
  181698. #endif
  181699. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181700. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181701. #ifdef PNG_NO_WRITE_TEXT
  181702. # define PNG_NO_WRITE_iTXt
  181703. # define PNG_NO_WRITE_tEXt
  181704. # define PNG_NO_WRITE_zTXt
  181705. #endif
  181706. #ifndef PNG_NO_WRITE_bKGD
  181707. # define PNG_WRITE_bKGD_SUPPORTED
  181708. # ifndef PNG_bKGD_SUPPORTED
  181709. # define PNG_bKGD_SUPPORTED
  181710. # endif
  181711. #endif
  181712. #ifndef PNG_NO_WRITE_cHRM
  181713. # define PNG_WRITE_cHRM_SUPPORTED
  181714. # ifndef PNG_cHRM_SUPPORTED
  181715. # define PNG_cHRM_SUPPORTED
  181716. # endif
  181717. #endif
  181718. #ifndef PNG_NO_WRITE_gAMA
  181719. # define PNG_WRITE_gAMA_SUPPORTED
  181720. # ifndef PNG_gAMA_SUPPORTED
  181721. # define PNG_gAMA_SUPPORTED
  181722. # endif
  181723. #endif
  181724. #ifndef PNG_NO_WRITE_hIST
  181725. # define PNG_WRITE_hIST_SUPPORTED
  181726. # ifndef PNG_hIST_SUPPORTED
  181727. # define PNG_hIST_SUPPORTED
  181728. # endif
  181729. #endif
  181730. #ifndef PNG_NO_WRITE_iCCP
  181731. # define PNG_WRITE_iCCP_SUPPORTED
  181732. # ifndef PNG_iCCP_SUPPORTED
  181733. # define PNG_iCCP_SUPPORTED
  181734. # endif
  181735. #endif
  181736. #ifndef PNG_NO_WRITE_iTXt
  181737. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181738. # define PNG_WRITE_iTXt_SUPPORTED
  181739. # endif
  181740. # ifndef PNG_iTXt_SUPPORTED
  181741. # define PNG_iTXt_SUPPORTED
  181742. # endif
  181743. #endif
  181744. #ifndef PNG_NO_WRITE_oFFs
  181745. # define PNG_WRITE_oFFs_SUPPORTED
  181746. # ifndef PNG_oFFs_SUPPORTED
  181747. # define PNG_oFFs_SUPPORTED
  181748. # endif
  181749. #endif
  181750. #ifndef PNG_NO_WRITE_pCAL
  181751. # define PNG_WRITE_pCAL_SUPPORTED
  181752. # ifndef PNG_pCAL_SUPPORTED
  181753. # define PNG_pCAL_SUPPORTED
  181754. # endif
  181755. #endif
  181756. #ifndef PNG_NO_WRITE_sCAL
  181757. # define PNG_WRITE_sCAL_SUPPORTED
  181758. # ifndef PNG_sCAL_SUPPORTED
  181759. # define PNG_sCAL_SUPPORTED
  181760. # endif
  181761. #endif
  181762. #ifndef PNG_NO_WRITE_pHYs
  181763. # define PNG_WRITE_pHYs_SUPPORTED
  181764. # ifndef PNG_pHYs_SUPPORTED
  181765. # define PNG_pHYs_SUPPORTED
  181766. # endif
  181767. #endif
  181768. #ifndef PNG_NO_WRITE_sBIT
  181769. # define PNG_WRITE_sBIT_SUPPORTED
  181770. # ifndef PNG_sBIT_SUPPORTED
  181771. # define PNG_sBIT_SUPPORTED
  181772. # endif
  181773. #endif
  181774. #ifndef PNG_NO_WRITE_sPLT
  181775. # define PNG_WRITE_sPLT_SUPPORTED
  181776. # ifndef PNG_sPLT_SUPPORTED
  181777. # define PNG_sPLT_SUPPORTED
  181778. # endif
  181779. #endif
  181780. #ifndef PNG_NO_WRITE_sRGB
  181781. # define PNG_WRITE_sRGB_SUPPORTED
  181782. # ifndef PNG_sRGB_SUPPORTED
  181783. # define PNG_sRGB_SUPPORTED
  181784. # endif
  181785. #endif
  181786. #ifndef PNG_NO_WRITE_tEXt
  181787. # define PNG_WRITE_tEXt_SUPPORTED
  181788. # ifndef PNG_tEXt_SUPPORTED
  181789. # define PNG_tEXt_SUPPORTED
  181790. # endif
  181791. #endif
  181792. #ifndef PNG_NO_WRITE_tIME
  181793. # define PNG_WRITE_tIME_SUPPORTED
  181794. # ifndef PNG_tIME_SUPPORTED
  181795. # define PNG_tIME_SUPPORTED
  181796. # endif
  181797. #endif
  181798. #ifndef PNG_NO_WRITE_tRNS
  181799. # define PNG_WRITE_tRNS_SUPPORTED
  181800. # ifndef PNG_tRNS_SUPPORTED
  181801. # define PNG_tRNS_SUPPORTED
  181802. # endif
  181803. #endif
  181804. #ifndef PNG_NO_WRITE_zTXt
  181805. # define PNG_WRITE_zTXt_SUPPORTED
  181806. # ifndef PNG_zTXt_SUPPORTED
  181807. # define PNG_zTXt_SUPPORTED
  181808. # endif
  181809. #endif
  181810. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181811. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181812. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181813. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181814. # endif
  181815. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181816. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181817. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181818. # endif
  181819. # endif
  181820. #endif
  181821. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181822. defined(PNG_WRITE_zTXt_SUPPORTED)
  181823. # define PNG_WRITE_TEXT_SUPPORTED
  181824. # ifndef PNG_TEXT_SUPPORTED
  181825. # define PNG_TEXT_SUPPORTED
  181826. # endif
  181827. #endif
  181828. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181829. /* Turn this off to disable png_read_png() and
  181830. * png_write_png() and leave the row_pointers member
  181831. * out of the info structure.
  181832. */
  181833. #ifndef PNG_NO_INFO_IMAGE
  181834. # define PNG_INFO_IMAGE_SUPPORTED
  181835. #endif
  181836. /* need the time information for reading tIME chunks */
  181837. #if defined(PNG_tIME_SUPPORTED)
  181838. # if !defined(_WIN32_WCE)
  181839. /* "time.h" functions are not supported on WindowsCE */
  181840. # include <time.h>
  181841. # endif
  181842. #endif
  181843. /* Some typedefs to get us started. These should be safe on most of the
  181844. * common platforms. The typedefs should be at least as large as the
  181845. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181846. * don't have to be exactly that size. Some compilers dislike passing
  181847. * unsigned shorts as function parameters, so you may be better off using
  181848. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181849. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181850. */
  181851. typedef unsigned long png_uint_32;
  181852. typedef long png_int_32;
  181853. typedef unsigned short png_uint_16;
  181854. typedef short png_int_16;
  181855. typedef unsigned char png_byte;
  181856. /* This is usually size_t. It is typedef'ed just in case you need it to
  181857. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181858. #ifdef PNG_SIZE_T
  181859. typedef PNG_SIZE_T png_size_t;
  181860. # define png_sizeof(x) png_convert_size(sizeof (x))
  181861. #else
  181862. typedef size_t png_size_t;
  181863. # define png_sizeof(x) sizeof (x)
  181864. #endif
  181865. /* The following is needed for medium model support. It cannot be in the
  181866. * PNG_INTERNAL section. Needs modification for other compilers besides
  181867. * MSC. Model independent support declares all arrays and pointers to be
  181868. * large using the far keyword. The zlib version used must also support
  181869. * model independent data. As of version zlib 1.0.4, the necessary changes
  181870. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181871. * changes that are needed. (Tim Wegner)
  181872. */
  181873. /* Separate compiler dependencies (problem here is that zlib.h always
  181874. defines FAR. (SJT) */
  181875. #ifdef __BORLANDC__
  181876. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181877. # define LDATA 1
  181878. # else
  181879. # define LDATA 0
  181880. # endif
  181881. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181882. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181883. # define PNG_MAX_MALLOC_64K
  181884. # if (LDATA != 1)
  181885. # ifndef FAR
  181886. # define FAR __far
  181887. # endif
  181888. # define USE_FAR_KEYWORD
  181889. # endif /* LDATA != 1 */
  181890. /* Possibly useful for moving data out of default segment.
  181891. * Uncomment it if you want. Could also define FARDATA as
  181892. * const if your compiler supports it. (SJT)
  181893. # define FARDATA FAR
  181894. */
  181895. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181896. #endif /* __BORLANDC__ */
  181897. /* Suggest testing for specific compiler first before testing for
  181898. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181899. * making reliance oncertain keywords suspect. (SJT)
  181900. */
  181901. /* MSC Medium model */
  181902. #if defined(FAR)
  181903. # if defined(M_I86MM)
  181904. # define USE_FAR_KEYWORD
  181905. # define FARDATA FAR
  181906. # include <dos.h>
  181907. # endif
  181908. #endif
  181909. /* SJT: default case */
  181910. #ifndef FAR
  181911. # define FAR
  181912. #endif
  181913. /* At this point FAR is always defined */
  181914. #ifndef FARDATA
  181915. # define FARDATA
  181916. #endif
  181917. /* Typedef for floating-point numbers that are converted
  181918. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181919. typedef png_int_32 png_fixed_point;
  181920. /* Add typedefs for pointers */
  181921. typedef void FAR * png_voidp;
  181922. typedef png_byte FAR * png_bytep;
  181923. typedef png_uint_32 FAR * png_uint_32p;
  181924. typedef png_int_32 FAR * png_int_32p;
  181925. typedef png_uint_16 FAR * png_uint_16p;
  181926. typedef png_int_16 FAR * png_int_16p;
  181927. typedef PNG_CONST char FAR * png_const_charp;
  181928. typedef char FAR * png_charp;
  181929. typedef png_fixed_point FAR * png_fixed_point_p;
  181930. #ifndef PNG_NO_STDIO
  181931. #if defined(_WIN32_WCE)
  181932. typedef HANDLE png_FILE_p;
  181933. #else
  181934. typedef FILE * png_FILE_p;
  181935. #endif
  181936. #endif
  181937. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181938. typedef double FAR * png_doublep;
  181939. #endif
  181940. /* Pointers to pointers; i.e. arrays */
  181941. typedef png_byte FAR * FAR * png_bytepp;
  181942. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181943. typedef png_int_32 FAR * FAR * png_int_32pp;
  181944. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181945. typedef png_int_16 FAR * FAR * png_int_16pp;
  181946. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181947. typedef char FAR * FAR * png_charpp;
  181948. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181949. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181950. typedef double FAR * FAR * png_doublepp;
  181951. #endif
  181952. /* Pointers to pointers to pointers; i.e., pointer to array */
  181953. typedef char FAR * FAR * FAR * png_charppp;
  181954. #if 0
  181955. /* SPC - Is this stuff deprecated? */
  181956. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181957. /* libpng typedefs for types in zlib. If zlib changes
  181958. * or another compression library is used, then change these.
  181959. * Eliminates need to change all the source files.
  181960. */
  181961. typedef charf * png_zcharp;
  181962. typedef charf * FAR * png_zcharpp;
  181963. typedef z_stream FAR * png_zstreamp;
  181964. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181965. /*
  181966. * Define PNG_BUILD_DLL if the module being built is a Windows
  181967. * LIBPNG DLL.
  181968. *
  181969. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181970. * It is equivalent to Microsoft predefined macro _DLL that is
  181971. * automatically defined when you compile using the share
  181972. * version of the CRT (C Run-Time library)
  181973. *
  181974. * The cygwin mods make this behavior a little different:
  181975. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181976. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181977. * -or- if you are building an application that you want to link to the
  181978. * static library.
  181979. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181980. * the other flags is defined.
  181981. */
  181982. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181983. # define PNG_DLL
  181984. #endif
  181985. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181986. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181987. * command-line override
  181988. */
  181989. #if defined(__CYGWIN__)
  181990. # if !defined(PNG_STATIC)
  181991. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181992. # undef PNG_USE_GLOBAL_ARRAYS
  181993. # endif
  181994. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181995. # define PNG_USE_LOCAL_ARRAYS
  181996. # endif
  181997. # else
  181998. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181999. # if defined(PNG_USE_GLOBAL_ARRAYS)
  182000. # undef PNG_USE_GLOBAL_ARRAYS
  182001. # endif
  182002. # endif
  182003. # endif
  182004. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182005. # define PNG_USE_LOCAL_ARRAYS
  182006. # endif
  182007. #endif
  182008. /* Do not use global arrays (helps with building DLL's)
  182009. * They are no longer used in libpng itself, since version 1.0.5c,
  182010. * but might be required for some pre-1.0.5c applications.
  182011. */
  182012. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182013. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  182014. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  182015. # define PNG_USE_LOCAL_ARRAYS
  182016. # else
  182017. # define PNG_USE_GLOBAL_ARRAYS
  182018. # endif
  182019. #endif
  182020. #if defined(__CYGWIN__)
  182021. # undef PNGAPI
  182022. # define PNGAPI __cdecl
  182023. # undef PNG_IMPEXP
  182024. # define PNG_IMPEXP
  182025. #endif
  182026. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182027. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182028. * Don't ignore those warnings; you must also reset the default calling
  182029. * convention in your compiler to match your PNGAPI, and you must build
  182030. * zlib and your applications the same way you build libpng.
  182031. */
  182032. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182033. # ifndef PNG_NO_MODULEDEF
  182034. # define PNG_NO_MODULEDEF
  182035. # endif
  182036. #endif
  182037. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182038. # define PNG_IMPEXP
  182039. #endif
  182040. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182041. (( defined(_Windows) || defined(_WINDOWS) || \
  182042. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182043. # ifndef PNGAPI
  182044. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182045. # define PNGAPI __cdecl
  182046. # else
  182047. # define PNGAPI _cdecl
  182048. # endif
  182049. # endif
  182050. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182051. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182052. # define PNG_IMPEXP
  182053. # endif
  182054. # if !defined(PNG_IMPEXP)
  182055. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182056. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182057. /* Borland/Microsoft */
  182058. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182059. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182060. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182061. # else
  182062. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182063. # if defined(PNG_BUILD_DLL)
  182064. # define PNG_IMPEXP __export
  182065. # else
  182066. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182067. VC++ */
  182068. # endif /* Exists in Borland C++ for
  182069. C++ classes (== huge) */
  182070. # endif
  182071. # endif
  182072. # if !defined(PNG_IMPEXP)
  182073. # if defined(PNG_BUILD_DLL)
  182074. # define PNG_IMPEXP __declspec(dllexport)
  182075. # else
  182076. # define PNG_IMPEXP __declspec(dllimport)
  182077. # endif
  182078. # endif
  182079. # endif /* PNG_IMPEXP */
  182080. #else /* !(DLL || non-cygwin WINDOWS) */
  182081. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182082. # ifndef PNGAPI
  182083. # define PNGAPI _System
  182084. # endif
  182085. # else
  182086. # if 0 /* ... other platforms, with other meanings */
  182087. # endif
  182088. # endif
  182089. #endif
  182090. #ifndef PNGAPI
  182091. # define PNGAPI
  182092. #endif
  182093. #ifndef PNG_IMPEXP
  182094. # define PNG_IMPEXP
  182095. #endif
  182096. #ifdef PNG_BUILDSYMS
  182097. # ifndef PNG_EXPORT
  182098. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182099. # endif
  182100. # ifdef PNG_USE_GLOBAL_ARRAYS
  182101. # ifndef PNG_EXPORT_VAR
  182102. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182103. # endif
  182104. # endif
  182105. #endif
  182106. #ifndef PNG_EXPORT
  182107. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182108. #endif
  182109. #ifdef PNG_USE_GLOBAL_ARRAYS
  182110. # ifndef PNG_EXPORT_VAR
  182111. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182112. # endif
  182113. #endif
  182114. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182115. * functions that are passed far data must be model independent.
  182116. */
  182117. #ifndef PNG_ABORT
  182118. # define PNG_ABORT() abort()
  182119. #endif
  182120. #ifdef PNG_SETJMP_SUPPORTED
  182121. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182122. #else
  182123. # define png_jmpbuf(png_ptr) \
  182124. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182125. #endif
  182126. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182127. /* use this to make far-to-near assignments */
  182128. # define CHECK 1
  182129. # define NOCHECK 0
  182130. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182131. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182132. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182133. # define png_strcpy _fstrcpy
  182134. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182135. # define png_strlen _fstrlen
  182136. # define png_memcmp _fmemcmp /* SJT: added */
  182137. # define png_memcpy _fmemcpy
  182138. # define png_memset _fmemset
  182139. #else /* use the usual functions */
  182140. # define CVT_PTR(ptr) (ptr)
  182141. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182142. # ifndef PNG_NO_SNPRINTF
  182143. # ifdef _MSC_VER
  182144. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182145. # define png_snprintf2 _snprintf
  182146. # define png_snprintf6 _snprintf
  182147. # else
  182148. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182149. # define png_snprintf2 snprintf
  182150. # define png_snprintf6 snprintf
  182151. # endif
  182152. # else
  182153. /* You don't have or don't want to use snprintf(). Caution: Using
  182154. * sprintf instead of snprintf exposes your application to accidental
  182155. * or malevolent buffer overflows. If you don't have snprintf()
  182156. * as a general rule you should provide one (you can get one from
  182157. * Portable OpenSSH). */
  182158. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182159. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182160. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182161. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182162. # endif
  182163. # define png_strcpy strcpy
  182164. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182165. # define png_strlen strlen
  182166. # define png_memcmp memcmp /* SJT: added */
  182167. # define png_memcpy memcpy
  182168. # define png_memset memset
  182169. #endif
  182170. /* End of memory model independent support */
  182171. /* Just a little check that someone hasn't tried to define something
  182172. * contradictory.
  182173. */
  182174. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182175. # undef PNG_ZBUF_SIZE
  182176. # define PNG_ZBUF_SIZE 65536L
  182177. #endif
  182178. /* Added at libpng-1.2.8 */
  182179. #endif /* PNG_VERSION_INFO_ONLY */
  182180. #endif /* PNGCONF_H */
  182181. /*** End of inlined file: pngconf.h ***/
  182182. #ifdef _MSC_VER
  182183. #pragma warning (disable: 4996 4100)
  182184. #endif
  182185. /*
  182186. * Added at libpng-1.2.8 */
  182187. /* Ref MSDN: Private as priority over Special
  182188. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182189. * procedures. If this value is given, the StringFileInfo block must
  182190. * contain a PrivateBuild string.
  182191. *
  182192. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182193. * standard release procedures but is a variation of the standard
  182194. * file of the same version number. If this value is given, the
  182195. * StringFileInfo block must contain a SpecialBuild string.
  182196. */
  182197. #if defined(PNG_USER_PRIVATEBUILD)
  182198. # define PNG_LIBPNG_BUILD_TYPE \
  182199. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182200. #else
  182201. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182202. # define PNG_LIBPNG_BUILD_TYPE \
  182203. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182204. # else
  182205. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182206. # endif
  182207. #endif
  182208. #ifndef PNG_VERSION_INFO_ONLY
  182209. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182210. #ifdef __cplusplus
  182211. //extern "C" {
  182212. #endif /* __cplusplus */
  182213. /* This file is arranged in several sections. The first section contains
  182214. * structure and type definitions. The second section contains the external
  182215. * library functions, while the third has the internal library functions,
  182216. * which applications aren't expected to use directly.
  182217. */
  182218. #ifndef PNG_NO_TYPECAST_NULL
  182219. #define int_p_NULL (int *)NULL
  182220. #define png_bytep_NULL (png_bytep)NULL
  182221. #define png_bytepp_NULL (png_bytepp)NULL
  182222. #define png_doublep_NULL (png_doublep)NULL
  182223. #define png_error_ptr_NULL (png_error_ptr)NULL
  182224. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182225. #define png_free_ptr_NULL (png_free_ptr)NULL
  182226. #define png_infopp_NULL (png_infopp)NULL
  182227. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182228. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182229. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182230. #define png_structp_NULL (png_structp)NULL
  182231. #define png_uint_16p_NULL (png_uint_16p)NULL
  182232. #define png_voidp_NULL (png_voidp)NULL
  182233. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182234. #else
  182235. #define int_p_NULL NULL
  182236. #define png_bytep_NULL NULL
  182237. #define png_bytepp_NULL NULL
  182238. #define png_doublep_NULL NULL
  182239. #define png_error_ptr_NULL NULL
  182240. #define png_flush_ptr_NULL NULL
  182241. #define png_free_ptr_NULL NULL
  182242. #define png_infopp_NULL NULL
  182243. #define png_malloc_ptr_NULL NULL
  182244. #define png_read_status_ptr_NULL NULL
  182245. #define png_rw_ptr_NULL NULL
  182246. #define png_structp_NULL NULL
  182247. #define png_uint_16p_NULL NULL
  182248. #define png_voidp_NULL NULL
  182249. #define png_write_status_ptr_NULL NULL
  182250. #endif
  182251. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182252. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182253. /* Version information for C files, stored in png.c. This had better match
  182254. * the version above.
  182255. */
  182256. #ifdef PNG_USE_GLOBAL_ARRAYS
  182257. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182258. /* need room for 99.99.99beta99z */
  182259. #else
  182260. #define png_libpng_ver png_get_header_ver(NULL)
  182261. #endif
  182262. #ifdef PNG_USE_GLOBAL_ARRAYS
  182263. /* This was removed in version 1.0.5c */
  182264. /* Structures to facilitate easy interlacing. See png.c for more details */
  182265. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182266. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182267. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182268. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182269. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182270. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182271. /* This isn't currently used. If you need it, see png.c for more details.
  182272. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182273. */
  182274. #endif
  182275. #endif /* PNG_NO_EXTERN */
  182276. /* Three color definitions. The order of the red, green, and blue, (and the
  182277. * exact size) is not important, although the size of the fields need to
  182278. * be png_byte or png_uint_16 (as defined below).
  182279. */
  182280. typedef struct png_color_struct
  182281. {
  182282. png_byte red;
  182283. png_byte green;
  182284. png_byte blue;
  182285. } png_color;
  182286. typedef png_color FAR * png_colorp;
  182287. typedef png_color FAR * FAR * png_colorpp;
  182288. typedef struct png_color_16_struct
  182289. {
  182290. png_byte index; /* used for palette files */
  182291. png_uint_16 red; /* for use in red green blue files */
  182292. png_uint_16 green;
  182293. png_uint_16 blue;
  182294. png_uint_16 gray; /* for use in grayscale files */
  182295. } png_color_16;
  182296. typedef png_color_16 FAR * png_color_16p;
  182297. typedef png_color_16 FAR * FAR * png_color_16pp;
  182298. typedef struct png_color_8_struct
  182299. {
  182300. png_byte red; /* for use in red green blue files */
  182301. png_byte green;
  182302. png_byte blue;
  182303. png_byte gray; /* for use in grayscale files */
  182304. png_byte alpha; /* for alpha channel files */
  182305. } png_color_8;
  182306. typedef png_color_8 FAR * png_color_8p;
  182307. typedef png_color_8 FAR * FAR * png_color_8pp;
  182308. /*
  182309. * The following two structures are used for the in-core representation
  182310. * of sPLT chunks.
  182311. */
  182312. typedef struct png_sPLT_entry_struct
  182313. {
  182314. png_uint_16 red;
  182315. png_uint_16 green;
  182316. png_uint_16 blue;
  182317. png_uint_16 alpha;
  182318. png_uint_16 frequency;
  182319. } png_sPLT_entry;
  182320. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182321. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182322. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182323. * occupy the LSB of their respective members, and the MSB of each member
  182324. * is zero-filled. The frequency member always occupies the full 16 bits.
  182325. */
  182326. typedef struct png_sPLT_struct
  182327. {
  182328. png_charp name; /* palette name */
  182329. png_byte depth; /* depth of palette samples */
  182330. png_sPLT_entryp entries; /* palette entries */
  182331. png_int_32 nentries; /* number of palette entries */
  182332. } png_sPLT_t;
  182333. typedef png_sPLT_t FAR * png_sPLT_tp;
  182334. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182335. #ifdef PNG_TEXT_SUPPORTED
  182336. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182337. * and whether that contents is compressed or not. The "key" field
  182338. * points to a regular zero-terminated C string. The "text", "lang", and
  182339. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182340. * However, the * structure returned by png_get_text() will always contain
  182341. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182342. * so they can be safely used in printf() and other string-handling functions.
  182343. */
  182344. typedef struct png_text_struct
  182345. {
  182346. int compression; /* compression value:
  182347. -1: tEXt, none
  182348. 0: zTXt, deflate
  182349. 1: iTXt, none
  182350. 2: iTXt, deflate */
  182351. png_charp key; /* keyword, 1-79 character description of "text" */
  182352. png_charp text; /* comment, may be an empty string (ie "")
  182353. or a NULL pointer */
  182354. png_size_t text_length; /* length of the text string */
  182355. #ifdef PNG_iTXt_SUPPORTED
  182356. png_size_t itxt_length; /* length of the itxt string */
  182357. png_charp lang; /* language code, 0-79 characters
  182358. or a NULL pointer */
  182359. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182360. chars or a NULL pointer */
  182361. #endif
  182362. } png_text;
  182363. typedef png_text FAR * png_textp;
  182364. typedef png_text FAR * FAR * png_textpp;
  182365. #endif
  182366. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182367. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182368. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182369. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182370. #define PNG_TEXT_COMPRESSION_NONE -1
  182371. #define PNG_TEXT_COMPRESSION_zTXt 0
  182372. #define PNG_ITXT_COMPRESSION_NONE 1
  182373. #define PNG_ITXT_COMPRESSION_zTXt 2
  182374. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182375. /* png_time is a way to hold the time in an machine independent way.
  182376. * Two conversions are provided, both from time_t and struct tm. There
  182377. * is no portable way to convert to either of these structures, as far
  182378. * as I know. If you know of a portable way, send it to me. As a side
  182379. * note - PNG has always been Year 2000 compliant!
  182380. */
  182381. typedef struct png_time_struct
  182382. {
  182383. png_uint_16 year; /* full year, as in, 1995 */
  182384. png_byte month; /* month of year, 1 - 12 */
  182385. png_byte day; /* day of month, 1 - 31 */
  182386. png_byte hour; /* hour of day, 0 - 23 */
  182387. png_byte minute; /* minute of hour, 0 - 59 */
  182388. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182389. } png_time;
  182390. typedef png_time FAR * png_timep;
  182391. typedef png_time FAR * FAR * png_timepp;
  182392. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182393. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182394. * no specific support. The idea is that we can use this to queue
  182395. * up private chunks for output even though the library doesn't actually
  182396. * know about their semantics.
  182397. */
  182398. typedef struct png_unknown_chunk_t
  182399. {
  182400. png_byte name[5];
  182401. png_byte *data;
  182402. png_size_t size;
  182403. /* libpng-using applications should NOT directly modify this byte. */
  182404. png_byte location; /* mode of operation at read time */
  182405. }
  182406. png_unknown_chunk;
  182407. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182408. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182409. #endif
  182410. /* png_info is a structure that holds the information in a PNG file so
  182411. * that the application can find out the characteristics of the image.
  182412. * If you are reading the file, this structure will tell you what is
  182413. * in the PNG file. If you are writing the file, fill in the information
  182414. * you want to put into the PNG file, then call png_write_info().
  182415. * The names chosen should be very close to the PNG specification, so
  182416. * consult that document for information about the meaning of each field.
  182417. *
  182418. * With libpng < 0.95, it was only possible to directly set and read the
  182419. * the values in the png_info_struct, which meant that the contents and
  182420. * order of the values had to remain fixed. With libpng 0.95 and later,
  182421. * however, there are now functions that abstract the contents of
  182422. * png_info_struct from the application, so this makes it easier to use
  182423. * libpng with dynamic libraries, and even makes it possible to use
  182424. * libraries that don't have all of the libpng ancillary chunk-handing
  182425. * functionality.
  182426. *
  182427. * In any case, the order of the parameters in png_info_struct should NOT
  182428. * be changed for as long as possible to keep compatibility with applications
  182429. * that use the old direct-access method with png_info_struct.
  182430. *
  182431. * The following members may have allocated storage attached that should be
  182432. * cleaned up before the structure is discarded: palette, trans, text,
  182433. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182434. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182435. * are automatically freed when the info structure is deallocated, if they were
  182436. * allocated internally by libpng. This behavior can be changed by means
  182437. * of the png_data_freer() function.
  182438. *
  182439. * More allocation details: all the chunk-reading functions that
  182440. * change these members go through the corresponding png_set_*
  182441. * functions. A function to clear these members is available: see
  182442. * png_free_data(). The png_set_* functions do not depend on being
  182443. * able to point info structure members to any of the storage they are
  182444. * passed (they make their own copies), EXCEPT that the png_set_text
  182445. * functions use the same storage passed to them in the text_ptr or
  182446. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182447. * functions do not make their own copies.
  182448. */
  182449. typedef struct png_info_struct
  182450. {
  182451. /* the following are necessary for every PNG file */
  182452. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182453. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182454. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182455. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182456. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182457. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182458. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182459. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182460. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182461. /* The following three should have been named *_method not *_type */
  182462. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182463. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182464. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182465. /* The following is informational only on read, and not used on writes. */
  182466. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182467. png_byte pixel_depth; /* number of bits per pixel */
  182468. png_byte spare_byte; /* to align the data, and for future use */
  182469. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182470. /* The rest of the data is optional. If you are reading, check the
  182471. * valid field to see if the information in these are valid. If you
  182472. * are writing, set the valid field to those chunks you want written,
  182473. * and initialize the appropriate fields below.
  182474. */
  182475. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182476. /* The gAMA chunk describes the gamma characteristics of the system
  182477. * on which the image was created, normally in the range [1.0, 2.5].
  182478. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182479. */
  182480. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182481. #endif
  182482. #if defined(PNG_sRGB_SUPPORTED)
  182483. /* GR-P, 0.96a */
  182484. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182485. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182486. #endif
  182487. #if defined(PNG_TEXT_SUPPORTED)
  182488. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182489. * uncompressed, compressed, and optionally compressed forms, respectively.
  182490. * The data in "text" is an array of pointers to uncompressed,
  182491. * null-terminated C strings. Each chunk has a keyword that describes the
  182492. * textual data contained in that chunk. Keywords are not required to be
  182493. * unique, and the text string may be empty. Any number of text chunks may
  182494. * be in an image.
  182495. */
  182496. int num_text; /* number of comments read/to write */
  182497. int max_text; /* current size of text array */
  182498. png_textp text; /* array of comments read/to write */
  182499. #endif /* PNG_TEXT_SUPPORTED */
  182500. #if defined(PNG_tIME_SUPPORTED)
  182501. /* The tIME chunk holds the last time the displayed image data was
  182502. * modified. See the png_time struct for the contents of this struct.
  182503. */
  182504. png_time mod_time;
  182505. #endif
  182506. #if defined(PNG_sBIT_SUPPORTED)
  182507. /* The sBIT chunk specifies the number of significant high-order bits
  182508. * in the pixel data. Values are in the range [1, bit_depth], and are
  182509. * only specified for the channels in the pixel data. The contents of
  182510. * the low-order bits is not specified. Data is valid if
  182511. * (valid & PNG_INFO_sBIT) is non-zero.
  182512. */
  182513. png_color_8 sig_bit; /* significant bits in color channels */
  182514. #endif
  182515. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182516. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182517. /* The tRNS chunk supplies transparency data for paletted images and
  182518. * other image types that don't need a full alpha channel. There are
  182519. * "num_trans" transparency values for a paletted image, stored in the
  182520. * same order as the palette colors, starting from index 0. Values
  182521. * for the data are in the range [0, 255], ranging from fully transparent
  182522. * to fully opaque, respectively. For non-paletted images, there is a
  182523. * single color specified that should be treated as fully transparent.
  182524. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182525. */
  182526. png_bytep trans; /* transparent values for paletted image */
  182527. png_color_16 trans_values; /* transparent color for non-palette image */
  182528. #endif
  182529. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182530. /* The bKGD chunk gives the suggested image background color if the
  182531. * display program does not have its own background color and the image
  182532. * is needs to composited onto a background before display. The colors
  182533. * in "background" are normally in the same color space/depth as the
  182534. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182535. */
  182536. png_color_16 background;
  182537. #endif
  182538. #if defined(PNG_oFFs_SUPPORTED)
  182539. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182540. * and downwards from the top-left corner of the display, page, or other
  182541. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182542. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182543. */
  182544. png_int_32 x_offset; /* x offset on page */
  182545. png_int_32 y_offset; /* y offset on page */
  182546. png_byte offset_unit_type; /* offset units type */
  182547. #endif
  182548. #if defined(PNG_pHYs_SUPPORTED)
  182549. /* The pHYs chunk gives the physical pixel density of the image for
  182550. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182551. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182552. */
  182553. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182554. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182555. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182556. #endif
  182557. #if defined(PNG_hIST_SUPPORTED)
  182558. /* The hIST chunk contains the relative frequency or importance of the
  182559. * various palette entries, so that a viewer can intelligently select a
  182560. * reduced-color palette, if required. Data is an array of "num_palette"
  182561. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182562. * is non-zero.
  182563. */
  182564. png_uint_16p hist;
  182565. #endif
  182566. #ifdef PNG_cHRM_SUPPORTED
  182567. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182568. * on which the PNG was created. This data allows the viewer to do gamut
  182569. * mapping of the input image to ensure that the viewer sees the same
  182570. * colors in the image as the creator. Values are in the range
  182571. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182572. */
  182573. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182574. float x_white;
  182575. float y_white;
  182576. float x_red;
  182577. float y_red;
  182578. float x_green;
  182579. float y_green;
  182580. float x_blue;
  182581. float y_blue;
  182582. #endif
  182583. #endif
  182584. #if defined(PNG_pCAL_SUPPORTED)
  182585. /* The pCAL chunk describes a transformation between the stored pixel
  182586. * values and original physical data values used to create the image.
  182587. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182588. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182589. * (possibly non-linear) transformation function given by "pcal_type"
  182590. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182591. * defines below, and the PNG-Group's PNG extensions document for a
  182592. * complete description of the transformations and how they should be
  182593. * implemented, and for a description of the ASCII parameter strings.
  182594. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182595. */
  182596. png_charp pcal_purpose; /* pCAL chunk description string */
  182597. png_int_32 pcal_X0; /* minimum value */
  182598. png_int_32 pcal_X1; /* maximum value */
  182599. png_charp pcal_units; /* Latin-1 string giving physical units */
  182600. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182601. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182602. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182603. #endif
  182604. /* New members added in libpng-1.0.6 */
  182605. #ifdef PNG_FREE_ME_SUPPORTED
  182606. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182607. #endif
  182608. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182609. /* storage for unknown chunks that the library doesn't recognize. */
  182610. png_unknown_chunkp unknown_chunks;
  182611. png_size_t unknown_chunks_num;
  182612. #endif
  182613. #if defined(PNG_iCCP_SUPPORTED)
  182614. /* iCCP chunk data. */
  182615. png_charp iccp_name; /* profile name */
  182616. png_charp iccp_profile; /* International Color Consortium profile data */
  182617. /* Note to maintainer: should be png_bytep */
  182618. png_uint_32 iccp_proflen; /* ICC profile data length */
  182619. png_byte iccp_compression; /* Always zero */
  182620. #endif
  182621. #if defined(PNG_sPLT_SUPPORTED)
  182622. /* data on sPLT chunks (there may be more than one). */
  182623. png_sPLT_tp splt_palettes;
  182624. png_uint_32 splt_palettes_num;
  182625. #endif
  182626. #if defined(PNG_sCAL_SUPPORTED)
  182627. /* The sCAL chunk describes the actual physical dimensions of the
  182628. * subject matter of the graphic. The chunk contains a unit specification
  182629. * a byte value, and two ASCII strings representing floating-point
  182630. * values. The values are width and height corresponsing to one pixel
  182631. * in the image. This external representation is converted to double
  182632. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182633. */
  182634. png_byte scal_unit; /* unit of physical scale */
  182635. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182636. double scal_pixel_width; /* width of one pixel */
  182637. double scal_pixel_height; /* height of one pixel */
  182638. #endif
  182639. #ifdef PNG_FIXED_POINT_SUPPORTED
  182640. png_charp scal_s_width; /* string containing height */
  182641. png_charp scal_s_height; /* string containing width */
  182642. #endif
  182643. #endif
  182644. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182645. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182646. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182647. png_bytepp row_pointers; /* the image bits */
  182648. #endif
  182649. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182650. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182651. #endif
  182652. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182653. png_fixed_point int_x_white;
  182654. png_fixed_point int_y_white;
  182655. png_fixed_point int_x_red;
  182656. png_fixed_point int_y_red;
  182657. png_fixed_point int_x_green;
  182658. png_fixed_point int_y_green;
  182659. png_fixed_point int_x_blue;
  182660. png_fixed_point int_y_blue;
  182661. #endif
  182662. } png_info;
  182663. typedef png_info FAR * png_infop;
  182664. typedef png_info FAR * FAR * png_infopp;
  182665. /* Maximum positive integer used in PNG is (2^31)-1 */
  182666. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182667. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182668. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182669. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182670. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182671. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182672. #endif
  182673. /* These describe the color_type field in png_info. */
  182674. /* color type masks */
  182675. #define PNG_COLOR_MASK_PALETTE 1
  182676. #define PNG_COLOR_MASK_COLOR 2
  182677. #define PNG_COLOR_MASK_ALPHA 4
  182678. /* color types. Note that not all combinations are legal */
  182679. #define PNG_COLOR_TYPE_GRAY 0
  182680. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182681. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182682. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182683. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182684. /* aliases */
  182685. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182686. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182687. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182688. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182689. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182690. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182691. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182692. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182693. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182694. /* These are for the interlacing type. These values should NOT be changed. */
  182695. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182696. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182697. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182698. /* These are for the oFFs chunk. These values should NOT be changed. */
  182699. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182700. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182701. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182702. /* These are for the pCAL chunk. These values should NOT be changed. */
  182703. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182704. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182705. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182706. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182707. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182708. /* These are for the sCAL chunk. These values should NOT be changed. */
  182709. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182710. #define PNG_SCALE_METER 1 /* meters per pixel */
  182711. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182712. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182713. /* These are for the pHYs chunk. These values should NOT be changed. */
  182714. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182715. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182716. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182717. /* These are for the sRGB chunk. These values should NOT be changed. */
  182718. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182719. #define PNG_sRGB_INTENT_RELATIVE 1
  182720. #define PNG_sRGB_INTENT_SATURATION 2
  182721. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182722. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182723. /* This is for text chunks */
  182724. #define PNG_KEYWORD_MAX_LENGTH 79
  182725. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182726. #define PNG_MAX_PALETTE_LENGTH 256
  182727. /* These determine if an ancillary chunk's data has been successfully read
  182728. * from the PNG header, or if the application has filled in the corresponding
  182729. * data in the info_struct to be written into the output file. The values
  182730. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182731. */
  182732. #define PNG_INFO_gAMA 0x0001
  182733. #define PNG_INFO_sBIT 0x0002
  182734. #define PNG_INFO_cHRM 0x0004
  182735. #define PNG_INFO_PLTE 0x0008
  182736. #define PNG_INFO_tRNS 0x0010
  182737. #define PNG_INFO_bKGD 0x0020
  182738. #define PNG_INFO_hIST 0x0040
  182739. #define PNG_INFO_pHYs 0x0080
  182740. #define PNG_INFO_oFFs 0x0100
  182741. #define PNG_INFO_tIME 0x0200
  182742. #define PNG_INFO_pCAL 0x0400
  182743. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182744. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182745. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182746. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182747. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182748. /* This is used for the transformation routines, as some of them
  182749. * change these values for the row. It also should enable using
  182750. * the routines for other purposes.
  182751. */
  182752. typedef struct png_row_info_struct
  182753. {
  182754. png_uint_32 width; /* width of row */
  182755. png_uint_32 rowbytes; /* number of bytes in row */
  182756. png_byte color_type; /* color type of row */
  182757. png_byte bit_depth; /* bit depth of row */
  182758. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182759. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182760. } png_row_info;
  182761. typedef png_row_info FAR * png_row_infop;
  182762. typedef png_row_info FAR * FAR * png_row_infopp;
  182763. /* These are the function types for the I/O functions and for the functions
  182764. * that allow the user to override the default I/O functions with his or her
  182765. * own. The png_error_ptr type should match that of user-supplied warning
  182766. * and error functions, while the png_rw_ptr type should match that of the
  182767. * user read/write data functions.
  182768. */
  182769. typedef struct png_struct_def png_struct;
  182770. typedef png_struct FAR * png_structp;
  182771. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182772. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182773. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182774. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182775. int));
  182776. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182777. int));
  182778. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182779. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182780. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182781. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182782. png_uint_32, int));
  182783. #endif
  182784. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182785. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182786. defined(PNG_LEGACY_SUPPORTED)
  182787. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182788. png_row_infop, png_bytep));
  182789. #endif
  182790. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182791. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182792. #endif
  182793. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182794. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182795. #endif
  182796. /* Transform masks for the high-level interface */
  182797. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182798. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182799. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182800. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182801. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182802. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182803. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182804. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182805. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182806. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182807. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182808. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182809. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182810. /* Flags for MNG supported features */
  182811. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182812. #define PNG_FLAG_MNG_FILTER_64 0x04
  182813. #define PNG_ALL_MNG_FEATURES 0x05
  182814. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182815. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182816. /* The structure that holds the information to read and write PNG files.
  182817. * The only people who need to care about what is inside of this are the
  182818. * people who will be modifying the library for their own special needs.
  182819. * It should NOT be accessed directly by an application, except to store
  182820. * the jmp_buf.
  182821. */
  182822. struct png_struct_def
  182823. {
  182824. #ifdef PNG_SETJMP_SUPPORTED
  182825. jmp_buf jmpbuf; /* used in png_error */
  182826. #endif
  182827. png_error_ptr error_fn; /* function for printing errors and aborting */
  182828. png_error_ptr warning_fn; /* function for printing warnings */
  182829. png_voidp error_ptr; /* user supplied struct for error functions */
  182830. png_rw_ptr write_data_fn; /* function for writing output data */
  182831. png_rw_ptr read_data_fn; /* function for reading input data */
  182832. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182833. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182834. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182835. #endif
  182836. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182837. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182838. #endif
  182839. /* These were added in libpng-1.0.2 */
  182840. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182841. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182842. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182843. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182844. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182845. png_byte user_transform_channels; /* channels in user transformed pixels */
  182846. #endif
  182847. #endif
  182848. png_uint_32 mode; /* tells us where we are in the PNG file */
  182849. png_uint_32 flags; /* flags indicating various things to libpng */
  182850. png_uint_32 transformations; /* which transformations to perform */
  182851. z_stream zstream; /* pointer to decompression structure (below) */
  182852. png_bytep zbuf; /* buffer for zlib */
  182853. png_size_t zbuf_size; /* size of zbuf */
  182854. int zlib_level; /* holds zlib compression level */
  182855. int zlib_method; /* holds zlib compression method */
  182856. int zlib_window_bits; /* holds zlib compression window bits */
  182857. int zlib_mem_level; /* holds zlib compression memory level */
  182858. int zlib_strategy; /* holds zlib compression strategy */
  182859. png_uint_32 width; /* width of image in pixels */
  182860. png_uint_32 height; /* height of image in pixels */
  182861. png_uint_32 num_rows; /* number of rows in current pass */
  182862. png_uint_32 usr_width; /* width of row at start of write */
  182863. png_uint_32 rowbytes; /* size of row in bytes */
  182864. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182865. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182866. png_uint_32 row_number; /* current row in interlace pass */
  182867. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182868. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182869. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182870. png_bytep up_row; /* buffer to save "up" row when filtering */
  182871. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182872. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182873. png_row_info row_info; /* used for transformation routines */
  182874. png_uint_32 idat_size; /* current IDAT size for read */
  182875. png_uint_32 crc; /* current chunk CRC value */
  182876. png_colorp palette; /* palette from the input file */
  182877. png_uint_16 num_palette; /* number of color entries in palette */
  182878. png_uint_16 num_trans; /* number of transparency values */
  182879. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182880. png_byte compression; /* file compression type (always 0) */
  182881. png_byte filter; /* file filter type (always 0) */
  182882. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182883. png_byte pass; /* current interlace pass (0 - 6) */
  182884. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182885. png_byte color_type; /* color type of file */
  182886. png_byte bit_depth; /* bit depth of file */
  182887. png_byte usr_bit_depth; /* bit depth of users row */
  182888. png_byte pixel_depth; /* number of bits per pixel */
  182889. png_byte channels; /* number of channels in file */
  182890. png_byte usr_channels; /* channels at start of write */
  182891. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182892. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182893. #ifdef PNG_LEGACY_SUPPORTED
  182894. png_byte filler; /* filler byte for pixel expansion */
  182895. #else
  182896. png_uint_16 filler; /* filler bytes for pixel expansion */
  182897. #endif
  182898. #endif
  182899. #if defined(PNG_bKGD_SUPPORTED)
  182900. png_byte background_gamma_type;
  182901. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182902. float background_gamma;
  182903. # endif
  182904. png_color_16 background; /* background color in screen gamma space */
  182905. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182906. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182907. #endif
  182908. #endif /* PNG_bKGD_SUPPORTED */
  182909. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182910. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182911. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182912. png_uint_32 flush_rows; /* number of rows written since last flush */
  182913. #endif
  182914. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182915. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182916. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182917. float gamma; /* file gamma value */
  182918. float screen_gamma; /* screen gamma value (display_exponent) */
  182919. #endif
  182920. #endif
  182921. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182922. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182923. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182924. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182925. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182926. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182927. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182928. #endif
  182929. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182930. png_color_8 sig_bit; /* significant bits in each available channel */
  182931. #endif
  182932. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182933. png_color_8 shift; /* shift for significant bit tranformation */
  182934. #endif
  182935. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182936. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182937. png_bytep trans; /* transparency values for paletted files */
  182938. png_color_16 trans_values; /* transparency values for non-paletted files */
  182939. #endif
  182940. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182941. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182942. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182943. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182944. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182945. png_progressive_end_ptr end_fn; /* called after image is complete */
  182946. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182947. png_bytep save_buffer; /* buffer for previously read data */
  182948. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182949. png_bytep current_buffer; /* buffer for recently used data */
  182950. png_uint_32 push_length; /* size of current input chunk */
  182951. png_uint_32 skip_length; /* bytes to skip in input data */
  182952. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182953. png_size_t save_buffer_max; /* total size of save_buffer */
  182954. png_size_t buffer_size; /* total amount of available input data */
  182955. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182956. int process_mode; /* what push library is currently doing */
  182957. int cur_palette; /* current push library palette index */
  182958. # if defined(PNG_TEXT_SUPPORTED)
  182959. png_size_t current_text_size; /* current size of text input data */
  182960. png_size_t current_text_left; /* how much text left to read in input */
  182961. png_charp current_text; /* current text chunk buffer */
  182962. png_charp current_text_ptr; /* current location in current_text */
  182963. # endif /* PNG_TEXT_SUPPORTED */
  182964. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182965. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182966. /* for the Borland special 64K segment handler */
  182967. png_bytepp offset_table_ptr;
  182968. png_bytep offset_table;
  182969. png_uint_16 offset_table_number;
  182970. png_uint_16 offset_table_count;
  182971. png_uint_16 offset_table_count_free;
  182972. #endif
  182973. #if defined(PNG_READ_DITHER_SUPPORTED)
  182974. png_bytep palette_lookup; /* lookup table for dithering */
  182975. png_bytep dither_index; /* index translation for palette files */
  182976. #endif
  182977. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182978. png_uint_16p hist; /* histogram */
  182979. #endif
  182980. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182981. png_byte heuristic_method; /* heuristic for row filter selection */
  182982. png_byte num_prev_filters; /* number of weights for previous rows */
  182983. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182984. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182985. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182986. png_uint_16p filter_costs; /* relative filter calculation cost */
  182987. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182988. #endif
  182989. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182990. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182991. #endif
  182992. /* New members added in libpng-1.0.6 */
  182993. #ifdef PNG_FREE_ME_SUPPORTED
  182994. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182995. #endif
  182996. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182997. png_voidp user_chunk_ptr;
  182998. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182999. #endif
  183000. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183001. int num_chunk_list;
  183002. png_bytep chunk_list;
  183003. #endif
  183004. /* New members added in libpng-1.0.3 */
  183005. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183006. png_byte rgb_to_gray_status;
  183007. /* These were changed from png_byte in libpng-1.0.6 */
  183008. png_uint_16 rgb_to_gray_red_coeff;
  183009. png_uint_16 rgb_to_gray_green_coeff;
  183010. png_uint_16 rgb_to_gray_blue_coeff;
  183011. #endif
  183012. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  183013. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  183014. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183015. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183016. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  183017. #ifdef PNG_1_0_X
  183018. png_byte mng_features_permitted;
  183019. #else
  183020. png_uint_32 mng_features_permitted;
  183021. #endif /* PNG_1_0_X */
  183022. #endif
  183023. /* New member added in libpng-1.0.7 */
  183024. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183025. png_fixed_point int_gamma;
  183026. #endif
  183027. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183028. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183029. png_byte filter_type;
  183030. #endif
  183031. #if defined(PNG_1_0_X)
  183032. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183033. png_uint_32 row_buf_size;
  183034. #endif
  183035. /* New members added in libpng-1.2.0 */
  183036. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183037. # if !defined(PNG_1_0_X)
  183038. # if defined(PNG_MMX_CODE_SUPPORTED)
  183039. png_byte mmx_bitdepth_threshold;
  183040. png_uint_32 mmx_rowbytes_threshold;
  183041. # endif
  183042. png_uint_32 asm_flags;
  183043. # endif
  183044. #endif
  183045. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183046. #ifdef PNG_USER_MEM_SUPPORTED
  183047. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183048. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183049. png_free_ptr free_fn; /* function for freeing memory */
  183050. #endif
  183051. /* New member added in libpng-1.0.13 and 1.2.0 */
  183052. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183053. #if defined(PNG_READ_DITHER_SUPPORTED)
  183054. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183055. png_bytep dither_sort; /* working sort array */
  183056. png_bytep index_to_palette; /* where the original index currently is */
  183057. /* in the palette */
  183058. png_bytep palette_to_index; /* which original index points to this */
  183059. /* palette color */
  183060. #endif
  183061. /* New members added in libpng-1.0.16 and 1.2.6 */
  183062. png_byte compression_type;
  183063. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183064. png_uint_32 user_width_max;
  183065. png_uint_32 user_height_max;
  183066. #endif
  183067. /* New member added in libpng-1.0.25 and 1.2.17 */
  183068. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183069. /* storage for unknown chunk that the library doesn't recognize. */
  183070. png_unknown_chunk unknown_chunk;
  183071. #endif
  183072. };
  183073. /* This triggers a compiler error in png.c, if png.c and png.h
  183074. * do not agree upon the version number.
  183075. */
  183076. typedef png_structp version_1_2_21;
  183077. typedef png_struct FAR * FAR * png_structpp;
  183078. /* Here are the function definitions most commonly used. This is not
  183079. * the place to find out how to use libpng. See libpng.txt for the
  183080. * full explanation, see example.c for the summary. This just provides
  183081. * a simple one line description of the use of each function.
  183082. */
  183083. /* Returns the version number of the library */
  183084. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183085. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183086. * Handling more than 8 bytes from the beginning of the file is an error.
  183087. */
  183088. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183089. int num_bytes));
  183090. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183091. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183092. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183093. * start > 7 will always fail (ie return non-zero).
  183094. */
  183095. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183096. png_size_t num_to_check));
  183097. /* Simple signature checking function. This is the same as calling
  183098. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183099. */
  183100. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183101. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183102. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183103. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183104. png_error_ptr error_fn, png_error_ptr warn_fn));
  183105. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183106. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183107. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183108. png_error_ptr error_fn, png_error_ptr warn_fn));
  183109. #ifdef PNG_WRITE_SUPPORTED
  183110. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183111. PNGARG((png_structp png_ptr));
  183112. #endif
  183113. #ifdef PNG_WRITE_SUPPORTED
  183114. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183115. PNGARG((png_structp png_ptr, png_uint_32 size));
  183116. #endif
  183117. /* Reset the compression stream */
  183118. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183119. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183120. #ifdef PNG_USER_MEM_SUPPORTED
  183121. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183122. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183123. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183124. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183125. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183126. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183127. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183128. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183129. #endif
  183130. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183131. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183132. png_bytep chunk_name, png_bytep data, png_size_t length));
  183133. /* Write the start of a PNG chunk - length and chunk name. */
  183134. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183135. png_bytep chunk_name, png_uint_32 length));
  183136. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183137. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183138. png_bytep data, png_size_t length));
  183139. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183140. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183141. /* Allocate and initialize the info structure */
  183142. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183143. PNGARG((png_structp png_ptr));
  183144. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183145. /* Initialize the info structure (old interface - DEPRECATED) */
  183146. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183147. #undef png_info_init
  183148. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183149. png_sizeof(png_info));
  183150. #endif
  183151. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183152. png_size_t png_info_struct_size));
  183153. /* Writes all the PNG information before the image. */
  183154. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183155. png_infop info_ptr));
  183156. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183157. png_infop info_ptr));
  183158. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183159. /* read the information before the actual image data. */
  183160. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183161. png_infop info_ptr));
  183162. #endif
  183163. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183164. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183165. PNGARG((png_structp png_ptr, png_timep ptime));
  183166. #endif
  183167. #if !defined(_WIN32_WCE)
  183168. /* "time.h" functions are not supported on WindowsCE */
  183169. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183170. /* convert from a struct tm to png_time */
  183171. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183172. struct tm FAR * ttime));
  183173. /* convert from time_t to png_time. Uses gmtime() */
  183174. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183175. time_t ttime));
  183176. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183177. #endif /* _WIN32_WCE */
  183178. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183179. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183180. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183181. #if !defined(PNG_1_0_X)
  183182. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183183. png_ptr));
  183184. #endif
  183185. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183186. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183187. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183188. /* Deprecated */
  183189. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183190. #endif
  183191. #endif
  183192. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183193. /* Use blue, green, red order for pixels. */
  183194. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183195. #endif
  183196. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183197. /* Expand the grayscale to 24-bit RGB if necessary. */
  183198. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183199. #endif
  183200. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183201. /* Reduce RGB to grayscale. */
  183202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183203. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183204. int error_action, double red, double green ));
  183205. #endif
  183206. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183207. int error_action, png_fixed_point red, png_fixed_point green ));
  183208. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183209. png_ptr));
  183210. #endif
  183211. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183212. png_colorp palette));
  183213. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183214. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183215. #endif
  183216. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183217. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183218. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183219. #endif
  183220. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183221. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183222. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183223. #endif
  183224. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183225. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183226. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183227. png_uint_32 filler, int flags));
  183228. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183229. #define PNG_FILLER_BEFORE 0
  183230. #define PNG_FILLER_AFTER 1
  183231. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183232. #if !defined(PNG_1_0_X)
  183233. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183234. png_uint_32 filler, int flags));
  183235. #endif
  183236. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183237. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183238. /* Swap bytes in 16-bit depth files. */
  183239. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183240. #endif
  183241. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183242. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183243. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183244. #endif
  183245. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183246. /* Swap packing order of pixels in bytes. */
  183247. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183248. #endif
  183249. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183250. /* Converts files to legal bit depths. */
  183251. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183252. png_color_8p true_bits));
  183253. #endif
  183254. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183255. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183256. /* Have the code handle the interlacing. Returns the number of passes. */
  183257. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183258. #endif
  183259. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183260. /* Invert monochrome files */
  183261. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183262. #endif
  183263. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183264. /* Handle alpha and tRNS by replacing with a background color. */
  183265. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183266. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183267. png_color_16p background_color, int background_gamma_code,
  183268. int need_expand, double background_gamma));
  183269. #endif
  183270. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183271. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183272. #define PNG_BACKGROUND_GAMMA_FILE 2
  183273. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183274. #endif
  183275. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183276. /* strip the second byte of information from a 16-bit depth file. */
  183277. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183278. #endif
  183279. #if defined(PNG_READ_DITHER_SUPPORTED)
  183280. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183281. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183282. png_colorp palette, int num_palette, int maximum_colors,
  183283. png_uint_16p histogram, int full_dither));
  183284. #endif
  183285. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183286. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183287. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183288. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183289. double screen_gamma, double default_file_gamma));
  183290. #endif
  183291. #endif
  183292. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183293. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183294. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183295. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183296. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183297. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183298. int empty_plte_permitted));
  183299. #endif
  183300. #endif
  183301. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183302. /* Set how many lines between output flushes - 0 for no flushing */
  183303. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183304. /* Flush the current PNG output buffer */
  183305. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183306. #endif
  183307. /* optional update palette with requested transformations */
  183308. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183309. /* optional call to update the users info structure */
  183310. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183311. png_infop info_ptr));
  183312. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183313. /* read one or more rows of image data. */
  183314. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183315. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183316. #endif
  183317. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183318. /* read a row of data. */
  183319. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183320. png_bytep row,
  183321. png_bytep display_row));
  183322. #endif
  183323. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183324. /* read the whole image into memory at once. */
  183325. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183326. png_bytepp image));
  183327. #endif
  183328. /* write a row of image data */
  183329. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183330. png_bytep row));
  183331. /* write a few rows of image data */
  183332. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183333. png_bytepp row, png_uint_32 num_rows));
  183334. /* write the image data */
  183335. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183336. png_bytepp image));
  183337. /* writes the end of the PNG file. */
  183338. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183339. png_infop info_ptr));
  183340. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183341. /* read the end of the PNG file. */
  183342. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183343. png_infop info_ptr));
  183344. #endif
  183345. /* free any memory associated with the png_info_struct */
  183346. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183347. png_infopp info_ptr_ptr));
  183348. /* free any memory associated with the png_struct and the png_info_structs */
  183349. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183350. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183351. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183352. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183353. png_infop end_info_ptr));
  183354. /* free any memory associated with the png_struct and the png_info_structs */
  183355. extern PNG_EXPORT(void,png_destroy_write_struct)
  183356. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183357. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183358. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183359. /* set the libpng method of handling chunk CRC errors */
  183360. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183361. int crit_action, int ancil_action));
  183362. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183363. * ancillary and critical chunks, and whether to use the data contained
  183364. * therein. Note that it is impossible to "discard" data in a critical
  183365. * chunk. For versions prior to 0.90, the action was always error/quit,
  183366. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183367. * chunks is warn/discard. These values should NOT be changed.
  183368. *
  183369. * value action:critical action:ancillary
  183370. */
  183371. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183372. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183373. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183374. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183375. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183376. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183377. /* These functions give the user control over the scan-line filtering in
  183378. * libpng and the compression methods used by zlib. These functions are
  183379. * mainly useful for testing, as the defaults should work with most users.
  183380. * Those users who are tight on memory or want faster performance at the
  183381. * expense of compression can modify them. See the compression library
  183382. * header file (zlib.h) for an explination of the compression functions.
  183383. */
  183384. /* set the filtering method(s) used by libpng. Currently, the only valid
  183385. * value for "method" is 0.
  183386. */
  183387. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183388. int filters));
  183389. /* Flags for png_set_filter() to say which filters to use. The flags
  183390. * are chosen so that they don't conflict with real filter types
  183391. * below, in case they are supplied instead of the #defined constants.
  183392. * These values should NOT be changed.
  183393. */
  183394. #define PNG_NO_FILTERS 0x00
  183395. #define PNG_FILTER_NONE 0x08
  183396. #define PNG_FILTER_SUB 0x10
  183397. #define PNG_FILTER_UP 0x20
  183398. #define PNG_FILTER_AVG 0x40
  183399. #define PNG_FILTER_PAETH 0x80
  183400. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183401. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183402. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183403. * These defines should NOT be changed.
  183404. */
  183405. #define PNG_FILTER_VALUE_NONE 0
  183406. #define PNG_FILTER_VALUE_SUB 1
  183407. #define PNG_FILTER_VALUE_UP 2
  183408. #define PNG_FILTER_VALUE_AVG 3
  183409. #define PNG_FILTER_VALUE_PAETH 4
  183410. #define PNG_FILTER_VALUE_LAST 5
  183411. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183412. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183413. * defines, either the default (minimum-sum-of-absolute-differences), or
  183414. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183415. *
  183416. * Weights are factors >= 1.0, indicating how important it is to keep the
  183417. * filter type consistent between rows. Larger numbers mean the current
  183418. * filter is that many times as likely to be the same as the "num_weights"
  183419. * previous filters. This is cumulative for each previous row with a weight.
  183420. * There needs to be "num_weights" values in "filter_weights", or it can be
  183421. * NULL if the weights aren't being specified. Weights have no influence on
  183422. * the selection of the first row filter. Well chosen weights can (in theory)
  183423. * improve the compression for a given image.
  183424. *
  183425. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183426. * filter type. Higher costs indicate more decoding expense, and are
  183427. * therefore less likely to be selected over a filter with lower computational
  183428. * costs. There needs to be a value in "filter_costs" for each valid filter
  183429. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183430. * setting the costs. Costs try to improve the speed of decompression without
  183431. * unduly increasing the compressed image size.
  183432. *
  183433. * A negative weight or cost indicates the default value is to be used, and
  183434. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183435. * The default values for both weights and costs are currently 1.0, but may
  183436. * change if good general weighting/cost heuristics can be found. If both
  183437. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183438. * to the UNWEIGHTED method, but with added encoding time/computation.
  183439. */
  183440. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183441. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183442. int heuristic_method, int num_weights, png_doublep filter_weights,
  183443. png_doublep filter_costs));
  183444. #endif
  183445. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183446. /* Heuristic used for row filter selection. These defines should NOT be
  183447. * changed.
  183448. */
  183449. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183450. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183451. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183452. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183453. /* Set the library compression level. Currently, valid values range from
  183454. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183455. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183456. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183457. * for PNG images, and do considerably fewer caclulations. In the future,
  183458. * these values may not correspond directly to the zlib compression levels.
  183459. */
  183460. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183461. int level));
  183462. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183463. PNGARG((png_structp png_ptr, int mem_level));
  183464. extern PNG_EXPORT(void,png_set_compression_strategy)
  183465. PNGARG((png_structp png_ptr, int strategy));
  183466. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183467. PNGARG((png_structp png_ptr, int window_bits));
  183468. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183469. int method));
  183470. /* These next functions are called for input/output, memory, and error
  183471. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183472. * and call standard C I/O routines such as fread(), fwrite(), and
  183473. * fprintf(). These functions can be made to use other I/O routines
  183474. * at run time for those applications that need to handle I/O in a
  183475. * different manner by calling png_set_???_fn(). See libpng.txt for
  183476. * more information.
  183477. */
  183478. #if !defined(PNG_NO_STDIO)
  183479. /* Initialize the input/output for the PNG file to the default functions. */
  183480. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183481. #endif
  183482. /* Replace the (error and abort), and warning functions with user
  183483. * supplied functions. If no messages are to be printed you must still
  183484. * write and use replacement functions. The replacement error_fn should
  183485. * still do a longjmp to the last setjmp location if you are using this
  183486. * method of error handling. If error_fn or warning_fn is NULL, the
  183487. * default function will be used.
  183488. */
  183489. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183490. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183491. /* Return the user pointer associated with the error functions */
  183492. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183493. /* Replace the default data output functions with a user supplied one(s).
  183494. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183495. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183496. * output_flush_fn will be ignored (and thus can be NULL).
  183497. */
  183498. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183499. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183500. /* Replace the default data input function with a user supplied one. */
  183501. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183502. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183503. /* Return the user pointer associated with the I/O functions */
  183504. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183505. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183506. png_read_status_ptr read_row_fn));
  183507. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183508. png_write_status_ptr write_row_fn));
  183509. #ifdef PNG_USER_MEM_SUPPORTED
  183510. /* Replace the default memory allocation functions with user supplied one(s). */
  183511. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183512. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183513. /* Return the user pointer associated with the memory functions */
  183514. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183515. #endif
  183516. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183517. defined(PNG_LEGACY_SUPPORTED)
  183518. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183519. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183520. #endif
  183521. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183522. defined(PNG_LEGACY_SUPPORTED)
  183523. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183524. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183525. #endif
  183526. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183527. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183528. defined(PNG_LEGACY_SUPPORTED)
  183529. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183530. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183531. int user_transform_channels));
  183532. /* Return the user pointer associated with the user transform functions */
  183533. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183534. PNGARG((png_structp png_ptr));
  183535. #endif
  183536. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183537. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183538. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183539. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183540. png_ptr));
  183541. #endif
  183542. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183543. /* Sets the function callbacks for the push reader, and a pointer to a
  183544. * user-defined structure available to the callback functions.
  183545. */
  183546. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183547. png_voidp progressive_ptr,
  183548. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183549. png_progressive_end_ptr end_fn));
  183550. /* returns the user pointer associated with the push read functions */
  183551. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183552. PNGARG((png_structp png_ptr));
  183553. /* function to be called when data becomes available */
  183554. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183555. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183556. /* function that combines rows. Not very much different than the
  183557. * png_combine_row() call. Is this even used?????
  183558. */
  183559. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183560. png_bytep old_row, png_bytep new_row));
  183561. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183562. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183563. png_uint_32 size));
  183564. #if defined(PNG_1_0_X)
  183565. # define png_malloc_warn png_malloc
  183566. #else
  183567. /* Added at libpng version 1.2.4 */
  183568. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183569. png_uint_32 size));
  183570. #endif
  183571. /* frees a pointer allocated by png_malloc() */
  183572. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183573. #if defined(PNG_1_0_X)
  183574. /* Function to allocate memory for zlib. */
  183575. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183576. uInt size));
  183577. /* Function to free memory for zlib */
  183578. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183579. #endif
  183580. /* Free data that was allocated internally */
  183581. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183582. png_infop info_ptr, png_uint_32 free_me, int num));
  183583. #ifdef PNG_FREE_ME_SUPPORTED
  183584. /* Reassign responsibility for freeing existing data, whether allocated
  183585. * by libpng or by the application */
  183586. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183587. png_infop info_ptr, int freer, png_uint_32 mask));
  183588. #endif
  183589. /* assignments for png_data_freer */
  183590. #define PNG_DESTROY_WILL_FREE_DATA 1
  183591. #define PNG_SET_WILL_FREE_DATA 1
  183592. #define PNG_USER_WILL_FREE_DATA 2
  183593. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183594. #define PNG_FREE_HIST 0x0008
  183595. #define PNG_FREE_ICCP 0x0010
  183596. #define PNG_FREE_SPLT 0x0020
  183597. #define PNG_FREE_ROWS 0x0040
  183598. #define PNG_FREE_PCAL 0x0080
  183599. #define PNG_FREE_SCAL 0x0100
  183600. #define PNG_FREE_UNKN 0x0200
  183601. #define PNG_FREE_LIST 0x0400
  183602. #define PNG_FREE_PLTE 0x1000
  183603. #define PNG_FREE_TRNS 0x2000
  183604. #define PNG_FREE_TEXT 0x4000
  183605. #define PNG_FREE_ALL 0x7fff
  183606. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183607. #ifdef PNG_USER_MEM_SUPPORTED
  183608. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183609. png_uint_32 size));
  183610. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183611. png_voidp ptr));
  183612. #endif
  183613. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183614. png_voidp s1, png_voidp s2, png_uint_32 size));
  183615. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183616. png_voidp s1, int value, png_uint_32 size));
  183617. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183618. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183619. int check));
  183620. #endif /* USE_FAR_KEYWORD */
  183621. #ifndef PNG_NO_ERROR_TEXT
  183622. /* Fatal error in PNG image of libpng - can't continue */
  183623. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183624. png_const_charp error_message));
  183625. /* The same, but the chunk name is prepended to the error string. */
  183626. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183627. png_const_charp error_message));
  183628. #else
  183629. /* Fatal error in PNG image of libpng - can't continue */
  183630. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183631. #endif
  183632. #ifndef PNG_NO_WARNINGS
  183633. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183634. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183635. png_const_charp warning_message));
  183636. #ifdef PNG_READ_SUPPORTED
  183637. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183638. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183639. png_const_charp warning_message));
  183640. #endif /* PNG_READ_SUPPORTED */
  183641. #endif /* PNG_NO_WARNINGS */
  183642. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183643. * Similarly, the png_get_<chunk> calls are used to read values from the
  183644. * png_info_struct, either storing the parameters in the passed variables, or
  183645. * setting pointers into the png_info_struct where the data is stored. The
  183646. * png_get_<chunk> functions return a non-zero value if the data was available
  183647. * in info_ptr, or return zero and do not change any of the parameters if the
  183648. * data was not available.
  183649. *
  183650. * These functions should be used instead of directly accessing png_info
  183651. * to avoid problems with future changes in the size and internal layout of
  183652. * png_info_struct.
  183653. */
  183654. /* Returns "flag" if chunk data is valid in info_ptr. */
  183655. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183656. png_infop info_ptr, png_uint_32 flag));
  183657. /* Returns number of bytes needed to hold a transformed row. */
  183658. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183659. png_infop info_ptr));
  183660. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183661. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183662. returned from png_read_png(). */
  183663. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183664. png_infop info_ptr));
  183665. /* Set row_pointers, which is an array of pointers to scanlines for use
  183666. by png_write_png(). */
  183667. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183668. png_infop info_ptr, png_bytepp row_pointers));
  183669. #endif
  183670. /* Returns number of color channels in image. */
  183671. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183672. png_infop info_ptr));
  183673. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183674. /* Returns image width in pixels. */
  183675. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183676. png_ptr, png_infop info_ptr));
  183677. /* Returns image height in pixels. */
  183678. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183679. png_ptr, png_infop info_ptr));
  183680. /* Returns image bit_depth. */
  183681. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183682. png_ptr, png_infop info_ptr));
  183683. /* Returns image color_type. */
  183684. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183685. png_ptr, png_infop info_ptr));
  183686. /* Returns image filter_type. */
  183687. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183688. png_ptr, png_infop info_ptr));
  183689. /* Returns image interlace_type. */
  183690. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183691. png_ptr, png_infop info_ptr));
  183692. /* Returns image compression_type. */
  183693. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183694. png_ptr, png_infop info_ptr));
  183695. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183696. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183697. png_ptr, png_infop info_ptr));
  183698. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183699. png_ptr, png_infop info_ptr));
  183700. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183701. png_ptr, png_infop info_ptr));
  183702. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183703. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183704. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183705. png_ptr, png_infop info_ptr));
  183706. #endif
  183707. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183708. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183709. png_ptr, png_infop info_ptr));
  183710. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183711. png_ptr, png_infop info_ptr));
  183712. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183713. png_ptr, png_infop info_ptr));
  183714. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183715. png_ptr, png_infop info_ptr));
  183716. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183717. /* Returns pointer to signature string read from PNG header */
  183718. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183719. png_infop info_ptr));
  183720. #if defined(PNG_bKGD_SUPPORTED)
  183721. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183722. png_infop info_ptr, png_color_16p *background));
  183723. #endif
  183724. #if defined(PNG_bKGD_SUPPORTED)
  183725. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183726. png_infop info_ptr, png_color_16p background));
  183727. #endif
  183728. #if defined(PNG_cHRM_SUPPORTED)
  183729. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183730. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183731. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183732. double *red_y, double *green_x, double *green_y, double *blue_x,
  183733. double *blue_y));
  183734. #endif
  183735. #ifdef PNG_FIXED_POINT_SUPPORTED
  183736. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183737. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183738. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183739. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183740. *int_blue_x, png_fixed_point *int_blue_y));
  183741. #endif
  183742. #endif
  183743. #if defined(PNG_cHRM_SUPPORTED)
  183744. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183745. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183746. png_infop info_ptr, double white_x, double white_y, double red_x,
  183747. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183748. #endif
  183749. #ifdef PNG_FIXED_POINT_SUPPORTED
  183750. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183751. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183752. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183753. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183754. png_fixed_point int_blue_y));
  183755. #endif
  183756. #endif
  183757. #if defined(PNG_gAMA_SUPPORTED)
  183758. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183759. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183760. png_infop info_ptr, double *file_gamma));
  183761. #endif
  183762. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183763. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183764. #endif
  183765. #if defined(PNG_gAMA_SUPPORTED)
  183766. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183767. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183768. png_infop info_ptr, double file_gamma));
  183769. #endif
  183770. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183771. png_infop info_ptr, png_fixed_point int_file_gamma));
  183772. #endif
  183773. #if defined(PNG_hIST_SUPPORTED)
  183774. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183775. png_infop info_ptr, png_uint_16p *hist));
  183776. #endif
  183777. #if defined(PNG_hIST_SUPPORTED)
  183778. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183779. png_infop info_ptr, png_uint_16p hist));
  183780. #endif
  183781. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183782. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183783. int *bit_depth, int *color_type, int *interlace_method,
  183784. int *compression_method, int *filter_method));
  183785. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183786. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183787. int color_type, int interlace_method, int compression_method,
  183788. int filter_method));
  183789. #if defined(PNG_oFFs_SUPPORTED)
  183790. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183791. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183792. int *unit_type));
  183793. #endif
  183794. #if defined(PNG_oFFs_SUPPORTED)
  183795. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183796. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183797. int unit_type));
  183798. #endif
  183799. #if defined(PNG_pCAL_SUPPORTED)
  183800. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183801. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183802. int *type, int *nparams, png_charp *units, png_charpp *params));
  183803. #endif
  183804. #if defined(PNG_pCAL_SUPPORTED)
  183805. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183806. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183807. int type, int nparams, png_charp units, png_charpp params));
  183808. #endif
  183809. #if defined(PNG_pHYs_SUPPORTED)
  183810. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183811. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183812. #endif
  183813. #if defined(PNG_pHYs_SUPPORTED)
  183814. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183815. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183816. #endif
  183817. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183818. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183819. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183820. png_infop info_ptr, png_colorp palette, int num_palette));
  183821. #if defined(PNG_sBIT_SUPPORTED)
  183822. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183823. png_infop info_ptr, png_color_8p *sig_bit));
  183824. #endif
  183825. #if defined(PNG_sBIT_SUPPORTED)
  183826. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183827. png_infop info_ptr, png_color_8p sig_bit));
  183828. #endif
  183829. #if defined(PNG_sRGB_SUPPORTED)
  183830. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183831. png_infop info_ptr, int *intent));
  183832. #endif
  183833. #if defined(PNG_sRGB_SUPPORTED)
  183834. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183835. png_infop info_ptr, int intent));
  183836. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183837. png_infop info_ptr, int intent));
  183838. #endif
  183839. #if defined(PNG_iCCP_SUPPORTED)
  183840. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183841. png_infop info_ptr, png_charpp name, int *compression_type,
  183842. png_charpp profile, png_uint_32 *proflen));
  183843. /* Note to maintainer: profile should be png_bytepp */
  183844. #endif
  183845. #if defined(PNG_iCCP_SUPPORTED)
  183846. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183847. png_infop info_ptr, png_charp name, int compression_type,
  183848. png_charp profile, png_uint_32 proflen));
  183849. /* Note to maintainer: profile should be png_bytep */
  183850. #endif
  183851. #if defined(PNG_sPLT_SUPPORTED)
  183852. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183853. png_infop info_ptr, png_sPLT_tpp entries));
  183854. #endif
  183855. #if defined(PNG_sPLT_SUPPORTED)
  183856. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183857. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183858. #endif
  183859. #if defined(PNG_TEXT_SUPPORTED)
  183860. /* png_get_text also returns the number of text chunks in *num_text */
  183861. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183862. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183863. #endif
  183864. /*
  183865. * Note while png_set_text() will accept a structure whose text,
  183866. * language, and translated keywords are NULL pointers, the structure
  183867. * returned by png_get_text will always contain regular
  183868. * zero-terminated C strings. They might be empty strings but
  183869. * they will never be NULL pointers.
  183870. */
  183871. #if defined(PNG_TEXT_SUPPORTED)
  183872. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183873. png_infop info_ptr, png_textp text_ptr, int num_text));
  183874. #endif
  183875. #if defined(PNG_tIME_SUPPORTED)
  183876. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183877. png_infop info_ptr, png_timep *mod_time));
  183878. #endif
  183879. #if defined(PNG_tIME_SUPPORTED)
  183880. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183881. png_infop info_ptr, png_timep mod_time));
  183882. #endif
  183883. #if defined(PNG_tRNS_SUPPORTED)
  183884. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183885. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183886. png_color_16p *trans_values));
  183887. #endif
  183888. #if defined(PNG_tRNS_SUPPORTED)
  183889. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183890. png_infop info_ptr, png_bytep trans, int num_trans,
  183891. png_color_16p trans_values));
  183892. #endif
  183893. #if defined(PNG_tRNS_SUPPORTED)
  183894. #endif
  183895. #if defined(PNG_sCAL_SUPPORTED)
  183896. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183897. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183898. png_infop info_ptr, int *unit, double *width, double *height));
  183899. #else
  183900. #ifdef PNG_FIXED_POINT_SUPPORTED
  183901. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183902. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183903. #endif
  183904. #endif
  183905. #endif /* PNG_sCAL_SUPPORTED */
  183906. #if defined(PNG_sCAL_SUPPORTED)
  183907. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183908. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183909. png_infop info_ptr, int unit, double width, double height));
  183910. #else
  183911. #ifdef PNG_FIXED_POINT_SUPPORTED
  183912. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183913. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183914. #endif
  183915. #endif
  183916. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183917. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183918. /* provide a list of chunks and how they are to be handled, if the built-in
  183919. handling or default unknown chunk handling is not desired. Any chunks not
  183920. listed will be handled in the default manner. The IHDR and IEND chunks
  183921. must not be listed.
  183922. keep = 0: follow default behaviour
  183923. = 1: do not keep
  183924. = 2: keep only if safe-to-copy
  183925. = 3: keep even if unsafe-to-copy
  183926. */
  183927. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183928. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183929. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183930. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183931. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183932. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183933. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183934. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183935. #endif
  183936. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183937. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183938. chunk_name));
  183939. #endif
  183940. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183941. If you need to turn it off for a chunk that your application has freed,
  183942. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183943. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183944. png_infop info_ptr, int mask));
  183945. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183946. /* The "params" pointer is currently not used and is for future expansion. */
  183947. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183948. png_infop info_ptr,
  183949. int transforms,
  183950. png_voidp params));
  183951. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183952. png_infop info_ptr,
  183953. int transforms,
  183954. png_voidp params));
  183955. #endif
  183956. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183957. * numbers for PNG_DEBUG mean more debugging information. This has
  183958. * only been added since version 0.95 so it is not implemented throughout
  183959. * libpng yet, but more support will be added as needed.
  183960. */
  183961. #ifdef PNG_DEBUG
  183962. #if (PNG_DEBUG > 0)
  183963. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183964. #include <crtdbg.h>
  183965. #if (PNG_DEBUG > 1)
  183966. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183967. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183968. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183969. #endif
  183970. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183971. #ifndef PNG_DEBUG_FILE
  183972. #define PNG_DEBUG_FILE stderr
  183973. #endif /* PNG_DEBUG_FILE */
  183974. #if (PNG_DEBUG > 1)
  183975. #define png_debug(l,m) \
  183976. { \
  183977. int num_tabs=l; \
  183978. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183979. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183980. }
  183981. #define png_debug1(l,m,p1) \
  183982. { \
  183983. int num_tabs=l; \
  183984. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183985. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183986. }
  183987. #define png_debug2(l,m,p1,p2) \
  183988. { \
  183989. int num_tabs=l; \
  183990. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183991. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183992. }
  183993. #endif /* (PNG_DEBUG > 1) */
  183994. #endif /* _MSC_VER */
  183995. #endif /* (PNG_DEBUG > 0) */
  183996. #endif /* PNG_DEBUG */
  183997. #ifndef png_debug
  183998. #define png_debug(l, m)
  183999. #endif
  184000. #ifndef png_debug1
  184001. #define png_debug1(l, m, p1)
  184002. #endif
  184003. #ifndef png_debug2
  184004. #define png_debug2(l, m, p1, p2)
  184005. #endif
  184006. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  184007. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  184008. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  184009. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  184010. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184011. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  184012. png_ptr, png_uint_32 mng_features_permitted));
  184013. #endif
  184014. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  184015. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  184016. #define PNG_HANDLE_CHUNK_NEVER 1
  184017. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  184018. #define PNG_HANDLE_CHUNK_ALWAYS 3
  184019. /* Added to version 1.2.0 */
  184020. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184021. #if defined(PNG_MMX_CODE_SUPPORTED)
  184022. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  184023. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184024. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184025. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184026. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184027. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184028. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184029. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184030. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184031. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184032. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184033. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184034. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184035. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184036. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184037. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184038. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184039. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184040. | PNG_MMX_READ_FLAGS \
  184041. | PNG_MMX_WRITE_FLAGS )
  184042. #define PNG_SELECT_READ 1
  184043. #define PNG_SELECT_WRITE 2
  184044. #endif /* PNG_MMX_CODE_SUPPORTED */
  184045. #if !defined(PNG_1_0_X)
  184046. /* pngget.c */
  184047. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184048. PNGARG((int flag_select, int *compilerID));
  184049. /* pngget.c */
  184050. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184051. PNGARG((int flag_select));
  184052. /* pngget.c */
  184053. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184054. PNGARG((png_structp png_ptr));
  184055. /* pngget.c */
  184056. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184057. PNGARG((png_structp png_ptr));
  184058. /* pngget.c */
  184059. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184060. PNGARG((png_structp png_ptr));
  184061. /* pngset.c */
  184062. extern PNG_EXPORT(void,png_set_asm_flags)
  184063. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184064. /* pngset.c */
  184065. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184066. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184067. png_uint_32 mmx_rowbytes_threshold));
  184068. #endif /* PNG_1_0_X */
  184069. #if !defined(PNG_1_0_X)
  184070. /* png.c, pnggccrd.c, or pngvcrd.c */
  184071. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184072. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184073. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184074. * messages before passing them to the error or warning handler. */
  184075. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184076. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184077. png_ptr, png_uint_32 strip_mode));
  184078. #endif
  184079. #endif /* PNG_1_0_X */
  184080. /* Added at libpng-1.2.6 */
  184081. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184082. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184083. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184084. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184085. png_ptr));
  184086. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184087. png_ptr));
  184088. #endif
  184089. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184090. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184091. /* With these routines we avoid an integer divide, which will be slower on
  184092. * most machines. However, it does take more operations than the corresponding
  184093. * divide method, so it may be slower on a few RISC systems. There are two
  184094. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184095. *
  184096. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184097. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184098. * standard method.
  184099. *
  184100. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184101. */
  184102. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184103. # define png_composite(composite, fg, alpha, bg) \
  184104. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184105. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184106. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184107. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184108. # define png_composite_16(composite, fg, alpha, bg) \
  184109. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184110. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184111. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184112. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184113. #else /* standard method using integer division */
  184114. # define png_composite(composite, fg, alpha, bg) \
  184115. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184116. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184117. (png_uint_16)127) / 255)
  184118. # define png_composite_16(composite, fg, alpha, bg) \
  184119. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184120. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184121. (png_uint_32)32767) / (png_uint_32)65535L)
  184122. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184123. /* Inline macros to do direct reads of bytes from the input buffer. These
  184124. * require that you are using an architecture that uses PNG byte ordering
  184125. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184126. * in big-endian mode and 680x0 are the only ones that will support this.
  184127. * The x86 line of processors definitely do not. The png_get_int_32()
  184128. * routine also assumes we are using two's complement format for negative
  184129. * values, which is almost certainly true.
  184130. */
  184131. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184132. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184133. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184134. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184135. #else
  184136. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184137. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184138. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184139. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184140. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184141. PNGARG((png_structp png_ptr, png_bytep buf));
  184142. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184143. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184144. */
  184145. extern PNG_EXPORT(void,png_save_uint_32)
  184146. PNGARG((png_bytep buf, png_uint_32 i));
  184147. extern PNG_EXPORT(void,png_save_int_32)
  184148. PNGARG((png_bytep buf, png_int_32 i));
  184149. /* Place a 16-bit number into a buffer in PNG byte order.
  184150. * The parameter is declared unsigned int, not png_uint_16,
  184151. * just to avoid potential problems on pre-ANSI C compilers.
  184152. */
  184153. extern PNG_EXPORT(void,png_save_uint_16)
  184154. PNGARG((png_bytep buf, unsigned int i));
  184155. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184156. /* ************************************************************************* */
  184157. /* These next functions are used internally in the code. They generally
  184158. * shouldn't be used unless you are writing code to add or replace some
  184159. * functionality in libpng. More information about most functions can
  184160. * be found in the files where the functions are located.
  184161. */
  184162. /* Various modes of operation, that are visible to applications because
  184163. * they are used for unknown chunk location.
  184164. */
  184165. #define PNG_HAVE_IHDR 0x01
  184166. #define PNG_HAVE_PLTE 0x02
  184167. #define PNG_HAVE_IDAT 0x04
  184168. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184169. #define PNG_HAVE_IEND 0x10
  184170. #if defined(PNG_INTERNAL)
  184171. /* More modes of operation. Note that after an init, mode is set to
  184172. * zero automatically when the structure is created.
  184173. */
  184174. #define PNG_HAVE_gAMA 0x20
  184175. #define PNG_HAVE_cHRM 0x40
  184176. #define PNG_HAVE_sRGB 0x80
  184177. #define PNG_HAVE_CHUNK_HEADER 0x100
  184178. #define PNG_WROTE_tIME 0x200
  184179. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184180. #define PNG_BACKGROUND_IS_GRAY 0x800
  184181. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184182. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184183. /* flags for the transformations the PNG library does on the image data */
  184184. #define PNG_BGR 0x0001
  184185. #define PNG_INTERLACE 0x0002
  184186. #define PNG_PACK 0x0004
  184187. #define PNG_SHIFT 0x0008
  184188. #define PNG_SWAP_BYTES 0x0010
  184189. #define PNG_INVERT_MONO 0x0020
  184190. #define PNG_DITHER 0x0040
  184191. #define PNG_BACKGROUND 0x0080
  184192. #define PNG_BACKGROUND_EXPAND 0x0100
  184193. /* 0x0200 unused */
  184194. #define PNG_16_TO_8 0x0400
  184195. #define PNG_RGBA 0x0800
  184196. #define PNG_EXPAND 0x1000
  184197. #define PNG_GAMMA 0x2000
  184198. #define PNG_GRAY_TO_RGB 0x4000
  184199. #define PNG_FILLER 0x8000L
  184200. #define PNG_PACKSWAP 0x10000L
  184201. #define PNG_SWAP_ALPHA 0x20000L
  184202. #define PNG_STRIP_ALPHA 0x40000L
  184203. #define PNG_INVERT_ALPHA 0x80000L
  184204. #define PNG_USER_TRANSFORM 0x100000L
  184205. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184206. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184207. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184208. /* 0x800000L Unused */
  184209. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184210. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184211. /* 0x4000000L unused */
  184212. /* 0x8000000L unused */
  184213. /* 0x10000000L unused */
  184214. /* 0x20000000L unused */
  184215. /* 0x40000000L unused */
  184216. /* flags for png_create_struct */
  184217. #define PNG_STRUCT_PNG 0x0001
  184218. #define PNG_STRUCT_INFO 0x0002
  184219. /* Scaling factor for filter heuristic weighting calculations */
  184220. #define PNG_WEIGHT_SHIFT 8
  184221. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184222. #define PNG_COST_SHIFT 3
  184223. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184224. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184225. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184226. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184227. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184228. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184229. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184230. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184231. #define PNG_FLAG_ROW_INIT 0x0040
  184232. #define PNG_FLAG_FILLER_AFTER 0x0080
  184233. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184234. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184235. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184236. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184237. #define PNG_FLAG_FREE_PLTE 0x1000
  184238. #define PNG_FLAG_FREE_TRNS 0x2000
  184239. #define PNG_FLAG_FREE_HIST 0x4000
  184240. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184241. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184242. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184243. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184244. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184245. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184246. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184247. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184248. /* 0x800000L unused */
  184249. /* 0x1000000L unused */
  184250. /* 0x2000000L unused */
  184251. /* 0x4000000L unused */
  184252. /* 0x8000000L unused */
  184253. /* 0x10000000L unused */
  184254. /* 0x20000000L unused */
  184255. /* 0x40000000L unused */
  184256. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184257. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184258. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184259. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184260. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184261. PNG_FLAG_CRC_CRITICAL_MASK)
  184262. /* save typing and make code easier to understand */
  184263. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184264. abs((int)((c1).green) - (int)((c2).green)) + \
  184265. abs((int)((c1).blue) - (int)((c2).blue)))
  184266. /* Added to libpng-1.2.6 JB */
  184267. #define PNG_ROWBYTES(pixel_bits, width) \
  184268. ((pixel_bits) >= 8 ? \
  184269. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184270. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184271. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184272. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184273. "ideal" and "delta" should be constants, normally simple
  184274. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184275. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184276. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184277. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184278. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184279. /* place to hold the signature string for a PNG file. */
  184280. #ifdef PNG_USE_GLOBAL_ARRAYS
  184281. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184282. #else
  184283. #endif
  184284. #endif /* PNG_NO_EXTERN */
  184285. /* Constant strings for known chunk types. If you need to add a chunk,
  184286. * define the name here, and add an invocation of the macro in png.c and
  184287. * wherever it's needed.
  184288. */
  184289. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184290. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184291. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184292. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184293. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184294. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184295. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184296. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184297. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184298. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184299. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184300. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184301. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184302. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184303. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184304. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184305. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184306. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184307. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184308. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184309. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184310. #ifdef PNG_USE_GLOBAL_ARRAYS
  184311. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184312. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184313. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184314. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184315. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184316. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184317. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184318. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184319. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184320. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184321. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184322. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184323. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184324. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184325. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184326. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184327. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184328. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184329. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184330. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184331. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184332. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184333. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184334. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184335. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184336. */
  184337. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184338. #undef png_read_init
  184339. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184340. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184341. #endif
  184342. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184343. png_const_charp user_png_ver, png_size_t png_struct_size));
  184344. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184345. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184346. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184347. png_info_size));
  184348. #endif
  184349. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184350. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184351. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184352. */
  184353. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184354. #undef png_write_init
  184355. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184356. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184357. #endif
  184358. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184359. png_const_charp user_png_ver, png_size_t png_struct_size));
  184360. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184361. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184362. png_info_size));
  184363. /* Allocate memory for an internal libpng struct */
  184364. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184365. /* Free memory from internal libpng struct */
  184366. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184367. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184368. malloc_fn, png_voidp mem_ptr));
  184369. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184370. png_free_ptr free_fn, png_voidp mem_ptr));
  184371. /* Free any memory that info_ptr points to and reset struct. */
  184372. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184373. png_infop info_ptr));
  184374. #ifndef PNG_1_0_X
  184375. /* Function to allocate memory for zlib. */
  184376. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184377. /* Function to free memory for zlib */
  184378. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184379. #ifdef PNG_SIZE_T
  184380. /* Function to convert a sizeof an item to png_sizeof item */
  184381. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184382. #endif
  184383. /* Next four functions are used internally as callbacks. PNGAPI is required
  184384. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184385. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184386. png_bytep data, png_size_t length));
  184387. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184388. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184389. png_bytep buffer, png_size_t length));
  184390. #endif
  184391. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184392. png_bytep data, png_size_t length));
  184393. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184394. #if !defined(PNG_NO_STDIO)
  184395. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184396. #endif
  184397. #endif
  184398. #else /* PNG_1_0_X */
  184399. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184400. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184401. png_bytep buffer, png_size_t length));
  184402. #endif
  184403. #endif /* PNG_1_0_X */
  184404. /* Reset the CRC variable */
  184405. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184406. /* Write the "data" buffer to whatever output you are using. */
  184407. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184408. png_size_t length));
  184409. /* Read data from whatever input you are using into the "data" buffer */
  184410. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184411. png_size_t length));
  184412. /* Read bytes into buf, and update png_ptr->crc */
  184413. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184414. png_size_t length));
  184415. /* Decompress data in a chunk that uses compression */
  184416. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184417. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184418. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184419. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184420. png_size_t prefix_length, png_size_t *data_length));
  184421. #endif
  184422. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184423. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184424. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184425. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184426. /* Calculate the CRC over a section of data. Note that we are only
  184427. * passing a maximum of 64K on systems that have this as a memory limit,
  184428. * since this is the maximum buffer size we can specify.
  184429. */
  184430. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184431. png_size_t length));
  184432. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184433. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184434. #endif
  184435. /* simple function to write the signature */
  184436. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184437. /* write various chunks */
  184438. /* Write the IHDR chunk, and update the png_struct with the necessary
  184439. * information.
  184440. */
  184441. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184442. png_uint_32 height,
  184443. int bit_depth, int color_type, int compression_method, int filter_method,
  184444. int interlace_method));
  184445. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184446. png_uint_32 num_pal));
  184447. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184448. png_size_t length));
  184449. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184450. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184451. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184452. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184453. #endif
  184454. #ifdef PNG_FIXED_POINT_SUPPORTED
  184455. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184456. file_gamma));
  184457. #endif
  184458. #endif
  184459. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184460. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184461. int color_type));
  184462. #endif
  184463. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184464. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184465. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184466. double white_x, double white_y,
  184467. double red_x, double red_y, double green_x, double green_y,
  184468. double blue_x, double blue_y));
  184469. #endif
  184470. #ifdef PNG_FIXED_POINT_SUPPORTED
  184471. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184472. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184473. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184474. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184475. png_fixed_point int_blue_y));
  184476. #endif
  184477. #endif
  184478. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184479. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184480. int intent));
  184481. #endif
  184482. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184483. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184484. png_charp name, int compression_type,
  184485. png_charp profile, int proflen));
  184486. /* Note to maintainer: profile should be png_bytep */
  184487. #endif
  184488. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184489. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184490. png_sPLT_tp palette));
  184491. #endif
  184492. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184493. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184494. png_color_16p values, int number, int color_type));
  184495. #endif
  184496. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184497. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184498. png_color_16p values, int color_type));
  184499. #endif
  184500. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184501. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184502. int num_hist));
  184503. #endif
  184504. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184505. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184506. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184507. png_charp key, png_charpp new_key));
  184508. #endif
  184509. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184510. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184511. png_charp text, png_size_t text_len));
  184512. #endif
  184513. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184514. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184515. png_charp text, png_size_t text_len, int compression));
  184516. #endif
  184517. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184518. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184519. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184520. png_charp text));
  184521. #endif
  184522. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184523. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184524. png_infop info_ptr, png_textp text_ptr, int num_text));
  184525. #endif
  184526. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184527. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184528. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184529. #endif
  184530. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184531. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184532. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184533. png_charp units, png_charpp params));
  184534. #endif
  184535. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184536. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184537. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184538. int unit_type));
  184539. #endif
  184540. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184541. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184542. png_timep mod_time));
  184543. #endif
  184544. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184545. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184546. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184547. int unit, double width, double height));
  184548. #else
  184549. #ifdef PNG_FIXED_POINT_SUPPORTED
  184550. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184551. int unit, png_charp width, png_charp height));
  184552. #endif
  184553. #endif
  184554. #endif
  184555. /* Called when finished processing a row of data */
  184556. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184557. /* Internal use only. Called before first row of data */
  184558. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184559. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184560. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184561. #endif
  184562. /* combine a row of data, dealing with alpha, etc. if requested */
  184563. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184564. int mask));
  184565. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184566. /* expand an interlaced row */
  184567. /* OLD pre-1.0.9 interface:
  184568. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184569. png_bytep row, int pass, png_uint_32 transformations));
  184570. */
  184571. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184572. #endif
  184573. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184574. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184575. /* grab pixels out of a row for an interlaced pass */
  184576. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184577. png_bytep row, int pass));
  184578. #endif
  184579. /* unfilter a row */
  184580. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184581. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184582. /* Choose the best filter to use and filter the row data */
  184583. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184584. png_row_infop row_info));
  184585. /* Write out the filtered row. */
  184586. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184587. png_bytep filtered_row));
  184588. /* finish a row while reading, dealing with interlacing passes, etc. */
  184589. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184590. /* initialize the row buffers, etc. */
  184591. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184592. /* optional call to update the users info structure */
  184593. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184594. png_infop info_ptr));
  184595. /* these are the functions that do the transformations */
  184596. #if defined(PNG_READ_FILLER_SUPPORTED)
  184597. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184598. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184599. #endif
  184600. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184601. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184602. png_bytep row));
  184603. #endif
  184604. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184605. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184606. png_bytep row));
  184607. #endif
  184608. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184609. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184610. png_bytep row));
  184611. #endif
  184612. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184613. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184614. png_bytep row));
  184615. #endif
  184616. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184617. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184618. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184619. png_bytep row, png_uint_32 flags));
  184620. #endif
  184621. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184622. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184623. #endif
  184624. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184625. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184626. #endif
  184627. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184628. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184629. row_info, png_bytep row));
  184630. #endif
  184631. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184632. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184633. png_bytep row));
  184634. #endif
  184635. #if defined(PNG_READ_PACK_SUPPORTED)
  184636. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184637. #endif
  184638. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184639. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184640. png_color_8p sig_bits));
  184641. #endif
  184642. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184643. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184644. #endif
  184645. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184646. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184647. #endif
  184648. #if defined(PNG_READ_DITHER_SUPPORTED)
  184649. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184650. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184651. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184652. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184653. png_colorp palette, int num_palette));
  184654. # endif
  184655. #endif
  184656. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184657. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184658. #endif
  184659. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184660. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184661. png_bytep row, png_uint_32 bit_depth));
  184662. #endif
  184663. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184664. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184665. png_color_8p bit_depth));
  184666. #endif
  184667. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184668. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184669. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184670. png_color_16p trans_values, png_color_16p background,
  184671. png_color_16p background_1,
  184672. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184673. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184674. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184675. #else
  184676. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184677. png_color_16p trans_values, png_color_16p background));
  184678. #endif
  184679. #endif
  184680. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184681. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184682. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184683. int gamma_shift));
  184684. #endif
  184685. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184686. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184687. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184688. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184689. png_bytep row, png_color_16p trans_value));
  184690. #endif
  184691. /* The following decodes the appropriate chunks, and does error correction,
  184692. * then calls the appropriate callback for the chunk if it is valid.
  184693. */
  184694. /* decode the IHDR chunk */
  184695. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184696. png_uint_32 length));
  184697. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184698. png_uint_32 length));
  184699. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184700. png_uint_32 length));
  184701. #if defined(PNG_READ_bKGD_SUPPORTED)
  184702. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184703. png_uint_32 length));
  184704. #endif
  184705. #if defined(PNG_READ_cHRM_SUPPORTED)
  184706. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184707. png_uint_32 length));
  184708. #endif
  184709. #if defined(PNG_READ_gAMA_SUPPORTED)
  184710. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184711. png_uint_32 length));
  184712. #endif
  184713. #if defined(PNG_READ_hIST_SUPPORTED)
  184714. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184715. png_uint_32 length));
  184716. #endif
  184717. #if defined(PNG_READ_iCCP_SUPPORTED)
  184718. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184719. png_uint_32 length));
  184720. #endif /* PNG_READ_iCCP_SUPPORTED */
  184721. #if defined(PNG_READ_iTXt_SUPPORTED)
  184722. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184723. png_uint_32 length));
  184724. #endif
  184725. #if defined(PNG_READ_oFFs_SUPPORTED)
  184726. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184727. png_uint_32 length));
  184728. #endif
  184729. #if defined(PNG_READ_pCAL_SUPPORTED)
  184730. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184731. png_uint_32 length));
  184732. #endif
  184733. #if defined(PNG_READ_pHYs_SUPPORTED)
  184734. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184735. png_uint_32 length));
  184736. #endif
  184737. #if defined(PNG_READ_sBIT_SUPPORTED)
  184738. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184739. png_uint_32 length));
  184740. #endif
  184741. #if defined(PNG_READ_sCAL_SUPPORTED)
  184742. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184743. png_uint_32 length));
  184744. #endif
  184745. #if defined(PNG_READ_sPLT_SUPPORTED)
  184746. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184747. png_uint_32 length));
  184748. #endif /* PNG_READ_sPLT_SUPPORTED */
  184749. #if defined(PNG_READ_sRGB_SUPPORTED)
  184750. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184751. png_uint_32 length));
  184752. #endif
  184753. #if defined(PNG_READ_tEXt_SUPPORTED)
  184754. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184755. png_uint_32 length));
  184756. #endif
  184757. #if defined(PNG_READ_tIME_SUPPORTED)
  184758. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184759. png_uint_32 length));
  184760. #endif
  184761. #if defined(PNG_READ_tRNS_SUPPORTED)
  184762. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184763. png_uint_32 length));
  184764. #endif
  184765. #if defined(PNG_READ_zTXt_SUPPORTED)
  184766. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184767. png_uint_32 length));
  184768. #endif
  184769. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184770. png_infop info_ptr, png_uint_32 length));
  184771. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184772. png_bytep chunk_name));
  184773. /* handle the transformations for reading and writing */
  184774. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184775. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184776. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184777. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184778. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184779. png_infop info_ptr));
  184780. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184781. png_infop info_ptr));
  184782. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184783. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184784. png_uint_32 length));
  184785. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184786. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184787. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184788. png_bytep buffer, png_size_t buffer_length));
  184789. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184790. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184791. png_bytep buffer, png_size_t buffer_length));
  184792. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184793. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184794. png_infop info_ptr, png_uint_32 length));
  184795. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184796. png_infop info_ptr));
  184797. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184798. png_infop info_ptr));
  184799. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184800. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184801. png_infop info_ptr));
  184802. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184803. png_infop info_ptr));
  184804. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184805. #if defined(PNG_READ_tEXt_SUPPORTED)
  184806. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184807. png_infop info_ptr, png_uint_32 length));
  184808. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184809. png_infop info_ptr));
  184810. #endif
  184811. #if defined(PNG_READ_zTXt_SUPPORTED)
  184812. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184813. png_infop info_ptr, png_uint_32 length));
  184814. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184815. png_infop info_ptr));
  184816. #endif
  184817. #if defined(PNG_READ_iTXt_SUPPORTED)
  184818. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184819. png_infop info_ptr, png_uint_32 length));
  184820. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184821. png_infop info_ptr));
  184822. #endif
  184823. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184824. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184825. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184826. png_bytep row));
  184827. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184828. png_bytep row));
  184829. #endif
  184830. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184831. #if defined(PNG_MMX_CODE_SUPPORTED)
  184832. /* png.c */ /* PRIVATE */
  184833. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184834. #endif
  184835. #endif
  184836. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184837. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184838. png_infop info_ptr));
  184839. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184840. png_infop info_ptr));
  184841. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184842. png_infop info_ptr));
  184843. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184844. png_infop info_ptr));
  184845. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184846. png_infop info_ptr));
  184847. #if defined(PNG_pHYs_SUPPORTED)
  184848. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184849. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184850. #endif /* PNG_pHYs_SUPPORTED */
  184851. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184852. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184853. #endif /* PNG_INTERNAL */
  184854. #ifdef __cplusplus
  184855. //}
  184856. #endif
  184857. #endif /* PNG_VERSION_INFO_ONLY */
  184858. /* do not put anything past this line */
  184859. #endif /* PNG_H */
  184860. /*** End of inlined file: png.h ***/
  184861. #define PNG_NO_EXTERN
  184862. /*** Start of inlined file: png.c ***/
  184863. /* png.c - location for general purpose libpng functions
  184864. *
  184865. * Last changed in libpng 1.2.21 [October 4, 2007]
  184866. * For conditions of distribution and use, see copyright notice in png.h
  184867. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184868. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184869. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184870. */
  184871. #define PNG_INTERNAL
  184872. #define PNG_NO_EXTERN
  184873. /* Generate a compiler error if there is an old png.h in the search path. */
  184874. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184875. /* Version information for C files. This had better match the version
  184876. * string defined in png.h. */
  184877. #ifdef PNG_USE_GLOBAL_ARRAYS
  184878. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184879. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184880. #ifdef PNG_READ_SUPPORTED
  184881. /* png_sig was changed to a function in version 1.0.5c */
  184882. /* Place to hold the signature string for a PNG file. */
  184883. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184884. #endif /* PNG_READ_SUPPORTED */
  184885. /* Invoke global declarations for constant strings for known chunk types */
  184886. PNG_IHDR;
  184887. PNG_IDAT;
  184888. PNG_IEND;
  184889. PNG_PLTE;
  184890. PNG_bKGD;
  184891. PNG_cHRM;
  184892. PNG_gAMA;
  184893. PNG_hIST;
  184894. PNG_iCCP;
  184895. PNG_iTXt;
  184896. PNG_oFFs;
  184897. PNG_pCAL;
  184898. PNG_sCAL;
  184899. PNG_pHYs;
  184900. PNG_sBIT;
  184901. PNG_sPLT;
  184902. PNG_sRGB;
  184903. PNG_tEXt;
  184904. PNG_tIME;
  184905. PNG_tRNS;
  184906. PNG_zTXt;
  184907. #ifdef PNG_READ_SUPPORTED
  184908. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184909. /* start of interlace block */
  184910. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184911. /* offset to next interlace block */
  184912. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184913. /* start of interlace block in the y direction */
  184914. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184915. /* offset to next interlace block in the y direction */
  184916. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184917. /* Height of interlace block. This is not currently used - if you need
  184918. * it, uncomment it here and in png.h
  184919. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184920. */
  184921. /* Mask to determine which pixels are valid in a pass */
  184922. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184923. /* Mask to determine which pixels to overwrite while displaying */
  184924. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184925. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184926. #endif /* PNG_READ_SUPPORTED */
  184927. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184928. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184929. * of the PNG file signature. If the PNG data is embedded into another
  184930. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184931. * or write any of the magic bytes before it starts on the IHDR.
  184932. */
  184933. #ifdef PNG_READ_SUPPORTED
  184934. void PNGAPI
  184935. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184936. {
  184937. if(png_ptr == NULL) return;
  184938. png_debug(1, "in png_set_sig_bytes\n");
  184939. if (num_bytes > 8)
  184940. png_error(png_ptr, "Too many bytes for PNG signature.");
  184941. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184942. }
  184943. /* Checks whether the supplied bytes match the PNG signature. We allow
  184944. * checking less than the full 8-byte signature so that those apps that
  184945. * already read the first few bytes of a file to determine the file type
  184946. * can simply check the remaining bytes for extra assurance. Returns
  184947. * an integer less than, equal to, or greater than zero if sig is found,
  184948. * respectively, to be less than, to match, or be greater than the correct
  184949. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184950. */
  184951. int PNGAPI
  184952. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184953. {
  184954. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184955. if (num_to_check > 8)
  184956. num_to_check = 8;
  184957. else if (num_to_check < 1)
  184958. return (-1);
  184959. if (start > 7)
  184960. return (-1);
  184961. if (start + num_to_check > 8)
  184962. num_to_check = 8 - start;
  184963. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184964. }
  184965. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184966. /* (Obsolete) function to check signature bytes. It does not allow one
  184967. * to check a partial signature. This function might be removed in the
  184968. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184969. */
  184970. int PNGAPI
  184971. png_check_sig(png_bytep sig, int num)
  184972. {
  184973. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184974. }
  184975. #endif
  184976. #endif /* PNG_READ_SUPPORTED */
  184977. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184978. /* Function to allocate memory for zlib and clear it to 0. */
  184979. #ifdef PNG_1_0_X
  184980. voidpf PNGAPI
  184981. #else
  184982. voidpf /* private */
  184983. #endif
  184984. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184985. {
  184986. png_voidp ptr;
  184987. png_structp p=(png_structp)png_ptr;
  184988. png_uint_32 save_flags=p->flags;
  184989. png_uint_32 num_bytes;
  184990. if(png_ptr == NULL) return (NULL);
  184991. if (items > PNG_UINT_32_MAX/size)
  184992. {
  184993. png_warning (p, "Potential overflow in png_zalloc()");
  184994. return (NULL);
  184995. }
  184996. num_bytes = (png_uint_32)items * size;
  184997. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184998. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184999. p->flags=save_flags;
  185000. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  185001. if (ptr == NULL)
  185002. return ((voidpf)ptr);
  185003. if (num_bytes > (png_uint_32)0x8000L)
  185004. {
  185005. png_memset(ptr, 0, (png_size_t)0x8000L);
  185006. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  185007. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  185008. }
  185009. else
  185010. {
  185011. png_memset(ptr, 0, (png_size_t)num_bytes);
  185012. }
  185013. #endif
  185014. return ((voidpf)ptr);
  185015. }
  185016. /* function to free memory for zlib */
  185017. #ifdef PNG_1_0_X
  185018. void PNGAPI
  185019. #else
  185020. void /* private */
  185021. #endif
  185022. png_zfree(voidpf png_ptr, voidpf ptr)
  185023. {
  185024. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185025. }
  185026. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185027. * in case CRC is > 32 bits to leave the top bits 0.
  185028. */
  185029. void /* PRIVATE */
  185030. png_reset_crc(png_structp png_ptr)
  185031. {
  185032. png_ptr->crc = crc32(0, Z_NULL, 0);
  185033. }
  185034. /* Calculate the CRC over a section of data. We can only pass as
  185035. * much data to this routine as the largest single buffer size. We
  185036. * also check that this data will actually be used before going to the
  185037. * trouble of calculating it.
  185038. */
  185039. void /* PRIVATE */
  185040. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185041. {
  185042. int need_crc = 1;
  185043. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185044. {
  185045. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185046. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185047. need_crc = 0;
  185048. }
  185049. else /* critical */
  185050. {
  185051. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185052. need_crc = 0;
  185053. }
  185054. if (need_crc)
  185055. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185056. }
  185057. /* Allocate the memory for an info_struct for the application. We don't
  185058. * really need the png_ptr, but it could potentially be useful in the
  185059. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185060. * and png_info_init() so that applications that want to use a shared
  185061. * libpng don't have to be recompiled if png_info changes size.
  185062. */
  185063. png_infop PNGAPI
  185064. png_create_info_struct(png_structp png_ptr)
  185065. {
  185066. png_infop info_ptr;
  185067. png_debug(1, "in png_create_info_struct\n");
  185068. if(png_ptr == NULL) return (NULL);
  185069. #ifdef PNG_USER_MEM_SUPPORTED
  185070. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185071. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185072. #else
  185073. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185074. #endif
  185075. if (info_ptr != NULL)
  185076. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185077. return (info_ptr);
  185078. }
  185079. /* This function frees the memory associated with a single info struct.
  185080. * Normally, one would use either png_destroy_read_struct() or
  185081. * png_destroy_write_struct() to free an info struct, but this may be
  185082. * useful for some applications.
  185083. */
  185084. void PNGAPI
  185085. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185086. {
  185087. png_infop info_ptr = NULL;
  185088. if(png_ptr == NULL) return;
  185089. png_debug(1, "in png_destroy_info_struct\n");
  185090. if (info_ptr_ptr != NULL)
  185091. info_ptr = *info_ptr_ptr;
  185092. if (info_ptr != NULL)
  185093. {
  185094. png_info_destroy(png_ptr, info_ptr);
  185095. #ifdef PNG_USER_MEM_SUPPORTED
  185096. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185097. png_ptr->mem_ptr);
  185098. #else
  185099. png_destroy_struct((png_voidp)info_ptr);
  185100. #endif
  185101. *info_ptr_ptr = NULL;
  185102. }
  185103. }
  185104. /* Initialize the info structure. This is now an internal function (0.89)
  185105. * and applications using it are urged to use png_create_info_struct()
  185106. * instead.
  185107. */
  185108. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185109. #undef png_info_init
  185110. void PNGAPI
  185111. png_info_init(png_infop info_ptr)
  185112. {
  185113. /* We only come here via pre-1.0.12-compiled applications */
  185114. png_info_init_3(&info_ptr, 0);
  185115. }
  185116. #endif
  185117. void PNGAPI
  185118. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185119. {
  185120. png_infop info_ptr = *ptr_ptr;
  185121. if(info_ptr == NULL) return;
  185122. png_debug(1, "in png_info_init_3\n");
  185123. if(png_sizeof(png_info) > png_info_struct_size)
  185124. {
  185125. png_destroy_struct(info_ptr);
  185126. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185127. *ptr_ptr = info_ptr;
  185128. }
  185129. /* set everything to 0 */
  185130. png_memset(info_ptr, 0, png_sizeof (png_info));
  185131. }
  185132. #ifdef PNG_FREE_ME_SUPPORTED
  185133. void PNGAPI
  185134. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185135. int freer, png_uint_32 mask)
  185136. {
  185137. png_debug(1, "in png_data_freer\n");
  185138. if (png_ptr == NULL || info_ptr == NULL)
  185139. return;
  185140. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185141. info_ptr->free_me |= mask;
  185142. else if(freer == PNG_USER_WILL_FREE_DATA)
  185143. info_ptr->free_me &= ~mask;
  185144. else
  185145. png_warning(png_ptr,
  185146. "Unknown freer parameter in png_data_freer.");
  185147. }
  185148. #endif
  185149. void PNGAPI
  185150. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185151. int num)
  185152. {
  185153. png_debug(1, "in png_free_data\n");
  185154. if (png_ptr == NULL || info_ptr == NULL)
  185155. return;
  185156. #if defined(PNG_TEXT_SUPPORTED)
  185157. /* free text item num or (if num == -1) all text items */
  185158. #ifdef PNG_FREE_ME_SUPPORTED
  185159. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185160. #else
  185161. if (mask & PNG_FREE_TEXT)
  185162. #endif
  185163. {
  185164. if (num != -1)
  185165. {
  185166. if (info_ptr->text && info_ptr->text[num].key)
  185167. {
  185168. png_free(png_ptr, info_ptr->text[num].key);
  185169. info_ptr->text[num].key = NULL;
  185170. }
  185171. }
  185172. else
  185173. {
  185174. int i;
  185175. for (i = 0; i < info_ptr->num_text; i++)
  185176. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185177. png_free(png_ptr, info_ptr->text);
  185178. info_ptr->text = NULL;
  185179. info_ptr->num_text=0;
  185180. }
  185181. }
  185182. #endif
  185183. #if defined(PNG_tRNS_SUPPORTED)
  185184. /* free any tRNS entry */
  185185. #ifdef PNG_FREE_ME_SUPPORTED
  185186. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185187. #else
  185188. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185189. #endif
  185190. {
  185191. png_free(png_ptr, info_ptr->trans);
  185192. info_ptr->valid &= ~PNG_INFO_tRNS;
  185193. #ifndef PNG_FREE_ME_SUPPORTED
  185194. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185195. #endif
  185196. info_ptr->trans = NULL;
  185197. }
  185198. #endif
  185199. #if defined(PNG_sCAL_SUPPORTED)
  185200. /* free any sCAL entry */
  185201. #ifdef PNG_FREE_ME_SUPPORTED
  185202. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185203. #else
  185204. if (mask & PNG_FREE_SCAL)
  185205. #endif
  185206. {
  185207. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185208. png_free(png_ptr, info_ptr->scal_s_width);
  185209. png_free(png_ptr, info_ptr->scal_s_height);
  185210. info_ptr->scal_s_width = NULL;
  185211. info_ptr->scal_s_height = NULL;
  185212. #endif
  185213. info_ptr->valid &= ~PNG_INFO_sCAL;
  185214. }
  185215. #endif
  185216. #if defined(PNG_pCAL_SUPPORTED)
  185217. /* free any pCAL entry */
  185218. #ifdef PNG_FREE_ME_SUPPORTED
  185219. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185220. #else
  185221. if (mask & PNG_FREE_PCAL)
  185222. #endif
  185223. {
  185224. png_free(png_ptr, info_ptr->pcal_purpose);
  185225. png_free(png_ptr, info_ptr->pcal_units);
  185226. info_ptr->pcal_purpose = NULL;
  185227. info_ptr->pcal_units = NULL;
  185228. if (info_ptr->pcal_params != NULL)
  185229. {
  185230. int i;
  185231. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185232. {
  185233. png_free(png_ptr, info_ptr->pcal_params[i]);
  185234. info_ptr->pcal_params[i]=NULL;
  185235. }
  185236. png_free(png_ptr, info_ptr->pcal_params);
  185237. info_ptr->pcal_params = NULL;
  185238. }
  185239. info_ptr->valid &= ~PNG_INFO_pCAL;
  185240. }
  185241. #endif
  185242. #if defined(PNG_iCCP_SUPPORTED)
  185243. /* free any iCCP entry */
  185244. #ifdef PNG_FREE_ME_SUPPORTED
  185245. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185246. #else
  185247. if (mask & PNG_FREE_ICCP)
  185248. #endif
  185249. {
  185250. png_free(png_ptr, info_ptr->iccp_name);
  185251. png_free(png_ptr, info_ptr->iccp_profile);
  185252. info_ptr->iccp_name = NULL;
  185253. info_ptr->iccp_profile = NULL;
  185254. info_ptr->valid &= ~PNG_INFO_iCCP;
  185255. }
  185256. #endif
  185257. #if defined(PNG_sPLT_SUPPORTED)
  185258. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185259. #ifdef PNG_FREE_ME_SUPPORTED
  185260. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185261. #else
  185262. if (mask & PNG_FREE_SPLT)
  185263. #endif
  185264. {
  185265. if (num != -1)
  185266. {
  185267. if(info_ptr->splt_palettes)
  185268. {
  185269. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185270. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185271. info_ptr->splt_palettes[num].name = NULL;
  185272. info_ptr->splt_palettes[num].entries = NULL;
  185273. }
  185274. }
  185275. else
  185276. {
  185277. if(info_ptr->splt_palettes_num)
  185278. {
  185279. int i;
  185280. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185281. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185282. png_free(png_ptr, info_ptr->splt_palettes);
  185283. info_ptr->splt_palettes = NULL;
  185284. info_ptr->splt_palettes_num = 0;
  185285. }
  185286. info_ptr->valid &= ~PNG_INFO_sPLT;
  185287. }
  185288. }
  185289. #endif
  185290. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185291. if(png_ptr->unknown_chunk.data)
  185292. {
  185293. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185294. png_ptr->unknown_chunk.data = NULL;
  185295. }
  185296. #ifdef PNG_FREE_ME_SUPPORTED
  185297. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185298. #else
  185299. if (mask & PNG_FREE_UNKN)
  185300. #endif
  185301. {
  185302. if (num != -1)
  185303. {
  185304. if(info_ptr->unknown_chunks)
  185305. {
  185306. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185307. info_ptr->unknown_chunks[num].data = NULL;
  185308. }
  185309. }
  185310. else
  185311. {
  185312. int i;
  185313. if(info_ptr->unknown_chunks_num)
  185314. {
  185315. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185316. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185317. png_free(png_ptr, info_ptr->unknown_chunks);
  185318. info_ptr->unknown_chunks = NULL;
  185319. info_ptr->unknown_chunks_num = 0;
  185320. }
  185321. }
  185322. }
  185323. #endif
  185324. #if defined(PNG_hIST_SUPPORTED)
  185325. /* free any hIST entry */
  185326. #ifdef PNG_FREE_ME_SUPPORTED
  185327. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185328. #else
  185329. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185330. #endif
  185331. {
  185332. png_free(png_ptr, info_ptr->hist);
  185333. info_ptr->hist = NULL;
  185334. info_ptr->valid &= ~PNG_INFO_hIST;
  185335. #ifndef PNG_FREE_ME_SUPPORTED
  185336. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185337. #endif
  185338. }
  185339. #endif
  185340. /* free any PLTE entry that was internally allocated */
  185341. #ifdef PNG_FREE_ME_SUPPORTED
  185342. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185343. #else
  185344. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185345. #endif
  185346. {
  185347. png_zfree(png_ptr, info_ptr->palette);
  185348. info_ptr->palette = NULL;
  185349. info_ptr->valid &= ~PNG_INFO_PLTE;
  185350. #ifndef PNG_FREE_ME_SUPPORTED
  185351. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185352. #endif
  185353. info_ptr->num_palette = 0;
  185354. }
  185355. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185356. /* free any image bits attached to the info structure */
  185357. #ifdef PNG_FREE_ME_SUPPORTED
  185358. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185359. #else
  185360. if (mask & PNG_FREE_ROWS)
  185361. #endif
  185362. {
  185363. if(info_ptr->row_pointers)
  185364. {
  185365. int row;
  185366. for (row = 0; row < (int)info_ptr->height; row++)
  185367. {
  185368. png_free(png_ptr, info_ptr->row_pointers[row]);
  185369. info_ptr->row_pointers[row]=NULL;
  185370. }
  185371. png_free(png_ptr, info_ptr->row_pointers);
  185372. info_ptr->row_pointers=NULL;
  185373. }
  185374. info_ptr->valid &= ~PNG_INFO_IDAT;
  185375. }
  185376. #endif
  185377. #ifdef PNG_FREE_ME_SUPPORTED
  185378. if(num == -1)
  185379. info_ptr->free_me &= ~mask;
  185380. else
  185381. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185382. #endif
  185383. }
  185384. /* This is an internal routine to free any memory that the info struct is
  185385. * pointing to before re-using it or freeing the struct itself. Recall
  185386. * that png_free() checks for NULL pointers for us.
  185387. */
  185388. void /* PRIVATE */
  185389. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185390. {
  185391. png_debug(1, "in png_info_destroy\n");
  185392. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185393. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185394. if (png_ptr->num_chunk_list)
  185395. {
  185396. png_free(png_ptr, png_ptr->chunk_list);
  185397. png_ptr->chunk_list=NULL;
  185398. png_ptr->num_chunk_list=0;
  185399. }
  185400. #endif
  185401. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185402. }
  185403. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185404. /* This function returns a pointer to the io_ptr associated with the user
  185405. * functions. The application should free any memory associated with this
  185406. * pointer before png_write_destroy() or png_read_destroy() are called.
  185407. */
  185408. png_voidp PNGAPI
  185409. png_get_io_ptr(png_structp png_ptr)
  185410. {
  185411. if(png_ptr == NULL) return (NULL);
  185412. return (png_ptr->io_ptr);
  185413. }
  185414. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185415. #if !defined(PNG_NO_STDIO)
  185416. /* Initialize the default input/output functions for the PNG file. If you
  185417. * use your own read or write routines, you can call either png_set_read_fn()
  185418. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185419. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185420. * necessarily available.
  185421. */
  185422. void PNGAPI
  185423. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185424. {
  185425. png_debug(1, "in png_init_io\n");
  185426. if(png_ptr == NULL) return;
  185427. png_ptr->io_ptr = (png_voidp)fp;
  185428. }
  185429. #endif
  185430. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185431. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185432. * a "Creation Time" or other text-based time string.
  185433. */
  185434. png_charp PNGAPI
  185435. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185436. {
  185437. static PNG_CONST char short_months[12][4] =
  185438. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185439. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185440. if(png_ptr == NULL) return (NULL);
  185441. if (png_ptr->time_buffer == NULL)
  185442. {
  185443. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185444. png_sizeof(char)));
  185445. }
  185446. #if defined(_WIN32_WCE)
  185447. {
  185448. wchar_t time_buf[29];
  185449. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185450. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185451. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185452. ptime->second % 61);
  185453. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185454. NULL, NULL);
  185455. }
  185456. #else
  185457. #ifdef USE_FAR_KEYWORD
  185458. {
  185459. char near_time_buf[29];
  185460. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185461. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185462. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185463. ptime->second % 61);
  185464. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185465. 29*png_sizeof(char));
  185466. }
  185467. #else
  185468. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185469. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185470. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185471. ptime->second % 61);
  185472. #endif
  185473. #endif /* _WIN32_WCE */
  185474. return ((png_charp)png_ptr->time_buffer);
  185475. }
  185476. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185477. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185478. png_charp PNGAPI
  185479. png_get_copyright(png_structp png_ptr)
  185480. {
  185481. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185482. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185483. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185484. Copyright (c) 1996-1997 Andreas Dilger\n\
  185485. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185486. }
  185487. /* The following return the library version as a short string in the
  185488. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185489. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185490. * is defined in png.h.
  185491. * Note: now there is no difference between png_get_libpng_ver() and
  185492. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185493. * it is guaranteed that png.c uses the correct version of png.h.
  185494. */
  185495. png_charp PNGAPI
  185496. png_get_libpng_ver(png_structp png_ptr)
  185497. {
  185498. /* Version of *.c files used when building libpng */
  185499. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185500. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185501. }
  185502. png_charp PNGAPI
  185503. png_get_header_ver(png_structp png_ptr)
  185504. {
  185505. /* Version of *.h files used when building libpng */
  185506. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185507. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185508. }
  185509. png_charp PNGAPI
  185510. png_get_header_version(png_structp png_ptr)
  185511. {
  185512. /* Returns longer string containing both version and date */
  185513. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185514. return ((png_charp) PNG_HEADER_VERSION_STRING
  185515. #ifndef PNG_READ_SUPPORTED
  185516. " (NO READ SUPPORT)"
  185517. #endif
  185518. "\n");
  185519. }
  185520. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185521. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185522. int PNGAPI
  185523. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185524. {
  185525. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185526. int i;
  185527. png_bytep p;
  185528. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185529. return 0;
  185530. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185531. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185532. if (!png_memcmp(chunk_name, p, 4))
  185533. return ((int)*(p+4));
  185534. return 0;
  185535. }
  185536. #endif
  185537. /* This function, added to libpng-1.0.6g, is untested. */
  185538. int PNGAPI
  185539. png_reset_zstream(png_structp png_ptr)
  185540. {
  185541. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185542. return (inflateReset(&png_ptr->zstream));
  185543. }
  185544. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185545. /* This function was added to libpng-1.0.7 */
  185546. png_uint_32 PNGAPI
  185547. png_access_version_number(void)
  185548. {
  185549. /* Version of *.c files used when building libpng */
  185550. return((png_uint_32) PNG_LIBPNG_VER);
  185551. }
  185552. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185553. #if !defined(PNG_1_0_X)
  185554. /* this function was added to libpng 1.2.0 */
  185555. int PNGAPI
  185556. png_mmx_support(void)
  185557. {
  185558. /* obsolete, to be removed from libpng-1.4.0 */
  185559. return -1;
  185560. }
  185561. #endif /* PNG_1_0_X */
  185562. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185563. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185564. #ifdef PNG_SIZE_T
  185565. /* Added at libpng version 1.2.6 */
  185566. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185567. png_size_t PNGAPI
  185568. png_convert_size(size_t size)
  185569. {
  185570. if (size > (png_size_t)-1)
  185571. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185572. return ((png_size_t)size);
  185573. }
  185574. #endif /* PNG_SIZE_T */
  185575. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185576. /*** End of inlined file: png.c ***/
  185577. /*** Start of inlined file: pngerror.c ***/
  185578. /* pngerror.c - stub functions for i/o and memory allocation
  185579. *
  185580. * Last changed in libpng 1.2.20 October 4, 2007
  185581. * For conditions of distribution and use, see copyright notice in png.h
  185582. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185583. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185584. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185585. *
  185586. * This file provides a location for all error handling. Users who
  185587. * need special error handling are expected to write replacement functions
  185588. * and use png_set_error_fn() to use those functions. See the instructions
  185589. * at each function.
  185590. */
  185591. #define PNG_INTERNAL
  185592. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185593. static void /* PRIVATE */
  185594. png_default_error PNGARG((png_structp png_ptr,
  185595. png_const_charp error_message));
  185596. #ifndef PNG_NO_WARNINGS
  185597. static void /* PRIVATE */
  185598. png_default_warning PNGARG((png_structp png_ptr,
  185599. png_const_charp warning_message));
  185600. #endif /* PNG_NO_WARNINGS */
  185601. /* This function is called whenever there is a fatal error. This function
  185602. * should not be changed. If there is a need to handle errors differently,
  185603. * you should supply a replacement error function and use png_set_error_fn()
  185604. * to replace the error function at run-time.
  185605. */
  185606. #ifndef PNG_NO_ERROR_TEXT
  185607. void PNGAPI
  185608. png_error(png_structp png_ptr, png_const_charp error_message)
  185609. {
  185610. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185611. char msg[16];
  185612. if (png_ptr != NULL)
  185613. {
  185614. if (png_ptr->flags&
  185615. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185616. {
  185617. if (*error_message == '#')
  185618. {
  185619. int offset;
  185620. for (offset=1; offset<15; offset++)
  185621. if (*(error_message+offset) == ' ')
  185622. break;
  185623. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185624. {
  185625. int i;
  185626. for (i=0; i<offset-1; i++)
  185627. msg[i]=error_message[i+1];
  185628. msg[i]='\0';
  185629. error_message=msg;
  185630. }
  185631. else
  185632. error_message+=offset;
  185633. }
  185634. else
  185635. {
  185636. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185637. {
  185638. msg[0]='0';
  185639. msg[1]='\0';
  185640. error_message=msg;
  185641. }
  185642. }
  185643. }
  185644. }
  185645. #endif
  185646. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185647. (*(png_ptr->error_fn))(png_ptr, error_message);
  185648. /* If the custom handler doesn't exist, or if it returns,
  185649. use the default handler, which will not return. */
  185650. png_default_error(png_ptr, error_message);
  185651. }
  185652. #else
  185653. void PNGAPI
  185654. png_err(png_structp png_ptr)
  185655. {
  185656. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185657. (*(png_ptr->error_fn))(png_ptr, '\0');
  185658. /* If the custom handler doesn't exist, or if it returns,
  185659. use the default handler, which will not return. */
  185660. png_default_error(png_ptr, '\0');
  185661. }
  185662. #endif /* PNG_NO_ERROR_TEXT */
  185663. #ifndef PNG_NO_WARNINGS
  185664. /* This function is called whenever there is a non-fatal error. This function
  185665. * should not be changed. If there is a need to handle warnings differently,
  185666. * you should supply a replacement warning function and use
  185667. * png_set_error_fn() to replace the warning function at run-time.
  185668. */
  185669. void PNGAPI
  185670. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185671. {
  185672. int offset = 0;
  185673. if (png_ptr != NULL)
  185674. {
  185675. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185676. if (png_ptr->flags&
  185677. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185678. #endif
  185679. {
  185680. if (*warning_message == '#')
  185681. {
  185682. for (offset=1; offset<15; offset++)
  185683. if (*(warning_message+offset) == ' ')
  185684. break;
  185685. }
  185686. }
  185687. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185688. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185689. }
  185690. else
  185691. png_default_warning(png_ptr, warning_message+offset);
  185692. }
  185693. #endif /* PNG_NO_WARNINGS */
  185694. /* These utilities are used internally to build an error message that relates
  185695. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185696. * this is used to prefix the message. The message is limited in length
  185697. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185698. * if the character is invalid.
  185699. */
  185700. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185701. /*static PNG_CONST char png_digit[16] = {
  185702. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185703. 'A', 'B', 'C', 'D', 'E', 'F'
  185704. };*/
  185705. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185706. static void /* PRIVATE */
  185707. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185708. error_message)
  185709. {
  185710. int iout = 0, iin = 0;
  185711. while (iin < 4)
  185712. {
  185713. int c = png_ptr->chunk_name[iin++];
  185714. if (isnonalpha(c))
  185715. {
  185716. buffer[iout++] = '[';
  185717. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185718. buffer[iout++] = png_digit[c & 0x0f];
  185719. buffer[iout++] = ']';
  185720. }
  185721. else
  185722. {
  185723. buffer[iout++] = (png_byte)c;
  185724. }
  185725. }
  185726. if (error_message == NULL)
  185727. buffer[iout] = 0;
  185728. else
  185729. {
  185730. buffer[iout++] = ':';
  185731. buffer[iout++] = ' ';
  185732. png_strncpy(buffer+iout, error_message, 63);
  185733. buffer[iout+63] = 0;
  185734. }
  185735. }
  185736. #ifdef PNG_READ_SUPPORTED
  185737. void PNGAPI
  185738. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185739. {
  185740. char msg[18+64];
  185741. if (png_ptr == NULL)
  185742. png_error(png_ptr, error_message);
  185743. else
  185744. {
  185745. png_format_buffer(png_ptr, msg, error_message);
  185746. png_error(png_ptr, msg);
  185747. }
  185748. }
  185749. #endif /* PNG_READ_SUPPORTED */
  185750. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185751. #ifndef PNG_NO_WARNINGS
  185752. void PNGAPI
  185753. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185754. {
  185755. char msg[18+64];
  185756. if (png_ptr == NULL)
  185757. png_warning(png_ptr, warning_message);
  185758. else
  185759. {
  185760. png_format_buffer(png_ptr, msg, warning_message);
  185761. png_warning(png_ptr, msg);
  185762. }
  185763. }
  185764. #endif /* PNG_NO_WARNINGS */
  185765. /* This is the default error handling function. Note that replacements for
  185766. * this function MUST NOT RETURN, or the program will likely crash. This
  185767. * function is used by default, or if the program supplies NULL for the
  185768. * error function pointer in png_set_error_fn().
  185769. */
  185770. static void /* PRIVATE */
  185771. png_default_error(png_structp, png_const_charp error_message)
  185772. {
  185773. #ifndef PNG_NO_CONSOLE_IO
  185774. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185775. if (*error_message == '#')
  185776. {
  185777. int offset;
  185778. char error_number[16];
  185779. for (offset=0; offset<15; offset++)
  185780. {
  185781. error_number[offset] = *(error_message+offset+1);
  185782. if (*(error_message+offset) == ' ')
  185783. break;
  185784. }
  185785. if((offset > 1) && (offset < 15))
  185786. {
  185787. error_number[offset-1]='\0';
  185788. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185789. error_message+offset);
  185790. }
  185791. else
  185792. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185793. }
  185794. else
  185795. #endif
  185796. fprintf(stderr, "libpng error: %s\n", error_message);
  185797. #endif
  185798. #ifdef PNG_SETJMP_SUPPORTED
  185799. if (png_ptr)
  185800. {
  185801. # ifdef USE_FAR_KEYWORD
  185802. {
  185803. jmp_buf jmpbuf;
  185804. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185805. longjmp(jmpbuf, 1);
  185806. }
  185807. # else
  185808. longjmp(png_ptr->jmpbuf, 1);
  185809. # endif
  185810. }
  185811. #else
  185812. PNG_ABORT();
  185813. #endif
  185814. #ifdef PNG_NO_CONSOLE_IO
  185815. error_message = error_message; /* make compiler happy */
  185816. #endif
  185817. }
  185818. #ifndef PNG_NO_WARNINGS
  185819. /* This function is called when there is a warning, but the library thinks
  185820. * it can continue anyway. Replacement functions don't have to do anything
  185821. * here if you don't want them to. In the default configuration, png_ptr is
  185822. * not used, but it is passed in case it may be useful.
  185823. */
  185824. static void /* PRIVATE */
  185825. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185826. {
  185827. #ifndef PNG_NO_CONSOLE_IO
  185828. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185829. if (*warning_message == '#')
  185830. {
  185831. int offset;
  185832. char warning_number[16];
  185833. for (offset=0; offset<15; offset++)
  185834. {
  185835. warning_number[offset]=*(warning_message+offset+1);
  185836. if (*(warning_message+offset) == ' ')
  185837. break;
  185838. }
  185839. if((offset > 1) && (offset < 15))
  185840. {
  185841. warning_number[offset-1]='\0';
  185842. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185843. warning_message+offset);
  185844. }
  185845. else
  185846. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185847. }
  185848. else
  185849. # endif
  185850. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185851. #else
  185852. warning_message = warning_message; /* make compiler happy */
  185853. #endif
  185854. png_ptr = png_ptr; /* make compiler happy */
  185855. }
  185856. #endif /* PNG_NO_WARNINGS */
  185857. /* This function is called when the application wants to use another method
  185858. * of handling errors and warnings. Note that the error function MUST NOT
  185859. * return to the calling routine or serious problems will occur. The return
  185860. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185861. */
  185862. void PNGAPI
  185863. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185864. png_error_ptr error_fn, png_error_ptr warning_fn)
  185865. {
  185866. if (png_ptr == NULL)
  185867. return;
  185868. png_ptr->error_ptr = error_ptr;
  185869. png_ptr->error_fn = error_fn;
  185870. png_ptr->warning_fn = warning_fn;
  185871. }
  185872. /* This function returns a pointer to the error_ptr associated with the user
  185873. * functions. The application should free any memory associated with this
  185874. * pointer before png_write_destroy and png_read_destroy are called.
  185875. */
  185876. png_voidp PNGAPI
  185877. png_get_error_ptr(png_structp png_ptr)
  185878. {
  185879. if (png_ptr == NULL)
  185880. return NULL;
  185881. return ((png_voidp)png_ptr->error_ptr);
  185882. }
  185883. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185884. void PNGAPI
  185885. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185886. {
  185887. if(png_ptr != NULL)
  185888. {
  185889. png_ptr->flags &=
  185890. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185891. }
  185892. }
  185893. #endif
  185894. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185895. /*** End of inlined file: pngerror.c ***/
  185896. /*** Start of inlined file: pngget.c ***/
  185897. /* pngget.c - retrieval of values from info struct
  185898. *
  185899. * Last changed in libpng 1.2.15 January 5, 2007
  185900. * For conditions of distribution and use, see copyright notice in png.h
  185901. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185902. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185903. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185904. */
  185905. #define PNG_INTERNAL
  185906. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185907. png_uint_32 PNGAPI
  185908. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185909. {
  185910. if (png_ptr != NULL && info_ptr != NULL)
  185911. return(info_ptr->valid & flag);
  185912. else
  185913. return(0);
  185914. }
  185915. png_uint_32 PNGAPI
  185916. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185917. {
  185918. if (png_ptr != NULL && info_ptr != NULL)
  185919. return(info_ptr->rowbytes);
  185920. else
  185921. return(0);
  185922. }
  185923. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185924. png_bytepp PNGAPI
  185925. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185926. {
  185927. if (png_ptr != NULL && info_ptr != NULL)
  185928. return(info_ptr->row_pointers);
  185929. else
  185930. return(0);
  185931. }
  185932. #endif
  185933. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185934. /* easy access to info, added in libpng-0.99 */
  185935. png_uint_32 PNGAPI
  185936. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185937. {
  185938. if (png_ptr != NULL && info_ptr != NULL)
  185939. {
  185940. return info_ptr->width;
  185941. }
  185942. return (0);
  185943. }
  185944. png_uint_32 PNGAPI
  185945. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185946. {
  185947. if (png_ptr != NULL && info_ptr != NULL)
  185948. {
  185949. return info_ptr->height;
  185950. }
  185951. return (0);
  185952. }
  185953. png_byte PNGAPI
  185954. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185955. {
  185956. if (png_ptr != NULL && info_ptr != NULL)
  185957. {
  185958. return info_ptr->bit_depth;
  185959. }
  185960. return (0);
  185961. }
  185962. png_byte PNGAPI
  185963. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185964. {
  185965. if (png_ptr != NULL && info_ptr != NULL)
  185966. {
  185967. return info_ptr->color_type;
  185968. }
  185969. return (0);
  185970. }
  185971. png_byte PNGAPI
  185972. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185973. {
  185974. if (png_ptr != NULL && info_ptr != NULL)
  185975. {
  185976. return info_ptr->filter_type;
  185977. }
  185978. return (0);
  185979. }
  185980. png_byte PNGAPI
  185981. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185982. {
  185983. if (png_ptr != NULL && info_ptr != NULL)
  185984. {
  185985. return info_ptr->interlace_type;
  185986. }
  185987. return (0);
  185988. }
  185989. png_byte PNGAPI
  185990. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185991. {
  185992. if (png_ptr != NULL && info_ptr != NULL)
  185993. {
  185994. return info_ptr->compression_type;
  185995. }
  185996. return (0);
  185997. }
  185998. png_uint_32 PNGAPI
  185999. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186000. {
  186001. if (png_ptr != NULL && info_ptr != NULL)
  186002. #if defined(PNG_pHYs_SUPPORTED)
  186003. if (info_ptr->valid & PNG_INFO_pHYs)
  186004. {
  186005. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  186006. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186007. return (0);
  186008. else return (info_ptr->x_pixels_per_unit);
  186009. }
  186010. #else
  186011. return (0);
  186012. #endif
  186013. return (0);
  186014. }
  186015. png_uint_32 PNGAPI
  186016. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186017. {
  186018. if (png_ptr != NULL && info_ptr != NULL)
  186019. #if defined(PNG_pHYs_SUPPORTED)
  186020. if (info_ptr->valid & PNG_INFO_pHYs)
  186021. {
  186022. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  186023. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186024. return (0);
  186025. else return (info_ptr->y_pixels_per_unit);
  186026. }
  186027. #else
  186028. return (0);
  186029. #endif
  186030. return (0);
  186031. }
  186032. png_uint_32 PNGAPI
  186033. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186034. {
  186035. if (png_ptr != NULL && info_ptr != NULL)
  186036. #if defined(PNG_pHYs_SUPPORTED)
  186037. if (info_ptr->valid & PNG_INFO_pHYs)
  186038. {
  186039. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186040. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186041. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186042. return (0);
  186043. else return (info_ptr->x_pixels_per_unit);
  186044. }
  186045. #else
  186046. return (0);
  186047. #endif
  186048. return (0);
  186049. }
  186050. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186051. float PNGAPI
  186052. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186053. {
  186054. if (png_ptr != NULL && info_ptr != NULL)
  186055. #if defined(PNG_pHYs_SUPPORTED)
  186056. if (info_ptr->valid & PNG_INFO_pHYs)
  186057. {
  186058. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186059. if (info_ptr->x_pixels_per_unit == 0)
  186060. return ((float)0.0);
  186061. else
  186062. return ((float)((float)info_ptr->y_pixels_per_unit
  186063. /(float)info_ptr->x_pixels_per_unit));
  186064. }
  186065. #else
  186066. return (0.0);
  186067. #endif
  186068. return ((float)0.0);
  186069. }
  186070. #endif
  186071. png_int_32 PNGAPI
  186072. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186073. {
  186074. if (png_ptr != NULL && info_ptr != NULL)
  186075. #if defined(PNG_oFFs_SUPPORTED)
  186076. if (info_ptr->valid & PNG_INFO_oFFs)
  186077. {
  186078. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186079. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186080. return (0);
  186081. else return (info_ptr->x_offset);
  186082. }
  186083. #else
  186084. return (0);
  186085. #endif
  186086. return (0);
  186087. }
  186088. png_int_32 PNGAPI
  186089. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186090. {
  186091. if (png_ptr != NULL && info_ptr != NULL)
  186092. #if defined(PNG_oFFs_SUPPORTED)
  186093. if (info_ptr->valid & PNG_INFO_oFFs)
  186094. {
  186095. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186096. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186097. return (0);
  186098. else return (info_ptr->y_offset);
  186099. }
  186100. #else
  186101. return (0);
  186102. #endif
  186103. return (0);
  186104. }
  186105. png_int_32 PNGAPI
  186106. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186107. {
  186108. if (png_ptr != NULL && info_ptr != NULL)
  186109. #if defined(PNG_oFFs_SUPPORTED)
  186110. if (info_ptr->valid & PNG_INFO_oFFs)
  186111. {
  186112. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186113. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186114. return (0);
  186115. else return (info_ptr->x_offset);
  186116. }
  186117. #else
  186118. return (0);
  186119. #endif
  186120. return (0);
  186121. }
  186122. png_int_32 PNGAPI
  186123. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186124. {
  186125. if (png_ptr != NULL && info_ptr != NULL)
  186126. #if defined(PNG_oFFs_SUPPORTED)
  186127. if (info_ptr->valid & PNG_INFO_oFFs)
  186128. {
  186129. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186130. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186131. return (0);
  186132. else return (info_ptr->y_offset);
  186133. }
  186134. #else
  186135. return (0);
  186136. #endif
  186137. return (0);
  186138. }
  186139. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186140. png_uint_32 PNGAPI
  186141. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186142. {
  186143. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186144. *.0254 +.5));
  186145. }
  186146. png_uint_32 PNGAPI
  186147. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186148. {
  186149. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186150. *.0254 +.5));
  186151. }
  186152. png_uint_32 PNGAPI
  186153. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186154. {
  186155. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186156. *.0254 +.5));
  186157. }
  186158. float PNGAPI
  186159. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186160. {
  186161. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186162. *.00003937);
  186163. }
  186164. float PNGAPI
  186165. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186166. {
  186167. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186168. *.00003937);
  186169. }
  186170. #if defined(PNG_pHYs_SUPPORTED)
  186171. png_uint_32 PNGAPI
  186172. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186173. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186174. {
  186175. png_uint_32 retval = 0;
  186176. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186177. {
  186178. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186179. if (res_x != NULL)
  186180. {
  186181. *res_x = info_ptr->x_pixels_per_unit;
  186182. retval |= PNG_INFO_pHYs;
  186183. }
  186184. if (res_y != NULL)
  186185. {
  186186. *res_y = info_ptr->y_pixels_per_unit;
  186187. retval |= PNG_INFO_pHYs;
  186188. }
  186189. if (unit_type != NULL)
  186190. {
  186191. *unit_type = (int)info_ptr->phys_unit_type;
  186192. retval |= PNG_INFO_pHYs;
  186193. if(*unit_type == 1)
  186194. {
  186195. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186196. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186197. }
  186198. }
  186199. }
  186200. return (retval);
  186201. }
  186202. #endif /* PNG_pHYs_SUPPORTED */
  186203. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186204. /* png_get_channels really belongs in here, too, but it's been around longer */
  186205. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186206. png_byte PNGAPI
  186207. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186208. {
  186209. if (png_ptr != NULL && info_ptr != NULL)
  186210. return(info_ptr->channels);
  186211. else
  186212. return (0);
  186213. }
  186214. png_bytep PNGAPI
  186215. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186216. {
  186217. if (png_ptr != NULL && info_ptr != NULL)
  186218. return(info_ptr->signature);
  186219. else
  186220. return (NULL);
  186221. }
  186222. #if defined(PNG_bKGD_SUPPORTED)
  186223. png_uint_32 PNGAPI
  186224. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186225. png_color_16p *background)
  186226. {
  186227. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186228. && background != NULL)
  186229. {
  186230. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186231. *background = &(info_ptr->background);
  186232. return (PNG_INFO_bKGD);
  186233. }
  186234. return (0);
  186235. }
  186236. #endif
  186237. #if defined(PNG_cHRM_SUPPORTED)
  186238. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186239. png_uint_32 PNGAPI
  186240. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186241. double *white_x, double *white_y, double *red_x, double *red_y,
  186242. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186243. {
  186244. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186245. {
  186246. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186247. if (white_x != NULL)
  186248. *white_x = (double)info_ptr->x_white;
  186249. if (white_y != NULL)
  186250. *white_y = (double)info_ptr->y_white;
  186251. if (red_x != NULL)
  186252. *red_x = (double)info_ptr->x_red;
  186253. if (red_y != NULL)
  186254. *red_y = (double)info_ptr->y_red;
  186255. if (green_x != NULL)
  186256. *green_x = (double)info_ptr->x_green;
  186257. if (green_y != NULL)
  186258. *green_y = (double)info_ptr->y_green;
  186259. if (blue_x != NULL)
  186260. *blue_x = (double)info_ptr->x_blue;
  186261. if (blue_y != NULL)
  186262. *blue_y = (double)info_ptr->y_blue;
  186263. return (PNG_INFO_cHRM);
  186264. }
  186265. return (0);
  186266. }
  186267. #endif
  186268. #ifdef PNG_FIXED_POINT_SUPPORTED
  186269. png_uint_32 PNGAPI
  186270. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186271. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186272. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186273. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186274. {
  186275. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186276. {
  186277. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186278. if (white_x != NULL)
  186279. *white_x = info_ptr->int_x_white;
  186280. if (white_y != NULL)
  186281. *white_y = info_ptr->int_y_white;
  186282. if (red_x != NULL)
  186283. *red_x = info_ptr->int_x_red;
  186284. if (red_y != NULL)
  186285. *red_y = info_ptr->int_y_red;
  186286. if (green_x != NULL)
  186287. *green_x = info_ptr->int_x_green;
  186288. if (green_y != NULL)
  186289. *green_y = info_ptr->int_y_green;
  186290. if (blue_x != NULL)
  186291. *blue_x = info_ptr->int_x_blue;
  186292. if (blue_y != NULL)
  186293. *blue_y = info_ptr->int_y_blue;
  186294. return (PNG_INFO_cHRM);
  186295. }
  186296. return (0);
  186297. }
  186298. #endif
  186299. #endif
  186300. #if defined(PNG_gAMA_SUPPORTED)
  186301. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186302. png_uint_32 PNGAPI
  186303. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186304. {
  186305. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186306. && file_gamma != NULL)
  186307. {
  186308. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186309. *file_gamma = (double)info_ptr->gamma;
  186310. return (PNG_INFO_gAMA);
  186311. }
  186312. return (0);
  186313. }
  186314. #endif
  186315. #ifdef PNG_FIXED_POINT_SUPPORTED
  186316. png_uint_32 PNGAPI
  186317. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186318. png_fixed_point *int_file_gamma)
  186319. {
  186320. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186321. && int_file_gamma != NULL)
  186322. {
  186323. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186324. *int_file_gamma = info_ptr->int_gamma;
  186325. return (PNG_INFO_gAMA);
  186326. }
  186327. return (0);
  186328. }
  186329. #endif
  186330. #endif
  186331. #if defined(PNG_sRGB_SUPPORTED)
  186332. png_uint_32 PNGAPI
  186333. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186334. {
  186335. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186336. && file_srgb_intent != NULL)
  186337. {
  186338. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186339. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186340. return (PNG_INFO_sRGB);
  186341. }
  186342. return (0);
  186343. }
  186344. #endif
  186345. #if defined(PNG_iCCP_SUPPORTED)
  186346. png_uint_32 PNGAPI
  186347. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186348. png_charpp name, int *compression_type,
  186349. png_charpp profile, png_uint_32 *proflen)
  186350. {
  186351. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186352. && name != NULL && profile != NULL && proflen != NULL)
  186353. {
  186354. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186355. *name = info_ptr->iccp_name;
  186356. *profile = info_ptr->iccp_profile;
  186357. /* compression_type is a dummy so the API won't have to change
  186358. if we introduce multiple compression types later. */
  186359. *proflen = (int)info_ptr->iccp_proflen;
  186360. *compression_type = (int)info_ptr->iccp_compression;
  186361. return (PNG_INFO_iCCP);
  186362. }
  186363. return (0);
  186364. }
  186365. #endif
  186366. #if defined(PNG_sPLT_SUPPORTED)
  186367. png_uint_32 PNGAPI
  186368. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186369. png_sPLT_tpp spalettes)
  186370. {
  186371. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186372. {
  186373. *spalettes = info_ptr->splt_palettes;
  186374. return ((png_uint_32)info_ptr->splt_palettes_num);
  186375. }
  186376. return (0);
  186377. }
  186378. #endif
  186379. #if defined(PNG_hIST_SUPPORTED)
  186380. png_uint_32 PNGAPI
  186381. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186382. {
  186383. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186384. && hist != NULL)
  186385. {
  186386. png_debug1(1, "in %s retrieval function\n", "hIST");
  186387. *hist = info_ptr->hist;
  186388. return (PNG_INFO_hIST);
  186389. }
  186390. return (0);
  186391. }
  186392. #endif
  186393. png_uint_32 PNGAPI
  186394. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186395. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186396. int *color_type, int *interlace_type, int *compression_type,
  186397. int *filter_type)
  186398. {
  186399. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186400. bit_depth != NULL && color_type != NULL)
  186401. {
  186402. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186403. *width = info_ptr->width;
  186404. *height = info_ptr->height;
  186405. *bit_depth = info_ptr->bit_depth;
  186406. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186407. png_error(png_ptr, "Invalid bit depth");
  186408. *color_type = info_ptr->color_type;
  186409. if (info_ptr->color_type > 6)
  186410. png_error(png_ptr, "Invalid color type");
  186411. if (compression_type != NULL)
  186412. *compression_type = info_ptr->compression_type;
  186413. if (filter_type != NULL)
  186414. *filter_type = info_ptr->filter_type;
  186415. if (interlace_type != NULL)
  186416. *interlace_type = info_ptr->interlace_type;
  186417. /* check for potential overflow of rowbytes */
  186418. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186419. png_error(png_ptr, "Invalid image width");
  186420. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186421. png_error(png_ptr, "Invalid image height");
  186422. if (info_ptr->width > (PNG_UINT_32_MAX
  186423. >> 3) /* 8-byte RGBA pixels */
  186424. - 64 /* bigrowbuf hack */
  186425. - 1 /* filter byte */
  186426. - 7*8 /* rounding of width to multiple of 8 pixels */
  186427. - 8) /* extra max_pixel_depth pad */
  186428. {
  186429. png_warning(png_ptr,
  186430. "Width too large for libpng to process image data.");
  186431. }
  186432. return (1);
  186433. }
  186434. return (0);
  186435. }
  186436. #if defined(PNG_oFFs_SUPPORTED)
  186437. png_uint_32 PNGAPI
  186438. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186439. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186440. {
  186441. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186442. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186443. {
  186444. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186445. *offset_x = info_ptr->x_offset;
  186446. *offset_y = info_ptr->y_offset;
  186447. *unit_type = (int)info_ptr->offset_unit_type;
  186448. return (PNG_INFO_oFFs);
  186449. }
  186450. return (0);
  186451. }
  186452. #endif
  186453. #if defined(PNG_pCAL_SUPPORTED)
  186454. png_uint_32 PNGAPI
  186455. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186456. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186457. png_charp *units, png_charpp *params)
  186458. {
  186459. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186460. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186461. nparams != NULL && units != NULL && params != NULL)
  186462. {
  186463. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186464. *purpose = info_ptr->pcal_purpose;
  186465. *X0 = info_ptr->pcal_X0;
  186466. *X1 = info_ptr->pcal_X1;
  186467. *type = (int)info_ptr->pcal_type;
  186468. *nparams = (int)info_ptr->pcal_nparams;
  186469. *units = info_ptr->pcal_units;
  186470. *params = info_ptr->pcal_params;
  186471. return (PNG_INFO_pCAL);
  186472. }
  186473. return (0);
  186474. }
  186475. #endif
  186476. #if defined(PNG_sCAL_SUPPORTED)
  186477. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186478. png_uint_32 PNGAPI
  186479. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186480. int *unit, double *width, double *height)
  186481. {
  186482. if (png_ptr != NULL && info_ptr != NULL &&
  186483. (info_ptr->valid & PNG_INFO_sCAL))
  186484. {
  186485. *unit = info_ptr->scal_unit;
  186486. *width = info_ptr->scal_pixel_width;
  186487. *height = info_ptr->scal_pixel_height;
  186488. return (PNG_INFO_sCAL);
  186489. }
  186490. return(0);
  186491. }
  186492. #else
  186493. #ifdef PNG_FIXED_POINT_SUPPORTED
  186494. png_uint_32 PNGAPI
  186495. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186496. int *unit, png_charpp width, png_charpp height)
  186497. {
  186498. if (png_ptr != NULL && info_ptr != NULL &&
  186499. (info_ptr->valid & PNG_INFO_sCAL))
  186500. {
  186501. *unit = info_ptr->scal_unit;
  186502. *width = info_ptr->scal_s_width;
  186503. *height = info_ptr->scal_s_height;
  186504. return (PNG_INFO_sCAL);
  186505. }
  186506. return(0);
  186507. }
  186508. #endif
  186509. #endif
  186510. #endif
  186511. #if defined(PNG_pHYs_SUPPORTED)
  186512. png_uint_32 PNGAPI
  186513. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186514. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186515. {
  186516. png_uint_32 retval = 0;
  186517. if (png_ptr != NULL && info_ptr != NULL &&
  186518. (info_ptr->valid & PNG_INFO_pHYs))
  186519. {
  186520. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186521. if (res_x != NULL)
  186522. {
  186523. *res_x = info_ptr->x_pixels_per_unit;
  186524. retval |= PNG_INFO_pHYs;
  186525. }
  186526. if (res_y != NULL)
  186527. {
  186528. *res_y = info_ptr->y_pixels_per_unit;
  186529. retval |= PNG_INFO_pHYs;
  186530. }
  186531. if (unit_type != NULL)
  186532. {
  186533. *unit_type = (int)info_ptr->phys_unit_type;
  186534. retval |= PNG_INFO_pHYs;
  186535. }
  186536. }
  186537. return (retval);
  186538. }
  186539. #endif
  186540. png_uint_32 PNGAPI
  186541. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186542. int *num_palette)
  186543. {
  186544. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186545. && palette != NULL)
  186546. {
  186547. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186548. *palette = info_ptr->palette;
  186549. *num_palette = info_ptr->num_palette;
  186550. png_debug1(3, "num_palette = %d\n", *num_palette);
  186551. return (PNG_INFO_PLTE);
  186552. }
  186553. return (0);
  186554. }
  186555. #if defined(PNG_sBIT_SUPPORTED)
  186556. png_uint_32 PNGAPI
  186557. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186558. {
  186559. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186560. && sig_bit != NULL)
  186561. {
  186562. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186563. *sig_bit = &(info_ptr->sig_bit);
  186564. return (PNG_INFO_sBIT);
  186565. }
  186566. return (0);
  186567. }
  186568. #endif
  186569. #if defined(PNG_TEXT_SUPPORTED)
  186570. png_uint_32 PNGAPI
  186571. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186572. int *num_text)
  186573. {
  186574. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186575. {
  186576. png_debug1(1, "in %s retrieval function\n",
  186577. (png_ptr->chunk_name[0] == '\0' ? "text"
  186578. : (png_const_charp)png_ptr->chunk_name));
  186579. if (text_ptr != NULL)
  186580. *text_ptr = info_ptr->text;
  186581. if (num_text != NULL)
  186582. *num_text = info_ptr->num_text;
  186583. return ((png_uint_32)info_ptr->num_text);
  186584. }
  186585. if (num_text != NULL)
  186586. *num_text = 0;
  186587. return(0);
  186588. }
  186589. #endif
  186590. #if defined(PNG_tIME_SUPPORTED)
  186591. png_uint_32 PNGAPI
  186592. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186593. {
  186594. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186595. && mod_time != NULL)
  186596. {
  186597. png_debug1(1, "in %s retrieval function\n", "tIME");
  186598. *mod_time = &(info_ptr->mod_time);
  186599. return (PNG_INFO_tIME);
  186600. }
  186601. return (0);
  186602. }
  186603. #endif
  186604. #if defined(PNG_tRNS_SUPPORTED)
  186605. png_uint_32 PNGAPI
  186606. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186607. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186608. {
  186609. png_uint_32 retval = 0;
  186610. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186611. {
  186612. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186613. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186614. {
  186615. if (trans != NULL)
  186616. {
  186617. *trans = info_ptr->trans;
  186618. retval |= PNG_INFO_tRNS;
  186619. }
  186620. if (trans_values != NULL)
  186621. *trans_values = &(info_ptr->trans_values);
  186622. }
  186623. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186624. {
  186625. if (trans_values != NULL)
  186626. {
  186627. *trans_values = &(info_ptr->trans_values);
  186628. retval |= PNG_INFO_tRNS;
  186629. }
  186630. if(trans != NULL)
  186631. *trans = NULL;
  186632. }
  186633. if(num_trans != NULL)
  186634. {
  186635. *num_trans = info_ptr->num_trans;
  186636. retval |= PNG_INFO_tRNS;
  186637. }
  186638. }
  186639. return (retval);
  186640. }
  186641. #endif
  186642. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186643. png_uint_32 PNGAPI
  186644. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186645. png_unknown_chunkpp unknowns)
  186646. {
  186647. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186648. {
  186649. *unknowns = info_ptr->unknown_chunks;
  186650. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186651. }
  186652. return (0);
  186653. }
  186654. #endif
  186655. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186656. png_byte PNGAPI
  186657. png_get_rgb_to_gray_status (png_structp png_ptr)
  186658. {
  186659. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186660. }
  186661. #endif
  186662. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186663. png_voidp PNGAPI
  186664. png_get_user_chunk_ptr(png_structp png_ptr)
  186665. {
  186666. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186667. }
  186668. #endif
  186669. #ifdef PNG_WRITE_SUPPORTED
  186670. png_uint_32 PNGAPI
  186671. png_get_compression_buffer_size(png_structp png_ptr)
  186672. {
  186673. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186674. }
  186675. #endif
  186676. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186677. #ifndef PNG_1_0_X
  186678. /* this function was added to libpng 1.2.0 and should exist by default */
  186679. png_uint_32 PNGAPI
  186680. png_get_asm_flags (png_structp png_ptr)
  186681. {
  186682. /* obsolete, to be removed from libpng-1.4.0 */
  186683. return (png_ptr? 0L: 0L);
  186684. }
  186685. /* this function was added to libpng 1.2.0 and should exist by default */
  186686. png_uint_32 PNGAPI
  186687. png_get_asm_flagmask (int flag_select)
  186688. {
  186689. /* obsolete, to be removed from libpng-1.4.0 */
  186690. flag_select=flag_select;
  186691. return 0L;
  186692. }
  186693. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186694. /* this function was added to libpng 1.2.0 */
  186695. png_uint_32 PNGAPI
  186696. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186697. {
  186698. /* obsolete, to be removed from libpng-1.4.0 */
  186699. flag_select=flag_select;
  186700. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186701. return 0L;
  186702. }
  186703. /* this function was added to libpng 1.2.0 */
  186704. png_byte PNGAPI
  186705. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186706. {
  186707. /* obsolete, to be removed from libpng-1.4.0 */
  186708. return (png_ptr? 0: 0);
  186709. }
  186710. /* this function was added to libpng 1.2.0 */
  186711. png_uint_32 PNGAPI
  186712. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186713. {
  186714. /* obsolete, to be removed from libpng-1.4.0 */
  186715. return (png_ptr? 0L: 0L);
  186716. }
  186717. #endif /* ?PNG_1_0_X */
  186718. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186719. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186720. /* these functions were added to libpng 1.2.6 */
  186721. png_uint_32 PNGAPI
  186722. png_get_user_width_max (png_structp png_ptr)
  186723. {
  186724. return (png_ptr? png_ptr->user_width_max : 0);
  186725. }
  186726. png_uint_32 PNGAPI
  186727. png_get_user_height_max (png_structp png_ptr)
  186728. {
  186729. return (png_ptr? png_ptr->user_height_max : 0);
  186730. }
  186731. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186732. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186733. /*** End of inlined file: pngget.c ***/
  186734. /*** Start of inlined file: pngmem.c ***/
  186735. /* pngmem.c - stub functions for memory allocation
  186736. *
  186737. * Last changed in libpng 1.2.13 November 13, 2006
  186738. * For conditions of distribution and use, see copyright notice in png.h
  186739. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186740. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186741. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186742. *
  186743. * This file provides a location for all memory allocation. Users who
  186744. * need special memory handling are expected to supply replacement
  186745. * functions for png_malloc() and png_free(), and to use
  186746. * png_create_read_struct_2() and png_create_write_struct_2() to
  186747. * identify the replacement functions.
  186748. */
  186749. #define PNG_INTERNAL
  186750. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186751. /* Borland DOS special memory handler */
  186752. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186753. /* if you change this, be sure to change the one in png.h also */
  186754. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186755. by a single call to calloc() if this is thought to improve performance. */
  186756. png_voidp /* PRIVATE */
  186757. png_create_struct(int type)
  186758. {
  186759. #ifdef PNG_USER_MEM_SUPPORTED
  186760. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186761. }
  186762. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186763. png_voidp /* PRIVATE */
  186764. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186765. {
  186766. #endif /* PNG_USER_MEM_SUPPORTED */
  186767. png_size_t size;
  186768. png_voidp struct_ptr;
  186769. if (type == PNG_STRUCT_INFO)
  186770. size = png_sizeof(png_info);
  186771. else if (type == PNG_STRUCT_PNG)
  186772. size = png_sizeof(png_struct);
  186773. else
  186774. return (png_get_copyright(NULL));
  186775. #ifdef PNG_USER_MEM_SUPPORTED
  186776. if(malloc_fn != NULL)
  186777. {
  186778. png_struct dummy_struct;
  186779. png_structp png_ptr = &dummy_struct;
  186780. png_ptr->mem_ptr=mem_ptr;
  186781. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186782. }
  186783. else
  186784. #endif /* PNG_USER_MEM_SUPPORTED */
  186785. struct_ptr = (png_voidp)farmalloc(size);
  186786. if (struct_ptr != NULL)
  186787. png_memset(struct_ptr, 0, size);
  186788. return (struct_ptr);
  186789. }
  186790. /* Free memory allocated by a png_create_struct() call */
  186791. void /* PRIVATE */
  186792. png_destroy_struct(png_voidp struct_ptr)
  186793. {
  186794. #ifdef PNG_USER_MEM_SUPPORTED
  186795. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186796. }
  186797. /* Free memory allocated by a png_create_struct() call */
  186798. void /* PRIVATE */
  186799. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186800. png_voidp mem_ptr)
  186801. {
  186802. #endif
  186803. if (struct_ptr != NULL)
  186804. {
  186805. #ifdef PNG_USER_MEM_SUPPORTED
  186806. if(free_fn != NULL)
  186807. {
  186808. png_struct dummy_struct;
  186809. png_structp png_ptr = &dummy_struct;
  186810. png_ptr->mem_ptr=mem_ptr;
  186811. (*(free_fn))(png_ptr, struct_ptr);
  186812. return;
  186813. }
  186814. #endif /* PNG_USER_MEM_SUPPORTED */
  186815. farfree (struct_ptr);
  186816. }
  186817. }
  186818. /* Allocate memory. For reasonable files, size should never exceed
  186819. * 64K. However, zlib may allocate more then 64K if you don't tell
  186820. * it not to. See zconf.h and png.h for more information. zlib does
  186821. * need to allocate exactly 64K, so whatever you call here must
  186822. * have the ability to do that.
  186823. *
  186824. * Borland seems to have a problem in DOS mode for exactly 64K.
  186825. * It gives you a segment with an offset of 8 (perhaps to store its
  186826. * memory stuff). zlib doesn't like this at all, so we have to
  186827. * detect and deal with it. This code should not be needed in
  186828. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186829. * been updated by Alexander Lehmann for version 0.89 to waste less
  186830. * memory.
  186831. *
  186832. * Note that we can't use png_size_t for the "size" declaration,
  186833. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186834. * result, we would be truncating potentially larger memory requests
  186835. * (which should cause a fatal error) and introducing major problems.
  186836. */
  186837. png_voidp PNGAPI
  186838. png_malloc(png_structp png_ptr, png_uint_32 size)
  186839. {
  186840. png_voidp ret;
  186841. if (png_ptr == NULL || size == 0)
  186842. return (NULL);
  186843. #ifdef PNG_USER_MEM_SUPPORTED
  186844. if(png_ptr->malloc_fn != NULL)
  186845. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186846. else
  186847. ret = (png_malloc_default(png_ptr, size));
  186848. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186849. png_error(png_ptr, "Out of memory!");
  186850. return (ret);
  186851. }
  186852. png_voidp PNGAPI
  186853. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186854. {
  186855. png_voidp ret;
  186856. #endif /* PNG_USER_MEM_SUPPORTED */
  186857. if (png_ptr == NULL || size == 0)
  186858. return (NULL);
  186859. #ifdef PNG_MAX_MALLOC_64K
  186860. if (size > (png_uint_32)65536L)
  186861. {
  186862. png_warning(png_ptr, "Cannot Allocate > 64K");
  186863. ret = NULL;
  186864. }
  186865. else
  186866. #endif
  186867. if (size != (size_t)size)
  186868. ret = NULL;
  186869. else if (size == (png_uint_32)65536L)
  186870. {
  186871. if (png_ptr->offset_table == NULL)
  186872. {
  186873. /* try to see if we need to do any of this fancy stuff */
  186874. ret = farmalloc(size);
  186875. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186876. {
  186877. int num_blocks;
  186878. png_uint_32 total_size;
  186879. png_bytep table;
  186880. int i;
  186881. png_byte huge * hptr;
  186882. if (ret != NULL)
  186883. {
  186884. farfree(ret);
  186885. ret = NULL;
  186886. }
  186887. if(png_ptr->zlib_window_bits > 14)
  186888. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186889. else
  186890. num_blocks = 1;
  186891. if (png_ptr->zlib_mem_level >= 7)
  186892. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186893. else
  186894. num_blocks++;
  186895. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186896. table = farmalloc(total_size);
  186897. if (table == NULL)
  186898. {
  186899. #ifndef PNG_USER_MEM_SUPPORTED
  186900. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186901. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186902. else
  186903. png_warning(png_ptr, "Out Of Memory.");
  186904. #endif
  186905. return (NULL);
  186906. }
  186907. if ((png_size_t)table & 0xfff0)
  186908. {
  186909. #ifndef PNG_USER_MEM_SUPPORTED
  186910. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186911. png_error(png_ptr,
  186912. "Farmalloc didn't return normalized pointer");
  186913. else
  186914. png_warning(png_ptr,
  186915. "Farmalloc didn't return normalized pointer");
  186916. #endif
  186917. return (NULL);
  186918. }
  186919. png_ptr->offset_table = table;
  186920. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186921. png_sizeof (png_bytep));
  186922. if (png_ptr->offset_table_ptr == NULL)
  186923. {
  186924. #ifndef PNG_USER_MEM_SUPPORTED
  186925. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186926. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186927. else
  186928. png_warning(png_ptr, "Out Of memory.");
  186929. #endif
  186930. return (NULL);
  186931. }
  186932. hptr = (png_byte huge *)table;
  186933. if ((png_size_t)hptr & 0xf)
  186934. {
  186935. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186936. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186937. }
  186938. for (i = 0; i < num_blocks; i++)
  186939. {
  186940. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186941. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186942. }
  186943. png_ptr->offset_table_number = num_blocks;
  186944. png_ptr->offset_table_count = 0;
  186945. png_ptr->offset_table_count_free = 0;
  186946. }
  186947. }
  186948. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186949. {
  186950. #ifndef PNG_USER_MEM_SUPPORTED
  186951. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186952. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186953. else
  186954. png_warning(png_ptr, "Out of Memory.");
  186955. #endif
  186956. return (NULL);
  186957. }
  186958. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186959. }
  186960. else
  186961. ret = farmalloc(size);
  186962. #ifndef PNG_USER_MEM_SUPPORTED
  186963. if (ret == NULL)
  186964. {
  186965. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186966. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186967. else
  186968. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186969. }
  186970. #endif
  186971. return (ret);
  186972. }
  186973. /* free a pointer allocated by png_malloc(). In the default
  186974. configuration, png_ptr is not used, but is passed in case it
  186975. is needed. If ptr is NULL, return without taking any action. */
  186976. void PNGAPI
  186977. png_free(png_structp png_ptr, png_voidp ptr)
  186978. {
  186979. if (png_ptr == NULL || ptr == NULL)
  186980. return;
  186981. #ifdef PNG_USER_MEM_SUPPORTED
  186982. if (png_ptr->free_fn != NULL)
  186983. {
  186984. (*(png_ptr->free_fn))(png_ptr, ptr);
  186985. return;
  186986. }
  186987. else png_free_default(png_ptr, ptr);
  186988. }
  186989. void PNGAPI
  186990. png_free_default(png_structp png_ptr, png_voidp ptr)
  186991. {
  186992. #endif /* PNG_USER_MEM_SUPPORTED */
  186993. if(png_ptr == NULL) return;
  186994. if (png_ptr->offset_table != NULL)
  186995. {
  186996. int i;
  186997. for (i = 0; i < png_ptr->offset_table_count; i++)
  186998. {
  186999. if (ptr == png_ptr->offset_table_ptr[i])
  187000. {
  187001. ptr = NULL;
  187002. png_ptr->offset_table_count_free++;
  187003. break;
  187004. }
  187005. }
  187006. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  187007. {
  187008. farfree(png_ptr->offset_table);
  187009. farfree(png_ptr->offset_table_ptr);
  187010. png_ptr->offset_table = NULL;
  187011. png_ptr->offset_table_ptr = NULL;
  187012. }
  187013. }
  187014. if (ptr != NULL)
  187015. {
  187016. farfree(ptr);
  187017. }
  187018. }
  187019. #else /* Not the Borland DOS special memory handler */
  187020. /* Allocate memory for a png_struct or a png_info. The malloc and
  187021. memset can be replaced by a single call to calloc() if this is thought
  187022. to improve performance noticably. */
  187023. png_voidp /* PRIVATE */
  187024. png_create_struct(int type)
  187025. {
  187026. #ifdef PNG_USER_MEM_SUPPORTED
  187027. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187028. }
  187029. /* Allocate memory for a png_struct or a png_info. The malloc and
  187030. memset can be replaced by a single call to calloc() if this is thought
  187031. to improve performance noticably. */
  187032. png_voidp /* PRIVATE */
  187033. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187034. {
  187035. #endif /* PNG_USER_MEM_SUPPORTED */
  187036. png_size_t size;
  187037. png_voidp struct_ptr;
  187038. if (type == PNG_STRUCT_INFO)
  187039. size = png_sizeof(png_info);
  187040. else if (type == PNG_STRUCT_PNG)
  187041. size = png_sizeof(png_struct);
  187042. else
  187043. return (NULL);
  187044. #ifdef PNG_USER_MEM_SUPPORTED
  187045. if(malloc_fn != NULL)
  187046. {
  187047. png_struct dummy_struct;
  187048. png_structp png_ptr = &dummy_struct;
  187049. png_ptr->mem_ptr=mem_ptr;
  187050. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187051. if (struct_ptr != NULL)
  187052. png_memset(struct_ptr, 0, size);
  187053. return (struct_ptr);
  187054. }
  187055. #endif /* PNG_USER_MEM_SUPPORTED */
  187056. #if defined(__TURBOC__) && !defined(__FLAT__)
  187057. struct_ptr = (png_voidp)farmalloc(size);
  187058. #else
  187059. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187060. struct_ptr = (png_voidp)halloc(size,1);
  187061. # else
  187062. struct_ptr = (png_voidp)malloc(size);
  187063. # endif
  187064. #endif
  187065. if (struct_ptr != NULL)
  187066. png_memset(struct_ptr, 0, size);
  187067. return (struct_ptr);
  187068. }
  187069. /* Free memory allocated by a png_create_struct() call */
  187070. void /* PRIVATE */
  187071. png_destroy_struct(png_voidp struct_ptr)
  187072. {
  187073. #ifdef PNG_USER_MEM_SUPPORTED
  187074. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187075. }
  187076. /* Free memory allocated by a png_create_struct() call */
  187077. void /* PRIVATE */
  187078. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187079. png_voidp mem_ptr)
  187080. {
  187081. #endif /* PNG_USER_MEM_SUPPORTED */
  187082. if (struct_ptr != NULL)
  187083. {
  187084. #ifdef PNG_USER_MEM_SUPPORTED
  187085. if(free_fn != NULL)
  187086. {
  187087. png_struct dummy_struct;
  187088. png_structp png_ptr = &dummy_struct;
  187089. png_ptr->mem_ptr=mem_ptr;
  187090. (*(free_fn))(png_ptr, struct_ptr);
  187091. return;
  187092. }
  187093. #endif /* PNG_USER_MEM_SUPPORTED */
  187094. #if defined(__TURBOC__) && !defined(__FLAT__)
  187095. farfree(struct_ptr);
  187096. #else
  187097. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187098. hfree(struct_ptr);
  187099. # else
  187100. free(struct_ptr);
  187101. # endif
  187102. #endif
  187103. }
  187104. }
  187105. /* Allocate memory. For reasonable files, size should never exceed
  187106. 64K. However, zlib may allocate more then 64K if you don't tell
  187107. it not to. See zconf.h and png.h for more information. zlib does
  187108. need to allocate exactly 64K, so whatever you call here must
  187109. have the ability to do that. */
  187110. png_voidp PNGAPI
  187111. png_malloc(png_structp png_ptr, png_uint_32 size)
  187112. {
  187113. png_voidp ret;
  187114. #ifdef PNG_USER_MEM_SUPPORTED
  187115. if (png_ptr == NULL || size == 0)
  187116. return (NULL);
  187117. if(png_ptr->malloc_fn != NULL)
  187118. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187119. else
  187120. ret = (png_malloc_default(png_ptr, size));
  187121. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187122. png_error(png_ptr, "Out of Memory!");
  187123. return (ret);
  187124. }
  187125. png_voidp PNGAPI
  187126. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187127. {
  187128. png_voidp ret;
  187129. #endif /* PNG_USER_MEM_SUPPORTED */
  187130. if (png_ptr == NULL || size == 0)
  187131. return (NULL);
  187132. #ifdef PNG_MAX_MALLOC_64K
  187133. if (size > (png_uint_32)65536L)
  187134. {
  187135. #ifndef PNG_USER_MEM_SUPPORTED
  187136. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187137. png_error(png_ptr, "Cannot Allocate > 64K");
  187138. else
  187139. #endif
  187140. return NULL;
  187141. }
  187142. #endif
  187143. /* Check for overflow */
  187144. #if defined(__TURBOC__) && !defined(__FLAT__)
  187145. if (size != (unsigned long)size)
  187146. ret = NULL;
  187147. else
  187148. ret = farmalloc(size);
  187149. #else
  187150. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187151. if (size != (unsigned long)size)
  187152. ret = NULL;
  187153. else
  187154. ret = halloc(size, 1);
  187155. # else
  187156. if (size != (size_t)size)
  187157. ret = NULL;
  187158. else
  187159. ret = malloc((size_t)size);
  187160. # endif
  187161. #endif
  187162. #ifndef PNG_USER_MEM_SUPPORTED
  187163. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187164. png_error(png_ptr, "Out of Memory");
  187165. #endif
  187166. return (ret);
  187167. }
  187168. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187169. without taking any action. */
  187170. void PNGAPI
  187171. png_free(png_structp png_ptr, png_voidp ptr)
  187172. {
  187173. if (png_ptr == NULL || ptr == NULL)
  187174. return;
  187175. #ifdef PNG_USER_MEM_SUPPORTED
  187176. if (png_ptr->free_fn != NULL)
  187177. {
  187178. (*(png_ptr->free_fn))(png_ptr, ptr);
  187179. return;
  187180. }
  187181. else png_free_default(png_ptr, ptr);
  187182. }
  187183. void PNGAPI
  187184. png_free_default(png_structp png_ptr, png_voidp ptr)
  187185. {
  187186. if (png_ptr == NULL || ptr == NULL)
  187187. return;
  187188. #endif /* PNG_USER_MEM_SUPPORTED */
  187189. #if defined(__TURBOC__) && !defined(__FLAT__)
  187190. farfree(ptr);
  187191. #else
  187192. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187193. hfree(ptr);
  187194. # else
  187195. free(ptr);
  187196. # endif
  187197. #endif
  187198. }
  187199. #endif /* Not Borland DOS special memory handler */
  187200. #if defined(PNG_1_0_X)
  187201. # define png_malloc_warn png_malloc
  187202. #else
  187203. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187204. * function will set up png_malloc() to issue a png_warning and return NULL
  187205. * instead of issuing a png_error, if it fails to allocate the requested
  187206. * memory.
  187207. */
  187208. png_voidp PNGAPI
  187209. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187210. {
  187211. png_voidp ptr;
  187212. png_uint_32 save_flags;
  187213. if(png_ptr == NULL) return (NULL);
  187214. save_flags=png_ptr->flags;
  187215. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187216. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187217. png_ptr->flags=save_flags;
  187218. return(ptr);
  187219. }
  187220. #endif
  187221. png_voidp PNGAPI
  187222. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187223. png_uint_32 length)
  187224. {
  187225. png_size_t size;
  187226. size = (png_size_t)length;
  187227. if ((png_uint_32)size != length)
  187228. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187229. return(png_memcpy (s1, s2, size));
  187230. }
  187231. png_voidp PNGAPI
  187232. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187233. png_uint_32 length)
  187234. {
  187235. png_size_t size;
  187236. size = (png_size_t)length;
  187237. if ((png_uint_32)size != length)
  187238. png_error(png_ptr,"Overflow in png_memset_check.");
  187239. return (png_memset (s1, value, size));
  187240. }
  187241. #ifdef PNG_USER_MEM_SUPPORTED
  187242. /* This function is called when the application wants to use another method
  187243. * of allocating and freeing memory.
  187244. */
  187245. void PNGAPI
  187246. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187247. malloc_fn, png_free_ptr free_fn)
  187248. {
  187249. if(png_ptr != NULL) {
  187250. png_ptr->mem_ptr = mem_ptr;
  187251. png_ptr->malloc_fn = malloc_fn;
  187252. png_ptr->free_fn = free_fn;
  187253. }
  187254. }
  187255. /* This function returns a pointer to the mem_ptr associated with the user
  187256. * functions. The application should free any memory associated with this
  187257. * pointer before png_write_destroy and png_read_destroy are called.
  187258. */
  187259. png_voidp PNGAPI
  187260. png_get_mem_ptr(png_structp png_ptr)
  187261. {
  187262. if(png_ptr == NULL) return (NULL);
  187263. return ((png_voidp)png_ptr->mem_ptr);
  187264. }
  187265. #endif /* PNG_USER_MEM_SUPPORTED */
  187266. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187267. /*** End of inlined file: pngmem.c ***/
  187268. /*** Start of inlined file: pngread.c ***/
  187269. /* pngread.c - read a PNG file
  187270. *
  187271. * Last changed in libpng 1.2.20 September 7, 2007
  187272. * For conditions of distribution and use, see copyright notice in png.h
  187273. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187274. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187275. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187276. *
  187277. * This file contains routines that an application calls directly to
  187278. * read a PNG file or stream.
  187279. */
  187280. #define PNG_INTERNAL
  187281. #if defined(PNG_READ_SUPPORTED)
  187282. /* Create a PNG structure for reading, and allocate any memory needed. */
  187283. png_structp PNGAPI
  187284. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187285. png_error_ptr error_fn, png_error_ptr warn_fn)
  187286. {
  187287. #ifdef PNG_USER_MEM_SUPPORTED
  187288. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187289. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187290. }
  187291. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187292. png_structp PNGAPI
  187293. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187294. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187295. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187296. {
  187297. #endif /* PNG_USER_MEM_SUPPORTED */
  187298. png_structp png_ptr;
  187299. #ifdef PNG_SETJMP_SUPPORTED
  187300. #ifdef USE_FAR_KEYWORD
  187301. jmp_buf jmpbuf;
  187302. #endif
  187303. #endif
  187304. int i;
  187305. png_debug(1, "in png_create_read_struct\n");
  187306. #ifdef PNG_USER_MEM_SUPPORTED
  187307. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187308. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187309. #else
  187310. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187311. #endif
  187312. if (png_ptr == NULL)
  187313. return (NULL);
  187314. /* added at libpng-1.2.6 */
  187315. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187316. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187317. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187318. #endif
  187319. #ifdef PNG_SETJMP_SUPPORTED
  187320. #ifdef USE_FAR_KEYWORD
  187321. if (setjmp(jmpbuf))
  187322. #else
  187323. if (setjmp(png_ptr->jmpbuf))
  187324. #endif
  187325. {
  187326. png_free(png_ptr, png_ptr->zbuf);
  187327. png_ptr->zbuf=NULL;
  187328. #ifdef PNG_USER_MEM_SUPPORTED
  187329. png_destroy_struct_2((png_voidp)png_ptr,
  187330. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187331. #else
  187332. png_destroy_struct((png_voidp)png_ptr);
  187333. #endif
  187334. return (NULL);
  187335. }
  187336. #ifdef USE_FAR_KEYWORD
  187337. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187338. #endif
  187339. #endif
  187340. #ifdef PNG_USER_MEM_SUPPORTED
  187341. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187342. #endif
  187343. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187344. i=0;
  187345. do
  187346. {
  187347. if(user_png_ver[i] != png_libpng_ver[i])
  187348. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187349. } while (png_libpng_ver[i++]);
  187350. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187351. {
  187352. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187353. * we must recompile any applications that use any older library version.
  187354. * For versions after libpng 1.0, we will be compatible, so we need
  187355. * only check the first digit.
  187356. */
  187357. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187358. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187359. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187360. {
  187361. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187362. char msg[80];
  187363. if (user_png_ver)
  187364. {
  187365. png_snprintf(msg, 80,
  187366. "Application was compiled with png.h from libpng-%.20s",
  187367. user_png_ver);
  187368. png_warning(png_ptr, msg);
  187369. }
  187370. png_snprintf(msg, 80,
  187371. "Application is running with png.c from libpng-%.20s",
  187372. png_libpng_ver);
  187373. png_warning(png_ptr, msg);
  187374. #endif
  187375. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187376. png_ptr->flags=0;
  187377. #endif
  187378. png_error(png_ptr,
  187379. "Incompatible libpng version in application and library");
  187380. }
  187381. }
  187382. /* initialize zbuf - compression buffer */
  187383. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187384. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187385. (png_uint_32)png_ptr->zbuf_size);
  187386. png_ptr->zstream.zalloc = png_zalloc;
  187387. png_ptr->zstream.zfree = png_zfree;
  187388. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187389. switch (inflateInit(&png_ptr->zstream))
  187390. {
  187391. case Z_OK: /* Do nothing */ break;
  187392. case Z_MEM_ERROR:
  187393. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187394. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187395. default: png_error(png_ptr, "Unknown zlib error");
  187396. }
  187397. png_ptr->zstream.next_out = png_ptr->zbuf;
  187398. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187399. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187400. #ifdef PNG_SETJMP_SUPPORTED
  187401. /* Applications that neglect to set up their own setjmp() and then encounter
  187402. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187403. abort instead of returning. */
  187404. #ifdef USE_FAR_KEYWORD
  187405. if (setjmp(jmpbuf))
  187406. PNG_ABORT();
  187407. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187408. #else
  187409. if (setjmp(png_ptr->jmpbuf))
  187410. PNG_ABORT();
  187411. #endif
  187412. #endif
  187413. return (png_ptr);
  187414. }
  187415. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187416. /* Initialize PNG structure for reading, and allocate any memory needed.
  187417. This interface is deprecated in favour of the png_create_read_struct(),
  187418. and it will disappear as of libpng-1.3.0. */
  187419. #undef png_read_init
  187420. void PNGAPI
  187421. png_read_init(png_structp png_ptr)
  187422. {
  187423. /* We only come here via pre-1.0.7-compiled applications */
  187424. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187425. }
  187426. void PNGAPI
  187427. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187428. png_size_t png_struct_size, png_size_t png_info_size)
  187429. {
  187430. /* We only come here via pre-1.0.12-compiled applications */
  187431. if(png_ptr == NULL) return;
  187432. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187433. if(png_sizeof(png_struct) > png_struct_size ||
  187434. png_sizeof(png_info) > png_info_size)
  187435. {
  187436. char msg[80];
  187437. png_ptr->warning_fn=NULL;
  187438. if (user_png_ver)
  187439. {
  187440. png_snprintf(msg, 80,
  187441. "Application was compiled with png.h from libpng-%.20s",
  187442. user_png_ver);
  187443. png_warning(png_ptr, msg);
  187444. }
  187445. png_snprintf(msg, 80,
  187446. "Application is running with png.c from libpng-%.20s",
  187447. png_libpng_ver);
  187448. png_warning(png_ptr, msg);
  187449. }
  187450. #endif
  187451. if(png_sizeof(png_struct) > png_struct_size)
  187452. {
  187453. png_ptr->error_fn=NULL;
  187454. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187455. png_ptr->flags=0;
  187456. #endif
  187457. png_error(png_ptr,
  187458. "The png struct allocated by the application for reading is too small.");
  187459. }
  187460. if(png_sizeof(png_info) > png_info_size)
  187461. {
  187462. png_ptr->error_fn=NULL;
  187463. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187464. png_ptr->flags=0;
  187465. #endif
  187466. png_error(png_ptr,
  187467. "The info struct allocated by application for reading is too small.");
  187468. }
  187469. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187470. }
  187471. #endif /* PNG_1_0_X || PNG_1_2_X */
  187472. void PNGAPI
  187473. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187474. png_size_t png_struct_size)
  187475. {
  187476. #ifdef PNG_SETJMP_SUPPORTED
  187477. jmp_buf tmp_jmp; /* to save current jump buffer */
  187478. #endif
  187479. int i=0;
  187480. png_structp png_ptr=*ptr_ptr;
  187481. if(png_ptr == NULL) return;
  187482. do
  187483. {
  187484. if(user_png_ver[i] != png_libpng_ver[i])
  187485. {
  187486. #ifdef PNG_LEGACY_SUPPORTED
  187487. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187488. #else
  187489. png_ptr->warning_fn=NULL;
  187490. png_warning(png_ptr,
  187491. "Application uses deprecated png_read_init() and should be recompiled.");
  187492. break;
  187493. #endif
  187494. }
  187495. } while (png_libpng_ver[i++]);
  187496. png_debug(1, "in png_read_init_3\n");
  187497. #ifdef PNG_SETJMP_SUPPORTED
  187498. /* save jump buffer and error functions */
  187499. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187500. #endif
  187501. if(png_sizeof(png_struct) > png_struct_size)
  187502. {
  187503. png_destroy_struct(png_ptr);
  187504. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187505. png_ptr = *ptr_ptr;
  187506. }
  187507. /* reset all variables to 0 */
  187508. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187509. #ifdef PNG_SETJMP_SUPPORTED
  187510. /* restore jump buffer */
  187511. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187512. #endif
  187513. /* added at libpng-1.2.6 */
  187514. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187515. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187516. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187517. #endif
  187518. /* initialize zbuf - compression buffer */
  187519. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187520. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187521. (png_uint_32)png_ptr->zbuf_size);
  187522. png_ptr->zstream.zalloc = png_zalloc;
  187523. png_ptr->zstream.zfree = png_zfree;
  187524. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187525. switch (inflateInit(&png_ptr->zstream))
  187526. {
  187527. case Z_OK: /* Do nothing */ break;
  187528. case Z_MEM_ERROR:
  187529. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187530. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187531. default: png_error(png_ptr, "Unknown zlib error");
  187532. }
  187533. png_ptr->zstream.next_out = png_ptr->zbuf;
  187534. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187535. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187536. }
  187537. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187538. /* Read the information before the actual image data. This has been
  187539. * changed in v0.90 to allow reading a file that already has the magic
  187540. * bytes read from the stream. You can tell libpng how many bytes have
  187541. * been read from the beginning of the stream (up to the maximum of 8)
  187542. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187543. * here. The application can then have access to the signature bytes we
  187544. * read if it is determined that this isn't a valid PNG file.
  187545. */
  187546. void PNGAPI
  187547. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187548. {
  187549. if(png_ptr == NULL) return;
  187550. png_debug(1, "in png_read_info\n");
  187551. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187552. if (png_ptr->sig_bytes < 8)
  187553. {
  187554. png_size_t num_checked = png_ptr->sig_bytes,
  187555. num_to_check = 8 - num_checked;
  187556. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187557. png_ptr->sig_bytes = 8;
  187558. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187559. {
  187560. if (num_checked < 4 &&
  187561. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187562. png_error(png_ptr, "Not a PNG file");
  187563. else
  187564. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187565. }
  187566. if (num_checked < 3)
  187567. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187568. }
  187569. for(;;)
  187570. {
  187571. #ifdef PNG_USE_LOCAL_ARRAYS
  187572. PNG_CONST PNG_IHDR;
  187573. PNG_CONST PNG_IDAT;
  187574. PNG_CONST PNG_IEND;
  187575. PNG_CONST PNG_PLTE;
  187576. #if defined(PNG_READ_bKGD_SUPPORTED)
  187577. PNG_CONST PNG_bKGD;
  187578. #endif
  187579. #if defined(PNG_READ_cHRM_SUPPORTED)
  187580. PNG_CONST PNG_cHRM;
  187581. #endif
  187582. #if defined(PNG_READ_gAMA_SUPPORTED)
  187583. PNG_CONST PNG_gAMA;
  187584. #endif
  187585. #if defined(PNG_READ_hIST_SUPPORTED)
  187586. PNG_CONST PNG_hIST;
  187587. #endif
  187588. #if defined(PNG_READ_iCCP_SUPPORTED)
  187589. PNG_CONST PNG_iCCP;
  187590. #endif
  187591. #if defined(PNG_READ_iTXt_SUPPORTED)
  187592. PNG_CONST PNG_iTXt;
  187593. #endif
  187594. #if defined(PNG_READ_oFFs_SUPPORTED)
  187595. PNG_CONST PNG_oFFs;
  187596. #endif
  187597. #if defined(PNG_READ_pCAL_SUPPORTED)
  187598. PNG_CONST PNG_pCAL;
  187599. #endif
  187600. #if defined(PNG_READ_pHYs_SUPPORTED)
  187601. PNG_CONST PNG_pHYs;
  187602. #endif
  187603. #if defined(PNG_READ_sBIT_SUPPORTED)
  187604. PNG_CONST PNG_sBIT;
  187605. #endif
  187606. #if defined(PNG_READ_sCAL_SUPPORTED)
  187607. PNG_CONST PNG_sCAL;
  187608. #endif
  187609. #if defined(PNG_READ_sPLT_SUPPORTED)
  187610. PNG_CONST PNG_sPLT;
  187611. #endif
  187612. #if defined(PNG_READ_sRGB_SUPPORTED)
  187613. PNG_CONST PNG_sRGB;
  187614. #endif
  187615. #if defined(PNG_READ_tEXt_SUPPORTED)
  187616. PNG_CONST PNG_tEXt;
  187617. #endif
  187618. #if defined(PNG_READ_tIME_SUPPORTED)
  187619. PNG_CONST PNG_tIME;
  187620. #endif
  187621. #if defined(PNG_READ_tRNS_SUPPORTED)
  187622. PNG_CONST PNG_tRNS;
  187623. #endif
  187624. #if defined(PNG_READ_zTXt_SUPPORTED)
  187625. PNG_CONST PNG_zTXt;
  187626. #endif
  187627. #endif /* PNG_USE_LOCAL_ARRAYS */
  187628. png_byte chunk_length[4];
  187629. png_uint_32 length;
  187630. png_read_data(png_ptr, chunk_length, 4);
  187631. length = png_get_uint_31(png_ptr,chunk_length);
  187632. png_reset_crc(png_ptr);
  187633. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187634. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187635. length);
  187636. /* This should be a binary subdivision search or a hash for
  187637. * matching the chunk name rather than a linear search.
  187638. */
  187639. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187640. if(png_ptr->mode & PNG_AFTER_IDAT)
  187641. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187642. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187643. png_handle_IHDR(png_ptr, info_ptr, length);
  187644. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187645. png_handle_IEND(png_ptr, info_ptr, length);
  187646. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187647. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187648. {
  187649. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187650. png_ptr->mode |= PNG_HAVE_IDAT;
  187651. png_handle_unknown(png_ptr, info_ptr, length);
  187652. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187653. png_ptr->mode |= PNG_HAVE_PLTE;
  187654. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187655. {
  187656. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187657. png_error(png_ptr, "Missing IHDR before IDAT");
  187658. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187659. !(png_ptr->mode & PNG_HAVE_PLTE))
  187660. png_error(png_ptr, "Missing PLTE before IDAT");
  187661. break;
  187662. }
  187663. }
  187664. #endif
  187665. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187666. png_handle_PLTE(png_ptr, info_ptr, length);
  187667. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187668. {
  187669. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187670. png_error(png_ptr, "Missing IHDR before IDAT");
  187671. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187672. !(png_ptr->mode & PNG_HAVE_PLTE))
  187673. png_error(png_ptr, "Missing PLTE before IDAT");
  187674. png_ptr->idat_size = length;
  187675. png_ptr->mode |= PNG_HAVE_IDAT;
  187676. break;
  187677. }
  187678. #if defined(PNG_READ_bKGD_SUPPORTED)
  187679. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187680. png_handle_bKGD(png_ptr, info_ptr, length);
  187681. #endif
  187682. #if defined(PNG_READ_cHRM_SUPPORTED)
  187683. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187684. png_handle_cHRM(png_ptr, info_ptr, length);
  187685. #endif
  187686. #if defined(PNG_READ_gAMA_SUPPORTED)
  187687. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187688. png_handle_gAMA(png_ptr, info_ptr, length);
  187689. #endif
  187690. #if defined(PNG_READ_hIST_SUPPORTED)
  187691. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187692. png_handle_hIST(png_ptr, info_ptr, length);
  187693. #endif
  187694. #if defined(PNG_READ_oFFs_SUPPORTED)
  187695. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187696. png_handle_oFFs(png_ptr, info_ptr, length);
  187697. #endif
  187698. #if defined(PNG_READ_pCAL_SUPPORTED)
  187699. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187700. png_handle_pCAL(png_ptr, info_ptr, length);
  187701. #endif
  187702. #if defined(PNG_READ_sCAL_SUPPORTED)
  187703. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187704. png_handle_sCAL(png_ptr, info_ptr, length);
  187705. #endif
  187706. #if defined(PNG_READ_pHYs_SUPPORTED)
  187707. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187708. png_handle_pHYs(png_ptr, info_ptr, length);
  187709. #endif
  187710. #if defined(PNG_READ_sBIT_SUPPORTED)
  187711. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187712. png_handle_sBIT(png_ptr, info_ptr, length);
  187713. #endif
  187714. #if defined(PNG_READ_sRGB_SUPPORTED)
  187715. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187716. png_handle_sRGB(png_ptr, info_ptr, length);
  187717. #endif
  187718. #if defined(PNG_READ_iCCP_SUPPORTED)
  187719. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187720. png_handle_iCCP(png_ptr, info_ptr, length);
  187721. #endif
  187722. #if defined(PNG_READ_sPLT_SUPPORTED)
  187723. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187724. png_handle_sPLT(png_ptr, info_ptr, length);
  187725. #endif
  187726. #if defined(PNG_READ_tEXt_SUPPORTED)
  187727. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187728. png_handle_tEXt(png_ptr, info_ptr, length);
  187729. #endif
  187730. #if defined(PNG_READ_tIME_SUPPORTED)
  187731. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187732. png_handle_tIME(png_ptr, info_ptr, length);
  187733. #endif
  187734. #if defined(PNG_READ_tRNS_SUPPORTED)
  187735. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187736. png_handle_tRNS(png_ptr, info_ptr, length);
  187737. #endif
  187738. #if defined(PNG_READ_zTXt_SUPPORTED)
  187739. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187740. png_handle_zTXt(png_ptr, info_ptr, length);
  187741. #endif
  187742. #if defined(PNG_READ_iTXt_SUPPORTED)
  187743. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187744. png_handle_iTXt(png_ptr, info_ptr, length);
  187745. #endif
  187746. else
  187747. png_handle_unknown(png_ptr, info_ptr, length);
  187748. }
  187749. }
  187750. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187751. /* optional call to update the users info_ptr structure */
  187752. void PNGAPI
  187753. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187754. {
  187755. png_debug(1, "in png_read_update_info\n");
  187756. if(png_ptr == NULL) return;
  187757. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187758. png_read_start_row(png_ptr);
  187759. else
  187760. png_warning(png_ptr,
  187761. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187762. png_read_transform_info(png_ptr, info_ptr);
  187763. }
  187764. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187765. /* Initialize palette, background, etc, after transformations
  187766. * are set, but before any reading takes place. This allows
  187767. * the user to obtain a gamma-corrected palette, for example.
  187768. * If the user doesn't call this, we will do it ourselves.
  187769. */
  187770. void PNGAPI
  187771. png_start_read_image(png_structp png_ptr)
  187772. {
  187773. png_debug(1, "in png_start_read_image\n");
  187774. if(png_ptr == NULL) return;
  187775. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187776. png_read_start_row(png_ptr);
  187777. }
  187778. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187779. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187780. void PNGAPI
  187781. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187782. {
  187783. #ifdef PNG_USE_LOCAL_ARRAYS
  187784. PNG_CONST PNG_IDAT;
  187785. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187786. 0xff};
  187787. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187788. #endif
  187789. int ret;
  187790. if(png_ptr == NULL) return;
  187791. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187792. png_ptr->row_number, png_ptr->pass);
  187793. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187794. png_read_start_row(png_ptr);
  187795. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187796. {
  187797. /* check for transforms that have been set but were defined out */
  187798. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187799. if (png_ptr->transformations & PNG_INVERT_MONO)
  187800. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187801. #endif
  187802. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187803. if (png_ptr->transformations & PNG_FILLER)
  187804. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187805. #endif
  187806. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187807. if (png_ptr->transformations & PNG_PACKSWAP)
  187808. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187809. #endif
  187810. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187811. if (png_ptr->transformations & PNG_PACK)
  187812. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187813. #endif
  187814. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187815. if (png_ptr->transformations & PNG_SHIFT)
  187816. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187817. #endif
  187818. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187819. if (png_ptr->transformations & PNG_BGR)
  187820. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187821. #endif
  187822. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187823. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187824. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187825. #endif
  187826. }
  187827. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187828. /* if interlaced and we do not need a new row, combine row and return */
  187829. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187830. {
  187831. switch (png_ptr->pass)
  187832. {
  187833. case 0:
  187834. if (png_ptr->row_number & 0x07)
  187835. {
  187836. if (dsp_row != NULL)
  187837. png_combine_row(png_ptr, dsp_row,
  187838. png_pass_dsp_mask[png_ptr->pass]);
  187839. png_read_finish_row(png_ptr);
  187840. return;
  187841. }
  187842. break;
  187843. case 1:
  187844. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187845. {
  187846. if (dsp_row != NULL)
  187847. png_combine_row(png_ptr, dsp_row,
  187848. png_pass_dsp_mask[png_ptr->pass]);
  187849. png_read_finish_row(png_ptr);
  187850. return;
  187851. }
  187852. break;
  187853. case 2:
  187854. if ((png_ptr->row_number & 0x07) != 4)
  187855. {
  187856. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187857. png_combine_row(png_ptr, dsp_row,
  187858. png_pass_dsp_mask[png_ptr->pass]);
  187859. png_read_finish_row(png_ptr);
  187860. return;
  187861. }
  187862. break;
  187863. case 3:
  187864. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187865. {
  187866. if (dsp_row != NULL)
  187867. png_combine_row(png_ptr, dsp_row,
  187868. png_pass_dsp_mask[png_ptr->pass]);
  187869. png_read_finish_row(png_ptr);
  187870. return;
  187871. }
  187872. break;
  187873. case 4:
  187874. if ((png_ptr->row_number & 3) != 2)
  187875. {
  187876. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187877. png_combine_row(png_ptr, dsp_row,
  187878. png_pass_dsp_mask[png_ptr->pass]);
  187879. png_read_finish_row(png_ptr);
  187880. return;
  187881. }
  187882. break;
  187883. case 5:
  187884. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187885. {
  187886. if (dsp_row != NULL)
  187887. png_combine_row(png_ptr, dsp_row,
  187888. png_pass_dsp_mask[png_ptr->pass]);
  187889. png_read_finish_row(png_ptr);
  187890. return;
  187891. }
  187892. break;
  187893. case 6:
  187894. if (!(png_ptr->row_number & 1))
  187895. {
  187896. png_read_finish_row(png_ptr);
  187897. return;
  187898. }
  187899. break;
  187900. }
  187901. }
  187902. #endif
  187903. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187904. png_error(png_ptr, "Invalid attempt to read row data");
  187905. png_ptr->zstream.next_out = png_ptr->row_buf;
  187906. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187907. do
  187908. {
  187909. if (!(png_ptr->zstream.avail_in))
  187910. {
  187911. while (!png_ptr->idat_size)
  187912. {
  187913. png_byte chunk_length[4];
  187914. png_crc_finish(png_ptr, 0);
  187915. png_read_data(png_ptr, chunk_length, 4);
  187916. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187917. png_reset_crc(png_ptr);
  187918. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187919. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187920. png_error(png_ptr, "Not enough image data");
  187921. }
  187922. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187923. png_ptr->zstream.next_in = png_ptr->zbuf;
  187924. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187925. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187926. png_crc_read(png_ptr, png_ptr->zbuf,
  187927. (png_size_t)png_ptr->zstream.avail_in);
  187928. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187929. }
  187930. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187931. if (ret == Z_STREAM_END)
  187932. {
  187933. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187934. png_ptr->idat_size)
  187935. png_error(png_ptr, "Extra compressed data");
  187936. png_ptr->mode |= PNG_AFTER_IDAT;
  187937. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187938. break;
  187939. }
  187940. if (ret != Z_OK)
  187941. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187942. "Decompression error");
  187943. } while (png_ptr->zstream.avail_out);
  187944. png_ptr->row_info.color_type = png_ptr->color_type;
  187945. png_ptr->row_info.width = png_ptr->iwidth;
  187946. png_ptr->row_info.channels = png_ptr->channels;
  187947. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187948. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187949. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187950. png_ptr->row_info.width);
  187951. if(png_ptr->row_buf[0])
  187952. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187953. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187954. (int)(png_ptr->row_buf[0]));
  187955. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187956. png_ptr->rowbytes + 1);
  187957. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187958. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187959. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187960. {
  187961. /* Intrapixel differencing */
  187962. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187963. }
  187964. #endif
  187965. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187966. png_do_read_transformations(png_ptr);
  187967. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187968. /* blow up interlaced rows to full size */
  187969. if (png_ptr->interlaced &&
  187970. (png_ptr->transformations & PNG_INTERLACE))
  187971. {
  187972. if (png_ptr->pass < 6)
  187973. /* old interface (pre-1.0.9):
  187974. png_do_read_interlace(&(png_ptr->row_info),
  187975. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187976. */
  187977. png_do_read_interlace(png_ptr);
  187978. if (dsp_row != NULL)
  187979. png_combine_row(png_ptr, dsp_row,
  187980. png_pass_dsp_mask[png_ptr->pass]);
  187981. if (row != NULL)
  187982. png_combine_row(png_ptr, row,
  187983. png_pass_mask[png_ptr->pass]);
  187984. }
  187985. else
  187986. #endif
  187987. {
  187988. if (row != NULL)
  187989. png_combine_row(png_ptr, row, 0xff);
  187990. if (dsp_row != NULL)
  187991. png_combine_row(png_ptr, dsp_row, 0xff);
  187992. }
  187993. png_read_finish_row(png_ptr);
  187994. if (png_ptr->read_row_fn != NULL)
  187995. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187996. }
  187997. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187998. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187999. /* Read one or more rows of image data. If the image is interlaced,
  188000. * and png_set_interlace_handling() has been called, the rows need to
  188001. * contain the contents of the rows from the previous pass. If the
  188002. * image has alpha or transparency, and png_handle_alpha()[*] has been
  188003. * called, the rows contents must be initialized to the contents of the
  188004. * screen.
  188005. *
  188006. * "row" holds the actual image, and pixels are placed in it
  188007. * as they arrive. If the image is displayed after each pass, it will
  188008. * appear to "sparkle" in. "display_row" can be used to display a
  188009. * "chunky" progressive image, with finer detail added as it becomes
  188010. * available. If you do not want this "chunky" display, you may pass
  188011. * NULL for display_row. If you do not want the sparkle display, and
  188012. * you have not called png_handle_alpha(), you may pass NULL for rows.
  188013. * If you have called png_handle_alpha(), and the image has either an
  188014. * alpha channel or a transparency chunk, you must provide a buffer for
  188015. * rows. In this case, you do not have to provide a display_row buffer
  188016. * also, but you may. If the image is not interlaced, or if you have
  188017. * not called png_set_interlace_handling(), the display_row buffer will
  188018. * be ignored, so pass NULL to it.
  188019. *
  188020. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188021. */
  188022. void PNGAPI
  188023. png_read_rows(png_structp png_ptr, png_bytepp row,
  188024. png_bytepp display_row, png_uint_32 num_rows)
  188025. {
  188026. png_uint_32 i;
  188027. png_bytepp rp;
  188028. png_bytepp dp;
  188029. png_debug(1, "in png_read_rows\n");
  188030. if(png_ptr == NULL) return;
  188031. rp = row;
  188032. dp = display_row;
  188033. if (rp != NULL && dp != NULL)
  188034. for (i = 0; i < num_rows; i++)
  188035. {
  188036. png_bytep rptr = *rp++;
  188037. png_bytep dptr = *dp++;
  188038. png_read_row(png_ptr, rptr, dptr);
  188039. }
  188040. else if(rp != NULL)
  188041. for (i = 0; i < num_rows; i++)
  188042. {
  188043. png_bytep rptr = *rp;
  188044. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188045. rp++;
  188046. }
  188047. else if(dp != NULL)
  188048. for (i = 0; i < num_rows; i++)
  188049. {
  188050. png_bytep dptr = *dp;
  188051. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188052. dp++;
  188053. }
  188054. }
  188055. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188056. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188057. /* Read the entire image. If the image has an alpha channel or a tRNS
  188058. * chunk, and you have called png_handle_alpha()[*], you will need to
  188059. * initialize the image to the current image that PNG will be overlaying.
  188060. * We set the num_rows again here, in case it was incorrectly set in
  188061. * png_read_start_row() by a call to png_read_update_info() or
  188062. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188063. * prior to either of these functions like it should have been. You can
  188064. * only call this function once. If you desire to have an image for
  188065. * each pass of a interlaced image, use png_read_rows() instead.
  188066. *
  188067. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188068. */
  188069. void PNGAPI
  188070. png_read_image(png_structp png_ptr, png_bytepp image)
  188071. {
  188072. png_uint_32 i,image_height;
  188073. int pass, j;
  188074. png_bytepp rp;
  188075. png_debug(1, "in png_read_image\n");
  188076. if(png_ptr == NULL) return;
  188077. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188078. pass = png_set_interlace_handling(png_ptr);
  188079. #else
  188080. if (png_ptr->interlaced)
  188081. png_error(png_ptr,
  188082. "Cannot read interlaced image -- interlace handler disabled.");
  188083. pass = 1;
  188084. #endif
  188085. image_height=png_ptr->height;
  188086. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188087. for (j = 0; j < pass; j++)
  188088. {
  188089. rp = image;
  188090. for (i = 0; i < image_height; i++)
  188091. {
  188092. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188093. rp++;
  188094. }
  188095. }
  188096. }
  188097. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188098. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188099. /* Read the end of the PNG file. Will not read past the end of the
  188100. * file, will verify the end is accurate, and will read any comments
  188101. * or time information at the end of the file, if info is not NULL.
  188102. */
  188103. void PNGAPI
  188104. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188105. {
  188106. png_byte chunk_length[4];
  188107. png_uint_32 length;
  188108. png_debug(1, "in png_read_end\n");
  188109. if(png_ptr == NULL) return;
  188110. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188111. do
  188112. {
  188113. #ifdef PNG_USE_LOCAL_ARRAYS
  188114. PNG_CONST PNG_IHDR;
  188115. PNG_CONST PNG_IDAT;
  188116. PNG_CONST PNG_IEND;
  188117. PNG_CONST PNG_PLTE;
  188118. #if defined(PNG_READ_bKGD_SUPPORTED)
  188119. PNG_CONST PNG_bKGD;
  188120. #endif
  188121. #if defined(PNG_READ_cHRM_SUPPORTED)
  188122. PNG_CONST PNG_cHRM;
  188123. #endif
  188124. #if defined(PNG_READ_gAMA_SUPPORTED)
  188125. PNG_CONST PNG_gAMA;
  188126. #endif
  188127. #if defined(PNG_READ_hIST_SUPPORTED)
  188128. PNG_CONST PNG_hIST;
  188129. #endif
  188130. #if defined(PNG_READ_iCCP_SUPPORTED)
  188131. PNG_CONST PNG_iCCP;
  188132. #endif
  188133. #if defined(PNG_READ_iTXt_SUPPORTED)
  188134. PNG_CONST PNG_iTXt;
  188135. #endif
  188136. #if defined(PNG_READ_oFFs_SUPPORTED)
  188137. PNG_CONST PNG_oFFs;
  188138. #endif
  188139. #if defined(PNG_READ_pCAL_SUPPORTED)
  188140. PNG_CONST PNG_pCAL;
  188141. #endif
  188142. #if defined(PNG_READ_pHYs_SUPPORTED)
  188143. PNG_CONST PNG_pHYs;
  188144. #endif
  188145. #if defined(PNG_READ_sBIT_SUPPORTED)
  188146. PNG_CONST PNG_sBIT;
  188147. #endif
  188148. #if defined(PNG_READ_sCAL_SUPPORTED)
  188149. PNG_CONST PNG_sCAL;
  188150. #endif
  188151. #if defined(PNG_READ_sPLT_SUPPORTED)
  188152. PNG_CONST PNG_sPLT;
  188153. #endif
  188154. #if defined(PNG_READ_sRGB_SUPPORTED)
  188155. PNG_CONST PNG_sRGB;
  188156. #endif
  188157. #if defined(PNG_READ_tEXt_SUPPORTED)
  188158. PNG_CONST PNG_tEXt;
  188159. #endif
  188160. #if defined(PNG_READ_tIME_SUPPORTED)
  188161. PNG_CONST PNG_tIME;
  188162. #endif
  188163. #if defined(PNG_READ_tRNS_SUPPORTED)
  188164. PNG_CONST PNG_tRNS;
  188165. #endif
  188166. #if defined(PNG_READ_zTXt_SUPPORTED)
  188167. PNG_CONST PNG_zTXt;
  188168. #endif
  188169. #endif /* PNG_USE_LOCAL_ARRAYS */
  188170. png_read_data(png_ptr, chunk_length, 4);
  188171. length = png_get_uint_31(png_ptr,chunk_length);
  188172. png_reset_crc(png_ptr);
  188173. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188174. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188175. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188176. png_handle_IHDR(png_ptr, info_ptr, length);
  188177. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188178. png_handle_IEND(png_ptr, info_ptr, length);
  188179. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188180. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188181. {
  188182. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188183. {
  188184. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188185. png_error(png_ptr, "Too many IDAT's found");
  188186. }
  188187. png_handle_unknown(png_ptr, info_ptr, length);
  188188. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188189. png_ptr->mode |= PNG_HAVE_PLTE;
  188190. }
  188191. #endif
  188192. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188193. {
  188194. /* Zero length IDATs are legal after the last IDAT has been
  188195. * read, but not after other chunks have been read.
  188196. */
  188197. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188198. png_error(png_ptr, "Too many IDAT's found");
  188199. png_crc_finish(png_ptr, length);
  188200. }
  188201. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188202. png_handle_PLTE(png_ptr, info_ptr, length);
  188203. #if defined(PNG_READ_bKGD_SUPPORTED)
  188204. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188205. png_handle_bKGD(png_ptr, info_ptr, length);
  188206. #endif
  188207. #if defined(PNG_READ_cHRM_SUPPORTED)
  188208. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188209. png_handle_cHRM(png_ptr, info_ptr, length);
  188210. #endif
  188211. #if defined(PNG_READ_gAMA_SUPPORTED)
  188212. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188213. png_handle_gAMA(png_ptr, info_ptr, length);
  188214. #endif
  188215. #if defined(PNG_READ_hIST_SUPPORTED)
  188216. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188217. png_handle_hIST(png_ptr, info_ptr, length);
  188218. #endif
  188219. #if defined(PNG_READ_oFFs_SUPPORTED)
  188220. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188221. png_handle_oFFs(png_ptr, info_ptr, length);
  188222. #endif
  188223. #if defined(PNG_READ_pCAL_SUPPORTED)
  188224. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188225. png_handle_pCAL(png_ptr, info_ptr, length);
  188226. #endif
  188227. #if defined(PNG_READ_sCAL_SUPPORTED)
  188228. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188229. png_handle_sCAL(png_ptr, info_ptr, length);
  188230. #endif
  188231. #if defined(PNG_READ_pHYs_SUPPORTED)
  188232. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188233. png_handle_pHYs(png_ptr, info_ptr, length);
  188234. #endif
  188235. #if defined(PNG_READ_sBIT_SUPPORTED)
  188236. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188237. png_handle_sBIT(png_ptr, info_ptr, length);
  188238. #endif
  188239. #if defined(PNG_READ_sRGB_SUPPORTED)
  188240. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188241. png_handle_sRGB(png_ptr, info_ptr, length);
  188242. #endif
  188243. #if defined(PNG_READ_iCCP_SUPPORTED)
  188244. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188245. png_handle_iCCP(png_ptr, info_ptr, length);
  188246. #endif
  188247. #if defined(PNG_READ_sPLT_SUPPORTED)
  188248. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188249. png_handle_sPLT(png_ptr, info_ptr, length);
  188250. #endif
  188251. #if defined(PNG_READ_tEXt_SUPPORTED)
  188252. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188253. png_handle_tEXt(png_ptr, info_ptr, length);
  188254. #endif
  188255. #if defined(PNG_READ_tIME_SUPPORTED)
  188256. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188257. png_handle_tIME(png_ptr, info_ptr, length);
  188258. #endif
  188259. #if defined(PNG_READ_tRNS_SUPPORTED)
  188260. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188261. png_handle_tRNS(png_ptr, info_ptr, length);
  188262. #endif
  188263. #if defined(PNG_READ_zTXt_SUPPORTED)
  188264. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188265. png_handle_zTXt(png_ptr, info_ptr, length);
  188266. #endif
  188267. #if defined(PNG_READ_iTXt_SUPPORTED)
  188268. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188269. png_handle_iTXt(png_ptr, info_ptr, length);
  188270. #endif
  188271. else
  188272. png_handle_unknown(png_ptr, info_ptr, length);
  188273. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188274. }
  188275. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188276. /* free all memory used by the read */
  188277. void PNGAPI
  188278. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188279. png_infopp end_info_ptr_ptr)
  188280. {
  188281. png_structp png_ptr = NULL;
  188282. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188283. #ifdef PNG_USER_MEM_SUPPORTED
  188284. png_free_ptr free_fn;
  188285. png_voidp mem_ptr;
  188286. #endif
  188287. png_debug(1, "in png_destroy_read_struct\n");
  188288. if (png_ptr_ptr != NULL)
  188289. png_ptr = *png_ptr_ptr;
  188290. if (info_ptr_ptr != NULL)
  188291. info_ptr = *info_ptr_ptr;
  188292. if (end_info_ptr_ptr != NULL)
  188293. end_info_ptr = *end_info_ptr_ptr;
  188294. #ifdef PNG_USER_MEM_SUPPORTED
  188295. free_fn = png_ptr->free_fn;
  188296. mem_ptr = png_ptr->mem_ptr;
  188297. #endif
  188298. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188299. if (info_ptr != NULL)
  188300. {
  188301. #if defined(PNG_TEXT_SUPPORTED)
  188302. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188303. #endif
  188304. #ifdef PNG_USER_MEM_SUPPORTED
  188305. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188306. (png_voidp)mem_ptr);
  188307. #else
  188308. png_destroy_struct((png_voidp)info_ptr);
  188309. #endif
  188310. *info_ptr_ptr = NULL;
  188311. }
  188312. if (end_info_ptr != NULL)
  188313. {
  188314. #if defined(PNG_READ_TEXT_SUPPORTED)
  188315. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188316. #endif
  188317. #ifdef PNG_USER_MEM_SUPPORTED
  188318. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188319. (png_voidp)mem_ptr);
  188320. #else
  188321. png_destroy_struct((png_voidp)end_info_ptr);
  188322. #endif
  188323. *end_info_ptr_ptr = NULL;
  188324. }
  188325. if (png_ptr != NULL)
  188326. {
  188327. #ifdef PNG_USER_MEM_SUPPORTED
  188328. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188329. (png_voidp)mem_ptr);
  188330. #else
  188331. png_destroy_struct((png_voidp)png_ptr);
  188332. #endif
  188333. *png_ptr_ptr = NULL;
  188334. }
  188335. }
  188336. /* free all memory used by the read (old method) */
  188337. void /* PRIVATE */
  188338. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188339. {
  188340. #ifdef PNG_SETJMP_SUPPORTED
  188341. jmp_buf tmp_jmp;
  188342. #endif
  188343. png_error_ptr error_fn;
  188344. png_error_ptr warning_fn;
  188345. png_voidp error_ptr;
  188346. #ifdef PNG_USER_MEM_SUPPORTED
  188347. png_free_ptr free_fn;
  188348. #endif
  188349. png_debug(1, "in png_read_destroy\n");
  188350. if (info_ptr != NULL)
  188351. png_info_destroy(png_ptr, info_ptr);
  188352. if (end_info_ptr != NULL)
  188353. png_info_destroy(png_ptr, end_info_ptr);
  188354. png_free(png_ptr, png_ptr->zbuf);
  188355. png_free(png_ptr, png_ptr->big_row_buf);
  188356. png_free(png_ptr, png_ptr->prev_row);
  188357. #if defined(PNG_READ_DITHER_SUPPORTED)
  188358. png_free(png_ptr, png_ptr->palette_lookup);
  188359. png_free(png_ptr, png_ptr->dither_index);
  188360. #endif
  188361. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188362. png_free(png_ptr, png_ptr->gamma_table);
  188363. #endif
  188364. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188365. png_free(png_ptr, png_ptr->gamma_from_1);
  188366. png_free(png_ptr, png_ptr->gamma_to_1);
  188367. #endif
  188368. #ifdef PNG_FREE_ME_SUPPORTED
  188369. if (png_ptr->free_me & PNG_FREE_PLTE)
  188370. png_zfree(png_ptr, png_ptr->palette);
  188371. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188372. #else
  188373. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188374. png_zfree(png_ptr, png_ptr->palette);
  188375. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188376. #endif
  188377. #if defined(PNG_tRNS_SUPPORTED) || \
  188378. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188379. #ifdef PNG_FREE_ME_SUPPORTED
  188380. if (png_ptr->free_me & PNG_FREE_TRNS)
  188381. png_free(png_ptr, png_ptr->trans);
  188382. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188383. #else
  188384. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188385. png_free(png_ptr, png_ptr->trans);
  188386. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188387. #endif
  188388. #endif
  188389. #if defined(PNG_READ_hIST_SUPPORTED)
  188390. #ifdef PNG_FREE_ME_SUPPORTED
  188391. if (png_ptr->free_me & PNG_FREE_HIST)
  188392. png_free(png_ptr, png_ptr->hist);
  188393. png_ptr->free_me &= ~PNG_FREE_HIST;
  188394. #else
  188395. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188396. png_free(png_ptr, png_ptr->hist);
  188397. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188398. #endif
  188399. #endif
  188400. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188401. if (png_ptr->gamma_16_table != NULL)
  188402. {
  188403. int i;
  188404. int istop = (1 << (8 - png_ptr->gamma_shift));
  188405. for (i = 0; i < istop; i++)
  188406. {
  188407. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188408. }
  188409. png_free(png_ptr, png_ptr->gamma_16_table);
  188410. }
  188411. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188412. if (png_ptr->gamma_16_from_1 != NULL)
  188413. {
  188414. int i;
  188415. int istop = (1 << (8 - png_ptr->gamma_shift));
  188416. for (i = 0; i < istop; i++)
  188417. {
  188418. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188419. }
  188420. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188421. }
  188422. if (png_ptr->gamma_16_to_1 != NULL)
  188423. {
  188424. int i;
  188425. int istop = (1 << (8 - png_ptr->gamma_shift));
  188426. for (i = 0; i < istop; i++)
  188427. {
  188428. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188429. }
  188430. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188431. }
  188432. #endif
  188433. #endif
  188434. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188435. png_free(png_ptr, png_ptr->time_buffer);
  188436. #endif
  188437. inflateEnd(&png_ptr->zstream);
  188438. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188439. png_free(png_ptr, png_ptr->save_buffer);
  188440. #endif
  188441. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188442. #ifdef PNG_TEXT_SUPPORTED
  188443. png_free(png_ptr, png_ptr->current_text);
  188444. #endif /* PNG_TEXT_SUPPORTED */
  188445. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188446. /* Save the important info out of the png_struct, in case it is
  188447. * being used again.
  188448. */
  188449. #ifdef PNG_SETJMP_SUPPORTED
  188450. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188451. #endif
  188452. error_fn = png_ptr->error_fn;
  188453. warning_fn = png_ptr->warning_fn;
  188454. error_ptr = png_ptr->error_ptr;
  188455. #ifdef PNG_USER_MEM_SUPPORTED
  188456. free_fn = png_ptr->free_fn;
  188457. #endif
  188458. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188459. png_ptr->error_fn = error_fn;
  188460. png_ptr->warning_fn = warning_fn;
  188461. png_ptr->error_ptr = error_ptr;
  188462. #ifdef PNG_USER_MEM_SUPPORTED
  188463. png_ptr->free_fn = free_fn;
  188464. #endif
  188465. #ifdef PNG_SETJMP_SUPPORTED
  188466. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188467. #endif
  188468. }
  188469. void PNGAPI
  188470. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188471. {
  188472. if(png_ptr == NULL) return;
  188473. png_ptr->read_row_fn = read_row_fn;
  188474. }
  188475. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188476. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188477. void PNGAPI
  188478. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188479. int transforms,
  188480. voidp params)
  188481. {
  188482. int row;
  188483. if(png_ptr == NULL) return;
  188484. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188485. /* invert the alpha channel from opacity to transparency
  188486. */
  188487. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188488. png_set_invert_alpha(png_ptr);
  188489. #endif
  188490. /* png_read_info() gives us all of the information from the
  188491. * PNG file before the first IDAT (image data chunk).
  188492. */
  188493. png_read_info(png_ptr, info_ptr);
  188494. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188495. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188496. /* -------------- image transformations start here ------------------- */
  188497. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188498. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188499. */
  188500. if (transforms & PNG_TRANSFORM_STRIP_16)
  188501. png_set_strip_16(png_ptr);
  188502. #endif
  188503. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188504. /* Strip alpha bytes from the input data without combining with
  188505. * the background (not recommended).
  188506. */
  188507. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188508. png_set_strip_alpha(png_ptr);
  188509. #endif
  188510. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188511. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188512. * byte into separate bytes (useful for paletted and grayscale images).
  188513. */
  188514. if (transforms & PNG_TRANSFORM_PACKING)
  188515. png_set_packing(png_ptr);
  188516. #endif
  188517. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188518. /* Change the order of packed pixels to least significant bit first
  188519. * (not useful if you are using png_set_packing).
  188520. */
  188521. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188522. png_set_packswap(png_ptr);
  188523. #endif
  188524. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188525. /* Expand paletted colors into true RGB triplets
  188526. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188527. * Expand paletted or RGB images with transparency to full alpha
  188528. * channels so the data will be available as RGBA quartets.
  188529. */
  188530. if (transforms & PNG_TRANSFORM_EXPAND)
  188531. if ((png_ptr->bit_depth < 8) ||
  188532. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188533. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188534. png_set_expand(png_ptr);
  188535. #endif
  188536. /* We don't handle background color or gamma transformation or dithering.
  188537. */
  188538. #if defined(PNG_READ_INVERT_SUPPORTED)
  188539. /* invert monochrome files to have 0 as white and 1 as black
  188540. */
  188541. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188542. png_set_invert_mono(png_ptr);
  188543. #endif
  188544. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188545. /* If you want to shift the pixel values from the range [0,255] or
  188546. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188547. * colors were originally in:
  188548. */
  188549. if ((transforms & PNG_TRANSFORM_SHIFT)
  188550. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188551. {
  188552. png_color_8p sig_bit;
  188553. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188554. png_set_shift(png_ptr, sig_bit);
  188555. }
  188556. #endif
  188557. #if defined(PNG_READ_BGR_SUPPORTED)
  188558. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188559. */
  188560. if (transforms & PNG_TRANSFORM_BGR)
  188561. png_set_bgr(png_ptr);
  188562. #endif
  188563. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188564. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188565. */
  188566. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188567. png_set_swap_alpha(png_ptr);
  188568. #endif
  188569. #if defined(PNG_READ_SWAP_SUPPORTED)
  188570. /* swap bytes of 16 bit files to least significant byte first
  188571. */
  188572. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188573. png_set_swap(png_ptr);
  188574. #endif
  188575. /* We don't handle adding filler bytes */
  188576. /* Optional call to gamma correct and add the background to the palette
  188577. * and update info structure. REQUIRED if you are expecting libpng to
  188578. * update the palette for you (i.e., you selected such a transform above).
  188579. */
  188580. png_read_update_info(png_ptr, info_ptr);
  188581. /* -------------- image transformations end here ------------------- */
  188582. #ifdef PNG_FREE_ME_SUPPORTED
  188583. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188584. #endif
  188585. if(info_ptr->row_pointers == NULL)
  188586. {
  188587. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188588. info_ptr->height * png_sizeof(png_bytep));
  188589. #ifdef PNG_FREE_ME_SUPPORTED
  188590. info_ptr->free_me |= PNG_FREE_ROWS;
  188591. #endif
  188592. for (row = 0; row < (int)info_ptr->height; row++)
  188593. {
  188594. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188595. png_get_rowbytes(png_ptr, info_ptr));
  188596. }
  188597. }
  188598. png_read_image(png_ptr, info_ptr->row_pointers);
  188599. info_ptr->valid |= PNG_INFO_IDAT;
  188600. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188601. png_read_end(png_ptr, info_ptr);
  188602. transforms = transforms; /* quiet compiler warnings */
  188603. params = params;
  188604. }
  188605. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188606. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188607. #endif /* PNG_READ_SUPPORTED */
  188608. /*** End of inlined file: pngread.c ***/
  188609. /*** Start of inlined file: pngpread.c ***/
  188610. /* pngpread.c - read a png file in push mode
  188611. *
  188612. * Last changed in libpng 1.2.21 October 4, 2007
  188613. * For conditions of distribution and use, see copyright notice in png.h
  188614. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188615. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188616. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188617. */
  188618. #define PNG_INTERNAL
  188619. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188620. /* push model modes */
  188621. #define PNG_READ_SIG_MODE 0
  188622. #define PNG_READ_CHUNK_MODE 1
  188623. #define PNG_READ_IDAT_MODE 2
  188624. #define PNG_SKIP_MODE 3
  188625. #define PNG_READ_tEXt_MODE 4
  188626. #define PNG_READ_zTXt_MODE 5
  188627. #define PNG_READ_DONE_MODE 6
  188628. #define PNG_READ_iTXt_MODE 7
  188629. #define PNG_ERROR_MODE 8
  188630. void PNGAPI
  188631. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188632. png_bytep buffer, png_size_t buffer_size)
  188633. {
  188634. if(png_ptr == NULL) return;
  188635. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188636. while (png_ptr->buffer_size)
  188637. {
  188638. png_process_some_data(png_ptr, info_ptr);
  188639. }
  188640. }
  188641. /* What we do with the incoming data depends on what we were previously
  188642. * doing before we ran out of data...
  188643. */
  188644. void /* PRIVATE */
  188645. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188646. {
  188647. if(png_ptr == NULL) return;
  188648. switch (png_ptr->process_mode)
  188649. {
  188650. case PNG_READ_SIG_MODE:
  188651. {
  188652. png_push_read_sig(png_ptr, info_ptr);
  188653. break;
  188654. }
  188655. case PNG_READ_CHUNK_MODE:
  188656. {
  188657. png_push_read_chunk(png_ptr, info_ptr);
  188658. break;
  188659. }
  188660. case PNG_READ_IDAT_MODE:
  188661. {
  188662. png_push_read_IDAT(png_ptr);
  188663. break;
  188664. }
  188665. #if defined(PNG_READ_tEXt_SUPPORTED)
  188666. case PNG_READ_tEXt_MODE:
  188667. {
  188668. png_push_read_tEXt(png_ptr, info_ptr);
  188669. break;
  188670. }
  188671. #endif
  188672. #if defined(PNG_READ_zTXt_SUPPORTED)
  188673. case PNG_READ_zTXt_MODE:
  188674. {
  188675. png_push_read_zTXt(png_ptr, info_ptr);
  188676. break;
  188677. }
  188678. #endif
  188679. #if defined(PNG_READ_iTXt_SUPPORTED)
  188680. case PNG_READ_iTXt_MODE:
  188681. {
  188682. png_push_read_iTXt(png_ptr, info_ptr);
  188683. break;
  188684. }
  188685. #endif
  188686. case PNG_SKIP_MODE:
  188687. {
  188688. png_push_crc_finish(png_ptr);
  188689. break;
  188690. }
  188691. default:
  188692. {
  188693. png_ptr->buffer_size = 0;
  188694. break;
  188695. }
  188696. }
  188697. }
  188698. /* Read any remaining signature bytes from the stream and compare them with
  188699. * the correct PNG signature. It is possible that this routine is called
  188700. * with bytes already read from the signature, either because they have been
  188701. * checked by the calling application, or because of multiple calls to this
  188702. * routine.
  188703. */
  188704. void /* PRIVATE */
  188705. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188706. {
  188707. png_size_t num_checked = png_ptr->sig_bytes,
  188708. num_to_check = 8 - num_checked;
  188709. if (png_ptr->buffer_size < num_to_check)
  188710. {
  188711. num_to_check = png_ptr->buffer_size;
  188712. }
  188713. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188714. num_to_check);
  188715. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188716. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188717. {
  188718. if (num_checked < 4 &&
  188719. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188720. png_error(png_ptr, "Not a PNG file");
  188721. else
  188722. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188723. }
  188724. else
  188725. {
  188726. if (png_ptr->sig_bytes >= 8)
  188727. {
  188728. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188729. }
  188730. }
  188731. }
  188732. void /* PRIVATE */
  188733. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188734. {
  188735. #ifdef PNG_USE_LOCAL_ARRAYS
  188736. PNG_CONST PNG_IHDR;
  188737. PNG_CONST PNG_IDAT;
  188738. PNG_CONST PNG_IEND;
  188739. PNG_CONST PNG_PLTE;
  188740. #if defined(PNG_READ_bKGD_SUPPORTED)
  188741. PNG_CONST PNG_bKGD;
  188742. #endif
  188743. #if defined(PNG_READ_cHRM_SUPPORTED)
  188744. PNG_CONST PNG_cHRM;
  188745. #endif
  188746. #if defined(PNG_READ_gAMA_SUPPORTED)
  188747. PNG_CONST PNG_gAMA;
  188748. #endif
  188749. #if defined(PNG_READ_hIST_SUPPORTED)
  188750. PNG_CONST PNG_hIST;
  188751. #endif
  188752. #if defined(PNG_READ_iCCP_SUPPORTED)
  188753. PNG_CONST PNG_iCCP;
  188754. #endif
  188755. #if defined(PNG_READ_iTXt_SUPPORTED)
  188756. PNG_CONST PNG_iTXt;
  188757. #endif
  188758. #if defined(PNG_READ_oFFs_SUPPORTED)
  188759. PNG_CONST PNG_oFFs;
  188760. #endif
  188761. #if defined(PNG_READ_pCAL_SUPPORTED)
  188762. PNG_CONST PNG_pCAL;
  188763. #endif
  188764. #if defined(PNG_READ_pHYs_SUPPORTED)
  188765. PNG_CONST PNG_pHYs;
  188766. #endif
  188767. #if defined(PNG_READ_sBIT_SUPPORTED)
  188768. PNG_CONST PNG_sBIT;
  188769. #endif
  188770. #if defined(PNG_READ_sCAL_SUPPORTED)
  188771. PNG_CONST PNG_sCAL;
  188772. #endif
  188773. #if defined(PNG_READ_sRGB_SUPPORTED)
  188774. PNG_CONST PNG_sRGB;
  188775. #endif
  188776. #if defined(PNG_READ_sPLT_SUPPORTED)
  188777. PNG_CONST PNG_sPLT;
  188778. #endif
  188779. #if defined(PNG_READ_tEXt_SUPPORTED)
  188780. PNG_CONST PNG_tEXt;
  188781. #endif
  188782. #if defined(PNG_READ_tIME_SUPPORTED)
  188783. PNG_CONST PNG_tIME;
  188784. #endif
  188785. #if defined(PNG_READ_tRNS_SUPPORTED)
  188786. PNG_CONST PNG_tRNS;
  188787. #endif
  188788. #if defined(PNG_READ_zTXt_SUPPORTED)
  188789. PNG_CONST PNG_zTXt;
  188790. #endif
  188791. #endif /* PNG_USE_LOCAL_ARRAYS */
  188792. /* First we make sure we have enough data for the 4 byte chunk name
  188793. * and the 4 byte chunk length before proceeding with decoding the
  188794. * chunk data. To fully decode each of these chunks, we also make
  188795. * sure we have enough data in the buffer for the 4 byte CRC at the
  188796. * end of every chunk (except IDAT, which is handled separately).
  188797. */
  188798. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188799. {
  188800. png_byte chunk_length[4];
  188801. if (png_ptr->buffer_size < 8)
  188802. {
  188803. png_push_save_buffer(png_ptr);
  188804. return;
  188805. }
  188806. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188807. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188808. png_reset_crc(png_ptr);
  188809. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188810. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188811. }
  188812. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188813. if(png_ptr->mode & PNG_AFTER_IDAT)
  188814. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188815. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188816. {
  188817. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188818. {
  188819. png_push_save_buffer(png_ptr);
  188820. return;
  188821. }
  188822. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188823. }
  188824. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188825. {
  188826. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188827. {
  188828. png_push_save_buffer(png_ptr);
  188829. return;
  188830. }
  188831. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188832. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188833. png_push_have_end(png_ptr, info_ptr);
  188834. }
  188835. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188836. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188837. {
  188838. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188839. {
  188840. png_push_save_buffer(png_ptr);
  188841. return;
  188842. }
  188843. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188844. png_ptr->mode |= PNG_HAVE_IDAT;
  188845. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188846. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188847. png_ptr->mode |= PNG_HAVE_PLTE;
  188848. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188849. {
  188850. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188851. png_error(png_ptr, "Missing IHDR before IDAT");
  188852. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188853. !(png_ptr->mode & PNG_HAVE_PLTE))
  188854. png_error(png_ptr, "Missing PLTE before IDAT");
  188855. }
  188856. }
  188857. #endif
  188858. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188859. {
  188860. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188861. {
  188862. png_push_save_buffer(png_ptr);
  188863. return;
  188864. }
  188865. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188866. }
  188867. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188868. {
  188869. /* If we reach an IDAT chunk, this means we have read all of the
  188870. * header chunks, and we can start reading the image (or if this
  188871. * is called after the image has been read - we have an error).
  188872. */
  188873. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188874. png_error(png_ptr, "Missing IHDR before IDAT");
  188875. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188876. !(png_ptr->mode & PNG_HAVE_PLTE))
  188877. png_error(png_ptr, "Missing PLTE before IDAT");
  188878. if (png_ptr->mode & PNG_HAVE_IDAT)
  188879. {
  188880. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188881. if (png_ptr->push_length == 0)
  188882. return;
  188883. if (png_ptr->mode & PNG_AFTER_IDAT)
  188884. png_error(png_ptr, "Too many IDAT's found");
  188885. }
  188886. png_ptr->idat_size = png_ptr->push_length;
  188887. png_ptr->mode |= PNG_HAVE_IDAT;
  188888. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188889. png_push_have_info(png_ptr, info_ptr);
  188890. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188891. png_ptr->zstream.next_out = png_ptr->row_buf;
  188892. return;
  188893. }
  188894. #if defined(PNG_READ_gAMA_SUPPORTED)
  188895. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188896. {
  188897. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188898. {
  188899. png_push_save_buffer(png_ptr);
  188900. return;
  188901. }
  188902. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188903. }
  188904. #endif
  188905. #if defined(PNG_READ_sBIT_SUPPORTED)
  188906. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188907. {
  188908. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188909. {
  188910. png_push_save_buffer(png_ptr);
  188911. return;
  188912. }
  188913. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188914. }
  188915. #endif
  188916. #if defined(PNG_READ_cHRM_SUPPORTED)
  188917. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188918. {
  188919. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188920. {
  188921. png_push_save_buffer(png_ptr);
  188922. return;
  188923. }
  188924. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188925. }
  188926. #endif
  188927. #if defined(PNG_READ_sRGB_SUPPORTED)
  188928. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188929. {
  188930. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188931. {
  188932. png_push_save_buffer(png_ptr);
  188933. return;
  188934. }
  188935. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188936. }
  188937. #endif
  188938. #if defined(PNG_READ_iCCP_SUPPORTED)
  188939. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188940. {
  188941. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188942. {
  188943. png_push_save_buffer(png_ptr);
  188944. return;
  188945. }
  188946. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188947. }
  188948. #endif
  188949. #if defined(PNG_READ_sPLT_SUPPORTED)
  188950. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  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_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188958. }
  188959. #endif
  188960. #if defined(PNG_READ_tRNS_SUPPORTED)
  188961. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188962. {
  188963. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188964. {
  188965. png_push_save_buffer(png_ptr);
  188966. return;
  188967. }
  188968. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188969. }
  188970. #endif
  188971. #if defined(PNG_READ_bKGD_SUPPORTED)
  188972. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188973. {
  188974. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188975. {
  188976. png_push_save_buffer(png_ptr);
  188977. return;
  188978. }
  188979. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188980. }
  188981. #endif
  188982. #if defined(PNG_READ_hIST_SUPPORTED)
  188983. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188984. {
  188985. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188986. {
  188987. png_push_save_buffer(png_ptr);
  188988. return;
  188989. }
  188990. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188991. }
  188992. #endif
  188993. #if defined(PNG_READ_pHYs_SUPPORTED)
  188994. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188995. {
  188996. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188997. {
  188998. png_push_save_buffer(png_ptr);
  188999. return;
  189000. }
  189001. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  189002. }
  189003. #endif
  189004. #if defined(PNG_READ_oFFs_SUPPORTED)
  189005. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  189006. {
  189007. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189008. {
  189009. png_push_save_buffer(png_ptr);
  189010. return;
  189011. }
  189012. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  189013. }
  189014. #endif
  189015. #if defined(PNG_READ_pCAL_SUPPORTED)
  189016. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  189017. {
  189018. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189019. {
  189020. png_push_save_buffer(png_ptr);
  189021. return;
  189022. }
  189023. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189024. }
  189025. #endif
  189026. #if defined(PNG_READ_sCAL_SUPPORTED)
  189027. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189028. {
  189029. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189030. {
  189031. png_push_save_buffer(png_ptr);
  189032. return;
  189033. }
  189034. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189035. }
  189036. #endif
  189037. #if defined(PNG_READ_tIME_SUPPORTED)
  189038. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189039. {
  189040. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189041. {
  189042. png_push_save_buffer(png_ptr);
  189043. return;
  189044. }
  189045. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189046. }
  189047. #endif
  189048. #if defined(PNG_READ_tEXt_SUPPORTED)
  189049. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189050. {
  189051. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189052. {
  189053. png_push_save_buffer(png_ptr);
  189054. return;
  189055. }
  189056. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189057. }
  189058. #endif
  189059. #if defined(PNG_READ_zTXt_SUPPORTED)
  189060. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189061. {
  189062. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189063. {
  189064. png_push_save_buffer(png_ptr);
  189065. return;
  189066. }
  189067. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189068. }
  189069. #endif
  189070. #if defined(PNG_READ_iTXt_SUPPORTED)
  189071. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189072. {
  189073. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189074. {
  189075. png_push_save_buffer(png_ptr);
  189076. return;
  189077. }
  189078. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189079. }
  189080. #endif
  189081. else
  189082. {
  189083. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189084. {
  189085. png_push_save_buffer(png_ptr);
  189086. return;
  189087. }
  189088. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189089. }
  189090. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189091. }
  189092. void /* PRIVATE */
  189093. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189094. {
  189095. png_ptr->process_mode = PNG_SKIP_MODE;
  189096. png_ptr->skip_length = skip;
  189097. }
  189098. void /* PRIVATE */
  189099. png_push_crc_finish(png_structp png_ptr)
  189100. {
  189101. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189102. {
  189103. png_size_t save_size;
  189104. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189105. save_size = (png_size_t)png_ptr->skip_length;
  189106. else
  189107. save_size = png_ptr->save_buffer_size;
  189108. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189109. png_ptr->skip_length -= save_size;
  189110. png_ptr->buffer_size -= save_size;
  189111. png_ptr->save_buffer_size -= save_size;
  189112. png_ptr->save_buffer_ptr += save_size;
  189113. }
  189114. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189115. {
  189116. png_size_t save_size;
  189117. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189118. save_size = (png_size_t)png_ptr->skip_length;
  189119. else
  189120. save_size = png_ptr->current_buffer_size;
  189121. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189122. png_ptr->skip_length -= save_size;
  189123. png_ptr->buffer_size -= save_size;
  189124. png_ptr->current_buffer_size -= save_size;
  189125. png_ptr->current_buffer_ptr += save_size;
  189126. }
  189127. if (!png_ptr->skip_length)
  189128. {
  189129. if (png_ptr->buffer_size < 4)
  189130. {
  189131. png_push_save_buffer(png_ptr);
  189132. return;
  189133. }
  189134. png_crc_finish(png_ptr, 0);
  189135. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189136. }
  189137. }
  189138. void PNGAPI
  189139. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189140. {
  189141. png_bytep ptr;
  189142. if(png_ptr == NULL) return;
  189143. ptr = buffer;
  189144. if (png_ptr->save_buffer_size)
  189145. {
  189146. png_size_t save_size;
  189147. if (length < png_ptr->save_buffer_size)
  189148. save_size = length;
  189149. else
  189150. save_size = png_ptr->save_buffer_size;
  189151. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189152. length -= save_size;
  189153. ptr += save_size;
  189154. png_ptr->buffer_size -= save_size;
  189155. png_ptr->save_buffer_size -= save_size;
  189156. png_ptr->save_buffer_ptr += save_size;
  189157. }
  189158. if (length && png_ptr->current_buffer_size)
  189159. {
  189160. png_size_t save_size;
  189161. if (length < png_ptr->current_buffer_size)
  189162. save_size = length;
  189163. else
  189164. save_size = png_ptr->current_buffer_size;
  189165. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189166. png_ptr->buffer_size -= save_size;
  189167. png_ptr->current_buffer_size -= save_size;
  189168. png_ptr->current_buffer_ptr += save_size;
  189169. }
  189170. }
  189171. void /* PRIVATE */
  189172. png_push_save_buffer(png_structp png_ptr)
  189173. {
  189174. if (png_ptr->save_buffer_size)
  189175. {
  189176. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189177. {
  189178. png_size_t i,istop;
  189179. png_bytep sp;
  189180. png_bytep dp;
  189181. istop = png_ptr->save_buffer_size;
  189182. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189183. i < istop; i++, sp++, dp++)
  189184. {
  189185. *dp = *sp;
  189186. }
  189187. }
  189188. }
  189189. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189190. png_ptr->save_buffer_max)
  189191. {
  189192. png_size_t new_max;
  189193. png_bytep old_buffer;
  189194. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189195. (png_ptr->current_buffer_size + 256))
  189196. {
  189197. png_error(png_ptr, "Potential overflow of save_buffer");
  189198. }
  189199. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189200. old_buffer = png_ptr->save_buffer;
  189201. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189202. (png_uint_32)new_max);
  189203. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189204. png_free(png_ptr, old_buffer);
  189205. png_ptr->save_buffer_max = new_max;
  189206. }
  189207. if (png_ptr->current_buffer_size)
  189208. {
  189209. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189210. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189211. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189212. png_ptr->current_buffer_size = 0;
  189213. }
  189214. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189215. png_ptr->buffer_size = 0;
  189216. }
  189217. void /* PRIVATE */
  189218. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189219. png_size_t buffer_length)
  189220. {
  189221. png_ptr->current_buffer = buffer;
  189222. png_ptr->current_buffer_size = buffer_length;
  189223. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189224. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189225. }
  189226. void /* PRIVATE */
  189227. png_push_read_IDAT(png_structp png_ptr)
  189228. {
  189229. #ifdef PNG_USE_LOCAL_ARRAYS
  189230. PNG_CONST PNG_IDAT;
  189231. #endif
  189232. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189233. {
  189234. png_byte chunk_length[4];
  189235. if (png_ptr->buffer_size < 8)
  189236. {
  189237. png_push_save_buffer(png_ptr);
  189238. return;
  189239. }
  189240. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189241. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189242. png_reset_crc(png_ptr);
  189243. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189244. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189245. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189246. {
  189247. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189248. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189249. png_error(png_ptr, "Not enough compressed data");
  189250. return;
  189251. }
  189252. png_ptr->idat_size = png_ptr->push_length;
  189253. }
  189254. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189255. {
  189256. png_size_t save_size;
  189257. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189258. {
  189259. save_size = (png_size_t)png_ptr->idat_size;
  189260. /* check for overflow */
  189261. if((png_uint_32)save_size != png_ptr->idat_size)
  189262. png_error(png_ptr, "save_size overflowed in pngpread");
  189263. }
  189264. else
  189265. save_size = png_ptr->save_buffer_size;
  189266. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189267. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189268. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189269. png_ptr->idat_size -= save_size;
  189270. png_ptr->buffer_size -= save_size;
  189271. png_ptr->save_buffer_size -= save_size;
  189272. png_ptr->save_buffer_ptr += save_size;
  189273. }
  189274. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189275. {
  189276. png_size_t save_size;
  189277. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189278. {
  189279. save_size = (png_size_t)png_ptr->idat_size;
  189280. /* check for overflow */
  189281. if((png_uint_32)save_size != png_ptr->idat_size)
  189282. png_error(png_ptr, "save_size overflowed in pngpread");
  189283. }
  189284. else
  189285. save_size = png_ptr->current_buffer_size;
  189286. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189287. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189288. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189289. png_ptr->idat_size -= save_size;
  189290. png_ptr->buffer_size -= save_size;
  189291. png_ptr->current_buffer_size -= save_size;
  189292. png_ptr->current_buffer_ptr += save_size;
  189293. }
  189294. if (!png_ptr->idat_size)
  189295. {
  189296. if (png_ptr->buffer_size < 4)
  189297. {
  189298. png_push_save_buffer(png_ptr);
  189299. return;
  189300. }
  189301. png_crc_finish(png_ptr, 0);
  189302. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189303. png_ptr->mode |= PNG_AFTER_IDAT;
  189304. }
  189305. }
  189306. void /* PRIVATE */
  189307. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189308. png_size_t buffer_length)
  189309. {
  189310. int ret;
  189311. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189312. png_error(png_ptr, "Extra compression data");
  189313. png_ptr->zstream.next_in = buffer;
  189314. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189315. for(;;)
  189316. {
  189317. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189318. if (ret != Z_OK)
  189319. {
  189320. if (ret == Z_STREAM_END)
  189321. {
  189322. if (png_ptr->zstream.avail_in)
  189323. png_error(png_ptr, "Extra compressed data");
  189324. if (!(png_ptr->zstream.avail_out))
  189325. {
  189326. png_push_process_row(png_ptr);
  189327. }
  189328. png_ptr->mode |= PNG_AFTER_IDAT;
  189329. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189330. break;
  189331. }
  189332. else if (ret == Z_BUF_ERROR)
  189333. break;
  189334. else
  189335. png_error(png_ptr, "Decompression Error");
  189336. }
  189337. if (!(png_ptr->zstream.avail_out))
  189338. {
  189339. if ((
  189340. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189341. png_ptr->interlaced && png_ptr->pass > 6) ||
  189342. (!png_ptr->interlaced &&
  189343. #endif
  189344. png_ptr->row_number == png_ptr->num_rows))
  189345. {
  189346. if (png_ptr->zstream.avail_in)
  189347. {
  189348. png_warning(png_ptr, "Too much data in IDAT chunks");
  189349. }
  189350. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189351. break;
  189352. }
  189353. png_push_process_row(png_ptr);
  189354. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189355. png_ptr->zstream.next_out = png_ptr->row_buf;
  189356. }
  189357. else
  189358. break;
  189359. }
  189360. }
  189361. void /* PRIVATE */
  189362. png_push_process_row(png_structp png_ptr)
  189363. {
  189364. png_ptr->row_info.color_type = png_ptr->color_type;
  189365. png_ptr->row_info.width = png_ptr->iwidth;
  189366. png_ptr->row_info.channels = png_ptr->channels;
  189367. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189368. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189369. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189370. png_ptr->row_info.width);
  189371. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189372. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189373. (int)(png_ptr->row_buf[0]));
  189374. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189375. png_ptr->rowbytes + 1);
  189376. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189377. png_do_read_transformations(png_ptr);
  189378. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189379. /* blow up interlaced rows to full size */
  189380. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189381. {
  189382. if (png_ptr->pass < 6)
  189383. /* old interface (pre-1.0.9):
  189384. png_do_read_interlace(&(png_ptr->row_info),
  189385. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189386. */
  189387. png_do_read_interlace(png_ptr);
  189388. switch (png_ptr->pass)
  189389. {
  189390. case 0:
  189391. {
  189392. int i;
  189393. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189394. {
  189395. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189396. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189397. }
  189398. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189399. {
  189400. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189401. {
  189402. png_push_have_row(png_ptr, png_bytep_NULL);
  189403. png_read_push_finish_row(png_ptr);
  189404. }
  189405. }
  189406. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189407. {
  189408. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189409. {
  189410. png_push_have_row(png_ptr, png_bytep_NULL);
  189411. png_read_push_finish_row(png_ptr);
  189412. }
  189413. }
  189414. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189415. {
  189416. png_push_have_row(png_ptr, png_bytep_NULL);
  189417. png_read_push_finish_row(png_ptr);
  189418. }
  189419. break;
  189420. }
  189421. case 1:
  189422. {
  189423. int i;
  189424. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189425. {
  189426. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189427. png_read_push_finish_row(png_ptr);
  189428. }
  189429. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189430. {
  189431. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189432. {
  189433. png_push_have_row(png_ptr, png_bytep_NULL);
  189434. png_read_push_finish_row(png_ptr);
  189435. }
  189436. }
  189437. break;
  189438. }
  189439. case 2:
  189440. {
  189441. int i;
  189442. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189443. {
  189444. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189445. png_read_push_finish_row(png_ptr);
  189446. }
  189447. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189448. {
  189449. png_push_have_row(png_ptr, png_bytep_NULL);
  189450. png_read_push_finish_row(png_ptr);
  189451. }
  189452. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189453. {
  189454. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189455. {
  189456. png_push_have_row(png_ptr, png_bytep_NULL);
  189457. png_read_push_finish_row(png_ptr);
  189458. }
  189459. }
  189460. break;
  189461. }
  189462. case 3:
  189463. {
  189464. int i;
  189465. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189466. {
  189467. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189468. png_read_push_finish_row(png_ptr);
  189469. }
  189470. if (png_ptr->pass == 4) /* skip top two generated rows */
  189471. {
  189472. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189473. {
  189474. png_push_have_row(png_ptr, png_bytep_NULL);
  189475. png_read_push_finish_row(png_ptr);
  189476. }
  189477. }
  189478. break;
  189479. }
  189480. case 4:
  189481. {
  189482. int i;
  189483. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189484. {
  189485. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189486. png_read_push_finish_row(png_ptr);
  189487. }
  189488. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189489. {
  189490. png_push_have_row(png_ptr, png_bytep_NULL);
  189491. png_read_push_finish_row(png_ptr);
  189492. }
  189493. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189494. {
  189495. png_push_have_row(png_ptr, png_bytep_NULL);
  189496. png_read_push_finish_row(png_ptr);
  189497. }
  189498. break;
  189499. }
  189500. case 5:
  189501. {
  189502. int i;
  189503. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189504. {
  189505. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189506. png_read_push_finish_row(png_ptr);
  189507. }
  189508. if (png_ptr->pass == 6) /* skip top generated row */
  189509. {
  189510. png_push_have_row(png_ptr, png_bytep_NULL);
  189511. png_read_push_finish_row(png_ptr);
  189512. }
  189513. break;
  189514. }
  189515. case 6:
  189516. {
  189517. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189518. png_read_push_finish_row(png_ptr);
  189519. if (png_ptr->pass != 6)
  189520. break;
  189521. png_push_have_row(png_ptr, png_bytep_NULL);
  189522. png_read_push_finish_row(png_ptr);
  189523. }
  189524. }
  189525. }
  189526. else
  189527. #endif
  189528. {
  189529. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189530. png_read_push_finish_row(png_ptr);
  189531. }
  189532. }
  189533. void /* PRIVATE */
  189534. png_read_push_finish_row(png_structp png_ptr)
  189535. {
  189536. #ifdef PNG_USE_LOCAL_ARRAYS
  189537. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189538. /* start of interlace block */
  189539. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189540. /* offset to next interlace block */
  189541. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189542. /* start of interlace block in the y direction */
  189543. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189544. /* offset to next interlace block in the y direction */
  189545. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189546. /* Height of interlace block. This is not currently used - if you need
  189547. * it, uncomment it here and in png.h
  189548. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189549. */
  189550. #endif
  189551. png_ptr->row_number++;
  189552. if (png_ptr->row_number < png_ptr->num_rows)
  189553. return;
  189554. if (png_ptr->interlaced)
  189555. {
  189556. png_ptr->row_number = 0;
  189557. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189558. png_ptr->rowbytes + 1);
  189559. do
  189560. {
  189561. png_ptr->pass++;
  189562. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189563. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189564. (png_ptr->pass == 5 && png_ptr->width < 2))
  189565. png_ptr->pass++;
  189566. if (png_ptr->pass > 7)
  189567. png_ptr->pass--;
  189568. if (png_ptr->pass >= 7)
  189569. break;
  189570. png_ptr->iwidth = (png_ptr->width +
  189571. png_pass_inc[png_ptr->pass] - 1 -
  189572. png_pass_start[png_ptr->pass]) /
  189573. png_pass_inc[png_ptr->pass];
  189574. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189575. png_ptr->iwidth) + 1;
  189576. if (png_ptr->transformations & PNG_INTERLACE)
  189577. break;
  189578. png_ptr->num_rows = (png_ptr->height +
  189579. png_pass_yinc[png_ptr->pass] - 1 -
  189580. png_pass_ystart[png_ptr->pass]) /
  189581. png_pass_yinc[png_ptr->pass];
  189582. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189583. }
  189584. }
  189585. #if defined(PNG_READ_tEXt_SUPPORTED)
  189586. void /* PRIVATE */
  189587. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189588. length)
  189589. {
  189590. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189591. {
  189592. png_error(png_ptr, "Out of place tEXt");
  189593. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189594. }
  189595. #ifdef PNG_MAX_MALLOC_64K
  189596. png_ptr->skip_length = 0; /* This may not be necessary */
  189597. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189598. {
  189599. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189600. png_ptr->skip_length = length - (png_uint_32)65535L;
  189601. length = (png_uint_32)65535L;
  189602. }
  189603. #endif
  189604. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189605. (png_uint_32)(length+1));
  189606. png_ptr->current_text[length] = '\0';
  189607. png_ptr->current_text_ptr = png_ptr->current_text;
  189608. png_ptr->current_text_size = (png_size_t)length;
  189609. png_ptr->current_text_left = (png_size_t)length;
  189610. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189611. }
  189612. void /* PRIVATE */
  189613. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189614. {
  189615. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189616. {
  189617. png_size_t text_size;
  189618. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189619. text_size = png_ptr->buffer_size;
  189620. else
  189621. text_size = png_ptr->current_text_left;
  189622. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189623. png_ptr->current_text_left -= text_size;
  189624. png_ptr->current_text_ptr += text_size;
  189625. }
  189626. if (!(png_ptr->current_text_left))
  189627. {
  189628. png_textp text_ptr;
  189629. png_charp text;
  189630. png_charp key;
  189631. int ret;
  189632. if (png_ptr->buffer_size < 4)
  189633. {
  189634. png_push_save_buffer(png_ptr);
  189635. return;
  189636. }
  189637. png_push_crc_finish(png_ptr);
  189638. #if defined(PNG_MAX_MALLOC_64K)
  189639. if (png_ptr->skip_length)
  189640. return;
  189641. #endif
  189642. key = png_ptr->current_text;
  189643. for (text = key; *text; text++)
  189644. /* empty loop */ ;
  189645. if (text < key + png_ptr->current_text_size)
  189646. text++;
  189647. text_ptr = (png_textp)png_malloc(png_ptr,
  189648. (png_uint_32)png_sizeof(png_text));
  189649. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189650. text_ptr->key = key;
  189651. #ifdef PNG_iTXt_SUPPORTED
  189652. text_ptr->lang = NULL;
  189653. text_ptr->lang_key = NULL;
  189654. #endif
  189655. text_ptr->text = text;
  189656. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189657. png_free(png_ptr, key);
  189658. png_free(png_ptr, text_ptr);
  189659. png_ptr->current_text = NULL;
  189660. if (ret)
  189661. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189662. }
  189663. }
  189664. #endif
  189665. #if defined(PNG_READ_zTXt_SUPPORTED)
  189666. void /* PRIVATE */
  189667. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189668. length)
  189669. {
  189670. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189671. {
  189672. png_error(png_ptr, "Out of place zTXt");
  189673. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189674. }
  189675. #ifdef PNG_MAX_MALLOC_64K
  189676. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189677. * to be able to store the uncompressed data. Actually, the threshold
  189678. * is probably around 32K, but it isn't as definite as 64K is.
  189679. */
  189680. if (length > (png_uint_32)65535L)
  189681. {
  189682. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189683. png_push_crc_skip(png_ptr, length);
  189684. return;
  189685. }
  189686. #endif
  189687. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189688. (png_uint_32)(length+1));
  189689. png_ptr->current_text[length] = '\0';
  189690. png_ptr->current_text_ptr = png_ptr->current_text;
  189691. png_ptr->current_text_size = (png_size_t)length;
  189692. png_ptr->current_text_left = (png_size_t)length;
  189693. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189694. }
  189695. void /* PRIVATE */
  189696. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189697. {
  189698. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189699. {
  189700. png_size_t text_size;
  189701. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189702. text_size = png_ptr->buffer_size;
  189703. else
  189704. text_size = png_ptr->current_text_left;
  189705. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189706. png_ptr->current_text_left -= text_size;
  189707. png_ptr->current_text_ptr += text_size;
  189708. }
  189709. if (!(png_ptr->current_text_left))
  189710. {
  189711. png_textp text_ptr;
  189712. png_charp text;
  189713. png_charp key;
  189714. int ret;
  189715. png_size_t text_size, key_size;
  189716. if (png_ptr->buffer_size < 4)
  189717. {
  189718. png_push_save_buffer(png_ptr);
  189719. return;
  189720. }
  189721. png_push_crc_finish(png_ptr);
  189722. key = png_ptr->current_text;
  189723. for (text = key; *text; text++)
  189724. /* empty loop */ ;
  189725. /* zTXt can't have zero text */
  189726. if (text >= key + png_ptr->current_text_size)
  189727. {
  189728. png_ptr->current_text = NULL;
  189729. png_free(png_ptr, key);
  189730. return;
  189731. }
  189732. text++;
  189733. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189734. {
  189735. png_ptr->current_text = NULL;
  189736. png_free(png_ptr, key);
  189737. return;
  189738. }
  189739. text++;
  189740. png_ptr->zstream.next_in = (png_bytep )text;
  189741. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189742. (text - key));
  189743. png_ptr->zstream.next_out = png_ptr->zbuf;
  189744. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189745. key_size = text - key;
  189746. text_size = 0;
  189747. text = NULL;
  189748. ret = Z_STREAM_END;
  189749. while (png_ptr->zstream.avail_in)
  189750. {
  189751. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189752. if (ret != Z_OK && ret != Z_STREAM_END)
  189753. {
  189754. inflateReset(&png_ptr->zstream);
  189755. png_ptr->zstream.avail_in = 0;
  189756. png_ptr->current_text = NULL;
  189757. png_free(png_ptr, key);
  189758. png_free(png_ptr, text);
  189759. return;
  189760. }
  189761. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189762. {
  189763. if (text == NULL)
  189764. {
  189765. text = (png_charp)png_malloc(png_ptr,
  189766. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189767. + key_size + 1));
  189768. png_memcpy(text + key_size, png_ptr->zbuf,
  189769. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189770. png_memcpy(text, key, key_size);
  189771. text_size = key_size + png_ptr->zbuf_size -
  189772. png_ptr->zstream.avail_out;
  189773. *(text + text_size) = '\0';
  189774. }
  189775. else
  189776. {
  189777. png_charp tmp;
  189778. tmp = text;
  189779. text = (png_charp)png_malloc(png_ptr, text_size +
  189780. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189781. + 1));
  189782. png_memcpy(text, tmp, text_size);
  189783. png_free(png_ptr, tmp);
  189784. png_memcpy(text + text_size, png_ptr->zbuf,
  189785. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189786. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189787. *(text + text_size) = '\0';
  189788. }
  189789. if (ret != Z_STREAM_END)
  189790. {
  189791. png_ptr->zstream.next_out = png_ptr->zbuf;
  189792. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189793. }
  189794. }
  189795. else
  189796. {
  189797. break;
  189798. }
  189799. if (ret == Z_STREAM_END)
  189800. break;
  189801. }
  189802. inflateReset(&png_ptr->zstream);
  189803. png_ptr->zstream.avail_in = 0;
  189804. if (ret != Z_STREAM_END)
  189805. {
  189806. png_ptr->current_text = NULL;
  189807. png_free(png_ptr, key);
  189808. png_free(png_ptr, text);
  189809. return;
  189810. }
  189811. png_ptr->current_text = NULL;
  189812. png_free(png_ptr, key);
  189813. key = text;
  189814. text += key_size;
  189815. text_ptr = (png_textp)png_malloc(png_ptr,
  189816. (png_uint_32)png_sizeof(png_text));
  189817. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189818. text_ptr->key = key;
  189819. #ifdef PNG_iTXt_SUPPORTED
  189820. text_ptr->lang = NULL;
  189821. text_ptr->lang_key = NULL;
  189822. #endif
  189823. text_ptr->text = text;
  189824. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189825. png_free(png_ptr, key);
  189826. png_free(png_ptr, text_ptr);
  189827. if (ret)
  189828. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189829. }
  189830. }
  189831. #endif
  189832. #if defined(PNG_READ_iTXt_SUPPORTED)
  189833. void /* PRIVATE */
  189834. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189835. length)
  189836. {
  189837. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189838. {
  189839. png_error(png_ptr, "Out of place iTXt");
  189840. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189841. }
  189842. #ifdef PNG_MAX_MALLOC_64K
  189843. png_ptr->skip_length = 0; /* This may not be necessary */
  189844. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189845. {
  189846. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189847. png_ptr->skip_length = length - (png_uint_32)65535L;
  189848. length = (png_uint_32)65535L;
  189849. }
  189850. #endif
  189851. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189852. (png_uint_32)(length+1));
  189853. png_ptr->current_text[length] = '\0';
  189854. png_ptr->current_text_ptr = png_ptr->current_text;
  189855. png_ptr->current_text_size = (png_size_t)length;
  189856. png_ptr->current_text_left = (png_size_t)length;
  189857. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189858. }
  189859. void /* PRIVATE */
  189860. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189861. {
  189862. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189863. {
  189864. png_size_t text_size;
  189865. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189866. text_size = png_ptr->buffer_size;
  189867. else
  189868. text_size = png_ptr->current_text_left;
  189869. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189870. png_ptr->current_text_left -= text_size;
  189871. png_ptr->current_text_ptr += text_size;
  189872. }
  189873. if (!(png_ptr->current_text_left))
  189874. {
  189875. png_textp text_ptr;
  189876. png_charp key;
  189877. int comp_flag;
  189878. png_charp lang;
  189879. png_charp lang_key;
  189880. png_charp text;
  189881. int ret;
  189882. if (png_ptr->buffer_size < 4)
  189883. {
  189884. png_push_save_buffer(png_ptr);
  189885. return;
  189886. }
  189887. png_push_crc_finish(png_ptr);
  189888. #if defined(PNG_MAX_MALLOC_64K)
  189889. if (png_ptr->skip_length)
  189890. return;
  189891. #endif
  189892. key = png_ptr->current_text;
  189893. for (lang = key; *lang; lang++)
  189894. /* empty loop */ ;
  189895. if (lang < key + png_ptr->current_text_size - 3)
  189896. lang++;
  189897. comp_flag = *lang++;
  189898. lang++; /* skip comp_type, always zero */
  189899. for (lang_key = lang; *lang_key; lang_key++)
  189900. /* empty loop */ ;
  189901. lang_key++; /* skip NUL separator */
  189902. text=lang_key;
  189903. if (lang_key < key + png_ptr->current_text_size - 1)
  189904. {
  189905. for (; *text; text++)
  189906. /* empty loop */ ;
  189907. }
  189908. if (text < key + png_ptr->current_text_size)
  189909. text++;
  189910. text_ptr = (png_textp)png_malloc(png_ptr,
  189911. (png_uint_32)png_sizeof(png_text));
  189912. text_ptr->compression = comp_flag + 2;
  189913. text_ptr->key = key;
  189914. text_ptr->lang = lang;
  189915. text_ptr->lang_key = lang_key;
  189916. text_ptr->text = text;
  189917. text_ptr->text_length = 0;
  189918. text_ptr->itxt_length = png_strlen(text);
  189919. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189920. png_ptr->current_text = NULL;
  189921. png_free(png_ptr, text_ptr);
  189922. if (ret)
  189923. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189924. }
  189925. }
  189926. #endif
  189927. /* This function is called when we haven't found a handler for this
  189928. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189929. * name or a critical chunk), the chunk is (currently) silently ignored.
  189930. */
  189931. void /* PRIVATE */
  189932. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189933. length)
  189934. {
  189935. png_uint_32 skip=0;
  189936. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189937. if (!(png_ptr->chunk_name[0] & 0x20))
  189938. {
  189939. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189940. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189941. PNG_HANDLE_CHUNK_ALWAYS
  189942. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189943. && png_ptr->read_user_chunk_fn == NULL
  189944. #endif
  189945. )
  189946. #endif
  189947. png_chunk_error(png_ptr, "unknown critical chunk");
  189948. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189949. }
  189950. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189951. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189952. {
  189953. #ifdef PNG_MAX_MALLOC_64K
  189954. if (length > (png_uint_32)65535L)
  189955. {
  189956. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189957. skip = length - (png_uint_32)65535L;
  189958. length = (png_uint_32)65535L;
  189959. }
  189960. #endif
  189961. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189962. (png_charp)png_ptr->chunk_name, 5);
  189963. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189964. png_ptr->unknown_chunk.size = (png_size_t)length;
  189965. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189966. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189967. if(png_ptr->read_user_chunk_fn != NULL)
  189968. {
  189969. /* callback to user unknown chunk handler */
  189970. int ret;
  189971. ret = (*(png_ptr->read_user_chunk_fn))
  189972. (png_ptr, &png_ptr->unknown_chunk);
  189973. if (ret < 0)
  189974. png_chunk_error(png_ptr, "error in user chunk");
  189975. if (ret == 0)
  189976. {
  189977. if (!(png_ptr->chunk_name[0] & 0x20))
  189978. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189979. PNG_HANDLE_CHUNK_ALWAYS)
  189980. png_chunk_error(png_ptr, "unknown critical chunk");
  189981. png_set_unknown_chunks(png_ptr, info_ptr,
  189982. &png_ptr->unknown_chunk, 1);
  189983. }
  189984. }
  189985. #else
  189986. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189987. #endif
  189988. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189989. png_ptr->unknown_chunk.data = NULL;
  189990. }
  189991. else
  189992. #endif
  189993. skip=length;
  189994. png_push_crc_skip(png_ptr, skip);
  189995. }
  189996. void /* PRIVATE */
  189997. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189998. {
  189999. if (png_ptr->info_fn != NULL)
  190000. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  190001. }
  190002. void /* PRIVATE */
  190003. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  190004. {
  190005. if (png_ptr->end_fn != NULL)
  190006. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  190007. }
  190008. void /* PRIVATE */
  190009. png_push_have_row(png_structp png_ptr, png_bytep row)
  190010. {
  190011. if (png_ptr->row_fn != NULL)
  190012. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  190013. (int)png_ptr->pass);
  190014. }
  190015. void PNGAPI
  190016. png_progressive_combine_row (png_structp png_ptr,
  190017. png_bytep old_row, png_bytep new_row)
  190018. {
  190019. #ifdef PNG_USE_LOCAL_ARRAYS
  190020. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  190021. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  190022. #endif
  190023. if(png_ptr == NULL) return;
  190024. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190025. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190026. }
  190027. void PNGAPI
  190028. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190029. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190030. png_progressive_end_ptr end_fn)
  190031. {
  190032. if(png_ptr == NULL) return;
  190033. png_ptr->info_fn = info_fn;
  190034. png_ptr->row_fn = row_fn;
  190035. png_ptr->end_fn = end_fn;
  190036. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190037. }
  190038. png_voidp PNGAPI
  190039. png_get_progressive_ptr(png_structp png_ptr)
  190040. {
  190041. if(png_ptr == NULL) return (NULL);
  190042. return png_ptr->io_ptr;
  190043. }
  190044. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190045. /*** End of inlined file: pngpread.c ***/
  190046. /*** Start of inlined file: pngrio.c ***/
  190047. /* pngrio.c - functions for data input
  190048. *
  190049. * Last changed in libpng 1.2.13 November 13, 2006
  190050. * For conditions of distribution and use, see copyright notice in png.h
  190051. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190052. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190053. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190054. *
  190055. * This file provides a location for all input. Users who need
  190056. * special handling are expected to write a function that has the same
  190057. * arguments as this and performs a similar function, but that possibly
  190058. * has a different input method. Note that you shouldn't change this
  190059. * function, but rather write a replacement function and then make
  190060. * libpng use it at run time with png_set_read_fn(...).
  190061. */
  190062. #define PNG_INTERNAL
  190063. #if defined(PNG_READ_SUPPORTED)
  190064. /* Read the data from whatever input you are using. The default routine
  190065. reads from a file pointer. Note that this routine sometimes gets called
  190066. with very small lengths, so you should implement some kind of simple
  190067. buffering if you are using unbuffered reads. This should never be asked
  190068. to read more then 64K on a 16 bit machine. */
  190069. void /* PRIVATE */
  190070. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190071. {
  190072. png_debug1(4,"reading %d bytes\n", (int)length);
  190073. if (png_ptr->read_data_fn != NULL)
  190074. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190075. else
  190076. png_error(png_ptr, "Call to NULL read function");
  190077. }
  190078. #if !defined(PNG_NO_STDIO)
  190079. /* This is the function that does the actual reading of data. If you are
  190080. not reading from a standard C stream, you should create a replacement
  190081. read_data function and use it at run time with png_set_read_fn(), rather
  190082. than changing the library. */
  190083. #ifndef USE_FAR_KEYWORD
  190084. void PNGAPI
  190085. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190086. {
  190087. png_size_t check;
  190088. if(png_ptr == NULL) return;
  190089. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190090. * instead of an int, which is what fread() actually returns.
  190091. */
  190092. #if defined(_WIN32_WCE)
  190093. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190094. check = 0;
  190095. #else
  190096. check = (png_size_t)fread(data, (png_size_t)1, length,
  190097. (png_FILE_p)png_ptr->io_ptr);
  190098. #endif
  190099. if (check != length)
  190100. png_error(png_ptr, "Read Error");
  190101. }
  190102. #else
  190103. /* this is the model-independent version. Since the standard I/O library
  190104. can't handle far buffers in the medium and small models, we have to copy
  190105. the data.
  190106. */
  190107. #define NEAR_BUF_SIZE 1024
  190108. #define MIN(a,b) (a <= b ? a : b)
  190109. static void PNGAPI
  190110. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190111. {
  190112. int check;
  190113. png_byte *n_data;
  190114. png_FILE_p io_ptr;
  190115. if(png_ptr == NULL) return;
  190116. /* Check if data really is near. If so, use usual code. */
  190117. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190118. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190119. if ((png_bytep)n_data == data)
  190120. {
  190121. #if defined(_WIN32_WCE)
  190122. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190123. check = 0;
  190124. #else
  190125. check = fread(n_data, 1, length, io_ptr);
  190126. #endif
  190127. }
  190128. else
  190129. {
  190130. png_byte buf[NEAR_BUF_SIZE];
  190131. png_size_t read, remaining, err;
  190132. check = 0;
  190133. remaining = length;
  190134. do
  190135. {
  190136. read = MIN(NEAR_BUF_SIZE, remaining);
  190137. #if defined(_WIN32_WCE)
  190138. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190139. err = 0;
  190140. #else
  190141. err = fread(buf, (png_size_t)1, read, io_ptr);
  190142. #endif
  190143. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190144. if(err != read)
  190145. break;
  190146. else
  190147. check += err;
  190148. data += read;
  190149. remaining -= read;
  190150. }
  190151. while (remaining != 0);
  190152. }
  190153. if ((png_uint_32)check != (png_uint_32)length)
  190154. png_error(png_ptr, "read Error");
  190155. }
  190156. #endif
  190157. #endif
  190158. /* This function allows the application to supply a new input function
  190159. for libpng if standard C streams aren't being used.
  190160. This function takes as its arguments:
  190161. png_ptr - pointer to a png input data structure
  190162. io_ptr - pointer to user supplied structure containing info about
  190163. the input functions. May be NULL.
  190164. read_data_fn - pointer to a new input function that takes as its
  190165. arguments a pointer to a png_struct, a pointer to
  190166. a location where input data can be stored, and a 32-bit
  190167. unsigned int that is the number of bytes to be read.
  190168. To exit and output any fatal error messages the new write
  190169. function should call png_error(png_ptr, "Error msg"). */
  190170. void PNGAPI
  190171. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190172. png_rw_ptr read_data_fn)
  190173. {
  190174. if(png_ptr == NULL) return;
  190175. png_ptr->io_ptr = io_ptr;
  190176. #if !defined(PNG_NO_STDIO)
  190177. if (read_data_fn != NULL)
  190178. png_ptr->read_data_fn = read_data_fn;
  190179. else
  190180. png_ptr->read_data_fn = png_default_read_data;
  190181. #else
  190182. png_ptr->read_data_fn = read_data_fn;
  190183. #endif
  190184. /* It is an error to write to a read device */
  190185. if (png_ptr->write_data_fn != NULL)
  190186. {
  190187. png_ptr->write_data_fn = NULL;
  190188. png_warning(png_ptr,
  190189. "It's an error to set both read_data_fn and write_data_fn in the ");
  190190. png_warning(png_ptr,
  190191. "same structure. Resetting write_data_fn to NULL.");
  190192. }
  190193. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190194. png_ptr->output_flush_fn = NULL;
  190195. #endif
  190196. }
  190197. #endif /* PNG_READ_SUPPORTED */
  190198. /*** End of inlined file: pngrio.c ***/
  190199. /*** Start of inlined file: pngrtran.c ***/
  190200. /* pngrtran.c - transforms the data in a row for PNG readers
  190201. *
  190202. * Last changed in libpng 1.2.21 [October 4, 2007]
  190203. * For conditions of distribution and use, see copyright notice in png.h
  190204. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190205. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190206. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190207. *
  190208. * This file contains functions optionally called by an application
  190209. * in order to tell libpng how to handle data when reading a PNG.
  190210. * Transformations that are used in both reading and writing are
  190211. * in pngtrans.c.
  190212. */
  190213. #define PNG_INTERNAL
  190214. #if defined(PNG_READ_SUPPORTED)
  190215. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190216. void PNGAPI
  190217. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190218. {
  190219. png_debug(1, "in png_set_crc_action\n");
  190220. /* Tell libpng how we react to CRC errors in critical chunks */
  190221. if(png_ptr == NULL) return;
  190222. switch (crit_action)
  190223. {
  190224. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190225. break;
  190226. case PNG_CRC_WARN_USE: /* warn/use data */
  190227. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190228. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190229. break;
  190230. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190231. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190232. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190233. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190234. break;
  190235. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190236. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190237. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190238. case PNG_CRC_DEFAULT:
  190239. default:
  190240. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190241. break;
  190242. }
  190243. switch (ancil_action)
  190244. {
  190245. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190246. break;
  190247. case PNG_CRC_WARN_USE: /* warn/use data */
  190248. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190249. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190250. break;
  190251. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190252. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190253. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190254. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190255. break;
  190256. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190257. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190258. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190259. break;
  190260. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190261. case PNG_CRC_DEFAULT:
  190262. default:
  190263. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190264. break;
  190265. }
  190266. }
  190267. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190268. defined(PNG_FLOATING_POINT_SUPPORTED)
  190269. /* handle alpha and tRNS via a background color */
  190270. void PNGAPI
  190271. png_set_background(png_structp png_ptr,
  190272. png_color_16p background_color, int background_gamma_code,
  190273. int need_expand, double background_gamma)
  190274. {
  190275. png_debug(1, "in png_set_background\n");
  190276. if(png_ptr == NULL) return;
  190277. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190278. {
  190279. png_warning(png_ptr, "Application must supply a known background gamma");
  190280. return;
  190281. }
  190282. png_ptr->transformations |= PNG_BACKGROUND;
  190283. png_memcpy(&(png_ptr->background), background_color,
  190284. png_sizeof(png_color_16));
  190285. png_ptr->background_gamma = (float)background_gamma;
  190286. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190287. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190288. }
  190289. #endif
  190290. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190291. /* strip 16 bit depth files to 8 bit depth */
  190292. void PNGAPI
  190293. png_set_strip_16(png_structp png_ptr)
  190294. {
  190295. png_debug(1, "in png_set_strip_16\n");
  190296. if(png_ptr == NULL) return;
  190297. png_ptr->transformations |= PNG_16_TO_8;
  190298. }
  190299. #endif
  190300. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190301. void PNGAPI
  190302. png_set_strip_alpha(png_structp png_ptr)
  190303. {
  190304. png_debug(1, "in png_set_strip_alpha\n");
  190305. if(png_ptr == NULL) return;
  190306. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190307. }
  190308. #endif
  190309. #if defined(PNG_READ_DITHER_SUPPORTED)
  190310. /* Dither file to 8 bit. Supply a palette, the current number
  190311. * of elements in the palette, the maximum number of elements
  190312. * allowed, and a histogram if possible. If the current number
  190313. * of colors is greater then the maximum number, the palette will be
  190314. * modified to fit in the maximum number. "full_dither" indicates
  190315. * whether we need a dithering cube set up for RGB images, or if we
  190316. * simply are reducing the number of colors in a paletted image.
  190317. */
  190318. typedef struct png_dsort_struct
  190319. {
  190320. struct png_dsort_struct FAR * next;
  190321. png_byte left;
  190322. png_byte right;
  190323. } png_dsort;
  190324. typedef png_dsort FAR * png_dsortp;
  190325. typedef png_dsort FAR * FAR * png_dsortpp;
  190326. void PNGAPI
  190327. png_set_dither(png_structp png_ptr, png_colorp palette,
  190328. int num_palette, int maximum_colors, png_uint_16p histogram,
  190329. int full_dither)
  190330. {
  190331. png_debug(1, "in png_set_dither\n");
  190332. if(png_ptr == NULL) return;
  190333. png_ptr->transformations |= PNG_DITHER;
  190334. if (!full_dither)
  190335. {
  190336. int i;
  190337. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190338. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190339. for (i = 0; i < num_palette; i++)
  190340. png_ptr->dither_index[i] = (png_byte)i;
  190341. }
  190342. if (num_palette > maximum_colors)
  190343. {
  190344. if (histogram != NULL)
  190345. {
  190346. /* This is easy enough, just throw out the least used colors.
  190347. Perhaps not the best solution, but good enough. */
  190348. int i;
  190349. /* initialize an array to sort colors */
  190350. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190351. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190352. /* initialize the dither_sort array */
  190353. for (i = 0; i < num_palette; i++)
  190354. png_ptr->dither_sort[i] = (png_byte)i;
  190355. /* Find the least used palette entries by starting a
  190356. bubble sort, and running it until we have sorted
  190357. out enough colors. Note that we don't care about
  190358. sorting all the colors, just finding which are
  190359. least used. */
  190360. for (i = num_palette - 1; i >= maximum_colors; i--)
  190361. {
  190362. int done; /* to stop early if the list is pre-sorted */
  190363. int j;
  190364. done = 1;
  190365. for (j = 0; j < i; j++)
  190366. {
  190367. if (histogram[png_ptr->dither_sort[j]]
  190368. < histogram[png_ptr->dither_sort[j + 1]])
  190369. {
  190370. png_byte t;
  190371. t = png_ptr->dither_sort[j];
  190372. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190373. png_ptr->dither_sort[j + 1] = t;
  190374. done = 0;
  190375. }
  190376. }
  190377. if (done)
  190378. break;
  190379. }
  190380. /* swap the palette around, and set up a table, if necessary */
  190381. if (full_dither)
  190382. {
  190383. int j = num_palette;
  190384. /* put all the useful colors within the max, but don't
  190385. move the others */
  190386. for (i = 0; i < maximum_colors; i++)
  190387. {
  190388. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190389. {
  190390. do
  190391. j--;
  190392. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190393. palette[i] = palette[j];
  190394. }
  190395. }
  190396. }
  190397. else
  190398. {
  190399. int j = num_palette;
  190400. /* move all the used colors inside the max limit, and
  190401. develop a translation table */
  190402. for (i = 0; i < maximum_colors; i++)
  190403. {
  190404. /* only move the colors we need to */
  190405. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190406. {
  190407. png_color tmp_color;
  190408. do
  190409. j--;
  190410. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190411. tmp_color = palette[j];
  190412. palette[j] = palette[i];
  190413. palette[i] = tmp_color;
  190414. /* indicate where the color went */
  190415. png_ptr->dither_index[j] = (png_byte)i;
  190416. png_ptr->dither_index[i] = (png_byte)j;
  190417. }
  190418. }
  190419. /* find closest color for those colors we are not using */
  190420. for (i = 0; i < num_palette; i++)
  190421. {
  190422. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190423. {
  190424. int min_d, k, min_k, d_index;
  190425. /* find the closest color to one we threw out */
  190426. d_index = png_ptr->dither_index[i];
  190427. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190428. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190429. {
  190430. int d;
  190431. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190432. if (d < min_d)
  190433. {
  190434. min_d = d;
  190435. min_k = k;
  190436. }
  190437. }
  190438. /* point to closest color */
  190439. png_ptr->dither_index[i] = (png_byte)min_k;
  190440. }
  190441. }
  190442. }
  190443. png_free(png_ptr, png_ptr->dither_sort);
  190444. png_ptr->dither_sort=NULL;
  190445. }
  190446. else
  190447. {
  190448. /* This is much harder to do simply (and quickly). Perhaps
  190449. we need to go through a median cut routine, but those
  190450. don't always behave themselves with only a few colors
  190451. as input. So we will just find the closest two colors,
  190452. and throw out one of them (chosen somewhat randomly).
  190453. [We don't understand this at all, so if someone wants to
  190454. work on improving it, be our guest - AED, GRP]
  190455. */
  190456. int i;
  190457. int max_d;
  190458. int num_new_palette;
  190459. png_dsortp t;
  190460. png_dsortpp hash;
  190461. t=NULL;
  190462. /* initialize palette index arrays */
  190463. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190464. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190465. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190466. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190467. /* initialize the sort array */
  190468. for (i = 0; i < num_palette; i++)
  190469. {
  190470. png_ptr->index_to_palette[i] = (png_byte)i;
  190471. png_ptr->palette_to_index[i] = (png_byte)i;
  190472. }
  190473. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190474. png_sizeof (png_dsortp)));
  190475. for (i = 0; i < 769; i++)
  190476. hash[i] = NULL;
  190477. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190478. num_new_palette = num_palette;
  190479. /* initial wild guess at how far apart the farthest pixel
  190480. pair we will be eliminating will be. Larger
  190481. numbers mean more areas will be allocated, Smaller
  190482. numbers run the risk of not saving enough data, and
  190483. having to do this all over again.
  190484. I have not done extensive checking on this number.
  190485. */
  190486. max_d = 96;
  190487. while (num_new_palette > maximum_colors)
  190488. {
  190489. for (i = 0; i < num_new_palette - 1; i++)
  190490. {
  190491. int j;
  190492. for (j = i + 1; j < num_new_palette; j++)
  190493. {
  190494. int d;
  190495. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190496. if (d <= max_d)
  190497. {
  190498. t = (png_dsortp)png_malloc_warn(png_ptr,
  190499. (png_uint_32)(png_sizeof(png_dsort)));
  190500. if (t == NULL)
  190501. break;
  190502. t->next = hash[d];
  190503. t->left = (png_byte)i;
  190504. t->right = (png_byte)j;
  190505. hash[d] = t;
  190506. }
  190507. }
  190508. if (t == NULL)
  190509. break;
  190510. }
  190511. if (t != NULL)
  190512. for (i = 0; i <= max_d; i++)
  190513. {
  190514. if (hash[i] != NULL)
  190515. {
  190516. png_dsortp p;
  190517. for (p = hash[i]; p; p = p->next)
  190518. {
  190519. if ((int)png_ptr->index_to_palette[p->left]
  190520. < num_new_palette &&
  190521. (int)png_ptr->index_to_palette[p->right]
  190522. < num_new_palette)
  190523. {
  190524. int j, next_j;
  190525. if (num_new_palette & 0x01)
  190526. {
  190527. j = p->left;
  190528. next_j = p->right;
  190529. }
  190530. else
  190531. {
  190532. j = p->right;
  190533. next_j = p->left;
  190534. }
  190535. num_new_palette--;
  190536. palette[png_ptr->index_to_palette[j]]
  190537. = palette[num_new_palette];
  190538. if (!full_dither)
  190539. {
  190540. int k;
  190541. for (k = 0; k < num_palette; k++)
  190542. {
  190543. if (png_ptr->dither_index[k] ==
  190544. png_ptr->index_to_palette[j])
  190545. png_ptr->dither_index[k] =
  190546. png_ptr->index_to_palette[next_j];
  190547. if ((int)png_ptr->dither_index[k] ==
  190548. num_new_palette)
  190549. png_ptr->dither_index[k] =
  190550. png_ptr->index_to_palette[j];
  190551. }
  190552. }
  190553. png_ptr->index_to_palette[png_ptr->palette_to_index
  190554. [num_new_palette]] = png_ptr->index_to_palette[j];
  190555. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190556. = png_ptr->palette_to_index[num_new_palette];
  190557. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190558. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190559. }
  190560. if (num_new_palette <= maximum_colors)
  190561. break;
  190562. }
  190563. if (num_new_palette <= maximum_colors)
  190564. break;
  190565. }
  190566. }
  190567. for (i = 0; i < 769; i++)
  190568. {
  190569. if (hash[i] != NULL)
  190570. {
  190571. png_dsortp p = hash[i];
  190572. while (p)
  190573. {
  190574. t = p->next;
  190575. png_free(png_ptr, p);
  190576. p = t;
  190577. }
  190578. }
  190579. hash[i] = 0;
  190580. }
  190581. max_d += 96;
  190582. }
  190583. png_free(png_ptr, hash);
  190584. png_free(png_ptr, png_ptr->palette_to_index);
  190585. png_free(png_ptr, png_ptr->index_to_palette);
  190586. png_ptr->palette_to_index=NULL;
  190587. png_ptr->index_to_palette=NULL;
  190588. }
  190589. num_palette = maximum_colors;
  190590. }
  190591. if (png_ptr->palette == NULL)
  190592. {
  190593. png_ptr->palette = palette;
  190594. }
  190595. png_ptr->num_palette = (png_uint_16)num_palette;
  190596. if (full_dither)
  190597. {
  190598. int i;
  190599. png_bytep distance;
  190600. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190601. PNG_DITHER_BLUE_BITS;
  190602. int num_red = (1 << PNG_DITHER_RED_BITS);
  190603. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190604. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190605. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190606. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190607. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190608. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190609. png_sizeof (png_byte));
  190610. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190611. png_sizeof(png_byte)));
  190612. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190613. for (i = 0; i < num_palette; i++)
  190614. {
  190615. int ir, ig, ib;
  190616. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190617. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190618. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190619. for (ir = 0; ir < num_red; ir++)
  190620. {
  190621. /* int dr = abs(ir - r); */
  190622. int dr = ((ir > r) ? ir - r : r - ir);
  190623. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190624. for (ig = 0; ig < num_green; ig++)
  190625. {
  190626. /* int dg = abs(ig - g); */
  190627. int dg = ((ig > g) ? ig - g : g - ig);
  190628. int dt = dr + dg;
  190629. int dm = ((dr > dg) ? dr : dg);
  190630. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190631. for (ib = 0; ib < num_blue; ib++)
  190632. {
  190633. int d_index = index_g | ib;
  190634. /* int db = abs(ib - b); */
  190635. int db = ((ib > b) ? ib - b : b - ib);
  190636. int dmax = ((dm > db) ? dm : db);
  190637. int d = dmax + dt + db;
  190638. if (d < (int)distance[d_index])
  190639. {
  190640. distance[d_index] = (png_byte)d;
  190641. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190642. }
  190643. }
  190644. }
  190645. }
  190646. }
  190647. png_free(png_ptr, distance);
  190648. }
  190649. }
  190650. #endif
  190651. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190652. /* Transform the image from the file_gamma to the screen_gamma. We
  190653. * only do transformations on images where the file_gamma and screen_gamma
  190654. * are not close reciprocals, otherwise it slows things down slightly, and
  190655. * also needlessly introduces small errors.
  190656. *
  190657. * We will turn off gamma transformation later if no semitransparent entries
  190658. * are present in the tRNS array for palette images. We can't do it here
  190659. * because we don't necessarily have the tRNS chunk yet.
  190660. */
  190661. void PNGAPI
  190662. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190663. {
  190664. png_debug(1, "in png_set_gamma\n");
  190665. if(png_ptr == NULL) return;
  190666. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190667. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190668. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190669. png_ptr->transformations |= PNG_GAMMA;
  190670. png_ptr->gamma = (float)file_gamma;
  190671. png_ptr->screen_gamma = (float)scrn_gamma;
  190672. }
  190673. #endif
  190674. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190675. /* Expand paletted images to RGB, expand grayscale images of
  190676. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190677. * to alpha channels.
  190678. */
  190679. void PNGAPI
  190680. png_set_expand(png_structp png_ptr)
  190681. {
  190682. png_debug(1, "in png_set_expand\n");
  190683. if(png_ptr == NULL) return;
  190684. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190685. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190686. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190687. #endif
  190688. }
  190689. /* GRR 19990627: the following three functions currently are identical
  190690. * to png_set_expand(). However, it is entirely reasonable that someone
  190691. * might wish to expand an indexed image to RGB but *not* expand a single,
  190692. * fully transparent palette entry to a full alpha channel--perhaps instead
  190693. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190694. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190695. * IOW, a future version of the library may make the transformations flag
  190696. * a bit more fine-grained, with separate bits for each of these three
  190697. * functions.
  190698. *
  190699. * More to the point, these functions make it obvious what libpng will be
  190700. * doing, whereas "expand" can (and does) mean any number of things.
  190701. *
  190702. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190703. * to expand only the sample depth but not to expand the tRNS to alpha.
  190704. */
  190705. /* Expand paletted images to RGB. */
  190706. void PNGAPI
  190707. png_set_palette_to_rgb(png_structp png_ptr)
  190708. {
  190709. png_debug(1, "in png_set_palette_to_rgb\n");
  190710. if(png_ptr == NULL) return;
  190711. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190712. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190713. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190714. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190715. #endif
  190716. }
  190717. #if !defined(PNG_1_0_X)
  190718. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190719. void PNGAPI
  190720. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190721. {
  190722. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190723. if(png_ptr == NULL) return;
  190724. png_ptr->transformations |= PNG_EXPAND;
  190725. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190726. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190727. #endif
  190728. }
  190729. #endif
  190730. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190731. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190732. /* Deprecated as of libpng-1.2.9 */
  190733. void PNGAPI
  190734. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190735. {
  190736. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190737. if(png_ptr == NULL) return;
  190738. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190739. }
  190740. #endif
  190741. /* Expand tRNS chunks to alpha channels. */
  190742. void PNGAPI
  190743. png_set_tRNS_to_alpha(png_structp png_ptr)
  190744. {
  190745. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190746. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190747. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190748. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190749. #endif
  190750. }
  190751. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190752. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190753. void PNGAPI
  190754. png_set_gray_to_rgb(png_structp png_ptr)
  190755. {
  190756. png_debug(1, "in png_set_gray_to_rgb\n");
  190757. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190758. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190759. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190760. #endif
  190761. }
  190762. #endif
  190763. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190764. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190765. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190766. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190767. */
  190768. void PNGAPI
  190769. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190770. double green)
  190771. {
  190772. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190773. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190774. if(png_ptr == NULL) return;
  190775. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190776. }
  190777. #endif
  190778. void PNGAPI
  190779. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190780. png_fixed_point red, png_fixed_point green)
  190781. {
  190782. png_debug(1, "in png_set_rgb_to_gray\n");
  190783. if(png_ptr == NULL) return;
  190784. switch(error_action)
  190785. {
  190786. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190787. break;
  190788. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190789. break;
  190790. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190791. }
  190792. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190793. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190794. png_ptr->transformations |= PNG_EXPAND;
  190795. #else
  190796. {
  190797. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190798. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190799. }
  190800. #endif
  190801. {
  190802. png_uint_16 red_int, green_int;
  190803. if(red < 0 || green < 0)
  190804. {
  190805. red_int = 6968; /* .212671 * 32768 + .5 */
  190806. green_int = 23434; /* .715160 * 32768 + .5 */
  190807. }
  190808. else if(red + green < 100000L)
  190809. {
  190810. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190811. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190812. }
  190813. else
  190814. {
  190815. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190816. red_int = 6968;
  190817. green_int = 23434;
  190818. }
  190819. png_ptr->rgb_to_gray_red_coeff = red_int;
  190820. png_ptr->rgb_to_gray_green_coeff = green_int;
  190821. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190822. }
  190823. }
  190824. #endif
  190825. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190826. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190827. defined(PNG_LEGACY_SUPPORTED)
  190828. void PNGAPI
  190829. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190830. read_user_transform_fn)
  190831. {
  190832. png_debug(1, "in png_set_read_user_transform_fn\n");
  190833. if(png_ptr == NULL) return;
  190834. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190835. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190836. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190837. #endif
  190838. #ifdef PNG_LEGACY_SUPPORTED
  190839. if(read_user_transform_fn)
  190840. png_warning(png_ptr,
  190841. "This version of libpng does not support user transforms");
  190842. #endif
  190843. }
  190844. #endif
  190845. /* Initialize everything needed for the read. This includes modifying
  190846. * the palette.
  190847. */
  190848. void /* PRIVATE */
  190849. png_init_read_transformations(png_structp png_ptr)
  190850. {
  190851. png_debug(1, "in png_init_read_transformations\n");
  190852. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190853. if(png_ptr != NULL)
  190854. #endif
  190855. {
  190856. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190857. || defined(PNG_READ_GAMMA_SUPPORTED)
  190858. int color_type = png_ptr->color_type;
  190859. #endif
  190860. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190861. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190862. /* Detect gray background and attempt to enable optimization
  190863. * for gray --> RGB case */
  190864. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190865. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190866. * background color might actually be gray yet not be flagged as such.
  190867. * This is not a problem for the current code, which uses
  190868. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190869. * png_do_gray_to_rgb() transformation.
  190870. */
  190871. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190872. !(color_type & PNG_COLOR_MASK_COLOR))
  190873. {
  190874. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190875. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190876. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190877. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190878. png_ptr->background.red == png_ptr->background.green &&
  190879. png_ptr->background.red == png_ptr->background.blue)
  190880. {
  190881. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190882. png_ptr->background.gray = png_ptr->background.red;
  190883. }
  190884. #endif
  190885. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190886. (png_ptr->transformations & PNG_EXPAND))
  190887. {
  190888. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190889. {
  190890. /* expand background and tRNS chunks */
  190891. switch (png_ptr->bit_depth)
  190892. {
  190893. case 1:
  190894. png_ptr->background.gray *= (png_uint_16)0xff;
  190895. png_ptr->background.red = png_ptr->background.green
  190896. = png_ptr->background.blue = png_ptr->background.gray;
  190897. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190898. {
  190899. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190900. png_ptr->trans_values.red = png_ptr->trans_values.green
  190901. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190902. }
  190903. break;
  190904. case 2:
  190905. png_ptr->background.gray *= (png_uint_16)0x55;
  190906. png_ptr->background.red = png_ptr->background.green
  190907. = png_ptr->background.blue = png_ptr->background.gray;
  190908. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190909. {
  190910. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190911. png_ptr->trans_values.red = png_ptr->trans_values.green
  190912. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190913. }
  190914. break;
  190915. case 4:
  190916. png_ptr->background.gray *= (png_uint_16)0x11;
  190917. png_ptr->background.red = png_ptr->background.green
  190918. = png_ptr->background.blue = png_ptr->background.gray;
  190919. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190920. {
  190921. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190922. png_ptr->trans_values.red = png_ptr->trans_values.green
  190923. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190924. }
  190925. break;
  190926. case 8:
  190927. case 16:
  190928. png_ptr->background.red = png_ptr->background.green
  190929. = png_ptr->background.blue = png_ptr->background.gray;
  190930. break;
  190931. }
  190932. }
  190933. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190934. {
  190935. png_ptr->background.red =
  190936. png_ptr->palette[png_ptr->background.index].red;
  190937. png_ptr->background.green =
  190938. png_ptr->palette[png_ptr->background.index].green;
  190939. png_ptr->background.blue =
  190940. png_ptr->palette[png_ptr->background.index].blue;
  190941. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190942. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190943. {
  190944. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190945. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190946. #endif
  190947. {
  190948. /* invert the alpha channel (in tRNS) unless the pixels are
  190949. going to be expanded, in which case leave it for later */
  190950. int i,istop;
  190951. istop=(int)png_ptr->num_trans;
  190952. for (i=0; i<istop; i++)
  190953. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190954. }
  190955. }
  190956. #endif
  190957. }
  190958. }
  190959. #endif
  190960. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190961. png_ptr->background_1 = png_ptr->background;
  190962. #endif
  190963. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190964. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190965. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190966. < PNG_GAMMA_THRESHOLD))
  190967. {
  190968. int i,k;
  190969. k=0;
  190970. for (i=0; i<png_ptr->num_trans; i++)
  190971. {
  190972. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190973. k=1; /* partial transparency is present */
  190974. }
  190975. if (k == 0)
  190976. png_ptr->transformations &= (~PNG_GAMMA);
  190977. }
  190978. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190979. png_ptr->gamma != 0.0)
  190980. {
  190981. png_build_gamma_table(png_ptr);
  190982. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190983. if (png_ptr->transformations & PNG_BACKGROUND)
  190984. {
  190985. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190986. {
  190987. /* could skip if no transparency and
  190988. */
  190989. png_color back, back_1;
  190990. png_colorp palette = png_ptr->palette;
  190991. int num_palette = png_ptr->num_palette;
  190992. int i;
  190993. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190994. {
  190995. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190996. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190997. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190998. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190999. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191000. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191001. }
  191002. else
  191003. {
  191004. double g, gs;
  191005. switch (png_ptr->background_gamma_type)
  191006. {
  191007. case PNG_BACKGROUND_GAMMA_SCREEN:
  191008. g = (png_ptr->screen_gamma);
  191009. gs = 1.0;
  191010. break;
  191011. case PNG_BACKGROUND_GAMMA_FILE:
  191012. g = 1.0 / (png_ptr->gamma);
  191013. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191014. break;
  191015. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191016. g = 1.0 / (png_ptr->background_gamma);
  191017. gs = 1.0 / (png_ptr->background_gamma *
  191018. png_ptr->screen_gamma);
  191019. break;
  191020. default:
  191021. g = 1.0; /* back_1 */
  191022. gs = 1.0; /* back */
  191023. }
  191024. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191025. {
  191026. back.red = (png_byte)png_ptr->background.red;
  191027. back.green = (png_byte)png_ptr->background.green;
  191028. back.blue = (png_byte)png_ptr->background.blue;
  191029. }
  191030. else
  191031. {
  191032. back.red = (png_byte)(pow(
  191033. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191034. back.green = (png_byte)(pow(
  191035. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191036. back.blue = (png_byte)(pow(
  191037. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191038. }
  191039. back_1.red = (png_byte)(pow(
  191040. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191041. back_1.green = (png_byte)(pow(
  191042. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191043. back_1.blue = (png_byte)(pow(
  191044. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191045. }
  191046. for (i = 0; i < num_palette; i++)
  191047. {
  191048. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191049. {
  191050. if (png_ptr->trans[i] == 0)
  191051. {
  191052. palette[i] = back;
  191053. }
  191054. else /* if (png_ptr->trans[i] != 0xff) */
  191055. {
  191056. png_byte v, w;
  191057. v = png_ptr->gamma_to_1[palette[i].red];
  191058. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191059. palette[i].red = png_ptr->gamma_from_1[w];
  191060. v = png_ptr->gamma_to_1[palette[i].green];
  191061. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191062. palette[i].green = png_ptr->gamma_from_1[w];
  191063. v = png_ptr->gamma_to_1[palette[i].blue];
  191064. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191065. palette[i].blue = png_ptr->gamma_from_1[w];
  191066. }
  191067. }
  191068. else
  191069. {
  191070. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191071. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191072. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191073. }
  191074. }
  191075. }
  191076. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191077. else
  191078. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191079. {
  191080. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191081. double g = 1.0;
  191082. double gs = 1.0;
  191083. switch (png_ptr->background_gamma_type)
  191084. {
  191085. case PNG_BACKGROUND_GAMMA_SCREEN:
  191086. g = (png_ptr->screen_gamma);
  191087. gs = 1.0;
  191088. break;
  191089. case PNG_BACKGROUND_GAMMA_FILE:
  191090. g = 1.0 / (png_ptr->gamma);
  191091. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191092. break;
  191093. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191094. g = 1.0 / (png_ptr->background_gamma);
  191095. gs = 1.0 / (png_ptr->background_gamma *
  191096. png_ptr->screen_gamma);
  191097. break;
  191098. }
  191099. png_ptr->background_1.gray = (png_uint_16)(pow(
  191100. (double)png_ptr->background.gray / m, g) * m + .5);
  191101. png_ptr->background.gray = (png_uint_16)(pow(
  191102. (double)png_ptr->background.gray / m, gs) * m + .5);
  191103. if ((png_ptr->background.red != png_ptr->background.green) ||
  191104. (png_ptr->background.red != png_ptr->background.blue) ||
  191105. (png_ptr->background.red != png_ptr->background.gray))
  191106. {
  191107. /* RGB or RGBA with color background */
  191108. png_ptr->background_1.red = (png_uint_16)(pow(
  191109. (double)png_ptr->background.red / m, g) * m + .5);
  191110. png_ptr->background_1.green = (png_uint_16)(pow(
  191111. (double)png_ptr->background.green / m, g) * m + .5);
  191112. png_ptr->background_1.blue = (png_uint_16)(pow(
  191113. (double)png_ptr->background.blue / m, g) * m + .5);
  191114. png_ptr->background.red = (png_uint_16)(pow(
  191115. (double)png_ptr->background.red / m, gs) * m + .5);
  191116. png_ptr->background.green = (png_uint_16)(pow(
  191117. (double)png_ptr->background.green / m, gs) * m + .5);
  191118. png_ptr->background.blue = (png_uint_16)(pow(
  191119. (double)png_ptr->background.blue / m, gs) * m + .5);
  191120. }
  191121. else
  191122. {
  191123. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191124. png_ptr->background_1.red = png_ptr->background_1.green
  191125. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191126. png_ptr->background.red = png_ptr->background.green
  191127. = png_ptr->background.blue = png_ptr->background.gray;
  191128. }
  191129. }
  191130. }
  191131. else
  191132. /* transformation does not include PNG_BACKGROUND */
  191133. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191134. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191135. {
  191136. png_colorp palette = png_ptr->palette;
  191137. int num_palette = png_ptr->num_palette;
  191138. int i;
  191139. for (i = 0; i < num_palette; i++)
  191140. {
  191141. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191142. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191143. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191144. }
  191145. }
  191146. }
  191147. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191148. else
  191149. #endif
  191150. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191151. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191152. /* No GAMMA transformation */
  191153. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191154. (color_type == PNG_COLOR_TYPE_PALETTE))
  191155. {
  191156. int i;
  191157. int istop = (int)png_ptr->num_trans;
  191158. png_color back;
  191159. png_colorp palette = png_ptr->palette;
  191160. back.red = (png_byte)png_ptr->background.red;
  191161. back.green = (png_byte)png_ptr->background.green;
  191162. back.blue = (png_byte)png_ptr->background.blue;
  191163. for (i = 0; i < istop; i++)
  191164. {
  191165. if (png_ptr->trans[i] == 0)
  191166. {
  191167. palette[i] = back;
  191168. }
  191169. else if (png_ptr->trans[i] != 0xff)
  191170. {
  191171. /* The png_composite() macro is defined in png.h */
  191172. png_composite(palette[i].red, palette[i].red,
  191173. png_ptr->trans[i], back.red);
  191174. png_composite(palette[i].green, palette[i].green,
  191175. png_ptr->trans[i], back.green);
  191176. png_composite(palette[i].blue, palette[i].blue,
  191177. png_ptr->trans[i], back.blue);
  191178. }
  191179. }
  191180. }
  191181. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191182. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191183. if ((png_ptr->transformations & PNG_SHIFT) &&
  191184. (color_type == PNG_COLOR_TYPE_PALETTE))
  191185. {
  191186. png_uint_16 i;
  191187. png_uint_16 istop = png_ptr->num_palette;
  191188. int sr = 8 - png_ptr->sig_bit.red;
  191189. int sg = 8 - png_ptr->sig_bit.green;
  191190. int sb = 8 - png_ptr->sig_bit.blue;
  191191. if (sr < 0 || sr > 8)
  191192. sr = 0;
  191193. if (sg < 0 || sg > 8)
  191194. sg = 0;
  191195. if (sb < 0 || sb > 8)
  191196. sb = 0;
  191197. for (i = 0; i < istop; i++)
  191198. {
  191199. png_ptr->palette[i].red >>= sr;
  191200. png_ptr->palette[i].green >>= sg;
  191201. png_ptr->palette[i].blue >>= sb;
  191202. }
  191203. }
  191204. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191205. }
  191206. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191207. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191208. if(png_ptr)
  191209. return;
  191210. #endif
  191211. }
  191212. /* Modify the info structure to reflect the transformations. The
  191213. * info should be updated so a PNG file could be written with it,
  191214. * assuming the transformations result in valid PNG data.
  191215. */
  191216. void /* PRIVATE */
  191217. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191218. {
  191219. png_debug(1, "in png_read_transform_info\n");
  191220. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191221. if (png_ptr->transformations & PNG_EXPAND)
  191222. {
  191223. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191224. {
  191225. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191226. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191227. else
  191228. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191229. info_ptr->bit_depth = 8;
  191230. info_ptr->num_trans = 0;
  191231. }
  191232. else
  191233. {
  191234. if (png_ptr->num_trans)
  191235. {
  191236. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191237. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191238. else
  191239. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191240. }
  191241. if (info_ptr->bit_depth < 8)
  191242. info_ptr->bit_depth = 8;
  191243. info_ptr->num_trans = 0;
  191244. }
  191245. }
  191246. #endif
  191247. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191248. if (png_ptr->transformations & PNG_BACKGROUND)
  191249. {
  191250. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191251. info_ptr->num_trans = 0;
  191252. info_ptr->background = png_ptr->background;
  191253. }
  191254. #endif
  191255. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191256. if (png_ptr->transformations & PNG_GAMMA)
  191257. {
  191258. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191259. info_ptr->gamma = png_ptr->gamma;
  191260. #endif
  191261. #ifdef PNG_FIXED_POINT_SUPPORTED
  191262. info_ptr->int_gamma = png_ptr->int_gamma;
  191263. #endif
  191264. }
  191265. #endif
  191266. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191267. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191268. info_ptr->bit_depth = 8;
  191269. #endif
  191270. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191271. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191272. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191273. #endif
  191274. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191275. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191276. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191277. #endif
  191278. #if defined(PNG_READ_DITHER_SUPPORTED)
  191279. if (png_ptr->transformations & PNG_DITHER)
  191280. {
  191281. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191282. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191283. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191284. {
  191285. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191286. }
  191287. }
  191288. #endif
  191289. #if defined(PNG_READ_PACK_SUPPORTED)
  191290. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191291. info_ptr->bit_depth = 8;
  191292. #endif
  191293. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191294. info_ptr->channels = 1;
  191295. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191296. info_ptr->channels = 3;
  191297. else
  191298. info_ptr->channels = 1;
  191299. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191300. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191301. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191302. #endif
  191303. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191304. info_ptr->channels++;
  191305. #if defined(PNG_READ_FILLER_SUPPORTED)
  191306. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191307. if ((png_ptr->transformations & PNG_FILLER) &&
  191308. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191309. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191310. {
  191311. info_ptr->channels++;
  191312. /* if adding a true alpha channel not just filler */
  191313. #if !defined(PNG_1_0_X)
  191314. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191315. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191316. #endif
  191317. }
  191318. #endif
  191319. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191320. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191321. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191322. {
  191323. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191324. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191325. if(info_ptr->channels < png_ptr->user_transform_channels)
  191326. info_ptr->channels = png_ptr->user_transform_channels;
  191327. }
  191328. #endif
  191329. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191330. info_ptr->bit_depth);
  191331. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191332. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191333. if(png_ptr)
  191334. return;
  191335. #endif
  191336. }
  191337. /* Transform the row. The order of transformations is significant,
  191338. * and is very touchy. If you add a transformation, take care to
  191339. * decide how it fits in with the other transformations here.
  191340. */
  191341. void /* PRIVATE */
  191342. png_do_read_transformations(png_structp png_ptr)
  191343. {
  191344. png_debug(1, "in png_do_read_transformations\n");
  191345. if (png_ptr->row_buf == NULL)
  191346. {
  191347. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191348. char msg[50];
  191349. png_snprintf2(msg, 50,
  191350. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191351. png_ptr->pass);
  191352. png_error(png_ptr, msg);
  191353. #else
  191354. png_error(png_ptr, "NULL row buffer");
  191355. #endif
  191356. }
  191357. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191358. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191359. /* Application has failed to call either png_read_start_image()
  191360. * or png_read_update_info() after setting transforms that expand
  191361. * pixels. This check added to libpng-1.2.19 */
  191362. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191363. png_error(png_ptr, "Uninitialized row");
  191364. #else
  191365. png_warning(png_ptr, "Uninitialized row");
  191366. #endif
  191367. #endif
  191368. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191369. if (png_ptr->transformations & PNG_EXPAND)
  191370. {
  191371. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191372. {
  191373. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191374. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191375. }
  191376. else
  191377. {
  191378. if (png_ptr->num_trans &&
  191379. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191380. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191381. &(png_ptr->trans_values));
  191382. else
  191383. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191384. NULL);
  191385. }
  191386. }
  191387. #endif
  191388. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191389. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191390. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191391. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191392. #endif
  191393. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191394. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191395. {
  191396. int rgb_error =
  191397. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191398. if(rgb_error)
  191399. {
  191400. png_ptr->rgb_to_gray_status=1;
  191401. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191402. PNG_RGB_TO_GRAY_WARN)
  191403. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191404. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191405. PNG_RGB_TO_GRAY_ERR)
  191406. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191407. }
  191408. }
  191409. #endif
  191410. /*
  191411. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191412. In most cases, the "simple transparency" should be done prior to doing
  191413. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191414. pixel is transparent. You would also need to make sure that the
  191415. transparency information is upgraded to RGB.
  191416. To summarize, the current flow is:
  191417. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191418. with background "in place" if transparent,
  191419. convert to RGB if necessary
  191420. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191421. convert to RGB if necessary
  191422. To support RGB backgrounds for gray images we need:
  191423. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191424. 3 or 6 bytes and composite with background
  191425. "in place" if transparent (3x compare/pixel
  191426. compared to doing composite with gray bkgrnd)
  191427. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191428. remove alpha bytes (3x float operations/pixel
  191429. compared with composite on gray background)
  191430. Greg's change will do this. The reason it wasn't done before is for
  191431. performance, as this increases the per-pixel operations. If we would check
  191432. in advance if the background was gray or RGB, and position the gray-to-RGB
  191433. transform appropriately, then it would save a lot of work/time.
  191434. */
  191435. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191436. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191437. * for performance reasons */
  191438. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191439. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191440. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191441. #endif
  191442. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191443. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191444. ((png_ptr->num_trans != 0 ) ||
  191445. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191446. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191447. &(png_ptr->trans_values), &(png_ptr->background)
  191448. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191449. , &(png_ptr->background_1),
  191450. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191451. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191452. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191453. png_ptr->gamma_shift
  191454. #endif
  191455. );
  191456. #endif
  191457. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191458. if ((png_ptr->transformations & PNG_GAMMA) &&
  191459. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191460. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191461. ((png_ptr->num_trans != 0) ||
  191462. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191463. #endif
  191464. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191465. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191466. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191467. png_ptr->gamma_shift);
  191468. #endif
  191469. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191470. if (png_ptr->transformations & PNG_16_TO_8)
  191471. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191472. #endif
  191473. #if defined(PNG_READ_DITHER_SUPPORTED)
  191474. if (png_ptr->transformations & PNG_DITHER)
  191475. {
  191476. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191477. png_ptr->palette_lookup, png_ptr->dither_index);
  191478. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191479. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191480. }
  191481. #endif
  191482. #if defined(PNG_READ_INVERT_SUPPORTED)
  191483. if (png_ptr->transformations & PNG_INVERT_MONO)
  191484. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191485. #endif
  191486. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191487. if (png_ptr->transformations & PNG_SHIFT)
  191488. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191489. &(png_ptr->shift));
  191490. #endif
  191491. #if defined(PNG_READ_PACK_SUPPORTED)
  191492. if (png_ptr->transformations & PNG_PACK)
  191493. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191494. #endif
  191495. #if defined(PNG_READ_BGR_SUPPORTED)
  191496. if (png_ptr->transformations & PNG_BGR)
  191497. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191498. #endif
  191499. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191500. if (png_ptr->transformations & PNG_PACKSWAP)
  191501. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191502. #endif
  191503. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191504. /* if gray -> RGB, do so now only if we did not do so above */
  191505. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191506. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191507. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191508. #endif
  191509. #if defined(PNG_READ_FILLER_SUPPORTED)
  191510. if (png_ptr->transformations & PNG_FILLER)
  191511. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191512. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191513. #endif
  191514. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191515. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191516. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191517. #endif
  191518. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191519. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191520. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191521. #endif
  191522. #if defined(PNG_READ_SWAP_SUPPORTED)
  191523. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191524. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191525. #endif
  191526. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191527. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191528. {
  191529. if(png_ptr->read_user_transform_fn != NULL)
  191530. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191531. (png_ptr, /* png_ptr */
  191532. &(png_ptr->row_info), /* row_info: */
  191533. /* png_uint_32 width; width of row */
  191534. /* png_uint_32 rowbytes; number of bytes in row */
  191535. /* png_byte color_type; color type of pixels */
  191536. /* png_byte bit_depth; bit depth of samples */
  191537. /* png_byte channels; number of channels (1-4) */
  191538. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191539. png_ptr->row_buf + 1); /* start of pixel data for row */
  191540. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191541. if(png_ptr->user_transform_depth)
  191542. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191543. if(png_ptr->user_transform_channels)
  191544. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191545. #endif
  191546. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191547. png_ptr->row_info.channels);
  191548. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191549. png_ptr->row_info.width);
  191550. }
  191551. #endif
  191552. }
  191553. #if defined(PNG_READ_PACK_SUPPORTED)
  191554. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191555. * without changing the actual values. Thus, if you had a row with
  191556. * a bit depth of 1, you would end up with bytes that only contained
  191557. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191558. * png_do_shift() after this.
  191559. */
  191560. void /* PRIVATE */
  191561. png_do_unpack(png_row_infop row_info, png_bytep row)
  191562. {
  191563. png_debug(1, "in png_do_unpack\n");
  191564. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191565. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191566. #else
  191567. if (row_info->bit_depth < 8)
  191568. #endif
  191569. {
  191570. png_uint_32 i;
  191571. png_uint_32 row_width=row_info->width;
  191572. switch (row_info->bit_depth)
  191573. {
  191574. case 1:
  191575. {
  191576. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191577. png_bytep dp = row + (png_size_t)row_width - 1;
  191578. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191579. for (i = 0; i < row_width; i++)
  191580. {
  191581. *dp = (png_byte)((*sp >> shift) & 0x01);
  191582. if (shift == 7)
  191583. {
  191584. shift = 0;
  191585. sp--;
  191586. }
  191587. else
  191588. shift++;
  191589. dp--;
  191590. }
  191591. break;
  191592. }
  191593. case 2:
  191594. {
  191595. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191596. png_bytep dp = row + (png_size_t)row_width - 1;
  191597. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191598. for (i = 0; i < row_width; i++)
  191599. {
  191600. *dp = (png_byte)((*sp >> shift) & 0x03);
  191601. if (shift == 6)
  191602. {
  191603. shift = 0;
  191604. sp--;
  191605. }
  191606. else
  191607. shift += 2;
  191608. dp--;
  191609. }
  191610. break;
  191611. }
  191612. case 4:
  191613. {
  191614. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191615. png_bytep dp = row + (png_size_t)row_width - 1;
  191616. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191617. for (i = 0; i < row_width; i++)
  191618. {
  191619. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191620. if (shift == 4)
  191621. {
  191622. shift = 0;
  191623. sp--;
  191624. }
  191625. else
  191626. shift = 4;
  191627. dp--;
  191628. }
  191629. break;
  191630. }
  191631. }
  191632. row_info->bit_depth = 8;
  191633. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191634. row_info->rowbytes = row_width * row_info->channels;
  191635. }
  191636. }
  191637. #endif
  191638. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191639. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191640. * pixels back to their significant bits values. Thus, if you have
  191641. * a row of bit depth 8, but only 5 are significant, this will shift
  191642. * the values back to 0 through 31.
  191643. */
  191644. void /* PRIVATE */
  191645. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191646. {
  191647. png_debug(1, "in png_do_unshift\n");
  191648. if (
  191649. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191650. row != NULL && row_info != NULL && sig_bits != NULL &&
  191651. #endif
  191652. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191653. {
  191654. int shift[4];
  191655. int channels = 0;
  191656. int c;
  191657. png_uint_16 value = 0;
  191658. png_uint_32 row_width = row_info->width;
  191659. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191660. {
  191661. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191662. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191663. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191664. }
  191665. else
  191666. {
  191667. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191668. }
  191669. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191670. {
  191671. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191672. }
  191673. for (c = 0; c < channels; c++)
  191674. {
  191675. if (shift[c] <= 0)
  191676. shift[c] = 0;
  191677. else
  191678. value = 1;
  191679. }
  191680. if (!value)
  191681. return;
  191682. switch (row_info->bit_depth)
  191683. {
  191684. case 2:
  191685. {
  191686. png_bytep bp;
  191687. png_uint_32 i;
  191688. png_uint_32 istop = row_info->rowbytes;
  191689. for (bp = row, i = 0; i < istop; i++)
  191690. {
  191691. *bp >>= 1;
  191692. *bp++ &= 0x55;
  191693. }
  191694. break;
  191695. }
  191696. case 4:
  191697. {
  191698. png_bytep bp = row;
  191699. png_uint_32 i;
  191700. png_uint_32 istop = row_info->rowbytes;
  191701. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191702. (png_byte)((int)0xf >> shift[0]));
  191703. for (i = 0; i < istop; i++)
  191704. {
  191705. *bp >>= shift[0];
  191706. *bp++ &= mask;
  191707. }
  191708. break;
  191709. }
  191710. case 8:
  191711. {
  191712. png_bytep bp = row;
  191713. png_uint_32 i;
  191714. png_uint_32 istop = row_width * channels;
  191715. for (i = 0; i < istop; i++)
  191716. {
  191717. *bp++ >>= shift[i%channels];
  191718. }
  191719. break;
  191720. }
  191721. case 16:
  191722. {
  191723. png_bytep bp = row;
  191724. png_uint_32 i;
  191725. png_uint_32 istop = channels * row_width;
  191726. for (i = 0; i < istop; i++)
  191727. {
  191728. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191729. value >>= shift[i%channels];
  191730. *bp++ = (png_byte)(value >> 8);
  191731. *bp++ = (png_byte)(value & 0xff);
  191732. }
  191733. break;
  191734. }
  191735. }
  191736. }
  191737. }
  191738. #endif
  191739. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191740. /* chop rows of bit depth 16 down to 8 */
  191741. void /* PRIVATE */
  191742. png_do_chop(png_row_infop row_info, png_bytep row)
  191743. {
  191744. png_debug(1, "in png_do_chop\n");
  191745. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191746. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191747. #else
  191748. if (row_info->bit_depth == 16)
  191749. #endif
  191750. {
  191751. png_bytep sp = row;
  191752. png_bytep dp = row;
  191753. png_uint_32 i;
  191754. png_uint_32 istop = row_info->width * row_info->channels;
  191755. for (i = 0; i<istop; i++, sp += 2, dp++)
  191756. {
  191757. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191758. /* This does a more accurate scaling of the 16-bit color
  191759. * value, rather than a simple low-byte truncation.
  191760. *
  191761. * What the ideal calculation should be:
  191762. * *dp = (((((png_uint_32)(*sp) << 8) |
  191763. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191764. *
  191765. * GRR: no, I think this is what it really should be:
  191766. * *dp = (((((png_uint_32)(*sp) << 8) |
  191767. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191768. *
  191769. * GRR: here's the exact calculation with shifts:
  191770. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191771. * *dp = (temp - (temp >> 8)) >> 8;
  191772. *
  191773. * Approximate calculation with shift/add instead of multiply/divide:
  191774. * *dp = ((((png_uint_32)(*sp) << 8) |
  191775. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191776. *
  191777. * What we actually do to avoid extra shifting and conversion:
  191778. */
  191779. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191780. #else
  191781. /* Simply discard the low order byte */
  191782. *dp = *sp;
  191783. #endif
  191784. }
  191785. row_info->bit_depth = 8;
  191786. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191787. row_info->rowbytes = row_info->width * row_info->channels;
  191788. }
  191789. }
  191790. #endif
  191791. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191792. void /* PRIVATE */
  191793. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191794. {
  191795. png_debug(1, "in png_do_read_swap_alpha\n");
  191796. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191797. if (row != NULL && row_info != NULL)
  191798. #endif
  191799. {
  191800. png_uint_32 row_width = row_info->width;
  191801. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191802. {
  191803. /* This converts from RGBA to ARGB */
  191804. if (row_info->bit_depth == 8)
  191805. {
  191806. png_bytep sp = row + row_info->rowbytes;
  191807. png_bytep dp = sp;
  191808. png_byte save;
  191809. png_uint_32 i;
  191810. for (i = 0; i < row_width; i++)
  191811. {
  191812. save = *(--sp);
  191813. *(--dp) = *(--sp);
  191814. *(--dp) = *(--sp);
  191815. *(--dp) = *(--sp);
  191816. *(--dp) = save;
  191817. }
  191818. }
  191819. /* This converts from RRGGBBAA to AARRGGBB */
  191820. else
  191821. {
  191822. png_bytep sp = row + row_info->rowbytes;
  191823. png_bytep dp = sp;
  191824. png_byte save[2];
  191825. png_uint_32 i;
  191826. for (i = 0; i < row_width; i++)
  191827. {
  191828. save[0] = *(--sp);
  191829. save[1] = *(--sp);
  191830. *(--dp) = *(--sp);
  191831. *(--dp) = *(--sp);
  191832. *(--dp) = *(--sp);
  191833. *(--dp) = *(--sp);
  191834. *(--dp) = *(--sp);
  191835. *(--dp) = *(--sp);
  191836. *(--dp) = save[0];
  191837. *(--dp) = save[1];
  191838. }
  191839. }
  191840. }
  191841. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191842. {
  191843. /* This converts from GA to AG */
  191844. if (row_info->bit_depth == 8)
  191845. {
  191846. png_bytep sp = row + row_info->rowbytes;
  191847. png_bytep dp = sp;
  191848. png_byte save;
  191849. png_uint_32 i;
  191850. for (i = 0; i < row_width; i++)
  191851. {
  191852. save = *(--sp);
  191853. *(--dp) = *(--sp);
  191854. *(--dp) = save;
  191855. }
  191856. }
  191857. /* This converts from GGAA to AAGG */
  191858. else
  191859. {
  191860. png_bytep sp = row + row_info->rowbytes;
  191861. png_bytep dp = sp;
  191862. png_byte save[2];
  191863. png_uint_32 i;
  191864. for (i = 0; i < row_width; i++)
  191865. {
  191866. save[0] = *(--sp);
  191867. save[1] = *(--sp);
  191868. *(--dp) = *(--sp);
  191869. *(--dp) = *(--sp);
  191870. *(--dp) = save[0];
  191871. *(--dp) = save[1];
  191872. }
  191873. }
  191874. }
  191875. }
  191876. }
  191877. #endif
  191878. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191879. void /* PRIVATE */
  191880. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191881. {
  191882. png_debug(1, "in png_do_read_invert_alpha\n");
  191883. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191884. if (row != NULL && row_info != NULL)
  191885. #endif
  191886. {
  191887. png_uint_32 row_width = row_info->width;
  191888. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191889. {
  191890. /* This inverts the alpha channel in RGBA */
  191891. if (row_info->bit_depth == 8)
  191892. {
  191893. png_bytep sp = row + row_info->rowbytes;
  191894. png_bytep dp = sp;
  191895. png_uint_32 i;
  191896. for (i = 0; i < row_width; i++)
  191897. {
  191898. *(--dp) = (png_byte)(255 - *(--sp));
  191899. /* This does nothing:
  191900. *(--dp) = *(--sp);
  191901. *(--dp) = *(--sp);
  191902. *(--dp) = *(--sp);
  191903. We can replace it with:
  191904. */
  191905. sp-=3;
  191906. dp=sp;
  191907. }
  191908. }
  191909. /* This inverts the alpha channel in RRGGBBAA */
  191910. else
  191911. {
  191912. png_bytep sp = row + row_info->rowbytes;
  191913. png_bytep dp = sp;
  191914. png_uint_32 i;
  191915. for (i = 0; i < row_width; i++)
  191916. {
  191917. *(--dp) = (png_byte)(255 - *(--sp));
  191918. *(--dp) = (png_byte)(255 - *(--sp));
  191919. /* This does nothing:
  191920. *(--dp) = *(--sp);
  191921. *(--dp) = *(--sp);
  191922. *(--dp) = *(--sp);
  191923. *(--dp) = *(--sp);
  191924. *(--dp) = *(--sp);
  191925. *(--dp) = *(--sp);
  191926. We can replace it with:
  191927. */
  191928. sp-=6;
  191929. dp=sp;
  191930. }
  191931. }
  191932. }
  191933. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191934. {
  191935. /* This inverts the alpha channel in GA */
  191936. if (row_info->bit_depth == 8)
  191937. {
  191938. png_bytep sp = row + row_info->rowbytes;
  191939. png_bytep dp = sp;
  191940. png_uint_32 i;
  191941. for (i = 0; i < row_width; i++)
  191942. {
  191943. *(--dp) = (png_byte)(255 - *(--sp));
  191944. *(--dp) = *(--sp);
  191945. }
  191946. }
  191947. /* This inverts the alpha channel in GGAA */
  191948. else
  191949. {
  191950. png_bytep sp = row + row_info->rowbytes;
  191951. png_bytep dp = sp;
  191952. png_uint_32 i;
  191953. for (i = 0; i < row_width; i++)
  191954. {
  191955. *(--dp) = (png_byte)(255 - *(--sp));
  191956. *(--dp) = (png_byte)(255 - *(--sp));
  191957. /*
  191958. *(--dp) = *(--sp);
  191959. *(--dp) = *(--sp);
  191960. */
  191961. sp-=2;
  191962. dp=sp;
  191963. }
  191964. }
  191965. }
  191966. }
  191967. }
  191968. #endif
  191969. #if defined(PNG_READ_FILLER_SUPPORTED)
  191970. /* Add filler channel if we have RGB color */
  191971. void /* PRIVATE */
  191972. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191973. png_uint_32 filler, png_uint_32 flags)
  191974. {
  191975. png_uint_32 i;
  191976. png_uint_32 row_width = row_info->width;
  191977. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191978. png_byte lo_filler = (png_byte)(filler & 0xff);
  191979. png_debug(1, "in png_do_read_filler\n");
  191980. if (
  191981. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191982. row != NULL && row_info != NULL &&
  191983. #endif
  191984. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191985. {
  191986. if(row_info->bit_depth == 8)
  191987. {
  191988. /* This changes the data from G to GX */
  191989. if (flags & PNG_FLAG_FILLER_AFTER)
  191990. {
  191991. png_bytep sp = row + (png_size_t)row_width;
  191992. png_bytep dp = sp + (png_size_t)row_width;
  191993. for (i = 1; i < row_width; i++)
  191994. {
  191995. *(--dp) = lo_filler;
  191996. *(--dp) = *(--sp);
  191997. }
  191998. *(--dp) = lo_filler;
  191999. row_info->channels = 2;
  192000. row_info->pixel_depth = 16;
  192001. row_info->rowbytes = row_width * 2;
  192002. }
  192003. /* This changes the data from G to XG */
  192004. else
  192005. {
  192006. png_bytep sp = row + (png_size_t)row_width;
  192007. png_bytep dp = sp + (png_size_t)row_width;
  192008. for (i = 0; i < row_width; i++)
  192009. {
  192010. *(--dp) = *(--sp);
  192011. *(--dp) = lo_filler;
  192012. }
  192013. row_info->channels = 2;
  192014. row_info->pixel_depth = 16;
  192015. row_info->rowbytes = row_width * 2;
  192016. }
  192017. }
  192018. else if(row_info->bit_depth == 16)
  192019. {
  192020. /* This changes the data from GG to GGXX */
  192021. if (flags & PNG_FLAG_FILLER_AFTER)
  192022. {
  192023. png_bytep sp = row + (png_size_t)row_width * 2;
  192024. png_bytep dp = sp + (png_size_t)row_width * 2;
  192025. for (i = 1; i < row_width; i++)
  192026. {
  192027. *(--dp) = hi_filler;
  192028. *(--dp) = lo_filler;
  192029. *(--dp) = *(--sp);
  192030. *(--dp) = *(--sp);
  192031. }
  192032. *(--dp) = hi_filler;
  192033. *(--dp) = lo_filler;
  192034. row_info->channels = 2;
  192035. row_info->pixel_depth = 32;
  192036. row_info->rowbytes = row_width * 4;
  192037. }
  192038. /* This changes the data from GG to XXGG */
  192039. else
  192040. {
  192041. png_bytep sp = row + (png_size_t)row_width * 2;
  192042. png_bytep dp = sp + (png_size_t)row_width * 2;
  192043. for (i = 0; i < row_width; i++)
  192044. {
  192045. *(--dp) = *(--sp);
  192046. *(--dp) = *(--sp);
  192047. *(--dp) = hi_filler;
  192048. *(--dp) = lo_filler;
  192049. }
  192050. row_info->channels = 2;
  192051. row_info->pixel_depth = 32;
  192052. row_info->rowbytes = row_width * 4;
  192053. }
  192054. }
  192055. } /* COLOR_TYPE == GRAY */
  192056. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192057. {
  192058. if(row_info->bit_depth == 8)
  192059. {
  192060. /* This changes the data from RGB to RGBX */
  192061. if (flags & PNG_FLAG_FILLER_AFTER)
  192062. {
  192063. png_bytep sp = row + (png_size_t)row_width * 3;
  192064. png_bytep dp = sp + (png_size_t)row_width;
  192065. for (i = 1; i < row_width; i++)
  192066. {
  192067. *(--dp) = lo_filler;
  192068. *(--dp) = *(--sp);
  192069. *(--dp) = *(--sp);
  192070. *(--dp) = *(--sp);
  192071. }
  192072. *(--dp) = lo_filler;
  192073. row_info->channels = 4;
  192074. row_info->pixel_depth = 32;
  192075. row_info->rowbytes = row_width * 4;
  192076. }
  192077. /* This changes the data from RGB to XRGB */
  192078. else
  192079. {
  192080. png_bytep sp = row + (png_size_t)row_width * 3;
  192081. png_bytep dp = sp + (png_size_t)row_width;
  192082. for (i = 0; i < row_width; i++)
  192083. {
  192084. *(--dp) = *(--sp);
  192085. *(--dp) = *(--sp);
  192086. *(--dp) = *(--sp);
  192087. *(--dp) = lo_filler;
  192088. }
  192089. row_info->channels = 4;
  192090. row_info->pixel_depth = 32;
  192091. row_info->rowbytes = row_width * 4;
  192092. }
  192093. }
  192094. else if(row_info->bit_depth == 16)
  192095. {
  192096. /* This changes the data from RRGGBB to RRGGBBXX */
  192097. if (flags & PNG_FLAG_FILLER_AFTER)
  192098. {
  192099. png_bytep sp = row + (png_size_t)row_width * 6;
  192100. png_bytep dp = sp + (png_size_t)row_width * 2;
  192101. for (i = 1; i < row_width; i++)
  192102. {
  192103. *(--dp) = hi_filler;
  192104. *(--dp) = lo_filler;
  192105. *(--dp) = *(--sp);
  192106. *(--dp) = *(--sp);
  192107. *(--dp) = *(--sp);
  192108. *(--dp) = *(--sp);
  192109. *(--dp) = *(--sp);
  192110. *(--dp) = *(--sp);
  192111. }
  192112. *(--dp) = hi_filler;
  192113. *(--dp) = lo_filler;
  192114. row_info->channels = 4;
  192115. row_info->pixel_depth = 64;
  192116. row_info->rowbytes = row_width * 8;
  192117. }
  192118. /* This changes the data from RRGGBB to XXRRGGBB */
  192119. else
  192120. {
  192121. png_bytep sp = row + (png_size_t)row_width * 6;
  192122. png_bytep dp = sp + (png_size_t)row_width * 2;
  192123. for (i = 0; i < row_width; i++)
  192124. {
  192125. *(--dp) = *(--sp);
  192126. *(--dp) = *(--sp);
  192127. *(--dp) = *(--sp);
  192128. *(--dp) = *(--sp);
  192129. *(--dp) = *(--sp);
  192130. *(--dp) = *(--sp);
  192131. *(--dp) = hi_filler;
  192132. *(--dp) = lo_filler;
  192133. }
  192134. row_info->channels = 4;
  192135. row_info->pixel_depth = 64;
  192136. row_info->rowbytes = row_width * 8;
  192137. }
  192138. }
  192139. } /* COLOR_TYPE == RGB */
  192140. }
  192141. #endif
  192142. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192143. /* expand grayscale files to RGB, with or without alpha */
  192144. void /* PRIVATE */
  192145. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192146. {
  192147. png_uint_32 i;
  192148. png_uint_32 row_width = row_info->width;
  192149. png_debug(1, "in png_do_gray_to_rgb\n");
  192150. if (row_info->bit_depth >= 8 &&
  192151. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192152. row != NULL && row_info != NULL &&
  192153. #endif
  192154. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192155. {
  192156. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192157. {
  192158. if (row_info->bit_depth == 8)
  192159. {
  192160. png_bytep sp = row + (png_size_t)row_width - 1;
  192161. png_bytep dp = sp + (png_size_t)row_width * 2;
  192162. for (i = 0; i < row_width; i++)
  192163. {
  192164. *(dp--) = *sp;
  192165. *(dp--) = *sp;
  192166. *(dp--) = *(sp--);
  192167. }
  192168. }
  192169. else
  192170. {
  192171. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192172. png_bytep dp = sp + (png_size_t)row_width * 4;
  192173. for (i = 0; i < row_width; i++)
  192174. {
  192175. *(dp--) = *sp;
  192176. *(dp--) = *(sp - 1);
  192177. *(dp--) = *sp;
  192178. *(dp--) = *(sp - 1);
  192179. *(dp--) = *(sp--);
  192180. *(dp--) = *(sp--);
  192181. }
  192182. }
  192183. }
  192184. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192185. {
  192186. if (row_info->bit_depth == 8)
  192187. {
  192188. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192189. png_bytep dp = sp + (png_size_t)row_width * 2;
  192190. for (i = 0; i < row_width; i++)
  192191. {
  192192. *(dp--) = *(sp--);
  192193. *(dp--) = *sp;
  192194. *(dp--) = *sp;
  192195. *(dp--) = *(sp--);
  192196. }
  192197. }
  192198. else
  192199. {
  192200. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192201. png_bytep dp = sp + (png_size_t)row_width * 4;
  192202. for (i = 0; i < row_width; i++)
  192203. {
  192204. *(dp--) = *(sp--);
  192205. *(dp--) = *(sp--);
  192206. *(dp--) = *sp;
  192207. *(dp--) = *(sp - 1);
  192208. *(dp--) = *sp;
  192209. *(dp--) = *(sp - 1);
  192210. *(dp--) = *(sp--);
  192211. *(dp--) = *(sp--);
  192212. }
  192213. }
  192214. }
  192215. row_info->channels += (png_byte)2;
  192216. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192217. row_info->pixel_depth = (png_byte)(row_info->channels *
  192218. row_info->bit_depth);
  192219. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192220. }
  192221. }
  192222. #endif
  192223. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192224. /* reduce RGB files to grayscale, with or without alpha
  192225. * using the equation given in Poynton's ColorFAQ at
  192226. * <http://www.inforamp.net/~poynton/>
  192227. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192228. *
  192229. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192230. *
  192231. * We approximate this with
  192232. *
  192233. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192234. *
  192235. * which can be expressed with integers as
  192236. *
  192237. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192238. *
  192239. * The calculation is to be done in a linear colorspace.
  192240. *
  192241. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192242. */
  192243. int /* PRIVATE */
  192244. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192245. {
  192246. png_uint_32 i;
  192247. png_uint_32 row_width = row_info->width;
  192248. int rgb_error = 0;
  192249. png_debug(1, "in png_do_rgb_to_gray\n");
  192250. if (
  192251. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192252. row != NULL && row_info != NULL &&
  192253. #endif
  192254. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192255. {
  192256. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192257. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192258. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192259. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192260. {
  192261. if (row_info->bit_depth == 8)
  192262. {
  192263. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192264. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192265. {
  192266. png_bytep sp = row;
  192267. png_bytep dp = row;
  192268. for (i = 0; i < row_width; i++)
  192269. {
  192270. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192271. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192272. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192273. if(red != green || red != blue)
  192274. {
  192275. rgb_error |= 1;
  192276. *(dp++) = png_ptr->gamma_from_1[
  192277. (rc*red+gc*green+bc*blue)>>15];
  192278. }
  192279. else
  192280. *(dp++) = *(sp-1);
  192281. }
  192282. }
  192283. else
  192284. #endif
  192285. {
  192286. png_bytep sp = row;
  192287. png_bytep dp = row;
  192288. for (i = 0; i < row_width; i++)
  192289. {
  192290. png_byte red = *(sp++);
  192291. png_byte green = *(sp++);
  192292. png_byte blue = *(sp++);
  192293. if(red != green || red != blue)
  192294. {
  192295. rgb_error |= 1;
  192296. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192297. }
  192298. else
  192299. *(dp++) = *(sp-1);
  192300. }
  192301. }
  192302. }
  192303. else /* RGB bit_depth == 16 */
  192304. {
  192305. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192306. if (png_ptr->gamma_16_to_1 != NULL &&
  192307. png_ptr->gamma_16_from_1 != NULL)
  192308. {
  192309. png_bytep sp = row;
  192310. png_bytep dp = row;
  192311. for (i = 0; i < row_width; i++)
  192312. {
  192313. png_uint_16 red, green, blue, w;
  192314. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192315. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192316. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192317. if(red == green && red == blue)
  192318. w = red;
  192319. else
  192320. {
  192321. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192322. png_ptr->gamma_shift][red>>8];
  192323. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192324. png_ptr->gamma_shift][green>>8];
  192325. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192326. png_ptr->gamma_shift][blue>>8];
  192327. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192328. + bc*blue_1)>>15);
  192329. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192330. png_ptr->gamma_shift][gray16 >> 8];
  192331. rgb_error |= 1;
  192332. }
  192333. *(dp++) = (png_byte)((w>>8) & 0xff);
  192334. *(dp++) = (png_byte)(w & 0xff);
  192335. }
  192336. }
  192337. else
  192338. #endif
  192339. {
  192340. png_bytep sp = row;
  192341. png_bytep dp = row;
  192342. for (i = 0; i < row_width; i++)
  192343. {
  192344. png_uint_16 red, green, blue, gray16;
  192345. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192346. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192347. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192348. if(red != green || red != blue)
  192349. rgb_error |= 1;
  192350. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192351. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192352. *(dp++) = (png_byte)(gray16 & 0xff);
  192353. }
  192354. }
  192355. }
  192356. }
  192357. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192358. {
  192359. if (row_info->bit_depth == 8)
  192360. {
  192361. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192362. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192363. {
  192364. png_bytep sp = row;
  192365. png_bytep dp = row;
  192366. for (i = 0; i < row_width; i++)
  192367. {
  192368. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192369. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192370. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192371. if(red != green || red != blue)
  192372. rgb_error |= 1;
  192373. *(dp++) = png_ptr->gamma_from_1
  192374. [(rc*red + gc*green + bc*blue)>>15];
  192375. *(dp++) = *(sp++); /* alpha */
  192376. }
  192377. }
  192378. else
  192379. #endif
  192380. {
  192381. png_bytep sp = row;
  192382. png_bytep dp = row;
  192383. for (i = 0; i < row_width; i++)
  192384. {
  192385. png_byte red = *(sp++);
  192386. png_byte green = *(sp++);
  192387. png_byte blue = *(sp++);
  192388. if(red != green || red != blue)
  192389. rgb_error |= 1;
  192390. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192391. *(dp++) = *(sp++); /* alpha */
  192392. }
  192393. }
  192394. }
  192395. else /* RGBA bit_depth == 16 */
  192396. {
  192397. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192398. if (png_ptr->gamma_16_to_1 != NULL &&
  192399. png_ptr->gamma_16_from_1 != NULL)
  192400. {
  192401. png_bytep sp = row;
  192402. png_bytep dp = row;
  192403. for (i = 0; i < row_width; i++)
  192404. {
  192405. png_uint_16 red, green, blue, w;
  192406. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192407. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192408. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192409. if(red == green && red == blue)
  192410. w = red;
  192411. else
  192412. {
  192413. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192414. png_ptr->gamma_shift][red>>8];
  192415. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192416. png_ptr->gamma_shift][green>>8];
  192417. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192418. png_ptr->gamma_shift][blue>>8];
  192419. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192420. + gc * green_1 + bc * blue_1)>>15);
  192421. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192422. png_ptr->gamma_shift][gray16 >> 8];
  192423. rgb_error |= 1;
  192424. }
  192425. *(dp++) = (png_byte)((w>>8) & 0xff);
  192426. *(dp++) = (png_byte)(w & 0xff);
  192427. *(dp++) = *(sp++); /* alpha */
  192428. *(dp++) = *(sp++);
  192429. }
  192430. }
  192431. else
  192432. #endif
  192433. {
  192434. png_bytep sp = row;
  192435. png_bytep dp = row;
  192436. for (i = 0; i < row_width; i++)
  192437. {
  192438. png_uint_16 red, green, blue, gray16;
  192439. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192440. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192441. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192442. if(red != green || red != blue)
  192443. rgb_error |= 1;
  192444. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192445. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192446. *(dp++) = (png_byte)(gray16 & 0xff);
  192447. *(dp++) = *(sp++); /* alpha */
  192448. *(dp++) = *(sp++);
  192449. }
  192450. }
  192451. }
  192452. }
  192453. row_info->channels -= (png_byte)2;
  192454. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192455. row_info->pixel_depth = (png_byte)(row_info->channels *
  192456. row_info->bit_depth);
  192457. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192458. }
  192459. return rgb_error;
  192460. }
  192461. #endif
  192462. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192463. * large of png_color. This lets grayscale images be treated as
  192464. * paletted. Most useful for gamma correction and simplification
  192465. * of code.
  192466. */
  192467. void PNGAPI
  192468. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192469. {
  192470. int num_palette;
  192471. int color_inc;
  192472. int i;
  192473. int v;
  192474. png_debug(1, "in png_do_build_grayscale_palette\n");
  192475. if (palette == NULL)
  192476. return;
  192477. switch (bit_depth)
  192478. {
  192479. case 1:
  192480. num_palette = 2;
  192481. color_inc = 0xff;
  192482. break;
  192483. case 2:
  192484. num_palette = 4;
  192485. color_inc = 0x55;
  192486. break;
  192487. case 4:
  192488. num_palette = 16;
  192489. color_inc = 0x11;
  192490. break;
  192491. case 8:
  192492. num_palette = 256;
  192493. color_inc = 1;
  192494. break;
  192495. default:
  192496. num_palette = 0;
  192497. color_inc = 0;
  192498. break;
  192499. }
  192500. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192501. {
  192502. palette[i].red = (png_byte)v;
  192503. palette[i].green = (png_byte)v;
  192504. palette[i].blue = (png_byte)v;
  192505. }
  192506. }
  192507. /* This function is currently unused. Do we really need it? */
  192508. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192509. void /* PRIVATE */
  192510. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192511. int num_palette)
  192512. {
  192513. png_debug(1, "in png_correct_palette\n");
  192514. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192515. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192516. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192517. {
  192518. png_color back, back_1;
  192519. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192520. {
  192521. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192522. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192523. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192524. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192525. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192526. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192527. }
  192528. else
  192529. {
  192530. double g;
  192531. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192532. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192533. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192534. {
  192535. back.red = png_ptr->background.red;
  192536. back.green = png_ptr->background.green;
  192537. back.blue = png_ptr->background.blue;
  192538. }
  192539. else
  192540. {
  192541. back.red =
  192542. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192543. 255.0 + 0.5);
  192544. back.green =
  192545. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192546. 255.0 + 0.5);
  192547. back.blue =
  192548. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192549. 255.0 + 0.5);
  192550. }
  192551. g = 1.0 / png_ptr->background_gamma;
  192552. back_1.red =
  192553. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192554. 255.0 + 0.5);
  192555. back_1.green =
  192556. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192557. 255.0 + 0.5);
  192558. back_1.blue =
  192559. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192560. 255.0 + 0.5);
  192561. }
  192562. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192563. {
  192564. png_uint_32 i;
  192565. for (i = 0; i < (png_uint_32)num_palette; i++)
  192566. {
  192567. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192568. {
  192569. palette[i] = back;
  192570. }
  192571. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192572. {
  192573. png_byte v, w;
  192574. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192575. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192576. palette[i].red = png_ptr->gamma_from_1[w];
  192577. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192578. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192579. palette[i].green = png_ptr->gamma_from_1[w];
  192580. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192581. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192582. palette[i].blue = png_ptr->gamma_from_1[w];
  192583. }
  192584. else
  192585. {
  192586. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192587. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192588. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192589. }
  192590. }
  192591. }
  192592. else
  192593. {
  192594. int i;
  192595. for (i = 0; i < num_palette; i++)
  192596. {
  192597. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192598. {
  192599. palette[i] = back;
  192600. }
  192601. else
  192602. {
  192603. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192604. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192605. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192606. }
  192607. }
  192608. }
  192609. }
  192610. else
  192611. #endif
  192612. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192613. if (png_ptr->transformations & PNG_GAMMA)
  192614. {
  192615. int i;
  192616. for (i = 0; i < num_palette; i++)
  192617. {
  192618. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192619. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192620. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192621. }
  192622. }
  192623. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192624. else
  192625. #endif
  192626. #endif
  192627. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192628. if (png_ptr->transformations & PNG_BACKGROUND)
  192629. {
  192630. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192631. {
  192632. png_color back;
  192633. back.red = (png_byte)png_ptr->background.red;
  192634. back.green = (png_byte)png_ptr->background.green;
  192635. back.blue = (png_byte)png_ptr->background.blue;
  192636. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192637. {
  192638. if (png_ptr->trans[i] == 0)
  192639. {
  192640. palette[i].red = back.red;
  192641. palette[i].green = back.green;
  192642. palette[i].blue = back.blue;
  192643. }
  192644. else if (png_ptr->trans[i] != 0xff)
  192645. {
  192646. png_composite(palette[i].red, png_ptr->palette[i].red,
  192647. png_ptr->trans[i], back.red);
  192648. png_composite(palette[i].green, png_ptr->palette[i].green,
  192649. png_ptr->trans[i], back.green);
  192650. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192651. png_ptr->trans[i], back.blue);
  192652. }
  192653. }
  192654. }
  192655. else /* assume grayscale palette (what else could it be?) */
  192656. {
  192657. int i;
  192658. for (i = 0; i < num_palette; i++)
  192659. {
  192660. if (i == (png_byte)png_ptr->trans_values.gray)
  192661. {
  192662. palette[i].red = (png_byte)png_ptr->background.red;
  192663. palette[i].green = (png_byte)png_ptr->background.green;
  192664. palette[i].blue = (png_byte)png_ptr->background.blue;
  192665. }
  192666. }
  192667. }
  192668. }
  192669. #endif
  192670. }
  192671. #endif
  192672. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192673. /* Replace any alpha or transparency with the supplied background color.
  192674. * "background" is already in the screen gamma, while "background_1" is
  192675. * at a gamma of 1.0. Paletted files have already been taken care of.
  192676. */
  192677. void /* PRIVATE */
  192678. png_do_background(png_row_infop row_info, png_bytep row,
  192679. png_color_16p trans_values, png_color_16p background
  192680. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192681. , png_color_16p background_1,
  192682. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192683. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192684. png_uint_16pp gamma_16_to_1, int gamma_shift
  192685. #endif
  192686. )
  192687. {
  192688. png_bytep sp, dp;
  192689. png_uint_32 i;
  192690. png_uint_32 row_width=row_info->width;
  192691. int shift;
  192692. png_debug(1, "in png_do_background\n");
  192693. if (background != NULL &&
  192694. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192695. row != NULL && row_info != NULL &&
  192696. #endif
  192697. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192698. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192699. {
  192700. switch (row_info->color_type)
  192701. {
  192702. case PNG_COLOR_TYPE_GRAY:
  192703. {
  192704. switch (row_info->bit_depth)
  192705. {
  192706. case 1:
  192707. {
  192708. sp = row;
  192709. shift = 7;
  192710. for (i = 0; i < row_width; i++)
  192711. {
  192712. if ((png_uint_16)((*sp >> shift) & 0x01)
  192713. == trans_values->gray)
  192714. {
  192715. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192716. *sp |= (png_byte)(background->gray << shift);
  192717. }
  192718. if (!shift)
  192719. {
  192720. shift = 7;
  192721. sp++;
  192722. }
  192723. else
  192724. shift--;
  192725. }
  192726. break;
  192727. }
  192728. case 2:
  192729. {
  192730. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192731. if (gamma_table != NULL)
  192732. {
  192733. sp = row;
  192734. shift = 6;
  192735. for (i = 0; i < row_width; i++)
  192736. {
  192737. if ((png_uint_16)((*sp >> shift) & 0x03)
  192738. == trans_values->gray)
  192739. {
  192740. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192741. *sp |= (png_byte)(background->gray << shift);
  192742. }
  192743. else
  192744. {
  192745. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192746. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192747. (p << 4) | (p << 6)] >> 6) & 0x03);
  192748. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192749. *sp |= (png_byte)(g << shift);
  192750. }
  192751. if (!shift)
  192752. {
  192753. shift = 6;
  192754. sp++;
  192755. }
  192756. else
  192757. shift -= 2;
  192758. }
  192759. }
  192760. else
  192761. #endif
  192762. {
  192763. sp = row;
  192764. shift = 6;
  192765. for (i = 0; i < row_width; i++)
  192766. {
  192767. if ((png_uint_16)((*sp >> shift) & 0x03)
  192768. == trans_values->gray)
  192769. {
  192770. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192771. *sp |= (png_byte)(background->gray << shift);
  192772. }
  192773. if (!shift)
  192774. {
  192775. shift = 6;
  192776. sp++;
  192777. }
  192778. else
  192779. shift -= 2;
  192780. }
  192781. }
  192782. break;
  192783. }
  192784. case 4:
  192785. {
  192786. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192787. if (gamma_table != NULL)
  192788. {
  192789. sp = row;
  192790. shift = 4;
  192791. for (i = 0; i < row_width; i++)
  192792. {
  192793. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192794. == trans_values->gray)
  192795. {
  192796. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192797. *sp |= (png_byte)(background->gray << shift);
  192798. }
  192799. else
  192800. {
  192801. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192802. png_byte g = (png_byte)((gamma_table[p |
  192803. (p << 4)] >> 4) & 0x0f);
  192804. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192805. *sp |= (png_byte)(g << shift);
  192806. }
  192807. if (!shift)
  192808. {
  192809. shift = 4;
  192810. sp++;
  192811. }
  192812. else
  192813. shift -= 4;
  192814. }
  192815. }
  192816. else
  192817. #endif
  192818. {
  192819. sp = row;
  192820. shift = 4;
  192821. for (i = 0; i < row_width; i++)
  192822. {
  192823. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192824. == trans_values->gray)
  192825. {
  192826. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192827. *sp |= (png_byte)(background->gray << shift);
  192828. }
  192829. if (!shift)
  192830. {
  192831. shift = 4;
  192832. sp++;
  192833. }
  192834. else
  192835. shift -= 4;
  192836. }
  192837. }
  192838. break;
  192839. }
  192840. case 8:
  192841. {
  192842. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192843. if (gamma_table != NULL)
  192844. {
  192845. sp = row;
  192846. for (i = 0; i < row_width; i++, sp++)
  192847. {
  192848. if (*sp == trans_values->gray)
  192849. {
  192850. *sp = (png_byte)background->gray;
  192851. }
  192852. else
  192853. {
  192854. *sp = gamma_table[*sp];
  192855. }
  192856. }
  192857. }
  192858. else
  192859. #endif
  192860. {
  192861. sp = row;
  192862. for (i = 0; i < row_width; i++, sp++)
  192863. {
  192864. if (*sp == trans_values->gray)
  192865. {
  192866. *sp = (png_byte)background->gray;
  192867. }
  192868. }
  192869. }
  192870. break;
  192871. }
  192872. case 16:
  192873. {
  192874. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192875. if (gamma_16 != NULL)
  192876. {
  192877. sp = row;
  192878. for (i = 0; i < row_width; i++, sp += 2)
  192879. {
  192880. png_uint_16 v;
  192881. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192882. if (v == trans_values->gray)
  192883. {
  192884. /* background is already in screen gamma */
  192885. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192886. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192887. }
  192888. else
  192889. {
  192890. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192891. *sp = (png_byte)((v >> 8) & 0xff);
  192892. *(sp + 1) = (png_byte)(v & 0xff);
  192893. }
  192894. }
  192895. }
  192896. else
  192897. #endif
  192898. {
  192899. sp = row;
  192900. for (i = 0; i < row_width; i++, sp += 2)
  192901. {
  192902. png_uint_16 v;
  192903. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192904. if (v == trans_values->gray)
  192905. {
  192906. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192907. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192908. }
  192909. }
  192910. }
  192911. break;
  192912. }
  192913. }
  192914. break;
  192915. }
  192916. case PNG_COLOR_TYPE_RGB:
  192917. {
  192918. if (row_info->bit_depth == 8)
  192919. {
  192920. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192921. if (gamma_table != NULL)
  192922. {
  192923. sp = row;
  192924. for (i = 0; i < row_width; i++, sp += 3)
  192925. {
  192926. if (*sp == trans_values->red &&
  192927. *(sp + 1) == trans_values->green &&
  192928. *(sp + 2) == trans_values->blue)
  192929. {
  192930. *sp = (png_byte)background->red;
  192931. *(sp + 1) = (png_byte)background->green;
  192932. *(sp + 2) = (png_byte)background->blue;
  192933. }
  192934. else
  192935. {
  192936. *sp = gamma_table[*sp];
  192937. *(sp + 1) = gamma_table[*(sp + 1)];
  192938. *(sp + 2) = gamma_table[*(sp + 2)];
  192939. }
  192940. }
  192941. }
  192942. else
  192943. #endif
  192944. {
  192945. sp = row;
  192946. for (i = 0; i < row_width; i++, sp += 3)
  192947. {
  192948. if (*sp == trans_values->red &&
  192949. *(sp + 1) == trans_values->green &&
  192950. *(sp + 2) == trans_values->blue)
  192951. {
  192952. *sp = (png_byte)background->red;
  192953. *(sp + 1) = (png_byte)background->green;
  192954. *(sp + 2) = (png_byte)background->blue;
  192955. }
  192956. }
  192957. }
  192958. }
  192959. else /* if (row_info->bit_depth == 16) */
  192960. {
  192961. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192962. if (gamma_16 != NULL)
  192963. {
  192964. sp = row;
  192965. for (i = 0; i < row_width; i++, sp += 6)
  192966. {
  192967. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192968. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192969. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192970. if (r == trans_values->red && g == trans_values->green &&
  192971. b == trans_values->blue)
  192972. {
  192973. /* background is already in screen gamma */
  192974. *sp = (png_byte)((background->red >> 8) & 0xff);
  192975. *(sp + 1) = (png_byte)(background->red & 0xff);
  192976. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192977. *(sp + 3) = (png_byte)(background->green & 0xff);
  192978. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192979. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192980. }
  192981. else
  192982. {
  192983. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192984. *sp = (png_byte)((v >> 8) & 0xff);
  192985. *(sp + 1) = (png_byte)(v & 0xff);
  192986. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192987. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192988. *(sp + 3) = (png_byte)(v & 0xff);
  192989. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192990. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192991. *(sp + 5) = (png_byte)(v & 0xff);
  192992. }
  192993. }
  192994. }
  192995. else
  192996. #endif
  192997. {
  192998. sp = row;
  192999. for (i = 0; i < row_width; i++, sp += 6)
  193000. {
  193001. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  193002. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193003. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  193004. if (r == trans_values->red && g == trans_values->green &&
  193005. b == trans_values->blue)
  193006. {
  193007. *sp = (png_byte)((background->red >> 8) & 0xff);
  193008. *(sp + 1) = (png_byte)(background->red & 0xff);
  193009. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193010. *(sp + 3) = (png_byte)(background->green & 0xff);
  193011. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193012. *(sp + 5) = (png_byte)(background->blue & 0xff);
  193013. }
  193014. }
  193015. }
  193016. }
  193017. break;
  193018. }
  193019. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193020. {
  193021. if (row_info->bit_depth == 8)
  193022. {
  193023. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193024. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193025. gamma_table != NULL)
  193026. {
  193027. sp = row;
  193028. dp = row;
  193029. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193030. {
  193031. png_uint_16 a = *(sp + 1);
  193032. if (a == 0xff)
  193033. {
  193034. *dp = gamma_table[*sp];
  193035. }
  193036. else if (a == 0)
  193037. {
  193038. /* background is already in screen gamma */
  193039. *dp = (png_byte)background->gray;
  193040. }
  193041. else
  193042. {
  193043. png_byte v, w;
  193044. v = gamma_to_1[*sp];
  193045. png_composite(w, v, a, background_1->gray);
  193046. *dp = gamma_from_1[w];
  193047. }
  193048. }
  193049. }
  193050. else
  193051. #endif
  193052. {
  193053. sp = row;
  193054. dp = row;
  193055. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193056. {
  193057. png_byte a = *(sp + 1);
  193058. if (a == 0xff)
  193059. {
  193060. *dp = *sp;
  193061. }
  193062. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193063. else if (a == 0)
  193064. {
  193065. *dp = (png_byte)background->gray;
  193066. }
  193067. else
  193068. {
  193069. png_composite(*dp, *sp, a, background_1->gray);
  193070. }
  193071. #else
  193072. *dp = (png_byte)background->gray;
  193073. #endif
  193074. }
  193075. }
  193076. }
  193077. else /* if (png_ptr->bit_depth == 16) */
  193078. {
  193079. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193080. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193081. gamma_16_to_1 != NULL)
  193082. {
  193083. sp = row;
  193084. dp = row;
  193085. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193086. {
  193087. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193088. if (a == (png_uint_16)0xffff)
  193089. {
  193090. png_uint_16 v;
  193091. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193092. *dp = (png_byte)((v >> 8) & 0xff);
  193093. *(dp + 1) = (png_byte)(v & 0xff);
  193094. }
  193095. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193096. else if (a == 0)
  193097. #else
  193098. else
  193099. #endif
  193100. {
  193101. /* background is already in screen gamma */
  193102. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193103. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193104. }
  193105. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193106. else
  193107. {
  193108. png_uint_16 g, v, w;
  193109. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193110. png_composite_16(v, g, a, background_1->gray);
  193111. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193112. *dp = (png_byte)((w >> 8) & 0xff);
  193113. *(dp + 1) = (png_byte)(w & 0xff);
  193114. }
  193115. #endif
  193116. }
  193117. }
  193118. else
  193119. #endif
  193120. {
  193121. sp = row;
  193122. dp = row;
  193123. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193124. {
  193125. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193126. if (a == (png_uint_16)0xffff)
  193127. {
  193128. png_memcpy(dp, sp, 2);
  193129. }
  193130. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193131. else if (a == 0)
  193132. #else
  193133. else
  193134. #endif
  193135. {
  193136. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193137. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193138. }
  193139. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193140. else
  193141. {
  193142. png_uint_16 g, v;
  193143. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193144. png_composite_16(v, g, a, background_1->gray);
  193145. *dp = (png_byte)((v >> 8) & 0xff);
  193146. *(dp + 1) = (png_byte)(v & 0xff);
  193147. }
  193148. #endif
  193149. }
  193150. }
  193151. }
  193152. break;
  193153. }
  193154. case PNG_COLOR_TYPE_RGB_ALPHA:
  193155. {
  193156. if (row_info->bit_depth == 8)
  193157. {
  193158. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193159. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193160. gamma_table != NULL)
  193161. {
  193162. sp = row;
  193163. dp = row;
  193164. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193165. {
  193166. png_byte a = *(sp + 3);
  193167. if (a == 0xff)
  193168. {
  193169. *dp = gamma_table[*sp];
  193170. *(dp + 1) = gamma_table[*(sp + 1)];
  193171. *(dp + 2) = gamma_table[*(sp + 2)];
  193172. }
  193173. else if (a == 0)
  193174. {
  193175. /* background is already in screen gamma */
  193176. *dp = (png_byte)background->red;
  193177. *(dp + 1) = (png_byte)background->green;
  193178. *(dp + 2) = (png_byte)background->blue;
  193179. }
  193180. else
  193181. {
  193182. png_byte v, w;
  193183. v = gamma_to_1[*sp];
  193184. png_composite(w, v, a, background_1->red);
  193185. *dp = gamma_from_1[w];
  193186. v = gamma_to_1[*(sp + 1)];
  193187. png_composite(w, v, a, background_1->green);
  193188. *(dp + 1) = gamma_from_1[w];
  193189. v = gamma_to_1[*(sp + 2)];
  193190. png_composite(w, v, a, background_1->blue);
  193191. *(dp + 2) = gamma_from_1[w];
  193192. }
  193193. }
  193194. }
  193195. else
  193196. #endif
  193197. {
  193198. sp = row;
  193199. dp = row;
  193200. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193201. {
  193202. png_byte a = *(sp + 3);
  193203. if (a == 0xff)
  193204. {
  193205. *dp = *sp;
  193206. *(dp + 1) = *(sp + 1);
  193207. *(dp + 2) = *(sp + 2);
  193208. }
  193209. else if (a == 0)
  193210. {
  193211. *dp = (png_byte)background->red;
  193212. *(dp + 1) = (png_byte)background->green;
  193213. *(dp + 2) = (png_byte)background->blue;
  193214. }
  193215. else
  193216. {
  193217. png_composite(*dp, *sp, a, background->red);
  193218. png_composite(*(dp + 1), *(sp + 1), a,
  193219. background->green);
  193220. png_composite(*(dp + 2), *(sp + 2), a,
  193221. background->blue);
  193222. }
  193223. }
  193224. }
  193225. }
  193226. else /* if (row_info->bit_depth == 16) */
  193227. {
  193228. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193229. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193230. gamma_16_to_1 != NULL)
  193231. {
  193232. sp = row;
  193233. dp = row;
  193234. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193235. {
  193236. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193237. << 8) + (png_uint_16)(*(sp + 7)));
  193238. if (a == (png_uint_16)0xffff)
  193239. {
  193240. png_uint_16 v;
  193241. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193242. *dp = (png_byte)((v >> 8) & 0xff);
  193243. *(dp + 1) = (png_byte)(v & 0xff);
  193244. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193245. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193246. *(dp + 3) = (png_byte)(v & 0xff);
  193247. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193248. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193249. *(dp + 5) = (png_byte)(v & 0xff);
  193250. }
  193251. else if (a == 0)
  193252. {
  193253. /* background is already in screen gamma */
  193254. *dp = (png_byte)((background->red >> 8) & 0xff);
  193255. *(dp + 1) = (png_byte)(background->red & 0xff);
  193256. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193257. *(dp + 3) = (png_byte)(background->green & 0xff);
  193258. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193259. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193260. }
  193261. else
  193262. {
  193263. png_uint_16 v, w, x;
  193264. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193265. png_composite_16(w, v, a, background_1->red);
  193266. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193267. *dp = (png_byte)((x >> 8) & 0xff);
  193268. *(dp + 1) = (png_byte)(x & 0xff);
  193269. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193270. png_composite_16(w, v, a, background_1->green);
  193271. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193272. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193273. *(dp + 3) = (png_byte)(x & 0xff);
  193274. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193275. png_composite_16(w, v, a, background_1->blue);
  193276. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193277. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193278. *(dp + 5) = (png_byte)(x & 0xff);
  193279. }
  193280. }
  193281. }
  193282. else
  193283. #endif
  193284. {
  193285. sp = row;
  193286. dp = row;
  193287. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193288. {
  193289. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193290. << 8) + (png_uint_16)(*(sp + 7)));
  193291. if (a == (png_uint_16)0xffff)
  193292. {
  193293. png_memcpy(dp, sp, 6);
  193294. }
  193295. else if (a == 0)
  193296. {
  193297. *dp = (png_byte)((background->red >> 8) & 0xff);
  193298. *(dp + 1) = (png_byte)(background->red & 0xff);
  193299. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193300. *(dp + 3) = (png_byte)(background->green & 0xff);
  193301. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193302. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193303. }
  193304. else
  193305. {
  193306. png_uint_16 v;
  193307. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193308. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193309. + *(sp + 3));
  193310. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193311. + *(sp + 5));
  193312. png_composite_16(v, r, a, background->red);
  193313. *dp = (png_byte)((v >> 8) & 0xff);
  193314. *(dp + 1) = (png_byte)(v & 0xff);
  193315. png_composite_16(v, g, a, background->green);
  193316. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193317. *(dp + 3) = (png_byte)(v & 0xff);
  193318. png_composite_16(v, b, a, background->blue);
  193319. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193320. *(dp + 5) = (png_byte)(v & 0xff);
  193321. }
  193322. }
  193323. }
  193324. }
  193325. break;
  193326. }
  193327. }
  193328. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193329. {
  193330. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193331. row_info->channels--;
  193332. row_info->pixel_depth = (png_byte)(row_info->channels *
  193333. row_info->bit_depth);
  193334. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193335. }
  193336. }
  193337. }
  193338. #endif
  193339. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193340. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193341. * you do this after you deal with the transparency issue on grayscale
  193342. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193343. * is 16, use gamma_16_table and gamma_shift. Build these with
  193344. * build_gamma_table().
  193345. */
  193346. void /* PRIVATE */
  193347. png_do_gamma(png_row_infop row_info, png_bytep row,
  193348. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193349. int gamma_shift)
  193350. {
  193351. png_bytep sp;
  193352. png_uint_32 i;
  193353. png_uint_32 row_width=row_info->width;
  193354. png_debug(1, "in png_do_gamma\n");
  193355. if (
  193356. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193357. row != NULL && row_info != NULL &&
  193358. #endif
  193359. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193360. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193361. {
  193362. switch (row_info->color_type)
  193363. {
  193364. case PNG_COLOR_TYPE_RGB:
  193365. {
  193366. if (row_info->bit_depth == 8)
  193367. {
  193368. sp = row;
  193369. for (i = 0; i < row_width; i++)
  193370. {
  193371. *sp = gamma_table[*sp];
  193372. sp++;
  193373. *sp = gamma_table[*sp];
  193374. sp++;
  193375. *sp = gamma_table[*sp];
  193376. sp++;
  193377. }
  193378. }
  193379. else /* if (row_info->bit_depth == 16) */
  193380. {
  193381. sp = row;
  193382. for (i = 0; i < row_width; i++)
  193383. {
  193384. png_uint_16 v;
  193385. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193386. *sp = (png_byte)((v >> 8) & 0xff);
  193387. *(sp + 1) = (png_byte)(v & 0xff);
  193388. sp += 2;
  193389. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193390. *sp = (png_byte)((v >> 8) & 0xff);
  193391. *(sp + 1) = (png_byte)(v & 0xff);
  193392. sp += 2;
  193393. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193394. *sp = (png_byte)((v >> 8) & 0xff);
  193395. *(sp + 1) = (png_byte)(v & 0xff);
  193396. sp += 2;
  193397. }
  193398. }
  193399. break;
  193400. }
  193401. case PNG_COLOR_TYPE_RGB_ALPHA:
  193402. {
  193403. if (row_info->bit_depth == 8)
  193404. {
  193405. sp = row;
  193406. for (i = 0; i < row_width; i++)
  193407. {
  193408. *sp = gamma_table[*sp];
  193409. sp++;
  193410. *sp = gamma_table[*sp];
  193411. sp++;
  193412. *sp = gamma_table[*sp];
  193413. sp++;
  193414. sp++;
  193415. }
  193416. }
  193417. else /* if (row_info->bit_depth == 16) */
  193418. {
  193419. sp = row;
  193420. for (i = 0; i < row_width; i++)
  193421. {
  193422. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193423. *sp = (png_byte)((v >> 8) & 0xff);
  193424. *(sp + 1) = (png_byte)(v & 0xff);
  193425. sp += 2;
  193426. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193427. *sp = (png_byte)((v >> 8) & 0xff);
  193428. *(sp + 1) = (png_byte)(v & 0xff);
  193429. sp += 2;
  193430. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193431. *sp = (png_byte)((v >> 8) & 0xff);
  193432. *(sp + 1) = (png_byte)(v & 0xff);
  193433. sp += 4;
  193434. }
  193435. }
  193436. break;
  193437. }
  193438. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193439. {
  193440. if (row_info->bit_depth == 8)
  193441. {
  193442. sp = row;
  193443. for (i = 0; i < row_width; i++)
  193444. {
  193445. *sp = gamma_table[*sp];
  193446. sp += 2;
  193447. }
  193448. }
  193449. else /* if (row_info->bit_depth == 16) */
  193450. {
  193451. sp = row;
  193452. for (i = 0; i < row_width; i++)
  193453. {
  193454. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193455. *sp = (png_byte)((v >> 8) & 0xff);
  193456. *(sp + 1) = (png_byte)(v & 0xff);
  193457. sp += 4;
  193458. }
  193459. }
  193460. break;
  193461. }
  193462. case PNG_COLOR_TYPE_GRAY:
  193463. {
  193464. if (row_info->bit_depth == 2)
  193465. {
  193466. sp = row;
  193467. for (i = 0; i < row_width; i += 4)
  193468. {
  193469. int a = *sp & 0xc0;
  193470. int b = *sp & 0x30;
  193471. int c = *sp & 0x0c;
  193472. int d = *sp & 0x03;
  193473. *sp = (png_byte)(
  193474. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193475. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193476. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193477. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193478. sp++;
  193479. }
  193480. }
  193481. if (row_info->bit_depth == 4)
  193482. {
  193483. sp = row;
  193484. for (i = 0; i < row_width; i += 2)
  193485. {
  193486. int msb = *sp & 0xf0;
  193487. int lsb = *sp & 0x0f;
  193488. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193489. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193490. sp++;
  193491. }
  193492. }
  193493. else if (row_info->bit_depth == 8)
  193494. {
  193495. sp = row;
  193496. for (i = 0; i < row_width; i++)
  193497. {
  193498. *sp = gamma_table[*sp];
  193499. sp++;
  193500. }
  193501. }
  193502. else if (row_info->bit_depth == 16)
  193503. {
  193504. sp = row;
  193505. for (i = 0; i < row_width; i++)
  193506. {
  193507. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193508. *sp = (png_byte)((v >> 8) & 0xff);
  193509. *(sp + 1) = (png_byte)(v & 0xff);
  193510. sp += 2;
  193511. }
  193512. }
  193513. break;
  193514. }
  193515. }
  193516. }
  193517. }
  193518. #endif
  193519. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193520. /* Expands a palette row to an RGB or RGBA row depending
  193521. * upon whether you supply trans and num_trans.
  193522. */
  193523. void /* PRIVATE */
  193524. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193525. png_colorp palette, png_bytep trans, int num_trans)
  193526. {
  193527. int shift, value;
  193528. png_bytep sp, dp;
  193529. png_uint_32 i;
  193530. png_uint_32 row_width=row_info->width;
  193531. png_debug(1, "in png_do_expand_palette\n");
  193532. if (
  193533. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193534. row != NULL && row_info != NULL &&
  193535. #endif
  193536. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193537. {
  193538. if (row_info->bit_depth < 8)
  193539. {
  193540. switch (row_info->bit_depth)
  193541. {
  193542. case 1:
  193543. {
  193544. sp = row + (png_size_t)((row_width - 1) >> 3);
  193545. dp = row + (png_size_t)row_width - 1;
  193546. shift = 7 - (int)((row_width + 7) & 0x07);
  193547. for (i = 0; i < row_width; i++)
  193548. {
  193549. if ((*sp >> shift) & 0x01)
  193550. *dp = 1;
  193551. else
  193552. *dp = 0;
  193553. if (shift == 7)
  193554. {
  193555. shift = 0;
  193556. sp--;
  193557. }
  193558. else
  193559. shift++;
  193560. dp--;
  193561. }
  193562. break;
  193563. }
  193564. case 2:
  193565. {
  193566. sp = row + (png_size_t)((row_width - 1) >> 2);
  193567. dp = row + (png_size_t)row_width - 1;
  193568. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193569. for (i = 0; i < row_width; i++)
  193570. {
  193571. value = (*sp >> shift) & 0x03;
  193572. *dp = (png_byte)value;
  193573. if (shift == 6)
  193574. {
  193575. shift = 0;
  193576. sp--;
  193577. }
  193578. else
  193579. shift += 2;
  193580. dp--;
  193581. }
  193582. break;
  193583. }
  193584. case 4:
  193585. {
  193586. sp = row + (png_size_t)((row_width - 1) >> 1);
  193587. dp = row + (png_size_t)row_width - 1;
  193588. shift = (int)((row_width & 0x01) << 2);
  193589. for (i = 0; i < row_width; i++)
  193590. {
  193591. value = (*sp >> shift) & 0x0f;
  193592. *dp = (png_byte)value;
  193593. if (shift == 4)
  193594. {
  193595. shift = 0;
  193596. sp--;
  193597. }
  193598. else
  193599. shift += 4;
  193600. dp--;
  193601. }
  193602. break;
  193603. }
  193604. }
  193605. row_info->bit_depth = 8;
  193606. row_info->pixel_depth = 8;
  193607. row_info->rowbytes = row_width;
  193608. }
  193609. switch (row_info->bit_depth)
  193610. {
  193611. case 8:
  193612. {
  193613. if (trans != NULL)
  193614. {
  193615. sp = row + (png_size_t)row_width - 1;
  193616. dp = row + (png_size_t)(row_width << 2) - 1;
  193617. for (i = 0; i < row_width; i++)
  193618. {
  193619. if ((int)(*sp) >= num_trans)
  193620. *dp-- = 0xff;
  193621. else
  193622. *dp-- = trans[*sp];
  193623. *dp-- = palette[*sp].blue;
  193624. *dp-- = palette[*sp].green;
  193625. *dp-- = palette[*sp].red;
  193626. sp--;
  193627. }
  193628. row_info->bit_depth = 8;
  193629. row_info->pixel_depth = 32;
  193630. row_info->rowbytes = row_width * 4;
  193631. row_info->color_type = 6;
  193632. row_info->channels = 4;
  193633. }
  193634. else
  193635. {
  193636. sp = row + (png_size_t)row_width - 1;
  193637. dp = row + (png_size_t)(row_width * 3) - 1;
  193638. for (i = 0; i < row_width; i++)
  193639. {
  193640. *dp-- = palette[*sp].blue;
  193641. *dp-- = palette[*sp].green;
  193642. *dp-- = palette[*sp].red;
  193643. sp--;
  193644. }
  193645. row_info->bit_depth = 8;
  193646. row_info->pixel_depth = 24;
  193647. row_info->rowbytes = row_width * 3;
  193648. row_info->color_type = 2;
  193649. row_info->channels = 3;
  193650. }
  193651. break;
  193652. }
  193653. }
  193654. }
  193655. }
  193656. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193657. * expanded transparency value is supplied, an alpha channel is built.
  193658. */
  193659. void /* PRIVATE */
  193660. png_do_expand(png_row_infop row_info, png_bytep row,
  193661. png_color_16p trans_value)
  193662. {
  193663. int shift, value;
  193664. png_bytep sp, dp;
  193665. png_uint_32 i;
  193666. png_uint_32 row_width=row_info->width;
  193667. png_debug(1, "in png_do_expand\n");
  193668. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193669. if (row != NULL && row_info != NULL)
  193670. #endif
  193671. {
  193672. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193673. {
  193674. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193675. if (row_info->bit_depth < 8)
  193676. {
  193677. switch (row_info->bit_depth)
  193678. {
  193679. case 1:
  193680. {
  193681. gray = (png_uint_16)((gray&0x01)*0xff);
  193682. sp = row + (png_size_t)((row_width - 1) >> 3);
  193683. dp = row + (png_size_t)row_width - 1;
  193684. shift = 7 - (int)((row_width + 7) & 0x07);
  193685. for (i = 0; i < row_width; i++)
  193686. {
  193687. if ((*sp >> shift) & 0x01)
  193688. *dp = 0xff;
  193689. else
  193690. *dp = 0;
  193691. if (shift == 7)
  193692. {
  193693. shift = 0;
  193694. sp--;
  193695. }
  193696. else
  193697. shift++;
  193698. dp--;
  193699. }
  193700. break;
  193701. }
  193702. case 2:
  193703. {
  193704. gray = (png_uint_16)((gray&0x03)*0x55);
  193705. sp = row + (png_size_t)((row_width - 1) >> 2);
  193706. dp = row + (png_size_t)row_width - 1;
  193707. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193708. for (i = 0; i < row_width; i++)
  193709. {
  193710. value = (*sp >> shift) & 0x03;
  193711. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193712. (value << 6));
  193713. if (shift == 6)
  193714. {
  193715. shift = 0;
  193716. sp--;
  193717. }
  193718. else
  193719. shift += 2;
  193720. dp--;
  193721. }
  193722. break;
  193723. }
  193724. case 4:
  193725. {
  193726. gray = (png_uint_16)((gray&0x0f)*0x11);
  193727. sp = row + (png_size_t)((row_width - 1) >> 1);
  193728. dp = row + (png_size_t)row_width - 1;
  193729. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193730. for (i = 0; i < row_width; i++)
  193731. {
  193732. value = (*sp >> shift) & 0x0f;
  193733. *dp = (png_byte)(value | (value << 4));
  193734. if (shift == 4)
  193735. {
  193736. shift = 0;
  193737. sp--;
  193738. }
  193739. else
  193740. shift = 4;
  193741. dp--;
  193742. }
  193743. break;
  193744. }
  193745. }
  193746. row_info->bit_depth = 8;
  193747. row_info->pixel_depth = 8;
  193748. row_info->rowbytes = row_width;
  193749. }
  193750. if (trans_value != NULL)
  193751. {
  193752. if (row_info->bit_depth == 8)
  193753. {
  193754. gray = gray & 0xff;
  193755. sp = row + (png_size_t)row_width - 1;
  193756. dp = row + (png_size_t)(row_width << 1) - 1;
  193757. for (i = 0; i < row_width; i++)
  193758. {
  193759. if (*sp == gray)
  193760. *dp-- = 0;
  193761. else
  193762. *dp-- = 0xff;
  193763. *dp-- = *sp--;
  193764. }
  193765. }
  193766. else if (row_info->bit_depth == 16)
  193767. {
  193768. png_byte gray_high = (gray >> 8) & 0xff;
  193769. png_byte gray_low = gray & 0xff;
  193770. sp = row + row_info->rowbytes - 1;
  193771. dp = row + (row_info->rowbytes << 1) - 1;
  193772. for (i = 0; i < row_width; i++)
  193773. {
  193774. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193775. {
  193776. *dp-- = 0;
  193777. *dp-- = 0;
  193778. }
  193779. else
  193780. {
  193781. *dp-- = 0xff;
  193782. *dp-- = 0xff;
  193783. }
  193784. *dp-- = *sp--;
  193785. *dp-- = *sp--;
  193786. }
  193787. }
  193788. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193789. row_info->channels = 2;
  193790. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193791. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193792. row_width);
  193793. }
  193794. }
  193795. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193796. {
  193797. if (row_info->bit_depth == 8)
  193798. {
  193799. png_byte red = trans_value->red & 0xff;
  193800. png_byte green = trans_value->green & 0xff;
  193801. png_byte blue = trans_value->blue & 0xff;
  193802. sp = row + (png_size_t)row_info->rowbytes - 1;
  193803. dp = row + (png_size_t)(row_width << 2) - 1;
  193804. for (i = 0; i < row_width; i++)
  193805. {
  193806. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193807. *dp-- = 0;
  193808. else
  193809. *dp-- = 0xff;
  193810. *dp-- = *sp--;
  193811. *dp-- = *sp--;
  193812. *dp-- = *sp--;
  193813. }
  193814. }
  193815. else if (row_info->bit_depth == 16)
  193816. {
  193817. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193818. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193819. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193820. png_byte red_low = trans_value->red & 0xff;
  193821. png_byte green_low = trans_value->green & 0xff;
  193822. png_byte blue_low = trans_value->blue & 0xff;
  193823. sp = row + row_info->rowbytes - 1;
  193824. dp = row + (png_size_t)(row_width << 3) - 1;
  193825. for (i = 0; i < row_width; i++)
  193826. {
  193827. if (*(sp - 5) == red_high &&
  193828. *(sp - 4) == red_low &&
  193829. *(sp - 3) == green_high &&
  193830. *(sp - 2) == green_low &&
  193831. *(sp - 1) == blue_high &&
  193832. *(sp ) == blue_low)
  193833. {
  193834. *dp-- = 0;
  193835. *dp-- = 0;
  193836. }
  193837. else
  193838. {
  193839. *dp-- = 0xff;
  193840. *dp-- = 0xff;
  193841. }
  193842. *dp-- = *sp--;
  193843. *dp-- = *sp--;
  193844. *dp-- = *sp--;
  193845. *dp-- = *sp--;
  193846. *dp-- = *sp--;
  193847. *dp-- = *sp--;
  193848. }
  193849. }
  193850. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193851. row_info->channels = 4;
  193852. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193853. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193854. }
  193855. }
  193856. }
  193857. #endif
  193858. #if defined(PNG_READ_DITHER_SUPPORTED)
  193859. void /* PRIVATE */
  193860. png_do_dither(png_row_infop row_info, png_bytep row,
  193861. png_bytep palette_lookup, png_bytep dither_lookup)
  193862. {
  193863. png_bytep sp, dp;
  193864. png_uint_32 i;
  193865. png_uint_32 row_width=row_info->width;
  193866. png_debug(1, "in png_do_dither\n");
  193867. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193868. if (row != NULL && row_info != NULL)
  193869. #endif
  193870. {
  193871. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193872. palette_lookup && row_info->bit_depth == 8)
  193873. {
  193874. int r, g, b, p;
  193875. sp = row;
  193876. dp = row;
  193877. for (i = 0; i < row_width; i++)
  193878. {
  193879. r = *sp++;
  193880. g = *sp++;
  193881. b = *sp++;
  193882. /* this looks real messy, but the compiler will reduce
  193883. it down to a reasonable formula. For example, with
  193884. 5 bits per color, we get:
  193885. p = (((r >> 3) & 0x1f) << 10) |
  193886. (((g >> 3) & 0x1f) << 5) |
  193887. ((b >> 3) & 0x1f);
  193888. */
  193889. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193890. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193891. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193892. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193893. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193894. (PNG_DITHER_BLUE_BITS)) |
  193895. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193896. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193897. *dp++ = palette_lookup[p];
  193898. }
  193899. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193900. row_info->channels = 1;
  193901. row_info->pixel_depth = row_info->bit_depth;
  193902. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193903. }
  193904. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193905. palette_lookup != NULL && row_info->bit_depth == 8)
  193906. {
  193907. int r, g, b, p;
  193908. sp = row;
  193909. dp = row;
  193910. for (i = 0; i < row_width; i++)
  193911. {
  193912. r = *sp++;
  193913. g = *sp++;
  193914. b = *sp++;
  193915. sp++;
  193916. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193917. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193918. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193919. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193920. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193921. (PNG_DITHER_BLUE_BITS)) |
  193922. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193923. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193924. *dp++ = palette_lookup[p];
  193925. }
  193926. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193927. row_info->channels = 1;
  193928. row_info->pixel_depth = row_info->bit_depth;
  193929. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193930. }
  193931. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193932. dither_lookup && row_info->bit_depth == 8)
  193933. {
  193934. sp = row;
  193935. for (i = 0; i < row_width; i++, sp++)
  193936. {
  193937. *sp = dither_lookup[*sp];
  193938. }
  193939. }
  193940. }
  193941. }
  193942. #endif
  193943. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193944. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193945. static PNG_CONST int png_gamma_shift[] =
  193946. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193947. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193948. * tables, we don't make a full table if we are reducing to 8-bit in
  193949. * the future. Note also how the gamma_16 tables are segmented so that
  193950. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193951. */
  193952. void /* PRIVATE */
  193953. png_build_gamma_table(png_structp png_ptr)
  193954. {
  193955. png_debug(1, "in png_build_gamma_table\n");
  193956. if (png_ptr->bit_depth <= 8)
  193957. {
  193958. int i;
  193959. double g;
  193960. if (png_ptr->screen_gamma > .000001)
  193961. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193962. else
  193963. g = 1.0;
  193964. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193965. (png_uint_32)256);
  193966. for (i = 0; i < 256; i++)
  193967. {
  193968. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193969. g) * 255.0 + .5);
  193970. }
  193971. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193972. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193973. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193974. {
  193975. g = 1.0 / (png_ptr->gamma);
  193976. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193977. (png_uint_32)256);
  193978. for (i = 0; i < 256; i++)
  193979. {
  193980. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193981. g) * 255.0 + .5);
  193982. }
  193983. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193984. (png_uint_32)256);
  193985. if(png_ptr->screen_gamma > 0.000001)
  193986. g = 1.0 / png_ptr->screen_gamma;
  193987. else
  193988. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193989. for (i = 0; i < 256; i++)
  193990. {
  193991. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193992. g) * 255.0 + .5);
  193993. }
  193994. }
  193995. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193996. }
  193997. else
  193998. {
  193999. double g;
  194000. int i, j, shift, num;
  194001. int sig_bit;
  194002. png_uint_32 ig;
  194003. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194004. {
  194005. sig_bit = (int)png_ptr->sig_bit.red;
  194006. if ((int)png_ptr->sig_bit.green > sig_bit)
  194007. sig_bit = png_ptr->sig_bit.green;
  194008. if ((int)png_ptr->sig_bit.blue > sig_bit)
  194009. sig_bit = png_ptr->sig_bit.blue;
  194010. }
  194011. else
  194012. {
  194013. sig_bit = (int)png_ptr->sig_bit.gray;
  194014. }
  194015. if (sig_bit > 0)
  194016. shift = 16 - sig_bit;
  194017. else
  194018. shift = 0;
  194019. if (png_ptr->transformations & PNG_16_TO_8)
  194020. {
  194021. if (shift < (16 - PNG_MAX_GAMMA_8))
  194022. shift = (16 - PNG_MAX_GAMMA_8);
  194023. }
  194024. if (shift > 8)
  194025. shift = 8;
  194026. if (shift < 0)
  194027. shift = 0;
  194028. png_ptr->gamma_shift = (png_byte)shift;
  194029. num = (1 << (8 - shift));
  194030. if (png_ptr->screen_gamma > .000001)
  194031. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194032. else
  194033. g = 1.0;
  194034. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194035. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194036. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194037. {
  194038. double fin, fout;
  194039. png_uint_32 last, max;
  194040. for (i = 0; i < num; i++)
  194041. {
  194042. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194043. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194044. }
  194045. g = 1.0 / g;
  194046. last = 0;
  194047. for (i = 0; i < 256; i++)
  194048. {
  194049. fout = ((double)i + 0.5) / 256.0;
  194050. fin = pow(fout, g);
  194051. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194052. while (last <= max)
  194053. {
  194054. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194055. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194056. (png_uint_16)i | ((png_uint_16)i << 8));
  194057. last++;
  194058. }
  194059. }
  194060. while (last < ((png_uint_32)num << 8))
  194061. {
  194062. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194063. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194064. last++;
  194065. }
  194066. }
  194067. else
  194068. {
  194069. for (i = 0; i < num; i++)
  194070. {
  194071. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194072. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194073. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194074. for (j = 0; j < 256; j++)
  194075. {
  194076. png_ptr->gamma_16_table[i][j] =
  194077. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194078. 65535.0, g) * 65535.0 + .5);
  194079. }
  194080. }
  194081. }
  194082. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194083. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194084. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194085. {
  194086. g = 1.0 / (png_ptr->gamma);
  194087. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194088. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194089. for (i = 0; i < num; i++)
  194090. {
  194091. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194092. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194093. ig = (((png_uint_32)i *
  194094. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194095. for (j = 0; j < 256; j++)
  194096. {
  194097. png_ptr->gamma_16_to_1[i][j] =
  194098. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194099. 65535.0, g) * 65535.0 + .5);
  194100. }
  194101. }
  194102. if(png_ptr->screen_gamma > 0.000001)
  194103. g = 1.0 / png_ptr->screen_gamma;
  194104. else
  194105. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194106. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194107. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194108. for (i = 0; i < num; i++)
  194109. {
  194110. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194111. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194112. ig = (((png_uint_32)i *
  194113. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194114. for (j = 0; j < 256; j++)
  194115. {
  194116. png_ptr->gamma_16_from_1[i][j] =
  194117. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194118. 65535.0, g) * 65535.0 + .5);
  194119. }
  194120. }
  194121. }
  194122. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194123. }
  194124. }
  194125. #endif
  194126. /* To do: install integer version of png_build_gamma_table here */
  194127. #endif
  194128. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194129. /* undoes intrapixel differencing */
  194130. void /* PRIVATE */
  194131. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194132. {
  194133. png_debug(1, "in png_do_read_intrapixel\n");
  194134. if (
  194135. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194136. row != NULL && row_info != NULL &&
  194137. #endif
  194138. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194139. {
  194140. int bytes_per_pixel;
  194141. png_uint_32 row_width = row_info->width;
  194142. if (row_info->bit_depth == 8)
  194143. {
  194144. png_bytep rp;
  194145. png_uint_32 i;
  194146. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194147. bytes_per_pixel = 3;
  194148. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194149. bytes_per_pixel = 4;
  194150. else
  194151. return;
  194152. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194153. {
  194154. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194155. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194156. }
  194157. }
  194158. else if (row_info->bit_depth == 16)
  194159. {
  194160. png_bytep rp;
  194161. png_uint_32 i;
  194162. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194163. bytes_per_pixel = 6;
  194164. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194165. bytes_per_pixel = 8;
  194166. else
  194167. return;
  194168. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194169. {
  194170. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194171. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194172. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194173. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194174. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194175. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194176. *(rp+1) = (png_byte)(red & 0xff);
  194177. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194178. *(rp+5) = (png_byte)(blue & 0xff);
  194179. }
  194180. }
  194181. }
  194182. }
  194183. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194184. #endif /* PNG_READ_SUPPORTED */
  194185. /*** End of inlined file: pngrtran.c ***/
  194186. /*** Start of inlined file: pngrutil.c ***/
  194187. /* pngrutil.c - utilities to read a PNG file
  194188. *
  194189. * Last changed in libpng 1.2.21 [October 4, 2007]
  194190. * For conditions of distribution and use, see copyright notice in png.h
  194191. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194192. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194193. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194194. *
  194195. * This file contains routines that are only called from within
  194196. * libpng itself during the course of reading an image.
  194197. */
  194198. #define PNG_INTERNAL
  194199. #if defined(PNG_READ_SUPPORTED)
  194200. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194201. # define WIN32_WCE_OLD
  194202. #endif
  194203. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194204. # if defined(WIN32_WCE_OLD)
  194205. /* strtod() function is not supported on WindowsCE */
  194206. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194207. {
  194208. double result = 0;
  194209. int len;
  194210. wchar_t *str, *end;
  194211. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194212. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194213. if ( NULL != str )
  194214. {
  194215. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194216. result = wcstod(str, &end);
  194217. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194218. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194219. png_free(png_ptr, str);
  194220. }
  194221. return result;
  194222. }
  194223. # else
  194224. # define png_strtod(p,a,b) strtod(a,b)
  194225. # endif
  194226. #endif
  194227. png_uint_32 PNGAPI
  194228. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194229. {
  194230. png_uint_32 i = png_get_uint_32(buf);
  194231. if (i > PNG_UINT_31_MAX)
  194232. png_error(png_ptr, "PNG unsigned integer out of range.");
  194233. return (i);
  194234. }
  194235. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194236. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194237. png_uint_32 PNGAPI
  194238. png_get_uint_32(png_bytep buf)
  194239. {
  194240. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194241. ((png_uint_32)(*(buf + 1)) << 16) +
  194242. ((png_uint_32)(*(buf + 2)) << 8) +
  194243. (png_uint_32)(*(buf + 3));
  194244. return (i);
  194245. }
  194246. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194247. * data is stored in the PNG file in two's complement format, and it is
  194248. * assumed that the machine format for signed integers is the same. */
  194249. png_int_32 PNGAPI
  194250. png_get_int_32(png_bytep buf)
  194251. {
  194252. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194253. ((png_int_32)(*(buf + 1)) << 16) +
  194254. ((png_int_32)(*(buf + 2)) << 8) +
  194255. (png_int_32)(*(buf + 3));
  194256. return (i);
  194257. }
  194258. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194259. png_uint_16 PNGAPI
  194260. png_get_uint_16(png_bytep buf)
  194261. {
  194262. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194263. (png_uint_16)(*(buf + 1)));
  194264. return (i);
  194265. }
  194266. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194267. /* Read data, and (optionally) run it through the CRC. */
  194268. void /* PRIVATE */
  194269. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194270. {
  194271. if(png_ptr == NULL) return;
  194272. png_read_data(png_ptr, buf, length);
  194273. png_calculate_crc(png_ptr, buf, length);
  194274. }
  194275. /* Optionally skip data and then check the CRC. Depending on whether we
  194276. are reading a ancillary or critical chunk, and how the program has set
  194277. things up, we may calculate the CRC on the data and print a message.
  194278. Returns '1' if there was a CRC error, '0' otherwise. */
  194279. int /* PRIVATE */
  194280. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194281. {
  194282. png_size_t i;
  194283. png_size_t istop = png_ptr->zbuf_size;
  194284. for (i = (png_size_t)skip; i > istop; i -= istop)
  194285. {
  194286. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194287. }
  194288. if (i)
  194289. {
  194290. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194291. }
  194292. if (png_crc_error(png_ptr))
  194293. {
  194294. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194295. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194296. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194297. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194298. {
  194299. png_chunk_warning(png_ptr, "CRC error");
  194300. }
  194301. else
  194302. {
  194303. png_chunk_error(png_ptr, "CRC error");
  194304. }
  194305. return (1);
  194306. }
  194307. return (0);
  194308. }
  194309. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194310. the data it has read thus far. */
  194311. int /* PRIVATE */
  194312. png_crc_error(png_structp png_ptr)
  194313. {
  194314. png_byte crc_bytes[4];
  194315. png_uint_32 crc;
  194316. int need_crc = 1;
  194317. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194318. {
  194319. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194320. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194321. need_crc = 0;
  194322. }
  194323. else /* critical */
  194324. {
  194325. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194326. need_crc = 0;
  194327. }
  194328. png_read_data(png_ptr, crc_bytes, 4);
  194329. if (need_crc)
  194330. {
  194331. crc = png_get_uint_32(crc_bytes);
  194332. return ((int)(crc != png_ptr->crc));
  194333. }
  194334. else
  194335. return (0);
  194336. }
  194337. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194338. defined(PNG_READ_iCCP_SUPPORTED)
  194339. /*
  194340. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194341. * points at an allocated area holding the contents of a chunk with a
  194342. * trailing compressed part. What we get back is an allocated area
  194343. * holding the original prefix part and an uncompressed version of the
  194344. * trailing part (the malloc area passed in is freed).
  194345. */
  194346. png_charp /* PRIVATE */
  194347. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194348. png_charp chunkdata, png_size_t chunklength,
  194349. png_size_t prefix_size, png_size_t *newlength)
  194350. {
  194351. static PNG_CONST char msg[] = "Error decoding compressed text";
  194352. png_charp text;
  194353. png_size_t text_size;
  194354. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194355. {
  194356. int ret = Z_OK;
  194357. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194358. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194359. png_ptr->zstream.next_out = png_ptr->zbuf;
  194360. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194361. text_size = 0;
  194362. text = NULL;
  194363. while (png_ptr->zstream.avail_in)
  194364. {
  194365. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194366. if (ret != Z_OK && ret != Z_STREAM_END)
  194367. {
  194368. if (png_ptr->zstream.msg != NULL)
  194369. png_warning(png_ptr, png_ptr->zstream.msg);
  194370. else
  194371. png_warning(png_ptr, msg);
  194372. inflateReset(&png_ptr->zstream);
  194373. png_ptr->zstream.avail_in = 0;
  194374. if (text == NULL)
  194375. {
  194376. text_size = prefix_size + png_sizeof(msg) + 1;
  194377. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194378. if (text == NULL)
  194379. {
  194380. png_free(png_ptr,chunkdata);
  194381. png_error(png_ptr,"Not enough memory to decompress chunk");
  194382. }
  194383. png_memcpy(text, chunkdata, prefix_size);
  194384. }
  194385. text[text_size - 1] = 0x00;
  194386. /* Copy what we can of the error message into the text chunk */
  194387. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194388. text_size = png_sizeof(msg) > text_size ? text_size :
  194389. png_sizeof(msg);
  194390. png_memcpy(text + prefix_size, msg, text_size + 1);
  194391. break;
  194392. }
  194393. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194394. {
  194395. if (text == NULL)
  194396. {
  194397. text_size = prefix_size +
  194398. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194399. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194400. if (text == NULL)
  194401. {
  194402. png_free(png_ptr,chunkdata);
  194403. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194404. }
  194405. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194406. text_size - prefix_size);
  194407. png_memcpy(text, chunkdata, prefix_size);
  194408. *(text + text_size) = 0x00;
  194409. }
  194410. else
  194411. {
  194412. png_charp tmp;
  194413. tmp = text;
  194414. text = (png_charp)png_malloc_warn(png_ptr,
  194415. (png_uint_32)(text_size +
  194416. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194417. if (text == NULL)
  194418. {
  194419. png_free(png_ptr, tmp);
  194420. png_free(png_ptr, chunkdata);
  194421. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194422. }
  194423. png_memcpy(text, tmp, text_size);
  194424. png_free(png_ptr, tmp);
  194425. png_memcpy(text + text_size, png_ptr->zbuf,
  194426. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194427. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194428. *(text + text_size) = 0x00;
  194429. }
  194430. if (ret == Z_STREAM_END)
  194431. break;
  194432. else
  194433. {
  194434. png_ptr->zstream.next_out = png_ptr->zbuf;
  194435. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194436. }
  194437. }
  194438. }
  194439. if (ret != Z_STREAM_END)
  194440. {
  194441. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194442. char umsg[52];
  194443. if (ret == Z_BUF_ERROR)
  194444. png_snprintf(umsg, 52,
  194445. "Buffer error in compressed datastream in %s chunk",
  194446. png_ptr->chunk_name);
  194447. else if (ret == Z_DATA_ERROR)
  194448. png_snprintf(umsg, 52,
  194449. "Data error in compressed datastream in %s chunk",
  194450. png_ptr->chunk_name);
  194451. else
  194452. png_snprintf(umsg, 52,
  194453. "Incomplete compressed datastream in %s chunk",
  194454. png_ptr->chunk_name);
  194455. png_warning(png_ptr, umsg);
  194456. #else
  194457. png_warning(png_ptr,
  194458. "Incomplete compressed datastream in chunk other than IDAT");
  194459. #endif
  194460. text_size=prefix_size;
  194461. if (text == NULL)
  194462. {
  194463. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194464. if (text == NULL)
  194465. {
  194466. png_free(png_ptr, chunkdata);
  194467. png_error(png_ptr,"Not enough memory for text.");
  194468. }
  194469. png_memcpy(text, chunkdata, prefix_size);
  194470. }
  194471. *(text + text_size) = 0x00;
  194472. }
  194473. inflateReset(&png_ptr->zstream);
  194474. png_ptr->zstream.avail_in = 0;
  194475. png_free(png_ptr, chunkdata);
  194476. chunkdata = text;
  194477. *newlength=text_size;
  194478. }
  194479. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194480. {
  194481. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194482. char umsg[50];
  194483. png_snprintf(umsg, 50,
  194484. "Unknown zTXt compression type %d", comp_type);
  194485. png_warning(png_ptr, umsg);
  194486. #else
  194487. png_warning(png_ptr, "Unknown zTXt compression type");
  194488. #endif
  194489. *(chunkdata + prefix_size) = 0x00;
  194490. *newlength=prefix_size;
  194491. }
  194492. return chunkdata;
  194493. }
  194494. #endif
  194495. /* read and check the IDHR chunk */
  194496. void /* PRIVATE */
  194497. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194498. {
  194499. png_byte buf[13];
  194500. png_uint_32 width, height;
  194501. int bit_depth, color_type, compression_type, filter_type;
  194502. int interlace_type;
  194503. png_debug(1, "in png_handle_IHDR\n");
  194504. if (png_ptr->mode & PNG_HAVE_IHDR)
  194505. png_error(png_ptr, "Out of place IHDR");
  194506. /* check the length */
  194507. if (length != 13)
  194508. png_error(png_ptr, "Invalid IHDR chunk");
  194509. png_ptr->mode |= PNG_HAVE_IHDR;
  194510. png_crc_read(png_ptr, buf, 13);
  194511. png_crc_finish(png_ptr, 0);
  194512. width = png_get_uint_31(png_ptr, buf);
  194513. height = png_get_uint_31(png_ptr, buf + 4);
  194514. bit_depth = buf[8];
  194515. color_type = buf[9];
  194516. compression_type = buf[10];
  194517. filter_type = buf[11];
  194518. interlace_type = buf[12];
  194519. /* set internal variables */
  194520. png_ptr->width = width;
  194521. png_ptr->height = height;
  194522. png_ptr->bit_depth = (png_byte)bit_depth;
  194523. png_ptr->interlaced = (png_byte)interlace_type;
  194524. png_ptr->color_type = (png_byte)color_type;
  194525. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194526. png_ptr->filter_type = (png_byte)filter_type;
  194527. #endif
  194528. png_ptr->compression_type = (png_byte)compression_type;
  194529. /* find number of channels */
  194530. switch (png_ptr->color_type)
  194531. {
  194532. case PNG_COLOR_TYPE_GRAY:
  194533. case PNG_COLOR_TYPE_PALETTE:
  194534. png_ptr->channels = 1;
  194535. break;
  194536. case PNG_COLOR_TYPE_RGB:
  194537. png_ptr->channels = 3;
  194538. break;
  194539. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194540. png_ptr->channels = 2;
  194541. break;
  194542. case PNG_COLOR_TYPE_RGB_ALPHA:
  194543. png_ptr->channels = 4;
  194544. break;
  194545. }
  194546. /* set up other useful info */
  194547. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194548. png_ptr->channels);
  194549. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194550. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194551. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194552. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194553. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194554. color_type, interlace_type, compression_type, filter_type);
  194555. }
  194556. /* read and check the palette */
  194557. void /* PRIVATE */
  194558. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194559. {
  194560. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194561. int num, i;
  194562. #ifndef PNG_NO_POINTER_INDEXING
  194563. png_colorp pal_ptr;
  194564. #endif
  194565. png_debug(1, "in png_handle_PLTE\n");
  194566. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194567. png_error(png_ptr, "Missing IHDR before PLTE");
  194568. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194569. {
  194570. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194571. png_crc_finish(png_ptr, length);
  194572. return;
  194573. }
  194574. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194575. png_error(png_ptr, "Duplicate PLTE chunk");
  194576. png_ptr->mode |= PNG_HAVE_PLTE;
  194577. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194578. {
  194579. png_warning(png_ptr,
  194580. "Ignoring PLTE chunk in grayscale PNG");
  194581. png_crc_finish(png_ptr, length);
  194582. return;
  194583. }
  194584. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194585. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194586. {
  194587. png_crc_finish(png_ptr, length);
  194588. return;
  194589. }
  194590. #endif
  194591. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194592. {
  194593. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194594. {
  194595. png_warning(png_ptr, "Invalid palette chunk");
  194596. png_crc_finish(png_ptr, length);
  194597. return;
  194598. }
  194599. else
  194600. {
  194601. png_error(png_ptr, "Invalid palette chunk");
  194602. }
  194603. }
  194604. num = (int)length / 3;
  194605. #ifndef PNG_NO_POINTER_INDEXING
  194606. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194607. {
  194608. png_byte buf[3];
  194609. png_crc_read(png_ptr, buf, 3);
  194610. pal_ptr->red = buf[0];
  194611. pal_ptr->green = buf[1];
  194612. pal_ptr->blue = buf[2];
  194613. }
  194614. #else
  194615. for (i = 0; i < num; i++)
  194616. {
  194617. png_byte buf[3];
  194618. png_crc_read(png_ptr, buf, 3);
  194619. /* don't depend upon png_color being any order */
  194620. palette[i].red = buf[0];
  194621. palette[i].green = buf[1];
  194622. palette[i].blue = buf[2];
  194623. }
  194624. #endif
  194625. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194626. whatever the normal CRC configuration tells us. However, if we
  194627. have an RGB image, the PLTE can be considered ancillary, so
  194628. we will act as though it is. */
  194629. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194630. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194631. #endif
  194632. {
  194633. png_crc_finish(png_ptr, 0);
  194634. }
  194635. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194636. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194637. {
  194638. /* If we don't want to use the data from an ancillary chunk,
  194639. we have two options: an error abort, or a warning and we
  194640. ignore the data in this chunk (which should be OK, since
  194641. it's considered ancillary for a RGB or RGBA image). */
  194642. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194643. {
  194644. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194645. {
  194646. png_chunk_error(png_ptr, "CRC error");
  194647. }
  194648. else
  194649. {
  194650. png_chunk_warning(png_ptr, "CRC error");
  194651. return;
  194652. }
  194653. }
  194654. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194655. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194656. {
  194657. png_chunk_warning(png_ptr, "CRC error");
  194658. }
  194659. }
  194660. #endif
  194661. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194662. #if defined(PNG_READ_tRNS_SUPPORTED)
  194663. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194664. {
  194665. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194666. {
  194667. if (png_ptr->num_trans > (png_uint_16)num)
  194668. {
  194669. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194670. png_ptr->num_trans = (png_uint_16)num;
  194671. }
  194672. if (info_ptr->num_trans > (png_uint_16)num)
  194673. {
  194674. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194675. info_ptr->num_trans = (png_uint_16)num;
  194676. }
  194677. }
  194678. }
  194679. #endif
  194680. }
  194681. void /* PRIVATE */
  194682. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194683. {
  194684. png_debug(1, "in png_handle_IEND\n");
  194685. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194686. {
  194687. png_error(png_ptr, "No image in file");
  194688. }
  194689. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194690. if (length != 0)
  194691. {
  194692. png_warning(png_ptr, "Incorrect IEND chunk length");
  194693. }
  194694. png_crc_finish(png_ptr, length);
  194695. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194696. }
  194697. #if defined(PNG_READ_gAMA_SUPPORTED)
  194698. void /* PRIVATE */
  194699. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194700. {
  194701. png_fixed_point igamma;
  194702. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194703. float file_gamma;
  194704. #endif
  194705. png_byte buf[4];
  194706. png_debug(1, "in png_handle_gAMA\n");
  194707. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194708. png_error(png_ptr, "Missing IHDR before gAMA");
  194709. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194710. {
  194711. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194712. png_crc_finish(png_ptr, length);
  194713. return;
  194714. }
  194715. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194716. /* Should be an error, but we can cope with it */
  194717. png_warning(png_ptr, "Out of place gAMA chunk");
  194718. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194719. #if defined(PNG_READ_sRGB_SUPPORTED)
  194720. && !(info_ptr->valid & PNG_INFO_sRGB)
  194721. #endif
  194722. )
  194723. {
  194724. png_warning(png_ptr, "Duplicate gAMA chunk");
  194725. png_crc_finish(png_ptr, length);
  194726. return;
  194727. }
  194728. if (length != 4)
  194729. {
  194730. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194731. png_crc_finish(png_ptr, length);
  194732. return;
  194733. }
  194734. png_crc_read(png_ptr, buf, 4);
  194735. if (png_crc_finish(png_ptr, 0))
  194736. return;
  194737. igamma = (png_fixed_point)png_get_uint_32(buf);
  194738. /* check for zero gamma */
  194739. if (igamma == 0)
  194740. {
  194741. png_warning(png_ptr,
  194742. "Ignoring gAMA chunk with gamma=0");
  194743. return;
  194744. }
  194745. #if defined(PNG_READ_sRGB_SUPPORTED)
  194746. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194747. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194748. {
  194749. png_warning(png_ptr,
  194750. "Ignoring incorrect gAMA value when sRGB is also present");
  194751. #ifndef PNG_NO_CONSOLE_IO
  194752. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194753. #endif
  194754. return;
  194755. }
  194756. #endif /* PNG_READ_sRGB_SUPPORTED */
  194757. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194758. file_gamma = (float)igamma / (float)100000.0;
  194759. # ifdef PNG_READ_GAMMA_SUPPORTED
  194760. png_ptr->gamma = file_gamma;
  194761. # endif
  194762. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194763. #endif
  194764. #ifdef PNG_FIXED_POINT_SUPPORTED
  194765. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194766. #endif
  194767. }
  194768. #endif
  194769. #if defined(PNG_READ_sBIT_SUPPORTED)
  194770. void /* PRIVATE */
  194771. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194772. {
  194773. png_size_t truelen;
  194774. png_byte buf[4];
  194775. png_debug(1, "in png_handle_sBIT\n");
  194776. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194777. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194778. png_error(png_ptr, "Missing IHDR before sBIT");
  194779. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194780. {
  194781. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194782. png_crc_finish(png_ptr, length);
  194783. return;
  194784. }
  194785. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194786. {
  194787. /* Should be an error, but we can cope with it */
  194788. png_warning(png_ptr, "Out of place sBIT chunk");
  194789. }
  194790. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194791. {
  194792. png_warning(png_ptr, "Duplicate sBIT chunk");
  194793. png_crc_finish(png_ptr, length);
  194794. return;
  194795. }
  194796. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194797. truelen = 3;
  194798. else
  194799. truelen = (png_size_t)png_ptr->channels;
  194800. if (length != truelen || length > 4)
  194801. {
  194802. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194803. png_crc_finish(png_ptr, length);
  194804. return;
  194805. }
  194806. png_crc_read(png_ptr, buf, truelen);
  194807. if (png_crc_finish(png_ptr, 0))
  194808. return;
  194809. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194810. {
  194811. png_ptr->sig_bit.red = buf[0];
  194812. png_ptr->sig_bit.green = buf[1];
  194813. png_ptr->sig_bit.blue = buf[2];
  194814. png_ptr->sig_bit.alpha = buf[3];
  194815. }
  194816. else
  194817. {
  194818. png_ptr->sig_bit.gray = buf[0];
  194819. png_ptr->sig_bit.red = buf[0];
  194820. png_ptr->sig_bit.green = buf[0];
  194821. png_ptr->sig_bit.blue = buf[0];
  194822. png_ptr->sig_bit.alpha = buf[1];
  194823. }
  194824. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194825. }
  194826. #endif
  194827. #if defined(PNG_READ_cHRM_SUPPORTED)
  194828. void /* PRIVATE */
  194829. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194830. {
  194831. png_byte buf[4];
  194832. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194833. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194834. #endif
  194835. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194836. int_y_green, int_x_blue, int_y_blue;
  194837. png_uint_32 uint_x, uint_y;
  194838. png_debug(1, "in png_handle_cHRM\n");
  194839. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194840. png_error(png_ptr, "Missing IHDR before cHRM");
  194841. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194842. {
  194843. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194844. png_crc_finish(png_ptr, length);
  194845. return;
  194846. }
  194847. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194848. /* Should be an error, but we can cope with it */
  194849. png_warning(png_ptr, "Missing PLTE before cHRM");
  194850. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194851. #if defined(PNG_READ_sRGB_SUPPORTED)
  194852. && !(info_ptr->valid & PNG_INFO_sRGB)
  194853. #endif
  194854. )
  194855. {
  194856. png_warning(png_ptr, "Duplicate cHRM chunk");
  194857. png_crc_finish(png_ptr, length);
  194858. return;
  194859. }
  194860. if (length != 32)
  194861. {
  194862. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194863. png_crc_finish(png_ptr, length);
  194864. return;
  194865. }
  194866. png_crc_read(png_ptr, buf, 4);
  194867. uint_x = png_get_uint_32(buf);
  194868. png_crc_read(png_ptr, buf, 4);
  194869. uint_y = png_get_uint_32(buf);
  194870. if (uint_x > 80000L || uint_y > 80000L ||
  194871. uint_x + uint_y > 100000L)
  194872. {
  194873. png_warning(png_ptr, "Invalid cHRM white point");
  194874. png_crc_finish(png_ptr, 24);
  194875. return;
  194876. }
  194877. int_x_white = (png_fixed_point)uint_x;
  194878. int_y_white = (png_fixed_point)uint_y;
  194879. png_crc_read(png_ptr, buf, 4);
  194880. uint_x = png_get_uint_32(buf);
  194881. png_crc_read(png_ptr, buf, 4);
  194882. uint_y = png_get_uint_32(buf);
  194883. if (uint_x + uint_y > 100000L)
  194884. {
  194885. png_warning(png_ptr, "Invalid cHRM red point");
  194886. png_crc_finish(png_ptr, 16);
  194887. return;
  194888. }
  194889. int_x_red = (png_fixed_point)uint_x;
  194890. int_y_red = (png_fixed_point)uint_y;
  194891. png_crc_read(png_ptr, buf, 4);
  194892. uint_x = png_get_uint_32(buf);
  194893. png_crc_read(png_ptr, buf, 4);
  194894. uint_y = png_get_uint_32(buf);
  194895. if (uint_x + uint_y > 100000L)
  194896. {
  194897. png_warning(png_ptr, "Invalid cHRM green point");
  194898. png_crc_finish(png_ptr, 8);
  194899. return;
  194900. }
  194901. int_x_green = (png_fixed_point)uint_x;
  194902. int_y_green = (png_fixed_point)uint_y;
  194903. png_crc_read(png_ptr, buf, 4);
  194904. uint_x = png_get_uint_32(buf);
  194905. png_crc_read(png_ptr, buf, 4);
  194906. uint_y = png_get_uint_32(buf);
  194907. if (uint_x + uint_y > 100000L)
  194908. {
  194909. png_warning(png_ptr, "Invalid cHRM blue point");
  194910. png_crc_finish(png_ptr, 0);
  194911. return;
  194912. }
  194913. int_x_blue = (png_fixed_point)uint_x;
  194914. int_y_blue = (png_fixed_point)uint_y;
  194915. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194916. white_x = (float)int_x_white / (float)100000.0;
  194917. white_y = (float)int_y_white / (float)100000.0;
  194918. red_x = (float)int_x_red / (float)100000.0;
  194919. red_y = (float)int_y_red / (float)100000.0;
  194920. green_x = (float)int_x_green / (float)100000.0;
  194921. green_y = (float)int_y_green / (float)100000.0;
  194922. blue_x = (float)int_x_blue / (float)100000.0;
  194923. blue_y = (float)int_y_blue / (float)100000.0;
  194924. #endif
  194925. #if defined(PNG_READ_sRGB_SUPPORTED)
  194926. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194927. {
  194928. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194929. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194930. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194931. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194932. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194933. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194934. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194935. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194936. {
  194937. png_warning(png_ptr,
  194938. "Ignoring incorrect cHRM value when sRGB is also present");
  194939. #ifndef PNG_NO_CONSOLE_IO
  194940. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194941. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194942. white_x, white_y, red_x, red_y);
  194943. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194944. green_x, green_y, blue_x, blue_y);
  194945. #else
  194946. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194947. int_x_white, int_y_white, int_x_red, int_y_red);
  194948. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194949. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194950. #endif
  194951. #endif /* PNG_NO_CONSOLE_IO */
  194952. }
  194953. png_crc_finish(png_ptr, 0);
  194954. return;
  194955. }
  194956. #endif /* PNG_READ_sRGB_SUPPORTED */
  194957. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194958. png_set_cHRM(png_ptr, info_ptr,
  194959. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194960. #endif
  194961. #ifdef PNG_FIXED_POINT_SUPPORTED
  194962. png_set_cHRM_fixed(png_ptr, info_ptr,
  194963. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194964. int_y_green, int_x_blue, int_y_blue);
  194965. #endif
  194966. if (png_crc_finish(png_ptr, 0))
  194967. return;
  194968. }
  194969. #endif
  194970. #if defined(PNG_READ_sRGB_SUPPORTED)
  194971. void /* PRIVATE */
  194972. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194973. {
  194974. int intent;
  194975. png_byte buf[1];
  194976. png_debug(1, "in png_handle_sRGB\n");
  194977. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194978. png_error(png_ptr, "Missing IHDR before sRGB");
  194979. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194980. {
  194981. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194982. png_crc_finish(png_ptr, length);
  194983. return;
  194984. }
  194985. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194986. /* Should be an error, but we can cope with it */
  194987. png_warning(png_ptr, "Out of place sRGB chunk");
  194988. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194989. {
  194990. png_warning(png_ptr, "Duplicate sRGB chunk");
  194991. png_crc_finish(png_ptr, length);
  194992. return;
  194993. }
  194994. if (length != 1)
  194995. {
  194996. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194997. png_crc_finish(png_ptr, length);
  194998. return;
  194999. }
  195000. png_crc_read(png_ptr, buf, 1);
  195001. if (png_crc_finish(png_ptr, 0))
  195002. return;
  195003. intent = buf[0];
  195004. /* check for bad intent */
  195005. if (intent >= PNG_sRGB_INTENT_LAST)
  195006. {
  195007. png_warning(png_ptr, "Unknown sRGB intent");
  195008. return;
  195009. }
  195010. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  195011. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  195012. {
  195013. png_fixed_point igamma;
  195014. #ifdef PNG_FIXED_POINT_SUPPORTED
  195015. igamma=info_ptr->int_gamma;
  195016. #else
  195017. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195018. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  195019. # endif
  195020. #endif
  195021. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195022. {
  195023. png_warning(png_ptr,
  195024. "Ignoring incorrect gAMA value when sRGB is also present");
  195025. #ifndef PNG_NO_CONSOLE_IO
  195026. # ifdef PNG_FIXED_POINT_SUPPORTED
  195027. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195028. # else
  195029. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195030. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195031. # endif
  195032. # endif
  195033. #endif
  195034. }
  195035. }
  195036. #endif /* PNG_READ_gAMA_SUPPORTED */
  195037. #ifdef PNG_READ_cHRM_SUPPORTED
  195038. #ifdef PNG_FIXED_POINT_SUPPORTED
  195039. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195040. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195041. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195042. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195043. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195044. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195045. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195046. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195047. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195048. {
  195049. png_warning(png_ptr,
  195050. "Ignoring incorrect cHRM value when sRGB is also present");
  195051. }
  195052. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195053. #endif /* PNG_READ_cHRM_SUPPORTED */
  195054. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195055. }
  195056. #endif /* PNG_READ_sRGB_SUPPORTED */
  195057. #if defined(PNG_READ_iCCP_SUPPORTED)
  195058. void /* PRIVATE */
  195059. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195060. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195061. {
  195062. png_charp chunkdata;
  195063. png_byte compression_type;
  195064. png_bytep pC;
  195065. png_charp profile;
  195066. png_uint_32 skip = 0;
  195067. png_uint_32 profile_size, profile_length;
  195068. png_size_t slength, prefix_length, data_length;
  195069. png_debug(1, "in png_handle_iCCP\n");
  195070. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195071. png_error(png_ptr, "Missing IHDR before iCCP");
  195072. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195073. {
  195074. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195075. png_crc_finish(png_ptr, length);
  195076. return;
  195077. }
  195078. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195079. /* Should be an error, but we can cope with it */
  195080. png_warning(png_ptr, "Out of place iCCP chunk");
  195081. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195082. {
  195083. png_warning(png_ptr, "Duplicate iCCP chunk");
  195084. png_crc_finish(png_ptr, length);
  195085. return;
  195086. }
  195087. #ifdef PNG_MAX_MALLOC_64K
  195088. if (length > (png_uint_32)65535L)
  195089. {
  195090. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195091. skip = length - (png_uint_32)65535L;
  195092. length = (png_uint_32)65535L;
  195093. }
  195094. #endif
  195095. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195096. slength = (png_size_t)length;
  195097. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195098. if (png_crc_finish(png_ptr, skip))
  195099. {
  195100. png_free(png_ptr, chunkdata);
  195101. return;
  195102. }
  195103. chunkdata[slength] = 0x00;
  195104. for (profile = chunkdata; *profile; profile++)
  195105. /* empty loop to find end of name */ ;
  195106. ++profile;
  195107. /* there should be at least one zero (the compression type byte)
  195108. following the separator, and we should be on it */
  195109. if ( profile >= chunkdata + slength - 1)
  195110. {
  195111. png_free(png_ptr, chunkdata);
  195112. png_warning(png_ptr, "Malformed iCCP chunk");
  195113. return;
  195114. }
  195115. /* compression_type should always be zero */
  195116. compression_type = *profile++;
  195117. if (compression_type)
  195118. {
  195119. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195120. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195121. wrote nonzero) */
  195122. }
  195123. prefix_length = profile - chunkdata;
  195124. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195125. slength, prefix_length, &data_length);
  195126. profile_length = data_length - prefix_length;
  195127. if ( prefix_length > data_length || profile_length < 4)
  195128. {
  195129. png_free(png_ptr, chunkdata);
  195130. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195131. return;
  195132. }
  195133. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195134. pC = (png_bytep)(chunkdata+prefix_length);
  195135. profile_size = ((*(pC ))<<24) |
  195136. ((*(pC+1))<<16) |
  195137. ((*(pC+2))<< 8) |
  195138. ((*(pC+3)) );
  195139. if(profile_size < profile_length)
  195140. profile_length = profile_size;
  195141. if(profile_size > profile_length)
  195142. {
  195143. png_free(png_ptr, chunkdata);
  195144. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195145. return;
  195146. }
  195147. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195148. chunkdata + prefix_length, profile_length);
  195149. png_free(png_ptr, chunkdata);
  195150. }
  195151. #endif /* PNG_READ_iCCP_SUPPORTED */
  195152. #if defined(PNG_READ_sPLT_SUPPORTED)
  195153. void /* PRIVATE */
  195154. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195155. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195156. {
  195157. png_bytep chunkdata;
  195158. png_bytep entry_start;
  195159. png_sPLT_t new_palette;
  195160. #ifdef PNG_NO_POINTER_INDEXING
  195161. png_sPLT_entryp pp;
  195162. #endif
  195163. int data_length, entry_size, i;
  195164. png_uint_32 skip = 0;
  195165. png_size_t slength;
  195166. png_debug(1, "in png_handle_sPLT\n");
  195167. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195168. png_error(png_ptr, "Missing IHDR before sPLT");
  195169. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195170. {
  195171. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195172. png_crc_finish(png_ptr, length);
  195173. return;
  195174. }
  195175. #ifdef PNG_MAX_MALLOC_64K
  195176. if (length > (png_uint_32)65535L)
  195177. {
  195178. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195179. skip = length - (png_uint_32)65535L;
  195180. length = (png_uint_32)65535L;
  195181. }
  195182. #endif
  195183. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195184. slength = (png_size_t)length;
  195185. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195186. if (png_crc_finish(png_ptr, skip))
  195187. {
  195188. png_free(png_ptr, chunkdata);
  195189. return;
  195190. }
  195191. chunkdata[slength] = 0x00;
  195192. for (entry_start = chunkdata; *entry_start; entry_start++)
  195193. /* empty loop to find end of name */ ;
  195194. ++entry_start;
  195195. /* a sample depth should follow the separator, and we should be on it */
  195196. if (entry_start > chunkdata + slength - 2)
  195197. {
  195198. png_free(png_ptr, chunkdata);
  195199. png_warning(png_ptr, "malformed sPLT chunk");
  195200. return;
  195201. }
  195202. new_palette.depth = *entry_start++;
  195203. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195204. data_length = (slength - (entry_start - chunkdata));
  195205. /* integrity-check the data length */
  195206. if (data_length % entry_size)
  195207. {
  195208. png_free(png_ptr, chunkdata);
  195209. png_warning(png_ptr, "sPLT chunk has bad length");
  195210. return;
  195211. }
  195212. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195213. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195214. png_sizeof(png_sPLT_entry)))
  195215. {
  195216. png_warning(png_ptr, "sPLT chunk too long");
  195217. return;
  195218. }
  195219. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195220. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195221. if (new_palette.entries == NULL)
  195222. {
  195223. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195224. return;
  195225. }
  195226. #ifndef PNG_NO_POINTER_INDEXING
  195227. for (i = 0; i < new_palette.nentries; i++)
  195228. {
  195229. png_sPLT_entryp pp = new_palette.entries + i;
  195230. if (new_palette.depth == 8)
  195231. {
  195232. pp->red = *entry_start++;
  195233. pp->green = *entry_start++;
  195234. pp->blue = *entry_start++;
  195235. pp->alpha = *entry_start++;
  195236. }
  195237. else
  195238. {
  195239. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195240. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195241. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195242. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195243. }
  195244. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195245. }
  195246. #else
  195247. pp = new_palette.entries;
  195248. for (i = 0; i < new_palette.nentries; i++)
  195249. {
  195250. if (new_palette.depth == 8)
  195251. {
  195252. pp[i].red = *entry_start++;
  195253. pp[i].green = *entry_start++;
  195254. pp[i].blue = *entry_start++;
  195255. pp[i].alpha = *entry_start++;
  195256. }
  195257. else
  195258. {
  195259. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195260. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195261. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195262. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195263. }
  195264. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195265. }
  195266. #endif
  195267. /* discard all chunk data except the name and stash that */
  195268. new_palette.name = (png_charp)chunkdata;
  195269. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195270. png_free(png_ptr, chunkdata);
  195271. png_free(png_ptr, new_palette.entries);
  195272. }
  195273. #endif /* PNG_READ_sPLT_SUPPORTED */
  195274. #if defined(PNG_READ_tRNS_SUPPORTED)
  195275. void /* PRIVATE */
  195276. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195277. {
  195278. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195279. int bit_mask;
  195280. png_debug(1, "in png_handle_tRNS\n");
  195281. /* For non-indexed color, mask off any bits in the tRNS value that
  195282. * exceed the bit depth. Some creators were writing extra bits there.
  195283. * This is not needed for indexed color. */
  195284. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195285. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195286. png_error(png_ptr, "Missing IHDR before tRNS");
  195287. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195288. {
  195289. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195290. png_crc_finish(png_ptr, length);
  195291. return;
  195292. }
  195293. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195294. {
  195295. png_warning(png_ptr, "Duplicate tRNS chunk");
  195296. png_crc_finish(png_ptr, length);
  195297. return;
  195298. }
  195299. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195300. {
  195301. png_byte buf[2];
  195302. if (length != 2)
  195303. {
  195304. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195305. png_crc_finish(png_ptr, length);
  195306. return;
  195307. }
  195308. png_crc_read(png_ptr, buf, 2);
  195309. png_ptr->num_trans = 1;
  195310. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195311. }
  195312. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195313. {
  195314. png_byte buf[6];
  195315. if (length != 6)
  195316. {
  195317. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195318. png_crc_finish(png_ptr, length);
  195319. return;
  195320. }
  195321. png_crc_read(png_ptr, buf, (png_size_t)length);
  195322. png_ptr->num_trans = 1;
  195323. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195324. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195325. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195326. }
  195327. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195328. {
  195329. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195330. {
  195331. /* Should be an error, but we can cope with it. */
  195332. png_warning(png_ptr, "Missing PLTE before tRNS");
  195333. }
  195334. if (length > (png_uint_32)png_ptr->num_palette ||
  195335. length > PNG_MAX_PALETTE_LENGTH)
  195336. {
  195337. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195338. png_crc_finish(png_ptr, length);
  195339. return;
  195340. }
  195341. if (length == 0)
  195342. {
  195343. png_warning(png_ptr, "Zero length tRNS chunk");
  195344. png_crc_finish(png_ptr, length);
  195345. return;
  195346. }
  195347. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195348. png_ptr->num_trans = (png_uint_16)length;
  195349. }
  195350. else
  195351. {
  195352. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195353. png_crc_finish(png_ptr, length);
  195354. return;
  195355. }
  195356. if (png_crc_finish(png_ptr, 0))
  195357. {
  195358. png_ptr->num_trans = 0;
  195359. return;
  195360. }
  195361. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195362. &(png_ptr->trans_values));
  195363. }
  195364. #endif
  195365. #if defined(PNG_READ_bKGD_SUPPORTED)
  195366. void /* PRIVATE */
  195367. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195368. {
  195369. png_size_t truelen;
  195370. png_byte buf[6];
  195371. png_debug(1, "in png_handle_bKGD\n");
  195372. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195373. png_error(png_ptr, "Missing IHDR before bKGD");
  195374. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195375. {
  195376. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195377. png_crc_finish(png_ptr, length);
  195378. return;
  195379. }
  195380. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195381. !(png_ptr->mode & PNG_HAVE_PLTE))
  195382. {
  195383. png_warning(png_ptr, "Missing PLTE before bKGD");
  195384. png_crc_finish(png_ptr, length);
  195385. return;
  195386. }
  195387. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195388. {
  195389. png_warning(png_ptr, "Duplicate bKGD chunk");
  195390. png_crc_finish(png_ptr, length);
  195391. return;
  195392. }
  195393. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195394. truelen = 1;
  195395. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195396. truelen = 6;
  195397. else
  195398. truelen = 2;
  195399. if (length != truelen)
  195400. {
  195401. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195402. png_crc_finish(png_ptr, length);
  195403. return;
  195404. }
  195405. png_crc_read(png_ptr, buf, truelen);
  195406. if (png_crc_finish(png_ptr, 0))
  195407. return;
  195408. /* We convert the index value into RGB components so that we can allow
  195409. * arbitrary RGB values for background when we have transparency, and
  195410. * so it is easy to determine the RGB values of the background color
  195411. * from the info_ptr struct. */
  195412. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195413. {
  195414. png_ptr->background.index = buf[0];
  195415. if(info_ptr->num_palette)
  195416. {
  195417. if(buf[0] > info_ptr->num_palette)
  195418. {
  195419. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195420. return;
  195421. }
  195422. png_ptr->background.red =
  195423. (png_uint_16)png_ptr->palette[buf[0]].red;
  195424. png_ptr->background.green =
  195425. (png_uint_16)png_ptr->palette[buf[0]].green;
  195426. png_ptr->background.blue =
  195427. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195428. }
  195429. }
  195430. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195431. {
  195432. png_ptr->background.red =
  195433. png_ptr->background.green =
  195434. png_ptr->background.blue =
  195435. png_ptr->background.gray = png_get_uint_16(buf);
  195436. }
  195437. else
  195438. {
  195439. png_ptr->background.red = png_get_uint_16(buf);
  195440. png_ptr->background.green = png_get_uint_16(buf + 2);
  195441. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195442. }
  195443. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195444. }
  195445. #endif
  195446. #if defined(PNG_READ_hIST_SUPPORTED)
  195447. void /* PRIVATE */
  195448. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195449. {
  195450. unsigned int num, i;
  195451. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195452. png_debug(1, "in png_handle_hIST\n");
  195453. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195454. png_error(png_ptr, "Missing IHDR before hIST");
  195455. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195456. {
  195457. png_warning(png_ptr, "Invalid hIST after IDAT");
  195458. png_crc_finish(png_ptr, length);
  195459. return;
  195460. }
  195461. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195462. {
  195463. png_warning(png_ptr, "Missing PLTE before hIST");
  195464. png_crc_finish(png_ptr, length);
  195465. return;
  195466. }
  195467. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195468. {
  195469. png_warning(png_ptr, "Duplicate hIST chunk");
  195470. png_crc_finish(png_ptr, length);
  195471. return;
  195472. }
  195473. num = length / 2 ;
  195474. if (num != (unsigned int) png_ptr->num_palette || num >
  195475. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195476. {
  195477. png_warning(png_ptr, "Incorrect hIST chunk length");
  195478. png_crc_finish(png_ptr, length);
  195479. return;
  195480. }
  195481. for (i = 0; i < num; i++)
  195482. {
  195483. png_byte buf[2];
  195484. png_crc_read(png_ptr, buf, 2);
  195485. readbuf[i] = png_get_uint_16(buf);
  195486. }
  195487. if (png_crc_finish(png_ptr, 0))
  195488. return;
  195489. png_set_hIST(png_ptr, info_ptr, readbuf);
  195490. }
  195491. #endif
  195492. #if defined(PNG_READ_pHYs_SUPPORTED)
  195493. void /* PRIVATE */
  195494. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195495. {
  195496. png_byte buf[9];
  195497. png_uint_32 res_x, res_y;
  195498. int unit_type;
  195499. png_debug(1, "in png_handle_pHYs\n");
  195500. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195501. png_error(png_ptr, "Missing IHDR before pHYs");
  195502. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195503. {
  195504. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195505. png_crc_finish(png_ptr, length);
  195506. return;
  195507. }
  195508. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195509. {
  195510. png_warning(png_ptr, "Duplicate pHYs chunk");
  195511. png_crc_finish(png_ptr, length);
  195512. return;
  195513. }
  195514. if (length != 9)
  195515. {
  195516. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195517. png_crc_finish(png_ptr, length);
  195518. return;
  195519. }
  195520. png_crc_read(png_ptr, buf, 9);
  195521. if (png_crc_finish(png_ptr, 0))
  195522. return;
  195523. res_x = png_get_uint_32(buf);
  195524. res_y = png_get_uint_32(buf + 4);
  195525. unit_type = buf[8];
  195526. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195527. }
  195528. #endif
  195529. #if defined(PNG_READ_oFFs_SUPPORTED)
  195530. void /* PRIVATE */
  195531. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195532. {
  195533. png_byte buf[9];
  195534. png_int_32 offset_x, offset_y;
  195535. int unit_type;
  195536. png_debug(1, "in png_handle_oFFs\n");
  195537. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195538. png_error(png_ptr, "Missing IHDR before oFFs");
  195539. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195540. {
  195541. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195542. png_crc_finish(png_ptr, length);
  195543. return;
  195544. }
  195545. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195546. {
  195547. png_warning(png_ptr, "Duplicate oFFs chunk");
  195548. png_crc_finish(png_ptr, length);
  195549. return;
  195550. }
  195551. if (length != 9)
  195552. {
  195553. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195554. png_crc_finish(png_ptr, length);
  195555. return;
  195556. }
  195557. png_crc_read(png_ptr, buf, 9);
  195558. if (png_crc_finish(png_ptr, 0))
  195559. return;
  195560. offset_x = png_get_int_32(buf);
  195561. offset_y = png_get_int_32(buf + 4);
  195562. unit_type = buf[8];
  195563. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195564. }
  195565. #endif
  195566. #if defined(PNG_READ_pCAL_SUPPORTED)
  195567. /* read the pCAL chunk (described in the PNG Extensions document) */
  195568. void /* PRIVATE */
  195569. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195570. {
  195571. png_charp purpose;
  195572. png_int_32 X0, X1;
  195573. png_byte type, nparams;
  195574. png_charp buf, units, endptr;
  195575. png_charpp params;
  195576. png_size_t slength;
  195577. int i;
  195578. png_debug(1, "in png_handle_pCAL\n");
  195579. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195580. png_error(png_ptr, "Missing IHDR before pCAL");
  195581. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195582. {
  195583. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195584. png_crc_finish(png_ptr, length);
  195585. return;
  195586. }
  195587. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195588. {
  195589. png_warning(png_ptr, "Duplicate pCAL chunk");
  195590. png_crc_finish(png_ptr, length);
  195591. return;
  195592. }
  195593. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195594. length + 1);
  195595. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195596. if (purpose == NULL)
  195597. {
  195598. png_warning(png_ptr, "No memory for pCAL purpose.");
  195599. return;
  195600. }
  195601. slength = (png_size_t)length;
  195602. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195603. if (png_crc_finish(png_ptr, 0))
  195604. {
  195605. png_free(png_ptr, purpose);
  195606. return;
  195607. }
  195608. purpose[slength] = 0x00; /* null terminate the last string */
  195609. png_debug(3, "Finding end of pCAL purpose string\n");
  195610. for (buf = purpose; *buf; buf++)
  195611. /* empty loop */ ;
  195612. endptr = purpose + slength;
  195613. /* We need to have at least 12 bytes after the purpose string
  195614. in order to get the parameter information. */
  195615. if (endptr <= buf + 12)
  195616. {
  195617. png_warning(png_ptr, "Invalid pCAL data");
  195618. png_free(png_ptr, purpose);
  195619. return;
  195620. }
  195621. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195622. X0 = png_get_int_32((png_bytep)buf+1);
  195623. X1 = png_get_int_32((png_bytep)buf+5);
  195624. type = buf[9];
  195625. nparams = buf[10];
  195626. units = buf + 11;
  195627. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195628. /* Check that we have the right number of parameters for known
  195629. equation types. */
  195630. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195631. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195632. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195633. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195634. {
  195635. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195636. png_free(png_ptr, purpose);
  195637. return;
  195638. }
  195639. else if (type >= PNG_EQUATION_LAST)
  195640. {
  195641. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195642. }
  195643. for (buf = units; *buf; buf++)
  195644. /* Empty loop to move past the units string. */ ;
  195645. png_debug(3, "Allocating pCAL parameters array\n");
  195646. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195647. *png_sizeof(png_charp))) ;
  195648. if (params == NULL)
  195649. {
  195650. png_free(png_ptr, purpose);
  195651. png_warning(png_ptr, "No memory for pCAL params.");
  195652. return;
  195653. }
  195654. /* Get pointers to the start of each parameter string. */
  195655. for (i = 0; i < (int)nparams; i++)
  195656. {
  195657. buf++; /* Skip the null string terminator from previous parameter. */
  195658. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195659. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195660. /* Empty loop to move past each parameter string */ ;
  195661. /* Make sure we haven't run out of data yet */
  195662. if (buf > endptr)
  195663. {
  195664. png_warning(png_ptr, "Invalid pCAL data");
  195665. png_free(png_ptr, purpose);
  195666. png_free(png_ptr, params);
  195667. return;
  195668. }
  195669. }
  195670. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195671. units, params);
  195672. png_free(png_ptr, purpose);
  195673. png_free(png_ptr, params);
  195674. }
  195675. #endif
  195676. #if defined(PNG_READ_sCAL_SUPPORTED)
  195677. /* read the sCAL chunk */
  195678. void /* PRIVATE */
  195679. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195680. {
  195681. png_charp buffer, ep;
  195682. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195683. double width, height;
  195684. png_charp vp;
  195685. #else
  195686. #ifdef PNG_FIXED_POINT_SUPPORTED
  195687. png_charp swidth, sheight;
  195688. #endif
  195689. #endif
  195690. png_size_t slength;
  195691. png_debug(1, "in png_handle_sCAL\n");
  195692. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195693. png_error(png_ptr, "Missing IHDR before sCAL");
  195694. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195695. {
  195696. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195697. png_crc_finish(png_ptr, length);
  195698. return;
  195699. }
  195700. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195701. {
  195702. png_warning(png_ptr, "Duplicate sCAL chunk");
  195703. png_crc_finish(png_ptr, length);
  195704. return;
  195705. }
  195706. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195707. length + 1);
  195708. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195709. if (buffer == NULL)
  195710. {
  195711. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195712. return;
  195713. }
  195714. slength = (png_size_t)length;
  195715. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195716. if (png_crc_finish(png_ptr, 0))
  195717. {
  195718. png_free(png_ptr, buffer);
  195719. return;
  195720. }
  195721. buffer[slength] = 0x00; /* null terminate the last string */
  195722. ep = buffer + 1; /* skip unit byte */
  195723. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195724. width = png_strtod(png_ptr, ep, &vp);
  195725. if (*vp)
  195726. {
  195727. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195728. return;
  195729. }
  195730. #else
  195731. #ifdef PNG_FIXED_POINT_SUPPORTED
  195732. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195733. if (swidth == NULL)
  195734. {
  195735. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195736. return;
  195737. }
  195738. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195739. #endif
  195740. #endif
  195741. for (ep = buffer; *ep; ep++)
  195742. /* empty loop */ ;
  195743. ep++;
  195744. if (buffer + slength < ep)
  195745. {
  195746. png_warning(png_ptr, "Truncated sCAL chunk");
  195747. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195748. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195749. png_free(png_ptr, swidth);
  195750. #endif
  195751. png_free(png_ptr, buffer);
  195752. return;
  195753. }
  195754. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195755. height = png_strtod(png_ptr, ep, &vp);
  195756. if (*vp)
  195757. {
  195758. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195759. return;
  195760. }
  195761. #else
  195762. #ifdef PNG_FIXED_POINT_SUPPORTED
  195763. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195764. if (swidth == NULL)
  195765. {
  195766. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195767. return;
  195768. }
  195769. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195770. #endif
  195771. #endif
  195772. if (buffer + slength < ep
  195773. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195774. || width <= 0. || height <= 0.
  195775. #endif
  195776. )
  195777. {
  195778. png_warning(png_ptr, "Invalid sCAL data");
  195779. png_free(png_ptr, buffer);
  195780. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195781. png_free(png_ptr, swidth);
  195782. png_free(png_ptr, sheight);
  195783. #endif
  195784. return;
  195785. }
  195786. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195787. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195788. #else
  195789. #ifdef PNG_FIXED_POINT_SUPPORTED
  195790. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195791. #endif
  195792. #endif
  195793. png_free(png_ptr, buffer);
  195794. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195795. png_free(png_ptr, swidth);
  195796. png_free(png_ptr, sheight);
  195797. #endif
  195798. }
  195799. #endif
  195800. #if defined(PNG_READ_tIME_SUPPORTED)
  195801. void /* PRIVATE */
  195802. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195803. {
  195804. png_byte buf[7];
  195805. png_time mod_time;
  195806. png_debug(1, "in png_handle_tIME\n");
  195807. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195808. png_error(png_ptr, "Out of place tIME chunk");
  195809. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195810. {
  195811. png_warning(png_ptr, "Duplicate tIME chunk");
  195812. png_crc_finish(png_ptr, length);
  195813. return;
  195814. }
  195815. if (png_ptr->mode & PNG_HAVE_IDAT)
  195816. png_ptr->mode |= PNG_AFTER_IDAT;
  195817. if (length != 7)
  195818. {
  195819. png_warning(png_ptr, "Incorrect tIME chunk length");
  195820. png_crc_finish(png_ptr, length);
  195821. return;
  195822. }
  195823. png_crc_read(png_ptr, buf, 7);
  195824. if (png_crc_finish(png_ptr, 0))
  195825. return;
  195826. mod_time.second = buf[6];
  195827. mod_time.minute = buf[5];
  195828. mod_time.hour = buf[4];
  195829. mod_time.day = buf[3];
  195830. mod_time.month = buf[2];
  195831. mod_time.year = png_get_uint_16(buf);
  195832. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195833. }
  195834. #endif
  195835. #if defined(PNG_READ_tEXt_SUPPORTED)
  195836. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195837. void /* PRIVATE */
  195838. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195839. {
  195840. png_textp text_ptr;
  195841. png_charp key;
  195842. png_charp text;
  195843. png_uint_32 skip = 0;
  195844. png_size_t slength;
  195845. int ret;
  195846. png_debug(1, "in png_handle_tEXt\n");
  195847. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195848. png_error(png_ptr, "Missing IHDR before tEXt");
  195849. if (png_ptr->mode & PNG_HAVE_IDAT)
  195850. png_ptr->mode |= PNG_AFTER_IDAT;
  195851. #ifdef PNG_MAX_MALLOC_64K
  195852. if (length > (png_uint_32)65535L)
  195853. {
  195854. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195855. skip = length - (png_uint_32)65535L;
  195856. length = (png_uint_32)65535L;
  195857. }
  195858. #endif
  195859. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195860. if (key == NULL)
  195861. {
  195862. png_warning(png_ptr, "No memory to process text chunk.");
  195863. return;
  195864. }
  195865. slength = (png_size_t)length;
  195866. png_crc_read(png_ptr, (png_bytep)key, slength);
  195867. if (png_crc_finish(png_ptr, skip))
  195868. {
  195869. png_free(png_ptr, key);
  195870. return;
  195871. }
  195872. key[slength] = 0x00;
  195873. for (text = key; *text; text++)
  195874. /* empty loop to find end of key */ ;
  195875. if (text != key + slength)
  195876. text++;
  195877. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195878. (png_uint_32)png_sizeof(png_text));
  195879. if (text_ptr == NULL)
  195880. {
  195881. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195882. png_free(png_ptr, key);
  195883. return;
  195884. }
  195885. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195886. text_ptr->key = key;
  195887. #ifdef PNG_iTXt_SUPPORTED
  195888. text_ptr->lang = NULL;
  195889. text_ptr->lang_key = NULL;
  195890. text_ptr->itxt_length = 0;
  195891. #endif
  195892. text_ptr->text = text;
  195893. text_ptr->text_length = png_strlen(text);
  195894. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195895. png_free(png_ptr, key);
  195896. png_free(png_ptr, text_ptr);
  195897. if (ret)
  195898. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195899. }
  195900. #endif
  195901. #if defined(PNG_READ_zTXt_SUPPORTED)
  195902. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195903. void /* PRIVATE */
  195904. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195905. {
  195906. png_textp text_ptr;
  195907. png_charp chunkdata;
  195908. png_charp text;
  195909. int comp_type;
  195910. int ret;
  195911. png_size_t slength, prefix_len, data_len;
  195912. png_debug(1, "in png_handle_zTXt\n");
  195913. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195914. png_error(png_ptr, "Missing IHDR before zTXt");
  195915. if (png_ptr->mode & PNG_HAVE_IDAT)
  195916. png_ptr->mode |= PNG_AFTER_IDAT;
  195917. #ifdef PNG_MAX_MALLOC_64K
  195918. /* We will no doubt have problems with chunks even half this size, but
  195919. there is no hard and fast rule to tell us where to stop. */
  195920. if (length > (png_uint_32)65535L)
  195921. {
  195922. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195923. png_crc_finish(png_ptr, length);
  195924. return;
  195925. }
  195926. #endif
  195927. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195928. if (chunkdata == NULL)
  195929. {
  195930. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195931. return;
  195932. }
  195933. slength = (png_size_t)length;
  195934. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195935. if (png_crc_finish(png_ptr, 0))
  195936. {
  195937. png_free(png_ptr, chunkdata);
  195938. return;
  195939. }
  195940. chunkdata[slength] = 0x00;
  195941. for (text = chunkdata; *text; text++)
  195942. /* empty loop */ ;
  195943. /* zTXt must have some text after the chunkdataword */
  195944. if (text >= chunkdata + slength - 2)
  195945. {
  195946. png_warning(png_ptr, "Truncated zTXt chunk");
  195947. png_free(png_ptr, chunkdata);
  195948. return;
  195949. }
  195950. else
  195951. {
  195952. comp_type = *(++text);
  195953. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195954. {
  195955. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195956. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195957. }
  195958. text++; /* skip the compression_method byte */
  195959. }
  195960. prefix_len = text - chunkdata;
  195961. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195962. (png_size_t)length, prefix_len, &data_len);
  195963. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195964. (png_uint_32)png_sizeof(png_text));
  195965. if (text_ptr == NULL)
  195966. {
  195967. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195968. png_free(png_ptr, chunkdata);
  195969. return;
  195970. }
  195971. text_ptr->compression = comp_type;
  195972. text_ptr->key = chunkdata;
  195973. #ifdef PNG_iTXt_SUPPORTED
  195974. text_ptr->lang = NULL;
  195975. text_ptr->lang_key = NULL;
  195976. text_ptr->itxt_length = 0;
  195977. #endif
  195978. text_ptr->text = chunkdata + prefix_len;
  195979. text_ptr->text_length = data_len;
  195980. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195981. png_free(png_ptr, text_ptr);
  195982. png_free(png_ptr, chunkdata);
  195983. if (ret)
  195984. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195985. }
  195986. #endif
  195987. #if defined(PNG_READ_iTXt_SUPPORTED)
  195988. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195989. void /* PRIVATE */
  195990. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195991. {
  195992. png_textp text_ptr;
  195993. png_charp chunkdata;
  195994. png_charp key, lang, text, lang_key;
  195995. int comp_flag;
  195996. int comp_type = 0;
  195997. int ret;
  195998. png_size_t slength, prefix_len, data_len;
  195999. png_debug(1, "in png_handle_iTXt\n");
  196000. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196001. png_error(png_ptr, "Missing IHDR before iTXt");
  196002. if (png_ptr->mode & PNG_HAVE_IDAT)
  196003. png_ptr->mode |= PNG_AFTER_IDAT;
  196004. #ifdef PNG_MAX_MALLOC_64K
  196005. /* We will no doubt have problems with chunks even half this size, but
  196006. there is no hard and fast rule to tell us where to stop. */
  196007. if (length > (png_uint_32)65535L)
  196008. {
  196009. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  196010. png_crc_finish(png_ptr, length);
  196011. return;
  196012. }
  196013. #endif
  196014. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196015. if (chunkdata == NULL)
  196016. {
  196017. png_warning(png_ptr, "No memory to process iTXt chunk.");
  196018. return;
  196019. }
  196020. slength = (png_size_t)length;
  196021. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196022. if (png_crc_finish(png_ptr, 0))
  196023. {
  196024. png_free(png_ptr, chunkdata);
  196025. return;
  196026. }
  196027. chunkdata[slength] = 0x00;
  196028. for (lang = chunkdata; *lang; lang++)
  196029. /* empty loop */ ;
  196030. lang++; /* skip NUL separator */
  196031. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196032. translated keyword (possibly empty), and possibly some text after the
  196033. keyword */
  196034. if (lang >= chunkdata + slength - 3)
  196035. {
  196036. png_warning(png_ptr, "Truncated iTXt chunk");
  196037. png_free(png_ptr, chunkdata);
  196038. return;
  196039. }
  196040. else
  196041. {
  196042. comp_flag = *lang++;
  196043. comp_type = *lang++;
  196044. }
  196045. for (lang_key = lang; *lang_key; lang_key++)
  196046. /* empty loop */ ;
  196047. lang_key++; /* skip NUL separator */
  196048. if (lang_key >= chunkdata + slength)
  196049. {
  196050. png_warning(png_ptr, "Truncated iTXt chunk");
  196051. png_free(png_ptr, chunkdata);
  196052. return;
  196053. }
  196054. for (text = lang_key; *text; text++)
  196055. /* empty loop */ ;
  196056. text++; /* skip NUL separator */
  196057. if (text >= chunkdata + slength)
  196058. {
  196059. png_warning(png_ptr, "Malformed iTXt chunk");
  196060. png_free(png_ptr, chunkdata);
  196061. return;
  196062. }
  196063. prefix_len = text - chunkdata;
  196064. key=chunkdata;
  196065. if (comp_flag)
  196066. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196067. (size_t)length, prefix_len, &data_len);
  196068. else
  196069. data_len=png_strlen(chunkdata + prefix_len);
  196070. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196071. (png_uint_32)png_sizeof(png_text));
  196072. if (text_ptr == NULL)
  196073. {
  196074. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196075. png_free(png_ptr, chunkdata);
  196076. return;
  196077. }
  196078. text_ptr->compression = (int)comp_flag + 1;
  196079. text_ptr->lang_key = chunkdata+(lang_key-key);
  196080. text_ptr->lang = chunkdata+(lang-key);
  196081. text_ptr->itxt_length = data_len;
  196082. text_ptr->text_length = 0;
  196083. text_ptr->key = chunkdata;
  196084. text_ptr->text = chunkdata + prefix_len;
  196085. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196086. png_free(png_ptr, text_ptr);
  196087. png_free(png_ptr, chunkdata);
  196088. if (ret)
  196089. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196090. }
  196091. #endif
  196092. /* This function is called when we haven't found a handler for a
  196093. chunk. If there isn't a problem with the chunk itself (ie bad
  196094. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196095. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196096. case it will be saved away to be written out later. */
  196097. void /* PRIVATE */
  196098. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196099. {
  196100. png_uint_32 skip = 0;
  196101. png_debug(1, "in png_handle_unknown\n");
  196102. if (png_ptr->mode & PNG_HAVE_IDAT)
  196103. {
  196104. #ifdef PNG_USE_LOCAL_ARRAYS
  196105. PNG_CONST PNG_IDAT;
  196106. #endif
  196107. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196108. png_ptr->mode |= PNG_AFTER_IDAT;
  196109. }
  196110. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196111. if (!(png_ptr->chunk_name[0] & 0x20))
  196112. {
  196113. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196114. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196115. PNG_HANDLE_CHUNK_ALWAYS
  196116. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196117. && png_ptr->read_user_chunk_fn == NULL
  196118. #endif
  196119. )
  196120. #endif
  196121. png_chunk_error(png_ptr, "unknown critical chunk");
  196122. }
  196123. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196124. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196125. (png_ptr->read_user_chunk_fn != NULL))
  196126. {
  196127. #ifdef PNG_MAX_MALLOC_64K
  196128. if (length > (png_uint_32)65535L)
  196129. {
  196130. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196131. skip = length - (png_uint_32)65535L;
  196132. length = (png_uint_32)65535L;
  196133. }
  196134. #endif
  196135. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196136. (png_charp)png_ptr->chunk_name, 5);
  196137. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196138. png_ptr->unknown_chunk.size = (png_size_t)length;
  196139. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196140. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196141. if(png_ptr->read_user_chunk_fn != NULL)
  196142. {
  196143. /* callback to user unknown chunk handler */
  196144. int ret;
  196145. ret = (*(png_ptr->read_user_chunk_fn))
  196146. (png_ptr, &png_ptr->unknown_chunk);
  196147. if (ret < 0)
  196148. png_chunk_error(png_ptr, "error in user chunk");
  196149. if (ret == 0)
  196150. {
  196151. if (!(png_ptr->chunk_name[0] & 0x20))
  196152. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196153. PNG_HANDLE_CHUNK_ALWAYS)
  196154. png_chunk_error(png_ptr, "unknown critical chunk");
  196155. png_set_unknown_chunks(png_ptr, info_ptr,
  196156. &png_ptr->unknown_chunk, 1);
  196157. }
  196158. }
  196159. #else
  196160. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196161. #endif
  196162. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196163. png_ptr->unknown_chunk.data = NULL;
  196164. }
  196165. else
  196166. #endif
  196167. skip = length;
  196168. png_crc_finish(png_ptr, skip);
  196169. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196170. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196171. #endif
  196172. }
  196173. /* This function is called to verify that a chunk name is valid.
  196174. This function can't have the "critical chunk check" incorporated
  196175. into it, since in the future we will need to be able to call user
  196176. functions to handle unknown critical chunks after we check that
  196177. the chunk name itself is valid. */
  196178. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196179. void /* PRIVATE */
  196180. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196181. {
  196182. png_debug(1, "in png_check_chunk_name\n");
  196183. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196184. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196185. {
  196186. png_chunk_error(png_ptr, "invalid chunk type");
  196187. }
  196188. }
  196189. /* Combines the row recently read in with the existing pixels in the
  196190. row. This routine takes care of alpha and transparency if requested.
  196191. This routine also handles the two methods of progressive display
  196192. of interlaced images, depending on the mask value.
  196193. The mask value describes which pixels are to be combined with
  196194. the row. The pattern always repeats every 8 pixels, so just 8
  196195. bits are needed. A one indicates the pixel is to be combined,
  196196. a zero indicates the pixel is to be skipped. This is in addition
  196197. to any alpha or transparency value associated with the pixel. If
  196198. you want all pixels to be combined, pass 0xff (255) in mask. */
  196199. void /* PRIVATE */
  196200. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196201. {
  196202. png_debug(1,"in png_combine_row\n");
  196203. if (mask == 0xff)
  196204. {
  196205. png_memcpy(row, png_ptr->row_buf + 1,
  196206. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196207. }
  196208. else
  196209. {
  196210. switch (png_ptr->row_info.pixel_depth)
  196211. {
  196212. case 1:
  196213. {
  196214. png_bytep sp = png_ptr->row_buf + 1;
  196215. png_bytep dp = row;
  196216. int s_inc, s_start, s_end;
  196217. int m = 0x80;
  196218. int shift;
  196219. png_uint_32 i;
  196220. png_uint_32 row_width = png_ptr->width;
  196221. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196222. if (png_ptr->transformations & PNG_PACKSWAP)
  196223. {
  196224. s_start = 0;
  196225. s_end = 7;
  196226. s_inc = 1;
  196227. }
  196228. else
  196229. #endif
  196230. {
  196231. s_start = 7;
  196232. s_end = 0;
  196233. s_inc = -1;
  196234. }
  196235. shift = s_start;
  196236. for (i = 0; i < row_width; i++)
  196237. {
  196238. if (m & mask)
  196239. {
  196240. int value;
  196241. value = (*sp >> shift) & 0x01;
  196242. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196243. *dp |= (png_byte)(value << shift);
  196244. }
  196245. if (shift == s_end)
  196246. {
  196247. shift = s_start;
  196248. sp++;
  196249. dp++;
  196250. }
  196251. else
  196252. shift += s_inc;
  196253. if (m == 1)
  196254. m = 0x80;
  196255. else
  196256. m >>= 1;
  196257. }
  196258. break;
  196259. }
  196260. case 2:
  196261. {
  196262. png_bytep sp = png_ptr->row_buf + 1;
  196263. png_bytep dp = row;
  196264. int s_start, s_end, s_inc;
  196265. int m = 0x80;
  196266. int shift;
  196267. png_uint_32 i;
  196268. png_uint_32 row_width = png_ptr->width;
  196269. int value;
  196270. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196271. if (png_ptr->transformations & PNG_PACKSWAP)
  196272. {
  196273. s_start = 0;
  196274. s_end = 6;
  196275. s_inc = 2;
  196276. }
  196277. else
  196278. #endif
  196279. {
  196280. s_start = 6;
  196281. s_end = 0;
  196282. s_inc = -2;
  196283. }
  196284. shift = s_start;
  196285. for (i = 0; i < row_width; i++)
  196286. {
  196287. if (m & mask)
  196288. {
  196289. value = (*sp >> shift) & 0x03;
  196290. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196291. *dp |= (png_byte)(value << shift);
  196292. }
  196293. if (shift == s_end)
  196294. {
  196295. shift = s_start;
  196296. sp++;
  196297. dp++;
  196298. }
  196299. else
  196300. shift += s_inc;
  196301. if (m == 1)
  196302. m = 0x80;
  196303. else
  196304. m >>= 1;
  196305. }
  196306. break;
  196307. }
  196308. case 4:
  196309. {
  196310. png_bytep sp = png_ptr->row_buf + 1;
  196311. png_bytep dp = row;
  196312. int s_start, s_end, s_inc;
  196313. int m = 0x80;
  196314. int shift;
  196315. png_uint_32 i;
  196316. png_uint_32 row_width = png_ptr->width;
  196317. int value;
  196318. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196319. if (png_ptr->transformations & PNG_PACKSWAP)
  196320. {
  196321. s_start = 0;
  196322. s_end = 4;
  196323. s_inc = 4;
  196324. }
  196325. else
  196326. #endif
  196327. {
  196328. s_start = 4;
  196329. s_end = 0;
  196330. s_inc = -4;
  196331. }
  196332. shift = s_start;
  196333. for (i = 0; i < row_width; i++)
  196334. {
  196335. if (m & mask)
  196336. {
  196337. value = (*sp >> shift) & 0xf;
  196338. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196339. *dp |= (png_byte)(value << shift);
  196340. }
  196341. if (shift == s_end)
  196342. {
  196343. shift = s_start;
  196344. sp++;
  196345. dp++;
  196346. }
  196347. else
  196348. shift += s_inc;
  196349. if (m == 1)
  196350. m = 0x80;
  196351. else
  196352. m >>= 1;
  196353. }
  196354. break;
  196355. }
  196356. default:
  196357. {
  196358. png_bytep sp = png_ptr->row_buf + 1;
  196359. png_bytep dp = row;
  196360. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196361. png_uint_32 i;
  196362. png_uint_32 row_width = png_ptr->width;
  196363. png_byte m = 0x80;
  196364. for (i = 0; i < row_width; i++)
  196365. {
  196366. if (m & mask)
  196367. {
  196368. png_memcpy(dp, sp, pixel_bytes);
  196369. }
  196370. sp += pixel_bytes;
  196371. dp += pixel_bytes;
  196372. if (m == 1)
  196373. m = 0x80;
  196374. else
  196375. m >>= 1;
  196376. }
  196377. break;
  196378. }
  196379. }
  196380. }
  196381. }
  196382. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196383. /* OLD pre-1.0.9 interface:
  196384. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196385. png_uint_32 transformations)
  196386. */
  196387. void /* PRIVATE */
  196388. png_do_read_interlace(png_structp png_ptr)
  196389. {
  196390. png_row_infop row_info = &(png_ptr->row_info);
  196391. png_bytep row = png_ptr->row_buf + 1;
  196392. int pass = png_ptr->pass;
  196393. png_uint_32 transformations = png_ptr->transformations;
  196394. #ifdef PNG_USE_LOCAL_ARRAYS
  196395. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196396. /* offset to next interlace block */
  196397. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196398. #endif
  196399. png_debug(1,"in png_do_read_interlace\n");
  196400. if (row != NULL && row_info != NULL)
  196401. {
  196402. png_uint_32 final_width;
  196403. final_width = row_info->width * png_pass_inc[pass];
  196404. switch (row_info->pixel_depth)
  196405. {
  196406. case 1:
  196407. {
  196408. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196409. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196410. int sshift, dshift;
  196411. int s_start, s_end, s_inc;
  196412. int jstop = png_pass_inc[pass];
  196413. png_byte v;
  196414. png_uint_32 i;
  196415. int j;
  196416. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196417. if (transformations & PNG_PACKSWAP)
  196418. {
  196419. sshift = (int)((row_info->width + 7) & 0x07);
  196420. dshift = (int)((final_width + 7) & 0x07);
  196421. s_start = 7;
  196422. s_end = 0;
  196423. s_inc = -1;
  196424. }
  196425. else
  196426. #endif
  196427. {
  196428. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196429. dshift = 7 - (int)((final_width + 7) & 0x07);
  196430. s_start = 0;
  196431. s_end = 7;
  196432. s_inc = 1;
  196433. }
  196434. for (i = 0; i < row_info->width; i++)
  196435. {
  196436. v = (png_byte)((*sp >> sshift) & 0x01);
  196437. for (j = 0; j < jstop; j++)
  196438. {
  196439. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196440. *dp |= (png_byte)(v << dshift);
  196441. if (dshift == s_end)
  196442. {
  196443. dshift = s_start;
  196444. dp--;
  196445. }
  196446. else
  196447. dshift += s_inc;
  196448. }
  196449. if (sshift == s_end)
  196450. {
  196451. sshift = s_start;
  196452. sp--;
  196453. }
  196454. else
  196455. sshift += s_inc;
  196456. }
  196457. break;
  196458. }
  196459. case 2:
  196460. {
  196461. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196462. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196463. int sshift, dshift;
  196464. int s_start, s_end, s_inc;
  196465. int jstop = png_pass_inc[pass];
  196466. png_uint_32 i;
  196467. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196468. if (transformations & PNG_PACKSWAP)
  196469. {
  196470. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196471. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196472. s_start = 6;
  196473. s_end = 0;
  196474. s_inc = -2;
  196475. }
  196476. else
  196477. #endif
  196478. {
  196479. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196480. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196481. s_start = 0;
  196482. s_end = 6;
  196483. s_inc = 2;
  196484. }
  196485. for (i = 0; i < row_info->width; i++)
  196486. {
  196487. png_byte v;
  196488. int j;
  196489. v = (png_byte)((*sp >> sshift) & 0x03);
  196490. for (j = 0; j < jstop; j++)
  196491. {
  196492. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196493. *dp |= (png_byte)(v << dshift);
  196494. if (dshift == s_end)
  196495. {
  196496. dshift = s_start;
  196497. dp--;
  196498. }
  196499. else
  196500. dshift += s_inc;
  196501. }
  196502. if (sshift == s_end)
  196503. {
  196504. sshift = s_start;
  196505. sp--;
  196506. }
  196507. else
  196508. sshift += s_inc;
  196509. }
  196510. break;
  196511. }
  196512. case 4:
  196513. {
  196514. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196515. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196516. int sshift, dshift;
  196517. int s_start, s_end, s_inc;
  196518. png_uint_32 i;
  196519. int jstop = png_pass_inc[pass];
  196520. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196521. if (transformations & PNG_PACKSWAP)
  196522. {
  196523. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196524. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196525. s_start = 4;
  196526. s_end = 0;
  196527. s_inc = -4;
  196528. }
  196529. else
  196530. #endif
  196531. {
  196532. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196533. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196534. s_start = 0;
  196535. s_end = 4;
  196536. s_inc = 4;
  196537. }
  196538. for (i = 0; i < row_info->width; i++)
  196539. {
  196540. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196541. int j;
  196542. for (j = 0; j < jstop; j++)
  196543. {
  196544. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196545. *dp |= (png_byte)(v << dshift);
  196546. if (dshift == s_end)
  196547. {
  196548. dshift = s_start;
  196549. dp--;
  196550. }
  196551. else
  196552. dshift += s_inc;
  196553. }
  196554. if (sshift == s_end)
  196555. {
  196556. sshift = s_start;
  196557. sp--;
  196558. }
  196559. else
  196560. sshift += s_inc;
  196561. }
  196562. break;
  196563. }
  196564. default:
  196565. {
  196566. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196567. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196568. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196569. int jstop = png_pass_inc[pass];
  196570. png_uint_32 i;
  196571. for (i = 0; i < row_info->width; i++)
  196572. {
  196573. png_byte v[8];
  196574. int j;
  196575. png_memcpy(v, sp, pixel_bytes);
  196576. for (j = 0; j < jstop; j++)
  196577. {
  196578. png_memcpy(dp, v, pixel_bytes);
  196579. dp -= pixel_bytes;
  196580. }
  196581. sp -= pixel_bytes;
  196582. }
  196583. break;
  196584. }
  196585. }
  196586. row_info->width = final_width;
  196587. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196588. }
  196589. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196590. transformations = transformations; /* silence compiler warning */
  196591. #endif
  196592. }
  196593. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196594. void /* PRIVATE */
  196595. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196596. png_bytep prev_row, int filter)
  196597. {
  196598. png_debug(1, "in png_read_filter_row\n");
  196599. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196600. switch (filter)
  196601. {
  196602. case PNG_FILTER_VALUE_NONE:
  196603. break;
  196604. case PNG_FILTER_VALUE_SUB:
  196605. {
  196606. png_uint_32 i;
  196607. png_uint_32 istop = row_info->rowbytes;
  196608. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196609. png_bytep rp = row + bpp;
  196610. png_bytep lp = row;
  196611. for (i = bpp; i < istop; i++)
  196612. {
  196613. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196614. rp++;
  196615. }
  196616. break;
  196617. }
  196618. case PNG_FILTER_VALUE_UP:
  196619. {
  196620. png_uint_32 i;
  196621. png_uint_32 istop = row_info->rowbytes;
  196622. png_bytep rp = row;
  196623. png_bytep pp = prev_row;
  196624. for (i = 0; i < istop; i++)
  196625. {
  196626. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196627. rp++;
  196628. }
  196629. break;
  196630. }
  196631. case PNG_FILTER_VALUE_AVG:
  196632. {
  196633. png_uint_32 i;
  196634. png_bytep rp = row;
  196635. png_bytep pp = prev_row;
  196636. png_bytep lp = row;
  196637. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196638. png_uint_32 istop = row_info->rowbytes - bpp;
  196639. for (i = 0; i < bpp; i++)
  196640. {
  196641. *rp = (png_byte)(((int)(*rp) +
  196642. ((int)(*pp++) / 2 )) & 0xff);
  196643. rp++;
  196644. }
  196645. for (i = 0; i < istop; i++)
  196646. {
  196647. *rp = (png_byte)(((int)(*rp) +
  196648. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196649. rp++;
  196650. }
  196651. break;
  196652. }
  196653. case PNG_FILTER_VALUE_PAETH:
  196654. {
  196655. png_uint_32 i;
  196656. png_bytep rp = row;
  196657. png_bytep pp = prev_row;
  196658. png_bytep lp = row;
  196659. png_bytep cp = prev_row;
  196660. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196661. png_uint_32 istop=row_info->rowbytes - bpp;
  196662. for (i = 0; i < bpp; i++)
  196663. {
  196664. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196665. rp++;
  196666. }
  196667. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196668. {
  196669. int a, b, c, pa, pb, pc, p;
  196670. a = *lp++;
  196671. b = *pp++;
  196672. c = *cp++;
  196673. p = b - c;
  196674. pc = a - c;
  196675. #ifdef PNG_USE_ABS
  196676. pa = abs(p);
  196677. pb = abs(pc);
  196678. pc = abs(p + pc);
  196679. #else
  196680. pa = p < 0 ? -p : p;
  196681. pb = pc < 0 ? -pc : pc;
  196682. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196683. #endif
  196684. /*
  196685. if (pa <= pb && pa <= pc)
  196686. p = a;
  196687. else if (pb <= pc)
  196688. p = b;
  196689. else
  196690. p = c;
  196691. */
  196692. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196693. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196694. rp++;
  196695. }
  196696. break;
  196697. }
  196698. default:
  196699. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196700. *row=0;
  196701. break;
  196702. }
  196703. }
  196704. void /* PRIVATE */
  196705. png_read_finish_row(png_structp png_ptr)
  196706. {
  196707. #ifdef PNG_USE_LOCAL_ARRAYS
  196708. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196709. /* start of interlace block */
  196710. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196711. /* offset to next interlace block */
  196712. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196713. /* start of interlace block in the y direction */
  196714. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196715. /* offset to next interlace block in the y direction */
  196716. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196717. #endif
  196718. png_debug(1, "in png_read_finish_row\n");
  196719. png_ptr->row_number++;
  196720. if (png_ptr->row_number < png_ptr->num_rows)
  196721. return;
  196722. if (png_ptr->interlaced)
  196723. {
  196724. png_ptr->row_number = 0;
  196725. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196726. png_ptr->rowbytes + 1);
  196727. do
  196728. {
  196729. png_ptr->pass++;
  196730. if (png_ptr->pass >= 7)
  196731. break;
  196732. png_ptr->iwidth = (png_ptr->width +
  196733. png_pass_inc[png_ptr->pass] - 1 -
  196734. png_pass_start[png_ptr->pass]) /
  196735. png_pass_inc[png_ptr->pass];
  196736. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196737. png_ptr->iwidth) + 1;
  196738. if (!(png_ptr->transformations & PNG_INTERLACE))
  196739. {
  196740. png_ptr->num_rows = (png_ptr->height +
  196741. png_pass_yinc[png_ptr->pass] - 1 -
  196742. png_pass_ystart[png_ptr->pass]) /
  196743. png_pass_yinc[png_ptr->pass];
  196744. if (!(png_ptr->num_rows))
  196745. continue;
  196746. }
  196747. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196748. break;
  196749. } while (png_ptr->iwidth == 0);
  196750. if (png_ptr->pass < 7)
  196751. return;
  196752. }
  196753. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196754. {
  196755. #ifdef PNG_USE_LOCAL_ARRAYS
  196756. PNG_CONST PNG_IDAT;
  196757. #endif
  196758. char extra;
  196759. int ret;
  196760. png_ptr->zstream.next_out = (Bytef *)&extra;
  196761. png_ptr->zstream.avail_out = (uInt)1;
  196762. for(;;)
  196763. {
  196764. if (!(png_ptr->zstream.avail_in))
  196765. {
  196766. while (!png_ptr->idat_size)
  196767. {
  196768. png_byte chunk_length[4];
  196769. png_crc_finish(png_ptr, 0);
  196770. png_read_data(png_ptr, chunk_length, 4);
  196771. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196772. png_reset_crc(png_ptr);
  196773. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196774. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196775. png_error(png_ptr, "Not enough image data");
  196776. }
  196777. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196778. png_ptr->zstream.next_in = png_ptr->zbuf;
  196779. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196780. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196781. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196782. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196783. }
  196784. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196785. if (ret == Z_STREAM_END)
  196786. {
  196787. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196788. png_ptr->idat_size)
  196789. png_warning(png_ptr, "Extra compressed data");
  196790. png_ptr->mode |= PNG_AFTER_IDAT;
  196791. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196792. break;
  196793. }
  196794. if (ret != Z_OK)
  196795. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196796. "Decompression Error");
  196797. if (!(png_ptr->zstream.avail_out))
  196798. {
  196799. png_warning(png_ptr, "Extra compressed data.");
  196800. png_ptr->mode |= PNG_AFTER_IDAT;
  196801. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196802. break;
  196803. }
  196804. }
  196805. png_ptr->zstream.avail_out = 0;
  196806. }
  196807. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196808. png_warning(png_ptr, "Extra compression data");
  196809. inflateReset(&png_ptr->zstream);
  196810. png_ptr->mode |= PNG_AFTER_IDAT;
  196811. }
  196812. void /* PRIVATE */
  196813. png_read_start_row(png_structp png_ptr)
  196814. {
  196815. #ifdef PNG_USE_LOCAL_ARRAYS
  196816. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196817. /* start of interlace block */
  196818. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196819. /* offset to next interlace block */
  196820. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196821. /* start of interlace block in the y direction */
  196822. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196823. /* offset to next interlace block in the y direction */
  196824. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196825. #endif
  196826. int max_pixel_depth;
  196827. png_uint_32 row_bytes;
  196828. png_debug(1, "in png_read_start_row\n");
  196829. png_ptr->zstream.avail_in = 0;
  196830. png_init_read_transformations(png_ptr);
  196831. if (png_ptr->interlaced)
  196832. {
  196833. if (!(png_ptr->transformations & PNG_INTERLACE))
  196834. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196835. png_pass_ystart[0]) / png_pass_yinc[0];
  196836. else
  196837. png_ptr->num_rows = png_ptr->height;
  196838. png_ptr->iwidth = (png_ptr->width +
  196839. png_pass_inc[png_ptr->pass] - 1 -
  196840. png_pass_start[png_ptr->pass]) /
  196841. png_pass_inc[png_ptr->pass];
  196842. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196843. png_ptr->irowbytes = (png_size_t)row_bytes;
  196844. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196845. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196846. }
  196847. else
  196848. {
  196849. png_ptr->num_rows = png_ptr->height;
  196850. png_ptr->iwidth = png_ptr->width;
  196851. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196852. }
  196853. max_pixel_depth = png_ptr->pixel_depth;
  196854. #if defined(PNG_READ_PACK_SUPPORTED)
  196855. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196856. max_pixel_depth = 8;
  196857. #endif
  196858. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196859. if (png_ptr->transformations & PNG_EXPAND)
  196860. {
  196861. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196862. {
  196863. if (png_ptr->num_trans)
  196864. max_pixel_depth = 32;
  196865. else
  196866. max_pixel_depth = 24;
  196867. }
  196868. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196869. {
  196870. if (max_pixel_depth < 8)
  196871. max_pixel_depth = 8;
  196872. if (png_ptr->num_trans)
  196873. max_pixel_depth *= 2;
  196874. }
  196875. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196876. {
  196877. if (png_ptr->num_trans)
  196878. {
  196879. max_pixel_depth *= 4;
  196880. max_pixel_depth /= 3;
  196881. }
  196882. }
  196883. }
  196884. #endif
  196885. #if defined(PNG_READ_FILLER_SUPPORTED)
  196886. if (png_ptr->transformations & (PNG_FILLER))
  196887. {
  196888. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196889. max_pixel_depth = 32;
  196890. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196891. {
  196892. if (max_pixel_depth <= 8)
  196893. max_pixel_depth = 16;
  196894. else
  196895. max_pixel_depth = 32;
  196896. }
  196897. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196898. {
  196899. if (max_pixel_depth <= 32)
  196900. max_pixel_depth = 32;
  196901. else
  196902. max_pixel_depth = 64;
  196903. }
  196904. }
  196905. #endif
  196906. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196907. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196908. {
  196909. if (
  196910. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196911. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196912. #endif
  196913. #if defined(PNG_READ_FILLER_SUPPORTED)
  196914. (png_ptr->transformations & (PNG_FILLER)) ||
  196915. #endif
  196916. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196917. {
  196918. if (max_pixel_depth <= 16)
  196919. max_pixel_depth = 32;
  196920. else
  196921. max_pixel_depth = 64;
  196922. }
  196923. else
  196924. {
  196925. if (max_pixel_depth <= 8)
  196926. {
  196927. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196928. max_pixel_depth = 32;
  196929. else
  196930. max_pixel_depth = 24;
  196931. }
  196932. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196933. max_pixel_depth = 64;
  196934. else
  196935. max_pixel_depth = 48;
  196936. }
  196937. }
  196938. #endif
  196939. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196940. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196941. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196942. {
  196943. int user_pixel_depth=png_ptr->user_transform_depth*
  196944. png_ptr->user_transform_channels;
  196945. if(user_pixel_depth > max_pixel_depth)
  196946. max_pixel_depth=user_pixel_depth;
  196947. }
  196948. #endif
  196949. /* align the width on the next larger 8 pixels. Mainly used
  196950. for interlacing */
  196951. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196952. /* calculate the maximum bytes needed, adding a byte and a pixel
  196953. for safety's sake */
  196954. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196955. 1 + ((max_pixel_depth + 7) >> 3);
  196956. #ifdef PNG_MAX_MALLOC_64K
  196957. if (row_bytes > (png_uint_32)65536L)
  196958. png_error(png_ptr, "This image requires a row greater than 64KB");
  196959. #endif
  196960. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196961. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196962. #ifdef PNG_MAX_MALLOC_64K
  196963. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196964. png_error(png_ptr, "This image requires a row greater than 64KB");
  196965. #endif
  196966. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196967. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196968. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196969. png_ptr->rowbytes + 1));
  196970. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196971. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196972. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196973. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196974. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196975. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196976. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196977. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196978. }
  196979. #endif /* PNG_READ_SUPPORTED */
  196980. /*** End of inlined file: pngrutil.c ***/
  196981. /*** Start of inlined file: pngset.c ***/
  196982. /* pngset.c - storage of image information into info struct
  196983. *
  196984. * Last changed in libpng 1.2.21 [October 4, 2007]
  196985. * For conditions of distribution and use, see copyright notice in png.h
  196986. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196987. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196988. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196989. *
  196990. * The functions here are used during reads to store data from the file
  196991. * into the info struct, and during writes to store application data
  196992. * into the info struct for writing into the file. This abstracts the
  196993. * info struct and allows us to change the structure in the future.
  196994. */
  196995. #define PNG_INTERNAL
  196996. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196997. #if defined(PNG_bKGD_SUPPORTED)
  196998. void PNGAPI
  196999. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  197000. {
  197001. png_debug1(1, "in %s storage function\n", "bKGD");
  197002. if (png_ptr == NULL || info_ptr == NULL)
  197003. return;
  197004. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  197005. info_ptr->valid |= PNG_INFO_bKGD;
  197006. }
  197007. #endif
  197008. #if defined(PNG_cHRM_SUPPORTED)
  197009. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197010. void PNGAPI
  197011. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  197012. double white_x, double white_y, double red_x, double red_y,
  197013. double green_x, double green_y, double blue_x, double blue_y)
  197014. {
  197015. png_debug1(1, "in %s storage function\n", "cHRM");
  197016. if (png_ptr == NULL || info_ptr == NULL)
  197017. return;
  197018. if (white_x < 0.0 || white_y < 0.0 ||
  197019. red_x < 0.0 || red_y < 0.0 ||
  197020. green_x < 0.0 || green_y < 0.0 ||
  197021. blue_x < 0.0 || blue_y < 0.0)
  197022. {
  197023. png_warning(png_ptr,
  197024. "Ignoring attempt to set negative chromaticity value");
  197025. return;
  197026. }
  197027. if (white_x > 21474.83 || white_y > 21474.83 ||
  197028. red_x > 21474.83 || red_y > 21474.83 ||
  197029. green_x > 21474.83 || green_y > 21474.83 ||
  197030. blue_x > 21474.83 || blue_y > 21474.83)
  197031. {
  197032. png_warning(png_ptr,
  197033. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197034. return;
  197035. }
  197036. info_ptr->x_white = (float)white_x;
  197037. info_ptr->y_white = (float)white_y;
  197038. info_ptr->x_red = (float)red_x;
  197039. info_ptr->y_red = (float)red_y;
  197040. info_ptr->x_green = (float)green_x;
  197041. info_ptr->y_green = (float)green_y;
  197042. info_ptr->x_blue = (float)blue_x;
  197043. info_ptr->y_blue = (float)blue_y;
  197044. #ifdef PNG_FIXED_POINT_SUPPORTED
  197045. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197046. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197047. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197048. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197049. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197050. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197051. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197052. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197053. #endif
  197054. info_ptr->valid |= PNG_INFO_cHRM;
  197055. }
  197056. #endif
  197057. #ifdef PNG_FIXED_POINT_SUPPORTED
  197058. void PNGAPI
  197059. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197060. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197061. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197062. png_fixed_point blue_x, png_fixed_point blue_y)
  197063. {
  197064. png_debug1(1, "in %s storage function\n", "cHRM");
  197065. if (png_ptr == NULL || info_ptr == NULL)
  197066. return;
  197067. if (white_x < 0 || white_y < 0 ||
  197068. red_x < 0 || red_y < 0 ||
  197069. green_x < 0 || green_y < 0 ||
  197070. blue_x < 0 || blue_y < 0)
  197071. {
  197072. png_warning(png_ptr,
  197073. "Ignoring attempt to set negative chromaticity value");
  197074. return;
  197075. }
  197076. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197077. if (white_x > (double) PNG_UINT_31_MAX ||
  197078. white_y > (double) PNG_UINT_31_MAX ||
  197079. red_x > (double) PNG_UINT_31_MAX ||
  197080. red_y > (double) PNG_UINT_31_MAX ||
  197081. green_x > (double) PNG_UINT_31_MAX ||
  197082. green_y > (double) PNG_UINT_31_MAX ||
  197083. blue_x > (double) PNG_UINT_31_MAX ||
  197084. blue_y > (double) PNG_UINT_31_MAX)
  197085. #else
  197086. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197087. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197088. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197089. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197090. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197091. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197092. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197093. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197094. #endif
  197095. {
  197096. png_warning(png_ptr,
  197097. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197098. return;
  197099. }
  197100. info_ptr->int_x_white = white_x;
  197101. info_ptr->int_y_white = white_y;
  197102. info_ptr->int_x_red = red_x;
  197103. info_ptr->int_y_red = red_y;
  197104. info_ptr->int_x_green = green_x;
  197105. info_ptr->int_y_green = green_y;
  197106. info_ptr->int_x_blue = blue_x;
  197107. info_ptr->int_y_blue = blue_y;
  197108. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197109. info_ptr->x_white = (float)(white_x/100000.);
  197110. info_ptr->y_white = (float)(white_y/100000.);
  197111. info_ptr->x_red = (float)( red_x/100000.);
  197112. info_ptr->y_red = (float)( red_y/100000.);
  197113. info_ptr->x_green = (float)(green_x/100000.);
  197114. info_ptr->y_green = (float)(green_y/100000.);
  197115. info_ptr->x_blue = (float)( blue_x/100000.);
  197116. info_ptr->y_blue = (float)( blue_y/100000.);
  197117. #endif
  197118. info_ptr->valid |= PNG_INFO_cHRM;
  197119. }
  197120. #endif
  197121. #endif
  197122. #if defined(PNG_gAMA_SUPPORTED)
  197123. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197124. void PNGAPI
  197125. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197126. {
  197127. double gamma;
  197128. png_debug1(1, "in %s storage function\n", "gAMA");
  197129. if (png_ptr == NULL || info_ptr == NULL)
  197130. return;
  197131. /* Check for overflow */
  197132. if (file_gamma > 21474.83)
  197133. {
  197134. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197135. gamma=21474.83;
  197136. }
  197137. else
  197138. gamma=file_gamma;
  197139. info_ptr->gamma = (float)gamma;
  197140. #ifdef PNG_FIXED_POINT_SUPPORTED
  197141. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197142. #endif
  197143. info_ptr->valid |= PNG_INFO_gAMA;
  197144. if(gamma == 0.0)
  197145. png_warning(png_ptr, "Setting gamma=0");
  197146. }
  197147. #endif
  197148. void PNGAPI
  197149. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197150. int_gamma)
  197151. {
  197152. png_fixed_point gamma;
  197153. png_debug1(1, "in %s storage function\n", "gAMA");
  197154. if (png_ptr == NULL || info_ptr == NULL)
  197155. return;
  197156. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197157. {
  197158. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197159. gamma=PNG_UINT_31_MAX;
  197160. }
  197161. else
  197162. {
  197163. if (int_gamma < 0)
  197164. {
  197165. png_warning(png_ptr, "Setting negative gamma to zero");
  197166. gamma=0;
  197167. }
  197168. else
  197169. gamma=int_gamma;
  197170. }
  197171. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197172. info_ptr->gamma = (float)(gamma/100000.);
  197173. #endif
  197174. #ifdef PNG_FIXED_POINT_SUPPORTED
  197175. info_ptr->int_gamma = gamma;
  197176. #endif
  197177. info_ptr->valid |= PNG_INFO_gAMA;
  197178. if(gamma == 0)
  197179. png_warning(png_ptr, "Setting gamma=0");
  197180. }
  197181. #endif
  197182. #if defined(PNG_hIST_SUPPORTED)
  197183. void PNGAPI
  197184. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197185. {
  197186. int i;
  197187. png_debug1(1, "in %s storage function\n", "hIST");
  197188. if (png_ptr == NULL || info_ptr == NULL)
  197189. return;
  197190. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197191. > PNG_MAX_PALETTE_LENGTH)
  197192. {
  197193. png_warning(png_ptr,
  197194. "Invalid palette size, hIST allocation skipped.");
  197195. return;
  197196. }
  197197. #ifdef PNG_FREE_ME_SUPPORTED
  197198. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197199. #endif
  197200. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197201. 1.2.1 */
  197202. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197203. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197204. if (png_ptr->hist == NULL)
  197205. {
  197206. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197207. return;
  197208. }
  197209. for (i = 0; i < info_ptr->num_palette; i++)
  197210. png_ptr->hist[i] = hist[i];
  197211. info_ptr->hist = png_ptr->hist;
  197212. info_ptr->valid |= PNG_INFO_hIST;
  197213. #ifdef PNG_FREE_ME_SUPPORTED
  197214. info_ptr->free_me |= PNG_FREE_HIST;
  197215. #else
  197216. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197217. #endif
  197218. }
  197219. #endif
  197220. void PNGAPI
  197221. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197222. png_uint_32 width, png_uint_32 height, int bit_depth,
  197223. int color_type, int interlace_type, int compression_type,
  197224. int filter_type)
  197225. {
  197226. png_debug1(1, "in %s storage function\n", "IHDR");
  197227. if (png_ptr == NULL || info_ptr == NULL)
  197228. return;
  197229. /* check for width and height valid values */
  197230. if (width == 0 || height == 0)
  197231. png_error(png_ptr, "Image width or height is zero in IHDR");
  197232. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197233. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197234. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197235. #else
  197236. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197237. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197238. #endif
  197239. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197240. png_error(png_ptr, "Invalid image size in IHDR");
  197241. if ( width > (PNG_UINT_32_MAX
  197242. >> 3) /* 8-byte RGBA pixels */
  197243. - 64 /* bigrowbuf hack */
  197244. - 1 /* filter byte */
  197245. - 7*8 /* rounding of width to multiple of 8 pixels */
  197246. - 8) /* extra max_pixel_depth pad */
  197247. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197248. /* check other values */
  197249. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197250. bit_depth != 8 && bit_depth != 16)
  197251. png_error(png_ptr, "Invalid bit depth in IHDR");
  197252. if (color_type < 0 || color_type == 1 ||
  197253. color_type == 5 || color_type > 6)
  197254. png_error(png_ptr, "Invalid color type in IHDR");
  197255. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197256. ((color_type == PNG_COLOR_TYPE_RGB ||
  197257. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197258. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197259. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197260. if (interlace_type >= PNG_INTERLACE_LAST)
  197261. png_error(png_ptr, "Unknown interlace method in IHDR");
  197262. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197263. png_error(png_ptr, "Unknown compression method in IHDR");
  197264. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197265. /* Accept filter_method 64 (intrapixel differencing) only if
  197266. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197267. * 2. Libpng did not read a PNG signature (this filter_method is only
  197268. * used in PNG datastreams that are embedded in MNG datastreams) and
  197269. * 3. The application called png_permit_mng_features with a mask that
  197270. * included PNG_FLAG_MNG_FILTER_64 and
  197271. * 4. The filter_method is 64 and
  197272. * 5. The color_type is RGB or RGBA
  197273. */
  197274. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197275. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197276. if(filter_type != PNG_FILTER_TYPE_BASE)
  197277. {
  197278. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197279. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197280. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197281. (color_type == PNG_COLOR_TYPE_RGB ||
  197282. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197283. png_error(png_ptr, "Unknown filter method in IHDR");
  197284. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197285. png_warning(png_ptr, "Invalid filter method in IHDR");
  197286. }
  197287. #else
  197288. if(filter_type != PNG_FILTER_TYPE_BASE)
  197289. png_error(png_ptr, "Unknown filter method in IHDR");
  197290. #endif
  197291. info_ptr->width = width;
  197292. info_ptr->height = height;
  197293. info_ptr->bit_depth = (png_byte)bit_depth;
  197294. info_ptr->color_type =(png_byte) color_type;
  197295. info_ptr->compression_type = (png_byte)compression_type;
  197296. info_ptr->filter_type = (png_byte)filter_type;
  197297. info_ptr->interlace_type = (png_byte)interlace_type;
  197298. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197299. info_ptr->channels = 1;
  197300. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197301. info_ptr->channels = 3;
  197302. else
  197303. info_ptr->channels = 1;
  197304. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197305. info_ptr->channels++;
  197306. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197307. /* check for potential overflow */
  197308. if (width > (PNG_UINT_32_MAX
  197309. >> 3) /* 8-byte RGBA pixels */
  197310. - 64 /* bigrowbuf hack */
  197311. - 1 /* filter byte */
  197312. - 7*8 /* rounding of width to multiple of 8 pixels */
  197313. - 8) /* extra max_pixel_depth pad */
  197314. info_ptr->rowbytes = (png_size_t)0;
  197315. else
  197316. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197317. }
  197318. #if defined(PNG_oFFs_SUPPORTED)
  197319. void PNGAPI
  197320. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197321. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197322. {
  197323. png_debug1(1, "in %s storage function\n", "oFFs");
  197324. if (png_ptr == NULL || info_ptr == NULL)
  197325. return;
  197326. info_ptr->x_offset = offset_x;
  197327. info_ptr->y_offset = offset_y;
  197328. info_ptr->offset_unit_type = (png_byte)unit_type;
  197329. info_ptr->valid |= PNG_INFO_oFFs;
  197330. }
  197331. #endif
  197332. #if defined(PNG_pCAL_SUPPORTED)
  197333. void PNGAPI
  197334. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197335. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197336. png_charp units, png_charpp params)
  197337. {
  197338. png_uint_32 length;
  197339. int i;
  197340. png_debug1(1, "in %s storage function\n", "pCAL");
  197341. if (png_ptr == NULL || info_ptr == NULL)
  197342. return;
  197343. length = png_strlen(purpose) + 1;
  197344. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197345. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197346. if (info_ptr->pcal_purpose == NULL)
  197347. {
  197348. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197349. return;
  197350. }
  197351. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197352. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197353. info_ptr->pcal_X0 = X0;
  197354. info_ptr->pcal_X1 = X1;
  197355. info_ptr->pcal_type = (png_byte)type;
  197356. info_ptr->pcal_nparams = (png_byte)nparams;
  197357. length = png_strlen(units) + 1;
  197358. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197359. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197360. if (info_ptr->pcal_units == NULL)
  197361. {
  197362. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197363. return;
  197364. }
  197365. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197366. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197367. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197368. if (info_ptr->pcal_params == NULL)
  197369. {
  197370. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197371. return;
  197372. }
  197373. info_ptr->pcal_params[nparams] = NULL;
  197374. for (i = 0; i < nparams; i++)
  197375. {
  197376. length = png_strlen(params[i]) + 1;
  197377. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197378. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197379. if (info_ptr->pcal_params[i] == NULL)
  197380. {
  197381. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197382. return;
  197383. }
  197384. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197385. }
  197386. info_ptr->valid |= PNG_INFO_pCAL;
  197387. #ifdef PNG_FREE_ME_SUPPORTED
  197388. info_ptr->free_me |= PNG_FREE_PCAL;
  197389. #endif
  197390. }
  197391. #endif
  197392. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197393. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197394. void PNGAPI
  197395. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197396. int unit, double width, double height)
  197397. {
  197398. png_debug1(1, "in %s storage function\n", "sCAL");
  197399. if (png_ptr == NULL || info_ptr == NULL)
  197400. return;
  197401. info_ptr->scal_unit = (png_byte)unit;
  197402. info_ptr->scal_pixel_width = width;
  197403. info_ptr->scal_pixel_height = height;
  197404. info_ptr->valid |= PNG_INFO_sCAL;
  197405. }
  197406. #else
  197407. #ifdef PNG_FIXED_POINT_SUPPORTED
  197408. void PNGAPI
  197409. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197410. int unit, png_charp swidth, png_charp sheight)
  197411. {
  197412. png_uint_32 length;
  197413. png_debug1(1, "in %s storage function\n", "sCAL");
  197414. if (png_ptr == NULL || info_ptr == NULL)
  197415. return;
  197416. info_ptr->scal_unit = (png_byte)unit;
  197417. length = png_strlen(swidth) + 1;
  197418. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197419. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197420. if (info_ptr->scal_s_width == NULL)
  197421. {
  197422. png_warning(png_ptr,
  197423. "Memory allocation failed while processing sCAL.");
  197424. }
  197425. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197426. length = png_strlen(sheight) + 1;
  197427. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197428. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197429. if (info_ptr->scal_s_height == NULL)
  197430. {
  197431. png_free (png_ptr, info_ptr->scal_s_width);
  197432. png_warning(png_ptr,
  197433. "Memory allocation failed while processing sCAL.");
  197434. }
  197435. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197436. info_ptr->valid |= PNG_INFO_sCAL;
  197437. #ifdef PNG_FREE_ME_SUPPORTED
  197438. info_ptr->free_me |= PNG_FREE_SCAL;
  197439. #endif
  197440. }
  197441. #endif
  197442. #endif
  197443. #endif
  197444. #if defined(PNG_pHYs_SUPPORTED)
  197445. void PNGAPI
  197446. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197447. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197448. {
  197449. png_debug1(1, "in %s storage function\n", "pHYs");
  197450. if (png_ptr == NULL || info_ptr == NULL)
  197451. return;
  197452. info_ptr->x_pixels_per_unit = res_x;
  197453. info_ptr->y_pixels_per_unit = res_y;
  197454. info_ptr->phys_unit_type = (png_byte)unit_type;
  197455. info_ptr->valid |= PNG_INFO_pHYs;
  197456. }
  197457. #endif
  197458. void PNGAPI
  197459. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197460. png_colorp palette, int num_palette)
  197461. {
  197462. png_debug1(1, "in %s storage function\n", "PLTE");
  197463. if (png_ptr == NULL || info_ptr == NULL)
  197464. return;
  197465. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197466. {
  197467. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197468. png_error(png_ptr, "Invalid palette length");
  197469. else
  197470. {
  197471. png_warning(png_ptr, "Invalid palette length");
  197472. return;
  197473. }
  197474. }
  197475. /*
  197476. * It may not actually be necessary to set png_ptr->palette here;
  197477. * we do it for backward compatibility with the way the png_handle_tRNS
  197478. * function used to do the allocation.
  197479. */
  197480. #ifdef PNG_FREE_ME_SUPPORTED
  197481. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197482. #endif
  197483. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197484. of num_palette entries,
  197485. in case of an invalid PNG file that has too-large sample values. */
  197486. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197487. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197488. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197489. png_sizeof(png_color));
  197490. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197491. info_ptr->palette = png_ptr->palette;
  197492. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197493. #ifdef PNG_FREE_ME_SUPPORTED
  197494. info_ptr->free_me |= PNG_FREE_PLTE;
  197495. #else
  197496. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197497. #endif
  197498. info_ptr->valid |= PNG_INFO_PLTE;
  197499. }
  197500. #if defined(PNG_sBIT_SUPPORTED)
  197501. void PNGAPI
  197502. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197503. png_color_8p sig_bit)
  197504. {
  197505. png_debug1(1, "in %s storage function\n", "sBIT");
  197506. if (png_ptr == NULL || info_ptr == NULL)
  197507. return;
  197508. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197509. info_ptr->valid |= PNG_INFO_sBIT;
  197510. }
  197511. #endif
  197512. #if defined(PNG_sRGB_SUPPORTED)
  197513. void PNGAPI
  197514. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197515. {
  197516. png_debug1(1, "in %s storage function\n", "sRGB");
  197517. if (png_ptr == NULL || info_ptr == NULL)
  197518. return;
  197519. info_ptr->srgb_intent = (png_byte)intent;
  197520. info_ptr->valid |= PNG_INFO_sRGB;
  197521. }
  197522. void PNGAPI
  197523. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197524. int intent)
  197525. {
  197526. #if defined(PNG_gAMA_SUPPORTED)
  197527. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197528. float file_gamma;
  197529. #endif
  197530. #ifdef PNG_FIXED_POINT_SUPPORTED
  197531. png_fixed_point int_file_gamma;
  197532. #endif
  197533. #endif
  197534. #if defined(PNG_cHRM_SUPPORTED)
  197535. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197536. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197537. #endif
  197538. #ifdef PNG_FIXED_POINT_SUPPORTED
  197539. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197540. int_green_y, int_blue_x, int_blue_y;
  197541. #endif
  197542. #endif
  197543. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197544. if (png_ptr == NULL || info_ptr == NULL)
  197545. return;
  197546. png_set_sRGB(png_ptr, info_ptr, intent);
  197547. #if defined(PNG_gAMA_SUPPORTED)
  197548. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197549. file_gamma = (float).45455;
  197550. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197551. #endif
  197552. #ifdef PNG_FIXED_POINT_SUPPORTED
  197553. int_file_gamma = 45455L;
  197554. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197555. #endif
  197556. #endif
  197557. #if defined(PNG_cHRM_SUPPORTED)
  197558. #ifdef PNG_FIXED_POINT_SUPPORTED
  197559. int_white_x = 31270L;
  197560. int_white_y = 32900L;
  197561. int_red_x = 64000L;
  197562. int_red_y = 33000L;
  197563. int_green_x = 30000L;
  197564. int_green_y = 60000L;
  197565. int_blue_x = 15000L;
  197566. int_blue_y = 6000L;
  197567. png_set_cHRM_fixed(png_ptr, info_ptr,
  197568. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197569. int_blue_x, int_blue_y);
  197570. #endif
  197571. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197572. white_x = (float).3127;
  197573. white_y = (float).3290;
  197574. red_x = (float).64;
  197575. red_y = (float).33;
  197576. green_x = (float).30;
  197577. green_y = (float).60;
  197578. blue_x = (float).15;
  197579. blue_y = (float).06;
  197580. png_set_cHRM(png_ptr, info_ptr,
  197581. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197582. #endif
  197583. #endif
  197584. }
  197585. #endif
  197586. #if defined(PNG_iCCP_SUPPORTED)
  197587. void PNGAPI
  197588. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197589. png_charp name, int compression_type,
  197590. png_charp profile, png_uint_32 proflen)
  197591. {
  197592. png_charp new_iccp_name;
  197593. png_charp new_iccp_profile;
  197594. png_debug1(1, "in %s storage function\n", "iCCP");
  197595. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197596. return;
  197597. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197598. if (new_iccp_name == NULL)
  197599. {
  197600. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197601. return;
  197602. }
  197603. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197604. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197605. if (new_iccp_profile == NULL)
  197606. {
  197607. png_free (png_ptr, new_iccp_name);
  197608. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197609. return;
  197610. }
  197611. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197612. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197613. info_ptr->iccp_proflen = proflen;
  197614. info_ptr->iccp_name = new_iccp_name;
  197615. info_ptr->iccp_profile = new_iccp_profile;
  197616. /* Compression is always zero but is here so the API and info structure
  197617. * does not have to change if we introduce multiple compression types */
  197618. info_ptr->iccp_compression = (png_byte)compression_type;
  197619. #ifdef PNG_FREE_ME_SUPPORTED
  197620. info_ptr->free_me |= PNG_FREE_ICCP;
  197621. #endif
  197622. info_ptr->valid |= PNG_INFO_iCCP;
  197623. }
  197624. #endif
  197625. #if defined(PNG_TEXT_SUPPORTED)
  197626. void PNGAPI
  197627. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197628. int num_text)
  197629. {
  197630. int ret;
  197631. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197632. if (ret)
  197633. png_error(png_ptr, "Insufficient memory to store text");
  197634. }
  197635. int /* PRIVATE */
  197636. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197637. int num_text)
  197638. {
  197639. int i;
  197640. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197641. "text" : (png_const_charp)png_ptr->chunk_name));
  197642. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197643. return(0);
  197644. /* Make sure we have enough space in the "text" array in info_struct
  197645. * to hold all of the incoming text_ptr objects.
  197646. */
  197647. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197648. {
  197649. if (info_ptr->text != NULL)
  197650. {
  197651. png_textp old_text;
  197652. int old_max;
  197653. old_max = info_ptr->max_text;
  197654. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197655. old_text = info_ptr->text;
  197656. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197657. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197658. if (info_ptr->text == NULL)
  197659. {
  197660. png_free(png_ptr, old_text);
  197661. return(1);
  197662. }
  197663. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197664. png_sizeof(png_text)));
  197665. png_free(png_ptr, old_text);
  197666. }
  197667. else
  197668. {
  197669. info_ptr->max_text = num_text + 8;
  197670. info_ptr->num_text = 0;
  197671. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197672. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197673. if (info_ptr->text == NULL)
  197674. return(1);
  197675. #ifdef PNG_FREE_ME_SUPPORTED
  197676. info_ptr->free_me |= PNG_FREE_TEXT;
  197677. #endif
  197678. }
  197679. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197680. info_ptr->max_text);
  197681. }
  197682. for (i = 0; i < num_text; i++)
  197683. {
  197684. png_size_t text_length,key_len;
  197685. png_size_t lang_len,lang_key_len;
  197686. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197687. if (text_ptr[i].key == NULL)
  197688. continue;
  197689. key_len = png_strlen(text_ptr[i].key);
  197690. if(text_ptr[i].compression <= 0)
  197691. {
  197692. lang_len = 0;
  197693. lang_key_len = 0;
  197694. }
  197695. else
  197696. #ifdef PNG_iTXt_SUPPORTED
  197697. {
  197698. /* set iTXt data */
  197699. if (text_ptr[i].lang != NULL)
  197700. lang_len = png_strlen(text_ptr[i].lang);
  197701. else
  197702. lang_len = 0;
  197703. if (text_ptr[i].lang_key != NULL)
  197704. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197705. else
  197706. lang_key_len = 0;
  197707. }
  197708. #else
  197709. {
  197710. png_warning(png_ptr, "iTXt chunk not supported.");
  197711. continue;
  197712. }
  197713. #endif
  197714. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197715. {
  197716. text_length = 0;
  197717. #ifdef PNG_iTXt_SUPPORTED
  197718. if(text_ptr[i].compression > 0)
  197719. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197720. else
  197721. #endif
  197722. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197723. }
  197724. else
  197725. {
  197726. text_length = png_strlen(text_ptr[i].text);
  197727. textp->compression = text_ptr[i].compression;
  197728. }
  197729. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197730. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197731. if (textp->key == NULL)
  197732. return(1);
  197733. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197734. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197735. (int)textp->key);
  197736. png_memcpy(textp->key, text_ptr[i].key,
  197737. (png_size_t)(key_len));
  197738. *(textp->key+key_len) = '\0';
  197739. #ifdef PNG_iTXt_SUPPORTED
  197740. if (text_ptr[i].compression > 0)
  197741. {
  197742. textp->lang=textp->key + key_len + 1;
  197743. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197744. *(textp->lang+lang_len) = '\0';
  197745. textp->lang_key=textp->lang + lang_len + 1;
  197746. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197747. *(textp->lang_key+lang_key_len) = '\0';
  197748. textp->text=textp->lang_key + lang_key_len + 1;
  197749. }
  197750. else
  197751. #endif
  197752. {
  197753. #ifdef PNG_iTXt_SUPPORTED
  197754. textp->lang=NULL;
  197755. textp->lang_key=NULL;
  197756. #endif
  197757. textp->text=textp->key + key_len + 1;
  197758. }
  197759. if(text_length)
  197760. png_memcpy(textp->text, text_ptr[i].text,
  197761. (png_size_t)(text_length));
  197762. *(textp->text+text_length) = '\0';
  197763. #ifdef PNG_iTXt_SUPPORTED
  197764. if(textp->compression > 0)
  197765. {
  197766. textp->text_length = 0;
  197767. textp->itxt_length = text_length;
  197768. }
  197769. else
  197770. #endif
  197771. {
  197772. textp->text_length = text_length;
  197773. #ifdef PNG_iTXt_SUPPORTED
  197774. textp->itxt_length = 0;
  197775. #endif
  197776. }
  197777. info_ptr->num_text++;
  197778. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197779. }
  197780. return(0);
  197781. }
  197782. #endif
  197783. #if defined(PNG_tIME_SUPPORTED)
  197784. void PNGAPI
  197785. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197786. {
  197787. png_debug1(1, "in %s storage function\n", "tIME");
  197788. if (png_ptr == NULL || info_ptr == NULL ||
  197789. (png_ptr->mode & PNG_WROTE_tIME))
  197790. return;
  197791. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197792. info_ptr->valid |= PNG_INFO_tIME;
  197793. }
  197794. #endif
  197795. #if defined(PNG_tRNS_SUPPORTED)
  197796. void PNGAPI
  197797. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197798. png_bytep trans, int num_trans, png_color_16p trans_values)
  197799. {
  197800. png_debug1(1, "in %s storage function\n", "tRNS");
  197801. if (png_ptr == NULL || info_ptr == NULL)
  197802. return;
  197803. if (trans != NULL)
  197804. {
  197805. /*
  197806. * It may not actually be necessary to set png_ptr->trans here;
  197807. * we do it for backward compatibility with the way the png_handle_tRNS
  197808. * function used to do the allocation.
  197809. */
  197810. #ifdef PNG_FREE_ME_SUPPORTED
  197811. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197812. #endif
  197813. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197814. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197815. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197816. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197817. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197818. #ifdef PNG_FREE_ME_SUPPORTED
  197819. info_ptr->free_me |= PNG_FREE_TRNS;
  197820. #else
  197821. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197822. #endif
  197823. }
  197824. if (trans_values != NULL)
  197825. {
  197826. png_memcpy(&(info_ptr->trans_values), trans_values,
  197827. png_sizeof(png_color_16));
  197828. if (num_trans == 0)
  197829. num_trans = 1;
  197830. }
  197831. info_ptr->num_trans = (png_uint_16)num_trans;
  197832. info_ptr->valid |= PNG_INFO_tRNS;
  197833. }
  197834. #endif
  197835. #if defined(PNG_sPLT_SUPPORTED)
  197836. void PNGAPI
  197837. png_set_sPLT(png_structp png_ptr,
  197838. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197839. {
  197840. png_sPLT_tp np;
  197841. int i;
  197842. if (png_ptr == NULL || info_ptr == NULL)
  197843. return;
  197844. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197845. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197846. if (np == NULL)
  197847. {
  197848. png_warning(png_ptr, "No memory for sPLT palettes.");
  197849. return;
  197850. }
  197851. png_memcpy(np, info_ptr->splt_palettes,
  197852. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197853. png_free(png_ptr, info_ptr->splt_palettes);
  197854. info_ptr->splt_palettes=NULL;
  197855. for (i = 0; i < nentries; i++)
  197856. {
  197857. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197858. png_sPLT_tp from = entries + i;
  197859. to->name = (png_charp)png_malloc_warn(png_ptr,
  197860. png_strlen(from->name) + 1);
  197861. if (to->name == NULL)
  197862. {
  197863. png_warning(png_ptr,
  197864. "Out of memory while processing sPLT chunk");
  197865. }
  197866. /* TODO: use png_malloc_warn */
  197867. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197868. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197869. from->nentries * png_sizeof(png_sPLT_entry));
  197870. /* TODO: use png_malloc_warn */
  197871. png_memcpy(to->entries, from->entries,
  197872. from->nentries * png_sizeof(png_sPLT_entry));
  197873. if (to->entries == NULL)
  197874. {
  197875. png_warning(png_ptr,
  197876. "Out of memory while processing sPLT chunk");
  197877. png_free(png_ptr,to->name);
  197878. to->name = NULL;
  197879. }
  197880. to->nentries = from->nentries;
  197881. to->depth = from->depth;
  197882. }
  197883. info_ptr->splt_palettes = np;
  197884. info_ptr->splt_palettes_num += nentries;
  197885. info_ptr->valid |= PNG_INFO_sPLT;
  197886. #ifdef PNG_FREE_ME_SUPPORTED
  197887. info_ptr->free_me |= PNG_FREE_SPLT;
  197888. #endif
  197889. }
  197890. #endif /* PNG_sPLT_SUPPORTED */
  197891. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197892. void PNGAPI
  197893. png_set_unknown_chunks(png_structp png_ptr,
  197894. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197895. {
  197896. png_unknown_chunkp np;
  197897. int i;
  197898. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197899. return;
  197900. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197901. (info_ptr->unknown_chunks_num + num_unknowns) *
  197902. png_sizeof(png_unknown_chunk));
  197903. if (np == NULL)
  197904. {
  197905. png_warning(png_ptr,
  197906. "Out of memory while processing unknown chunk.");
  197907. return;
  197908. }
  197909. png_memcpy(np, info_ptr->unknown_chunks,
  197910. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197911. png_free(png_ptr, info_ptr->unknown_chunks);
  197912. info_ptr->unknown_chunks=NULL;
  197913. for (i = 0; i < num_unknowns; i++)
  197914. {
  197915. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197916. png_unknown_chunkp from = unknowns + i;
  197917. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197918. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197919. if (to->data == NULL)
  197920. {
  197921. png_warning(png_ptr,
  197922. "Out of memory while processing unknown chunk.");
  197923. }
  197924. else
  197925. {
  197926. png_memcpy(to->data, from->data, from->size);
  197927. to->size = from->size;
  197928. /* note our location in the read or write sequence */
  197929. to->location = (png_byte)(png_ptr->mode & 0xff);
  197930. }
  197931. }
  197932. info_ptr->unknown_chunks = np;
  197933. info_ptr->unknown_chunks_num += num_unknowns;
  197934. #ifdef PNG_FREE_ME_SUPPORTED
  197935. info_ptr->free_me |= PNG_FREE_UNKN;
  197936. #endif
  197937. }
  197938. void PNGAPI
  197939. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197940. int chunk, int location)
  197941. {
  197942. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197943. (int)info_ptr->unknown_chunks_num)
  197944. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197945. }
  197946. #endif
  197947. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197948. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197949. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197950. void PNGAPI
  197951. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197952. {
  197953. /* This function is deprecated in favor of png_permit_mng_features()
  197954. and will be removed from libpng-1.3.0 */
  197955. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197956. if (png_ptr == NULL)
  197957. return;
  197958. png_ptr->mng_features_permitted = (png_byte)
  197959. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197960. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197961. }
  197962. #endif
  197963. #endif
  197964. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197965. png_uint_32 PNGAPI
  197966. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197967. {
  197968. png_debug(1, "in png_permit_mng_features\n");
  197969. if (png_ptr == NULL)
  197970. return (png_uint_32)0;
  197971. png_ptr->mng_features_permitted =
  197972. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197973. return (png_uint_32)png_ptr->mng_features_permitted;
  197974. }
  197975. #endif
  197976. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197977. void PNGAPI
  197978. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197979. chunk_list, int num_chunks)
  197980. {
  197981. png_bytep new_list, p;
  197982. int i, old_num_chunks;
  197983. if (png_ptr == NULL)
  197984. return;
  197985. if (num_chunks == 0)
  197986. {
  197987. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197988. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197989. else
  197990. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197991. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197992. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197993. else
  197994. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197995. return;
  197996. }
  197997. if (chunk_list == NULL)
  197998. return;
  197999. old_num_chunks=png_ptr->num_chunk_list;
  198000. new_list=(png_bytep)png_malloc(png_ptr,
  198001. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  198002. if(png_ptr->chunk_list != NULL)
  198003. {
  198004. png_memcpy(new_list, png_ptr->chunk_list,
  198005. (png_size_t)(5*old_num_chunks));
  198006. png_free(png_ptr, png_ptr->chunk_list);
  198007. png_ptr->chunk_list=NULL;
  198008. }
  198009. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  198010. (png_size_t)(5*num_chunks));
  198011. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  198012. *p=(png_byte)keep;
  198013. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  198014. png_ptr->chunk_list=new_list;
  198015. #ifdef PNG_FREE_ME_SUPPORTED
  198016. png_ptr->free_me |= PNG_FREE_LIST;
  198017. #endif
  198018. }
  198019. #endif
  198020. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  198021. void PNGAPI
  198022. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  198023. png_user_chunk_ptr read_user_chunk_fn)
  198024. {
  198025. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198026. if (png_ptr == NULL)
  198027. return;
  198028. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198029. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198030. }
  198031. #endif
  198032. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198033. void PNGAPI
  198034. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198035. {
  198036. png_debug1(1, "in %s storage function\n", "rows");
  198037. if (png_ptr == NULL || info_ptr == NULL)
  198038. return;
  198039. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198040. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198041. info_ptr->row_pointers = row_pointers;
  198042. if(row_pointers)
  198043. info_ptr->valid |= PNG_INFO_IDAT;
  198044. }
  198045. #endif
  198046. #ifdef PNG_WRITE_SUPPORTED
  198047. void PNGAPI
  198048. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198049. {
  198050. if (png_ptr == NULL)
  198051. return;
  198052. if(png_ptr->zbuf)
  198053. png_free(png_ptr, png_ptr->zbuf);
  198054. png_ptr->zbuf_size = (png_size_t)size;
  198055. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198056. png_ptr->zstream.next_out = png_ptr->zbuf;
  198057. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198058. }
  198059. #endif
  198060. void PNGAPI
  198061. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198062. {
  198063. if (png_ptr && info_ptr)
  198064. info_ptr->valid &= ~(mask);
  198065. }
  198066. #ifndef PNG_1_0_X
  198067. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198068. /* function was added to libpng 1.2.0 and should always exist by default */
  198069. void PNGAPI
  198070. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198071. {
  198072. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198073. if (png_ptr != NULL)
  198074. png_ptr->asm_flags = 0;
  198075. }
  198076. /* this function was added to libpng 1.2.0 */
  198077. void PNGAPI
  198078. png_set_mmx_thresholds (png_structp png_ptr,
  198079. png_byte,
  198080. png_uint_32)
  198081. {
  198082. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198083. if (png_ptr == NULL)
  198084. return;
  198085. }
  198086. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198087. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198088. /* this function was added to libpng 1.2.6 */
  198089. void PNGAPI
  198090. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198091. png_uint_32 user_height_max)
  198092. {
  198093. /* Images with dimensions larger than these limits will be
  198094. * rejected by png_set_IHDR(). To accept any PNG datastream
  198095. * regardless of dimensions, set both limits to 0x7ffffffL.
  198096. */
  198097. if(png_ptr == NULL) return;
  198098. png_ptr->user_width_max = user_width_max;
  198099. png_ptr->user_height_max = user_height_max;
  198100. }
  198101. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198102. #endif /* ?PNG_1_0_X */
  198103. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198104. /*** End of inlined file: pngset.c ***/
  198105. /*** Start of inlined file: pngtrans.c ***/
  198106. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198107. *
  198108. * Last changed in libpng 1.2.17 May 15, 2007
  198109. * For conditions of distribution and use, see copyright notice in png.h
  198110. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198111. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198112. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198113. */
  198114. #define PNG_INTERNAL
  198115. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198116. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198117. /* turn on BGR-to-RGB mapping */
  198118. void PNGAPI
  198119. png_set_bgr(png_structp png_ptr)
  198120. {
  198121. png_debug(1, "in png_set_bgr\n");
  198122. if(png_ptr == NULL) return;
  198123. png_ptr->transformations |= PNG_BGR;
  198124. }
  198125. #endif
  198126. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198127. /* turn on 16 bit byte swapping */
  198128. void PNGAPI
  198129. png_set_swap(png_structp png_ptr)
  198130. {
  198131. png_debug(1, "in png_set_swap\n");
  198132. if(png_ptr == NULL) return;
  198133. if (png_ptr->bit_depth == 16)
  198134. png_ptr->transformations |= PNG_SWAP_BYTES;
  198135. }
  198136. #endif
  198137. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198138. /* turn on pixel packing */
  198139. void PNGAPI
  198140. png_set_packing(png_structp png_ptr)
  198141. {
  198142. png_debug(1, "in png_set_packing\n");
  198143. if(png_ptr == NULL) return;
  198144. if (png_ptr->bit_depth < 8)
  198145. {
  198146. png_ptr->transformations |= PNG_PACK;
  198147. png_ptr->usr_bit_depth = 8;
  198148. }
  198149. }
  198150. #endif
  198151. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198152. /* turn on packed pixel swapping */
  198153. void PNGAPI
  198154. png_set_packswap(png_structp png_ptr)
  198155. {
  198156. png_debug(1, "in png_set_packswap\n");
  198157. if(png_ptr == NULL) return;
  198158. if (png_ptr->bit_depth < 8)
  198159. png_ptr->transformations |= PNG_PACKSWAP;
  198160. }
  198161. #endif
  198162. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198163. void PNGAPI
  198164. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198165. {
  198166. png_debug(1, "in png_set_shift\n");
  198167. if(png_ptr == NULL) return;
  198168. png_ptr->transformations |= PNG_SHIFT;
  198169. png_ptr->shift = *true_bits;
  198170. }
  198171. #endif
  198172. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198173. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198174. int PNGAPI
  198175. png_set_interlace_handling(png_structp png_ptr)
  198176. {
  198177. png_debug(1, "in png_set_interlace handling\n");
  198178. if (png_ptr && png_ptr->interlaced)
  198179. {
  198180. png_ptr->transformations |= PNG_INTERLACE;
  198181. return (7);
  198182. }
  198183. return (1);
  198184. }
  198185. #endif
  198186. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198187. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198188. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198189. * for 48-bit input data, as well as to avoid problems with some compilers
  198190. * that don't like bytes as parameters.
  198191. */
  198192. void PNGAPI
  198193. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198194. {
  198195. png_debug(1, "in png_set_filler\n");
  198196. if(png_ptr == NULL) return;
  198197. png_ptr->transformations |= PNG_FILLER;
  198198. png_ptr->filler = (png_byte)filler;
  198199. if (filler_loc == PNG_FILLER_AFTER)
  198200. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198201. else
  198202. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198203. /* This should probably go in the "do_read_filler" routine.
  198204. * I attempted to do that in libpng-1.0.1a but that caused problems
  198205. * so I restored it in libpng-1.0.2a
  198206. */
  198207. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198208. {
  198209. png_ptr->usr_channels = 4;
  198210. }
  198211. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198212. * a less-than-8-bit grayscale to GA? */
  198213. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198214. {
  198215. png_ptr->usr_channels = 2;
  198216. }
  198217. }
  198218. #if !defined(PNG_1_0_X)
  198219. /* Added to libpng-1.2.7 */
  198220. void PNGAPI
  198221. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198222. {
  198223. png_debug(1, "in png_set_add_alpha\n");
  198224. if(png_ptr == NULL) return;
  198225. png_set_filler(png_ptr, filler, filler_loc);
  198226. png_ptr->transformations |= PNG_ADD_ALPHA;
  198227. }
  198228. #endif
  198229. #endif
  198230. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198231. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198232. void PNGAPI
  198233. png_set_swap_alpha(png_structp png_ptr)
  198234. {
  198235. png_debug(1, "in png_set_swap_alpha\n");
  198236. if(png_ptr == NULL) return;
  198237. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198238. }
  198239. #endif
  198240. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198241. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198242. void PNGAPI
  198243. png_set_invert_alpha(png_structp png_ptr)
  198244. {
  198245. png_debug(1, "in png_set_invert_alpha\n");
  198246. if(png_ptr == NULL) return;
  198247. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198248. }
  198249. #endif
  198250. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198251. void PNGAPI
  198252. png_set_invert_mono(png_structp png_ptr)
  198253. {
  198254. png_debug(1, "in png_set_invert_mono\n");
  198255. if(png_ptr == NULL) return;
  198256. png_ptr->transformations |= PNG_INVERT_MONO;
  198257. }
  198258. /* invert monochrome grayscale data */
  198259. void /* PRIVATE */
  198260. png_do_invert(png_row_infop row_info, png_bytep row)
  198261. {
  198262. png_debug(1, "in png_do_invert\n");
  198263. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198264. * if (row_info->bit_depth == 1 &&
  198265. */
  198266. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198267. if (row == NULL || row_info == NULL)
  198268. return;
  198269. #endif
  198270. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198271. {
  198272. png_bytep rp = row;
  198273. png_uint_32 i;
  198274. png_uint_32 istop = row_info->rowbytes;
  198275. for (i = 0; i < istop; i++)
  198276. {
  198277. *rp = (png_byte)(~(*rp));
  198278. rp++;
  198279. }
  198280. }
  198281. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198282. row_info->bit_depth == 8)
  198283. {
  198284. png_bytep rp = row;
  198285. png_uint_32 i;
  198286. png_uint_32 istop = row_info->rowbytes;
  198287. for (i = 0; i < istop; i+=2)
  198288. {
  198289. *rp = (png_byte)(~(*rp));
  198290. rp+=2;
  198291. }
  198292. }
  198293. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198294. row_info->bit_depth == 16)
  198295. {
  198296. png_bytep rp = row;
  198297. png_uint_32 i;
  198298. png_uint_32 istop = row_info->rowbytes;
  198299. for (i = 0; i < istop; i+=4)
  198300. {
  198301. *rp = (png_byte)(~(*rp));
  198302. *(rp+1) = (png_byte)(~(*(rp+1)));
  198303. rp+=4;
  198304. }
  198305. }
  198306. }
  198307. #endif
  198308. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198309. /* swaps byte order on 16 bit depth images */
  198310. void /* PRIVATE */
  198311. png_do_swap(png_row_infop row_info, png_bytep row)
  198312. {
  198313. png_debug(1, "in png_do_swap\n");
  198314. if (
  198315. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198316. row != NULL && row_info != NULL &&
  198317. #endif
  198318. row_info->bit_depth == 16)
  198319. {
  198320. png_bytep rp = row;
  198321. png_uint_32 i;
  198322. png_uint_32 istop= row_info->width * row_info->channels;
  198323. for (i = 0; i < istop; i++, rp += 2)
  198324. {
  198325. png_byte t = *rp;
  198326. *rp = *(rp + 1);
  198327. *(rp + 1) = t;
  198328. }
  198329. }
  198330. }
  198331. #endif
  198332. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198333. static PNG_CONST png_byte onebppswaptable[256] = {
  198334. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198335. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198336. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198337. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198338. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198339. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198340. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198341. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198342. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198343. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198344. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198345. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198346. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198347. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198348. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198349. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198350. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198351. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198352. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198353. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198354. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198355. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198356. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198357. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198358. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198359. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198360. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198361. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198362. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198363. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198364. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198365. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198366. };
  198367. static PNG_CONST png_byte twobppswaptable[256] = {
  198368. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198369. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198370. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198371. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198372. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198373. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198374. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198375. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198376. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198377. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198378. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198379. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198380. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198381. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198382. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198383. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198384. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198385. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198386. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198387. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198388. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198389. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198390. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198391. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198392. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198393. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198394. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198395. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198396. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198397. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198398. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198399. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198400. };
  198401. static PNG_CONST png_byte fourbppswaptable[256] = {
  198402. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198403. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198404. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198405. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198406. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198407. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198408. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198409. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198410. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198411. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198412. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198413. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198414. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198415. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198416. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198417. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198418. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198419. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198420. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198421. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198422. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198423. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198424. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198425. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198426. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198427. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198428. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198429. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198430. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198431. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198432. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198433. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198434. };
  198435. /* swaps pixel packing order within bytes */
  198436. void /* PRIVATE */
  198437. png_do_packswap(png_row_infop row_info, png_bytep row)
  198438. {
  198439. png_debug(1, "in png_do_packswap\n");
  198440. if (
  198441. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198442. row != NULL && row_info != NULL &&
  198443. #endif
  198444. row_info->bit_depth < 8)
  198445. {
  198446. png_bytep rp, end, table;
  198447. end = row + row_info->rowbytes;
  198448. if (row_info->bit_depth == 1)
  198449. table = (png_bytep)onebppswaptable;
  198450. else if (row_info->bit_depth == 2)
  198451. table = (png_bytep)twobppswaptable;
  198452. else if (row_info->bit_depth == 4)
  198453. table = (png_bytep)fourbppswaptable;
  198454. else
  198455. return;
  198456. for (rp = row; rp < end; rp++)
  198457. *rp = table[*rp];
  198458. }
  198459. }
  198460. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198461. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198462. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198463. /* remove filler or alpha byte(s) */
  198464. void /* PRIVATE */
  198465. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198466. {
  198467. png_debug(1, "in png_do_strip_filler\n");
  198468. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198469. if (row != NULL && row_info != NULL)
  198470. #endif
  198471. {
  198472. png_bytep sp=row;
  198473. png_bytep dp=row;
  198474. png_uint_32 row_width=row_info->width;
  198475. png_uint_32 i;
  198476. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198477. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198478. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198479. row_info->channels == 4)
  198480. {
  198481. if (row_info->bit_depth == 8)
  198482. {
  198483. /* This converts from RGBX or RGBA to RGB */
  198484. if (flags & PNG_FLAG_FILLER_AFTER)
  198485. {
  198486. dp+=3; sp+=4;
  198487. for (i = 1; i < row_width; i++)
  198488. {
  198489. *dp++ = *sp++;
  198490. *dp++ = *sp++;
  198491. *dp++ = *sp++;
  198492. sp++;
  198493. }
  198494. }
  198495. /* This converts from XRGB or ARGB to RGB */
  198496. else
  198497. {
  198498. for (i = 0; i < row_width; i++)
  198499. {
  198500. sp++;
  198501. *dp++ = *sp++;
  198502. *dp++ = *sp++;
  198503. *dp++ = *sp++;
  198504. }
  198505. }
  198506. row_info->pixel_depth = 24;
  198507. row_info->rowbytes = row_width * 3;
  198508. }
  198509. else /* if (row_info->bit_depth == 16) */
  198510. {
  198511. if (flags & PNG_FLAG_FILLER_AFTER)
  198512. {
  198513. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198514. sp += 8; dp += 6;
  198515. for (i = 1; i < row_width; i++)
  198516. {
  198517. /* This could be (although png_memcpy is probably slower):
  198518. png_memcpy(dp, sp, 6);
  198519. sp += 8;
  198520. dp += 6;
  198521. */
  198522. *dp++ = *sp++;
  198523. *dp++ = *sp++;
  198524. *dp++ = *sp++;
  198525. *dp++ = *sp++;
  198526. *dp++ = *sp++;
  198527. *dp++ = *sp++;
  198528. sp += 2;
  198529. }
  198530. }
  198531. else
  198532. {
  198533. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198534. for (i = 0; i < row_width; i++)
  198535. {
  198536. /* This could be (although png_memcpy is probably slower):
  198537. png_memcpy(dp, sp, 6);
  198538. sp += 8;
  198539. dp += 6;
  198540. */
  198541. sp+=2;
  198542. *dp++ = *sp++;
  198543. *dp++ = *sp++;
  198544. *dp++ = *sp++;
  198545. *dp++ = *sp++;
  198546. *dp++ = *sp++;
  198547. *dp++ = *sp++;
  198548. }
  198549. }
  198550. row_info->pixel_depth = 48;
  198551. row_info->rowbytes = row_width * 6;
  198552. }
  198553. row_info->channels = 3;
  198554. }
  198555. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198556. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198557. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198558. row_info->channels == 2)
  198559. {
  198560. if (row_info->bit_depth == 8)
  198561. {
  198562. /* This converts from GX or GA to G */
  198563. if (flags & PNG_FLAG_FILLER_AFTER)
  198564. {
  198565. for (i = 0; i < row_width; i++)
  198566. {
  198567. *dp++ = *sp++;
  198568. sp++;
  198569. }
  198570. }
  198571. /* This converts from XG or AG to G */
  198572. else
  198573. {
  198574. for (i = 0; i < row_width; i++)
  198575. {
  198576. sp++;
  198577. *dp++ = *sp++;
  198578. }
  198579. }
  198580. row_info->pixel_depth = 8;
  198581. row_info->rowbytes = row_width;
  198582. }
  198583. else /* if (row_info->bit_depth == 16) */
  198584. {
  198585. if (flags & PNG_FLAG_FILLER_AFTER)
  198586. {
  198587. /* This converts from GGXX or GGAA to GG */
  198588. sp += 4; dp += 2;
  198589. for (i = 1; i < row_width; i++)
  198590. {
  198591. *dp++ = *sp++;
  198592. *dp++ = *sp++;
  198593. sp += 2;
  198594. }
  198595. }
  198596. else
  198597. {
  198598. /* This converts from XXGG or AAGG to GG */
  198599. for (i = 0; i < row_width; i++)
  198600. {
  198601. sp += 2;
  198602. *dp++ = *sp++;
  198603. *dp++ = *sp++;
  198604. }
  198605. }
  198606. row_info->pixel_depth = 16;
  198607. row_info->rowbytes = row_width * 2;
  198608. }
  198609. row_info->channels = 1;
  198610. }
  198611. if (flags & PNG_FLAG_STRIP_ALPHA)
  198612. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198613. }
  198614. }
  198615. #endif
  198616. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198617. /* swaps red and blue bytes within a pixel */
  198618. void /* PRIVATE */
  198619. png_do_bgr(png_row_infop row_info, png_bytep row)
  198620. {
  198621. png_debug(1, "in png_do_bgr\n");
  198622. if (
  198623. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198624. row != NULL && row_info != NULL &&
  198625. #endif
  198626. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198627. {
  198628. png_uint_32 row_width = row_info->width;
  198629. if (row_info->bit_depth == 8)
  198630. {
  198631. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198632. {
  198633. png_bytep rp;
  198634. png_uint_32 i;
  198635. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198636. {
  198637. png_byte save = *rp;
  198638. *rp = *(rp + 2);
  198639. *(rp + 2) = save;
  198640. }
  198641. }
  198642. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198643. {
  198644. png_bytep rp;
  198645. png_uint_32 i;
  198646. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198647. {
  198648. png_byte save = *rp;
  198649. *rp = *(rp + 2);
  198650. *(rp + 2) = save;
  198651. }
  198652. }
  198653. }
  198654. else if (row_info->bit_depth == 16)
  198655. {
  198656. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198657. {
  198658. png_bytep rp;
  198659. png_uint_32 i;
  198660. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198661. {
  198662. png_byte save = *rp;
  198663. *rp = *(rp + 4);
  198664. *(rp + 4) = save;
  198665. save = *(rp + 1);
  198666. *(rp + 1) = *(rp + 5);
  198667. *(rp + 5) = save;
  198668. }
  198669. }
  198670. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198671. {
  198672. png_bytep rp;
  198673. png_uint_32 i;
  198674. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198675. {
  198676. png_byte save = *rp;
  198677. *rp = *(rp + 4);
  198678. *(rp + 4) = save;
  198679. save = *(rp + 1);
  198680. *(rp + 1) = *(rp + 5);
  198681. *(rp + 5) = save;
  198682. }
  198683. }
  198684. }
  198685. }
  198686. }
  198687. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198688. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198689. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198690. defined(PNG_LEGACY_SUPPORTED)
  198691. void PNGAPI
  198692. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198693. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198694. {
  198695. png_debug(1, "in png_set_user_transform_info\n");
  198696. if(png_ptr == NULL) return;
  198697. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198698. png_ptr->user_transform_ptr = user_transform_ptr;
  198699. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198700. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198701. #else
  198702. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198703. png_warning(png_ptr,
  198704. "This version of libpng does not support user transform info");
  198705. #endif
  198706. }
  198707. #endif
  198708. /* This function returns a pointer to the user_transform_ptr associated with
  198709. * the user transform functions. The application should free any memory
  198710. * associated with this pointer before png_write_destroy and png_read_destroy
  198711. * are called.
  198712. */
  198713. png_voidp PNGAPI
  198714. png_get_user_transform_ptr(png_structp png_ptr)
  198715. {
  198716. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198717. if (png_ptr == NULL) return (NULL);
  198718. return ((png_voidp)png_ptr->user_transform_ptr);
  198719. #else
  198720. return (NULL);
  198721. #endif
  198722. }
  198723. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198724. /*** End of inlined file: pngtrans.c ***/
  198725. /*** Start of inlined file: pngwio.c ***/
  198726. /* pngwio.c - functions for data output
  198727. *
  198728. * Last changed in libpng 1.2.13 November 13, 2006
  198729. * For conditions of distribution and use, see copyright notice in png.h
  198730. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198731. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198732. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198733. *
  198734. * This file provides a location for all output. Users who need
  198735. * special handling are expected to write functions that have the same
  198736. * arguments as these and perform similar functions, but that possibly
  198737. * use different output methods. Note that you shouldn't change these
  198738. * functions, but rather write replacement functions and then change
  198739. * them at run time with png_set_write_fn(...).
  198740. */
  198741. #define PNG_INTERNAL
  198742. #ifdef PNG_WRITE_SUPPORTED
  198743. /* Write the data to whatever output you are using. The default routine
  198744. writes to a file pointer. Note that this routine sometimes gets called
  198745. with very small lengths, so you should implement some kind of simple
  198746. buffering if you are using unbuffered writes. This should never be asked
  198747. to write more than 64K on a 16 bit machine. */
  198748. void /* PRIVATE */
  198749. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198750. {
  198751. if (png_ptr->write_data_fn != NULL )
  198752. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198753. else
  198754. png_error(png_ptr, "Call to NULL write function");
  198755. }
  198756. #if !defined(PNG_NO_STDIO)
  198757. /* This is the function that does the actual writing of data. If you are
  198758. not writing to a standard C stream, you should create a replacement
  198759. write_data function and use it at run time with png_set_write_fn(), rather
  198760. than changing the library. */
  198761. #ifndef USE_FAR_KEYWORD
  198762. void PNGAPI
  198763. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198764. {
  198765. png_uint_32 check;
  198766. if(png_ptr == NULL) return;
  198767. #if defined(_WIN32_WCE)
  198768. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198769. check = 0;
  198770. #else
  198771. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198772. #endif
  198773. if (check != length)
  198774. png_error(png_ptr, "Write Error");
  198775. }
  198776. #else
  198777. /* this is the model-independent version. Since the standard I/O library
  198778. can't handle far buffers in the medium and small models, we have to copy
  198779. the data.
  198780. */
  198781. #define NEAR_BUF_SIZE 1024
  198782. #define MIN(a,b) (a <= b ? a : b)
  198783. void PNGAPI
  198784. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198785. {
  198786. png_uint_32 check;
  198787. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198788. png_FILE_p io_ptr;
  198789. if(png_ptr == NULL) return;
  198790. /* Check if data really is near. If so, use usual code. */
  198791. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198792. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198793. if ((png_bytep)near_data == data)
  198794. {
  198795. #if defined(_WIN32_WCE)
  198796. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198797. check = 0;
  198798. #else
  198799. check = fwrite(near_data, 1, length, io_ptr);
  198800. #endif
  198801. }
  198802. else
  198803. {
  198804. png_byte buf[NEAR_BUF_SIZE];
  198805. png_size_t written, remaining, err;
  198806. check = 0;
  198807. remaining = length;
  198808. do
  198809. {
  198810. written = MIN(NEAR_BUF_SIZE, remaining);
  198811. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198812. #if defined(_WIN32_WCE)
  198813. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198814. err = 0;
  198815. #else
  198816. err = fwrite(buf, 1, written, io_ptr);
  198817. #endif
  198818. if (err != written)
  198819. break;
  198820. else
  198821. check += err;
  198822. data += written;
  198823. remaining -= written;
  198824. }
  198825. while (remaining != 0);
  198826. }
  198827. if (check != length)
  198828. png_error(png_ptr, "Write Error");
  198829. }
  198830. #endif
  198831. #endif
  198832. /* This function is called to output any data pending writing (normally
  198833. to disk). After png_flush is called, there should be no data pending
  198834. writing in any buffers. */
  198835. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198836. void /* PRIVATE */
  198837. png_flush(png_structp png_ptr)
  198838. {
  198839. if (png_ptr->output_flush_fn != NULL)
  198840. (*(png_ptr->output_flush_fn))(png_ptr);
  198841. }
  198842. #if !defined(PNG_NO_STDIO)
  198843. void PNGAPI
  198844. png_default_flush(png_structp png_ptr)
  198845. {
  198846. #if !defined(_WIN32_WCE)
  198847. png_FILE_p io_ptr;
  198848. #endif
  198849. if(png_ptr == NULL) return;
  198850. #if !defined(_WIN32_WCE)
  198851. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198852. if (io_ptr != NULL)
  198853. fflush(io_ptr);
  198854. #endif
  198855. }
  198856. #endif
  198857. #endif
  198858. /* This function allows the application to supply new output functions for
  198859. libpng if standard C streams aren't being used.
  198860. This function takes as its arguments:
  198861. png_ptr - pointer to a png output data structure
  198862. io_ptr - pointer to user supplied structure containing info about
  198863. the output functions. May be NULL.
  198864. write_data_fn - pointer to a new output function that takes as its
  198865. arguments a pointer to a png_struct, a pointer to
  198866. data to be written, and a 32-bit unsigned int that is
  198867. the number of bytes to be written. The new write
  198868. function should call png_error(png_ptr, "Error msg")
  198869. to exit and output any fatal error messages.
  198870. flush_data_fn - pointer to a new flush function that takes as its
  198871. arguments a pointer to a png_struct. After a call to
  198872. the flush function, there should be no data in any buffers
  198873. or pending transmission. If the output method doesn't do
  198874. any buffering of ouput, a function prototype must still be
  198875. supplied although it doesn't have to do anything. If
  198876. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198877. time, output_flush_fn will be ignored, although it must be
  198878. supplied for compatibility. */
  198879. void PNGAPI
  198880. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198881. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198882. {
  198883. if(png_ptr == NULL) return;
  198884. png_ptr->io_ptr = io_ptr;
  198885. #if !defined(PNG_NO_STDIO)
  198886. if (write_data_fn != NULL)
  198887. png_ptr->write_data_fn = write_data_fn;
  198888. else
  198889. png_ptr->write_data_fn = png_default_write_data;
  198890. #else
  198891. png_ptr->write_data_fn = write_data_fn;
  198892. #endif
  198893. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198894. #if !defined(PNG_NO_STDIO)
  198895. if (output_flush_fn != NULL)
  198896. png_ptr->output_flush_fn = output_flush_fn;
  198897. else
  198898. png_ptr->output_flush_fn = png_default_flush;
  198899. #else
  198900. png_ptr->output_flush_fn = output_flush_fn;
  198901. #endif
  198902. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198903. /* It is an error to read while writing a png file */
  198904. if (png_ptr->read_data_fn != NULL)
  198905. {
  198906. png_ptr->read_data_fn = NULL;
  198907. png_warning(png_ptr,
  198908. "Attempted to set both read_data_fn and write_data_fn in");
  198909. png_warning(png_ptr,
  198910. "the same structure. Resetting read_data_fn to NULL.");
  198911. }
  198912. }
  198913. #if defined(USE_FAR_KEYWORD)
  198914. #if defined(_MSC_VER)
  198915. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198916. {
  198917. void *near_ptr;
  198918. void FAR *far_ptr;
  198919. FP_OFF(near_ptr) = FP_OFF(ptr);
  198920. far_ptr = (void FAR *)near_ptr;
  198921. if(check != 0)
  198922. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198923. png_error(png_ptr,"segment lost in conversion");
  198924. return(near_ptr);
  198925. }
  198926. # else
  198927. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198928. {
  198929. void *near_ptr;
  198930. void FAR *far_ptr;
  198931. near_ptr = (void FAR *)ptr;
  198932. far_ptr = (void FAR *)near_ptr;
  198933. if(check != 0)
  198934. if(far_ptr != ptr)
  198935. png_error(png_ptr,"segment lost in conversion");
  198936. return(near_ptr);
  198937. }
  198938. # endif
  198939. # endif
  198940. #endif /* PNG_WRITE_SUPPORTED */
  198941. /*** End of inlined file: pngwio.c ***/
  198942. /*** Start of inlined file: pngwrite.c ***/
  198943. /* pngwrite.c - general routines to write a PNG file
  198944. *
  198945. * Last changed in libpng 1.2.15 January 5, 2007
  198946. * For conditions of distribution and use, see copyright notice in png.h
  198947. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198948. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198949. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198950. */
  198951. /* get internal access to png.h */
  198952. #define PNG_INTERNAL
  198953. #ifdef PNG_WRITE_SUPPORTED
  198954. /* Writes all the PNG information. This is the suggested way to use the
  198955. * library. If you have a new chunk to add, make a function to write it,
  198956. * and put it in the correct location here. If you want the chunk written
  198957. * after the image data, put it in png_write_end(). I strongly encourage
  198958. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198959. * the chunk, as that will keep the code from breaking if you want to just
  198960. * write a plain PNG file. If you have long comments, I suggest writing
  198961. * them in png_write_end(), and compressing them.
  198962. */
  198963. void PNGAPI
  198964. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198965. {
  198966. png_debug(1, "in png_write_info_before_PLTE\n");
  198967. if (png_ptr == NULL || info_ptr == NULL)
  198968. return;
  198969. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198970. {
  198971. png_write_sig(png_ptr); /* write PNG signature */
  198972. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198973. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198974. {
  198975. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198976. png_ptr->mng_features_permitted=0;
  198977. }
  198978. #endif
  198979. /* write IHDR information. */
  198980. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198981. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198982. info_ptr->filter_type,
  198983. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198984. info_ptr->interlace_type);
  198985. #else
  198986. 0);
  198987. #endif
  198988. /* the rest of these check to see if the valid field has the appropriate
  198989. flag set, and if it does, writes the chunk. */
  198990. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198991. if (info_ptr->valid & PNG_INFO_gAMA)
  198992. {
  198993. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198994. png_write_gAMA(png_ptr, info_ptr->gamma);
  198995. #else
  198996. #ifdef PNG_FIXED_POINT_SUPPORTED
  198997. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198998. # endif
  198999. #endif
  199000. }
  199001. #endif
  199002. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  199003. if (info_ptr->valid & PNG_INFO_sRGB)
  199004. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  199005. #endif
  199006. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  199007. if (info_ptr->valid & PNG_INFO_iCCP)
  199008. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  199009. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  199010. #endif
  199011. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  199012. if (info_ptr->valid & PNG_INFO_sBIT)
  199013. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  199014. #endif
  199015. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  199016. if (info_ptr->valid & PNG_INFO_cHRM)
  199017. {
  199018. #ifdef PNG_FLOATING_POINT_SUPPORTED
  199019. png_write_cHRM(png_ptr,
  199020. info_ptr->x_white, info_ptr->y_white,
  199021. info_ptr->x_red, info_ptr->y_red,
  199022. info_ptr->x_green, info_ptr->y_green,
  199023. info_ptr->x_blue, info_ptr->y_blue);
  199024. #else
  199025. # ifdef PNG_FIXED_POINT_SUPPORTED
  199026. png_write_cHRM_fixed(png_ptr,
  199027. info_ptr->int_x_white, info_ptr->int_y_white,
  199028. info_ptr->int_x_red, info_ptr->int_y_red,
  199029. info_ptr->int_x_green, info_ptr->int_y_green,
  199030. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199031. # endif
  199032. #endif
  199033. }
  199034. #endif
  199035. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199036. if (info_ptr->unknown_chunks_num)
  199037. {
  199038. png_unknown_chunk *up;
  199039. png_debug(5, "writing extra chunks\n");
  199040. for (up = info_ptr->unknown_chunks;
  199041. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199042. up++)
  199043. {
  199044. int keep=png_handle_as_unknown(png_ptr, up->name);
  199045. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199046. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199047. !(up->location & PNG_HAVE_IDAT) &&
  199048. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199049. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199050. {
  199051. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199052. }
  199053. }
  199054. }
  199055. #endif
  199056. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199057. }
  199058. }
  199059. void PNGAPI
  199060. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199061. {
  199062. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199063. int i;
  199064. #endif
  199065. png_debug(1, "in png_write_info\n");
  199066. if (png_ptr == NULL || info_ptr == NULL)
  199067. return;
  199068. png_write_info_before_PLTE(png_ptr, info_ptr);
  199069. if (info_ptr->valid & PNG_INFO_PLTE)
  199070. png_write_PLTE(png_ptr, info_ptr->palette,
  199071. (png_uint_32)info_ptr->num_palette);
  199072. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199073. png_error(png_ptr, "Valid palette required for paletted images");
  199074. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199075. if (info_ptr->valid & PNG_INFO_tRNS)
  199076. {
  199077. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199078. /* invert the alpha channel (in tRNS) */
  199079. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199080. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199081. {
  199082. int j;
  199083. for (j=0; j<(int)info_ptr->num_trans; j++)
  199084. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199085. }
  199086. #endif
  199087. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199088. info_ptr->num_trans, info_ptr->color_type);
  199089. }
  199090. #endif
  199091. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199092. if (info_ptr->valid & PNG_INFO_bKGD)
  199093. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199094. #endif
  199095. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199096. if (info_ptr->valid & PNG_INFO_hIST)
  199097. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199098. #endif
  199099. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199100. if (info_ptr->valid & PNG_INFO_oFFs)
  199101. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199102. info_ptr->offset_unit_type);
  199103. #endif
  199104. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199105. if (info_ptr->valid & PNG_INFO_pCAL)
  199106. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199107. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199108. info_ptr->pcal_units, info_ptr->pcal_params);
  199109. #endif
  199110. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199111. if (info_ptr->valid & PNG_INFO_sCAL)
  199112. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199113. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199114. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199115. #else
  199116. #ifdef PNG_FIXED_POINT_SUPPORTED
  199117. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199118. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199119. #else
  199120. png_warning(png_ptr,
  199121. "png_write_sCAL not supported; sCAL chunk not written.");
  199122. #endif
  199123. #endif
  199124. #endif
  199125. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199126. if (info_ptr->valid & PNG_INFO_pHYs)
  199127. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199128. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199129. #endif
  199130. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199131. if (info_ptr->valid & PNG_INFO_tIME)
  199132. {
  199133. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199134. png_ptr->mode |= PNG_WROTE_tIME;
  199135. }
  199136. #endif
  199137. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199138. if (info_ptr->valid & PNG_INFO_sPLT)
  199139. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199140. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199141. #endif
  199142. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199143. /* Check to see if we need to write text chunks */
  199144. for (i = 0; i < info_ptr->num_text; i++)
  199145. {
  199146. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199147. info_ptr->text[i].compression);
  199148. /* an internationalized chunk? */
  199149. if (info_ptr->text[i].compression > 0)
  199150. {
  199151. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199152. /* write international chunk */
  199153. png_write_iTXt(png_ptr,
  199154. info_ptr->text[i].compression,
  199155. info_ptr->text[i].key,
  199156. info_ptr->text[i].lang,
  199157. info_ptr->text[i].lang_key,
  199158. info_ptr->text[i].text);
  199159. #else
  199160. png_warning(png_ptr, "Unable to write international text");
  199161. #endif
  199162. /* Mark this chunk as written */
  199163. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199164. }
  199165. /* If we want a compressed text chunk */
  199166. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199167. {
  199168. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199169. /* write compressed chunk */
  199170. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199171. info_ptr->text[i].text, 0,
  199172. info_ptr->text[i].compression);
  199173. #else
  199174. png_warning(png_ptr, "Unable to write compressed text");
  199175. #endif
  199176. /* Mark this chunk as written */
  199177. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199178. }
  199179. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199180. {
  199181. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199182. /* write uncompressed chunk */
  199183. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199184. info_ptr->text[i].text,
  199185. 0);
  199186. #else
  199187. png_warning(png_ptr, "Unable to write uncompressed text");
  199188. #endif
  199189. /* Mark this chunk as written */
  199190. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199191. }
  199192. }
  199193. #endif
  199194. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199195. if (info_ptr->unknown_chunks_num)
  199196. {
  199197. png_unknown_chunk *up;
  199198. png_debug(5, "writing extra chunks\n");
  199199. for (up = info_ptr->unknown_chunks;
  199200. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199201. up++)
  199202. {
  199203. int keep=png_handle_as_unknown(png_ptr, up->name);
  199204. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199205. up->location && (up->location & PNG_HAVE_PLTE) &&
  199206. !(up->location & PNG_HAVE_IDAT) &&
  199207. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199208. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199209. {
  199210. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199211. }
  199212. }
  199213. }
  199214. #endif
  199215. }
  199216. /* Writes the end of the PNG file. If you don't want to write comments or
  199217. * time information, you can pass NULL for info. If you already wrote these
  199218. * in png_write_info(), do not write them again here. If you have long
  199219. * comments, I suggest writing them here, and compressing them.
  199220. */
  199221. void PNGAPI
  199222. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199223. {
  199224. png_debug(1, "in png_write_end\n");
  199225. if (png_ptr == NULL)
  199226. return;
  199227. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199228. png_error(png_ptr, "No IDATs written into file");
  199229. /* see if user wants us to write information chunks */
  199230. if (info_ptr != NULL)
  199231. {
  199232. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199233. int i; /* local index variable */
  199234. #endif
  199235. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199236. /* check to see if user has supplied a time chunk */
  199237. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199238. !(png_ptr->mode & PNG_WROTE_tIME))
  199239. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199240. #endif
  199241. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199242. /* loop through comment chunks */
  199243. for (i = 0; i < info_ptr->num_text; i++)
  199244. {
  199245. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199246. info_ptr->text[i].compression);
  199247. /* an internationalized chunk? */
  199248. if (info_ptr->text[i].compression > 0)
  199249. {
  199250. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199251. /* write international chunk */
  199252. png_write_iTXt(png_ptr,
  199253. info_ptr->text[i].compression,
  199254. info_ptr->text[i].key,
  199255. info_ptr->text[i].lang,
  199256. info_ptr->text[i].lang_key,
  199257. info_ptr->text[i].text);
  199258. #else
  199259. png_warning(png_ptr, "Unable to write international text");
  199260. #endif
  199261. /* Mark this chunk as written */
  199262. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199263. }
  199264. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199265. {
  199266. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199267. /* write compressed chunk */
  199268. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199269. info_ptr->text[i].text, 0,
  199270. info_ptr->text[i].compression);
  199271. #else
  199272. png_warning(png_ptr, "Unable to write compressed text");
  199273. #endif
  199274. /* Mark this chunk as written */
  199275. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199276. }
  199277. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199278. {
  199279. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199280. /* write uncompressed chunk */
  199281. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199282. info_ptr->text[i].text, 0);
  199283. #else
  199284. png_warning(png_ptr, "Unable to write uncompressed text");
  199285. #endif
  199286. /* Mark this chunk as written */
  199287. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199288. }
  199289. }
  199290. #endif
  199291. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199292. if (info_ptr->unknown_chunks_num)
  199293. {
  199294. png_unknown_chunk *up;
  199295. png_debug(5, "writing extra chunks\n");
  199296. for (up = info_ptr->unknown_chunks;
  199297. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199298. up++)
  199299. {
  199300. int keep=png_handle_as_unknown(png_ptr, up->name);
  199301. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199302. up->location && (up->location & PNG_AFTER_IDAT) &&
  199303. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199304. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199305. {
  199306. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199307. }
  199308. }
  199309. }
  199310. #endif
  199311. }
  199312. png_ptr->mode |= PNG_AFTER_IDAT;
  199313. /* write end of PNG file */
  199314. png_write_IEND(png_ptr);
  199315. }
  199316. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199317. #if !defined(_WIN32_WCE)
  199318. /* "time.h" functions are not supported on WindowsCE */
  199319. void PNGAPI
  199320. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199321. {
  199322. png_debug(1, "in png_convert_from_struct_tm\n");
  199323. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199324. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199325. ptime->day = (png_byte)ttime->tm_mday;
  199326. ptime->hour = (png_byte)ttime->tm_hour;
  199327. ptime->minute = (png_byte)ttime->tm_min;
  199328. ptime->second = (png_byte)ttime->tm_sec;
  199329. }
  199330. void PNGAPI
  199331. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199332. {
  199333. struct tm *tbuf;
  199334. png_debug(1, "in png_convert_from_time_t\n");
  199335. tbuf = gmtime(&ttime);
  199336. png_convert_from_struct_tm(ptime, tbuf);
  199337. }
  199338. #endif
  199339. #endif
  199340. /* Initialize png_ptr structure, and allocate any memory needed */
  199341. png_structp PNGAPI
  199342. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199343. png_error_ptr error_fn, png_error_ptr warn_fn)
  199344. {
  199345. #ifdef PNG_USER_MEM_SUPPORTED
  199346. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199347. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199348. }
  199349. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199350. png_structp PNGAPI
  199351. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199352. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199353. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199354. {
  199355. #endif /* PNG_USER_MEM_SUPPORTED */
  199356. png_structp png_ptr;
  199357. #ifdef PNG_SETJMP_SUPPORTED
  199358. #ifdef USE_FAR_KEYWORD
  199359. jmp_buf jmpbuf;
  199360. #endif
  199361. #endif
  199362. int i;
  199363. png_debug(1, "in png_create_write_struct\n");
  199364. #ifdef PNG_USER_MEM_SUPPORTED
  199365. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199366. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199367. #else
  199368. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199369. #endif /* PNG_USER_MEM_SUPPORTED */
  199370. if (png_ptr == NULL)
  199371. return (NULL);
  199372. /* added at libpng-1.2.6 */
  199373. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199374. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199375. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199376. #endif
  199377. #ifdef PNG_SETJMP_SUPPORTED
  199378. #ifdef USE_FAR_KEYWORD
  199379. if (setjmp(jmpbuf))
  199380. #else
  199381. if (setjmp(png_ptr->jmpbuf))
  199382. #endif
  199383. {
  199384. png_free(png_ptr, png_ptr->zbuf);
  199385. png_ptr->zbuf=NULL;
  199386. png_destroy_struct(png_ptr);
  199387. return (NULL);
  199388. }
  199389. #ifdef USE_FAR_KEYWORD
  199390. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199391. #endif
  199392. #endif
  199393. #ifdef PNG_USER_MEM_SUPPORTED
  199394. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199395. #endif /* PNG_USER_MEM_SUPPORTED */
  199396. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199397. i=0;
  199398. do
  199399. {
  199400. if(user_png_ver[i] != png_libpng_ver[i])
  199401. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199402. } while (png_libpng_ver[i++]);
  199403. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199404. {
  199405. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199406. * we must recompile any applications that use any older library version.
  199407. * For versions after libpng 1.0, we will be compatible, so we need
  199408. * only check the first digit.
  199409. */
  199410. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199411. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199412. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199413. {
  199414. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199415. char msg[80];
  199416. if (user_png_ver)
  199417. {
  199418. png_snprintf(msg, 80,
  199419. "Application was compiled with png.h from libpng-%.20s",
  199420. user_png_ver);
  199421. png_warning(png_ptr, msg);
  199422. }
  199423. png_snprintf(msg, 80,
  199424. "Application is running with png.c from libpng-%.20s",
  199425. png_libpng_ver);
  199426. png_warning(png_ptr, msg);
  199427. #endif
  199428. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199429. png_ptr->flags=0;
  199430. #endif
  199431. png_error(png_ptr,
  199432. "Incompatible libpng version in application and library");
  199433. }
  199434. }
  199435. /* initialize zbuf - compression buffer */
  199436. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199437. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199438. (png_uint_32)png_ptr->zbuf_size);
  199439. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199440. png_flush_ptr_NULL);
  199441. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199442. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199443. 1, png_doublep_NULL, png_doublep_NULL);
  199444. #endif
  199445. #ifdef PNG_SETJMP_SUPPORTED
  199446. /* Applications that neglect to set up their own setjmp() and then encounter
  199447. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199448. abort instead of returning. */
  199449. #ifdef USE_FAR_KEYWORD
  199450. if (setjmp(jmpbuf))
  199451. PNG_ABORT();
  199452. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199453. #else
  199454. if (setjmp(png_ptr->jmpbuf))
  199455. PNG_ABORT();
  199456. #endif
  199457. #endif
  199458. return (png_ptr);
  199459. }
  199460. /* Initialize png_ptr structure, and allocate any memory needed */
  199461. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199462. /* Deprecated. */
  199463. #undef png_write_init
  199464. void PNGAPI
  199465. png_write_init(png_structp png_ptr)
  199466. {
  199467. /* We only come here via pre-1.0.7-compiled applications */
  199468. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199469. }
  199470. void PNGAPI
  199471. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199472. png_size_t png_struct_size, png_size_t png_info_size)
  199473. {
  199474. /* We only come here via pre-1.0.12-compiled applications */
  199475. if(png_ptr == NULL) return;
  199476. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199477. if(png_sizeof(png_struct) > png_struct_size ||
  199478. png_sizeof(png_info) > png_info_size)
  199479. {
  199480. char msg[80];
  199481. png_ptr->warning_fn=NULL;
  199482. if (user_png_ver)
  199483. {
  199484. png_snprintf(msg, 80,
  199485. "Application was compiled with png.h from libpng-%.20s",
  199486. user_png_ver);
  199487. png_warning(png_ptr, msg);
  199488. }
  199489. png_snprintf(msg, 80,
  199490. "Application is running with png.c from libpng-%.20s",
  199491. png_libpng_ver);
  199492. png_warning(png_ptr, msg);
  199493. }
  199494. #endif
  199495. if(png_sizeof(png_struct) > png_struct_size)
  199496. {
  199497. png_ptr->error_fn=NULL;
  199498. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199499. png_ptr->flags=0;
  199500. #endif
  199501. png_error(png_ptr,
  199502. "The png struct allocated by the application for writing is too small.");
  199503. }
  199504. if(png_sizeof(png_info) > png_info_size)
  199505. {
  199506. png_ptr->error_fn=NULL;
  199507. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199508. png_ptr->flags=0;
  199509. #endif
  199510. png_error(png_ptr,
  199511. "The info struct allocated by the application for writing is too small.");
  199512. }
  199513. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199514. }
  199515. #endif /* PNG_1_0_X || PNG_1_2_X */
  199516. void PNGAPI
  199517. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199518. png_size_t png_struct_size)
  199519. {
  199520. png_structp png_ptr=*ptr_ptr;
  199521. #ifdef PNG_SETJMP_SUPPORTED
  199522. jmp_buf tmp_jmp; /* to save current jump buffer */
  199523. #endif
  199524. int i = 0;
  199525. if (png_ptr == NULL)
  199526. return;
  199527. do
  199528. {
  199529. if (user_png_ver[i] != png_libpng_ver[i])
  199530. {
  199531. #ifdef PNG_LEGACY_SUPPORTED
  199532. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199533. #else
  199534. png_ptr->warning_fn=NULL;
  199535. png_warning(png_ptr,
  199536. "Application uses deprecated png_write_init() and should be recompiled.");
  199537. break;
  199538. #endif
  199539. }
  199540. } while (png_libpng_ver[i++]);
  199541. png_debug(1, "in png_write_init_3\n");
  199542. #ifdef PNG_SETJMP_SUPPORTED
  199543. /* save jump buffer and error functions */
  199544. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199545. #endif
  199546. if (png_sizeof(png_struct) > png_struct_size)
  199547. {
  199548. png_destroy_struct(png_ptr);
  199549. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199550. *ptr_ptr = png_ptr;
  199551. }
  199552. /* reset all variables to 0 */
  199553. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199554. /* added at libpng-1.2.6 */
  199555. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199556. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199557. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199558. #endif
  199559. #ifdef PNG_SETJMP_SUPPORTED
  199560. /* restore jump buffer */
  199561. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199562. #endif
  199563. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199564. png_flush_ptr_NULL);
  199565. /* initialize zbuf - compression buffer */
  199566. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199567. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199568. (png_uint_32)png_ptr->zbuf_size);
  199569. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199570. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199571. 1, png_doublep_NULL, png_doublep_NULL);
  199572. #endif
  199573. }
  199574. /* Write a few rows of image data. If the image is interlaced,
  199575. * either you will have to write the 7 sub images, or, if you
  199576. * have called png_set_interlace_handling(), you will have to
  199577. * "write" the image seven times.
  199578. */
  199579. void PNGAPI
  199580. png_write_rows(png_structp png_ptr, png_bytepp row,
  199581. png_uint_32 num_rows)
  199582. {
  199583. png_uint_32 i; /* row counter */
  199584. png_bytepp rp; /* row pointer */
  199585. png_debug(1, "in png_write_rows\n");
  199586. if (png_ptr == NULL)
  199587. return;
  199588. /* loop through the rows */
  199589. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199590. {
  199591. png_write_row(png_ptr, *rp);
  199592. }
  199593. }
  199594. /* Write the image. You only need to call this function once, even
  199595. * if you are writing an interlaced image.
  199596. */
  199597. void PNGAPI
  199598. png_write_image(png_structp png_ptr, png_bytepp image)
  199599. {
  199600. png_uint_32 i; /* row index */
  199601. int pass, num_pass; /* pass variables */
  199602. png_bytepp rp; /* points to current row */
  199603. if (png_ptr == NULL)
  199604. return;
  199605. png_debug(1, "in png_write_image\n");
  199606. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199607. /* intialize interlace handling. If image is not interlaced,
  199608. this will set pass to 1 */
  199609. num_pass = png_set_interlace_handling(png_ptr);
  199610. #else
  199611. num_pass = 1;
  199612. #endif
  199613. /* loop through passes */
  199614. for (pass = 0; pass < num_pass; pass++)
  199615. {
  199616. /* loop through image */
  199617. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199618. {
  199619. png_write_row(png_ptr, *rp);
  199620. }
  199621. }
  199622. }
  199623. /* called by user to write a row of image data */
  199624. void PNGAPI
  199625. png_write_row(png_structp png_ptr, png_bytep row)
  199626. {
  199627. if (png_ptr == NULL)
  199628. return;
  199629. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199630. png_ptr->row_number, png_ptr->pass);
  199631. /* initialize transformations and other stuff if first time */
  199632. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199633. {
  199634. /* make sure we wrote the header info */
  199635. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199636. png_error(png_ptr,
  199637. "png_write_info was never called before png_write_row.");
  199638. /* check for transforms that have been set but were defined out */
  199639. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199640. if (png_ptr->transformations & PNG_INVERT_MONO)
  199641. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199642. #endif
  199643. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199644. if (png_ptr->transformations & PNG_FILLER)
  199645. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199646. #endif
  199647. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199648. if (png_ptr->transformations & PNG_PACKSWAP)
  199649. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199650. #endif
  199651. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199652. if (png_ptr->transformations & PNG_PACK)
  199653. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199654. #endif
  199655. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199656. if (png_ptr->transformations & PNG_SHIFT)
  199657. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199658. #endif
  199659. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199660. if (png_ptr->transformations & PNG_BGR)
  199661. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199662. #endif
  199663. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199664. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199665. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199666. #endif
  199667. png_write_start_row(png_ptr);
  199668. }
  199669. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199670. /* if interlaced and not interested in row, return */
  199671. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199672. {
  199673. switch (png_ptr->pass)
  199674. {
  199675. case 0:
  199676. if (png_ptr->row_number & 0x07)
  199677. {
  199678. png_write_finish_row(png_ptr);
  199679. return;
  199680. }
  199681. break;
  199682. case 1:
  199683. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199684. {
  199685. png_write_finish_row(png_ptr);
  199686. return;
  199687. }
  199688. break;
  199689. case 2:
  199690. if ((png_ptr->row_number & 0x07) != 4)
  199691. {
  199692. png_write_finish_row(png_ptr);
  199693. return;
  199694. }
  199695. break;
  199696. case 3:
  199697. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199698. {
  199699. png_write_finish_row(png_ptr);
  199700. return;
  199701. }
  199702. break;
  199703. case 4:
  199704. if ((png_ptr->row_number & 0x03) != 2)
  199705. {
  199706. png_write_finish_row(png_ptr);
  199707. return;
  199708. }
  199709. break;
  199710. case 5:
  199711. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199712. {
  199713. png_write_finish_row(png_ptr);
  199714. return;
  199715. }
  199716. break;
  199717. case 6:
  199718. if (!(png_ptr->row_number & 0x01))
  199719. {
  199720. png_write_finish_row(png_ptr);
  199721. return;
  199722. }
  199723. break;
  199724. }
  199725. }
  199726. #endif
  199727. /* set up row info for transformations */
  199728. png_ptr->row_info.color_type = png_ptr->color_type;
  199729. png_ptr->row_info.width = png_ptr->usr_width;
  199730. png_ptr->row_info.channels = png_ptr->usr_channels;
  199731. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199732. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199733. png_ptr->row_info.channels);
  199734. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199735. png_ptr->row_info.width);
  199736. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199737. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199738. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199739. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199740. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199741. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199742. /* Copy user's row into buffer, leaving room for filter byte. */
  199743. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199744. png_ptr->row_info.rowbytes);
  199745. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199746. /* handle interlacing */
  199747. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199748. (png_ptr->transformations & PNG_INTERLACE))
  199749. {
  199750. png_do_write_interlace(&(png_ptr->row_info),
  199751. png_ptr->row_buf + 1, png_ptr->pass);
  199752. /* this should always get caught above, but still ... */
  199753. if (!(png_ptr->row_info.width))
  199754. {
  199755. png_write_finish_row(png_ptr);
  199756. return;
  199757. }
  199758. }
  199759. #endif
  199760. /* handle other transformations */
  199761. if (png_ptr->transformations)
  199762. png_do_write_transformations(png_ptr);
  199763. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199764. /* Write filter_method 64 (intrapixel differencing) only if
  199765. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199766. * 2. Libpng did not write a PNG signature (this filter_method is only
  199767. * used in PNG datastreams that are embedded in MNG datastreams) and
  199768. * 3. The application called png_permit_mng_features with a mask that
  199769. * included PNG_FLAG_MNG_FILTER_64 and
  199770. * 4. The filter_method is 64 and
  199771. * 5. The color_type is RGB or RGBA
  199772. */
  199773. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199774. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199775. {
  199776. /* Intrapixel differencing */
  199777. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199778. }
  199779. #endif
  199780. /* Find a filter if necessary, filter the row and write it out. */
  199781. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199782. if (png_ptr->write_row_fn != NULL)
  199783. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199784. }
  199785. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199786. /* Set the automatic flush interval or 0 to turn flushing off */
  199787. void PNGAPI
  199788. png_set_flush(png_structp png_ptr, int nrows)
  199789. {
  199790. png_debug(1, "in png_set_flush\n");
  199791. if (png_ptr == NULL)
  199792. return;
  199793. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199794. }
  199795. /* flush the current output buffers now */
  199796. void PNGAPI
  199797. png_write_flush(png_structp png_ptr)
  199798. {
  199799. int wrote_IDAT;
  199800. png_debug(1, "in png_write_flush\n");
  199801. if (png_ptr == NULL)
  199802. return;
  199803. /* We have already written out all of the data */
  199804. if (png_ptr->row_number >= png_ptr->num_rows)
  199805. return;
  199806. do
  199807. {
  199808. int ret;
  199809. /* compress the data */
  199810. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199811. wrote_IDAT = 0;
  199812. /* check for compression errors */
  199813. if (ret != Z_OK)
  199814. {
  199815. if (png_ptr->zstream.msg != NULL)
  199816. png_error(png_ptr, png_ptr->zstream.msg);
  199817. else
  199818. png_error(png_ptr, "zlib error");
  199819. }
  199820. if (!(png_ptr->zstream.avail_out))
  199821. {
  199822. /* write the IDAT and reset the zlib output buffer */
  199823. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199824. png_ptr->zbuf_size);
  199825. png_ptr->zstream.next_out = png_ptr->zbuf;
  199826. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199827. wrote_IDAT = 1;
  199828. }
  199829. } while(wrote_IDAT == 1);
  199830. /* If there is any data left to be output, write it into a new IDAT */
  199831. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199832. {
  199833. /* write the IDAT and reset the zlib output buffer */
  199834. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199835. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199836. png_ptr->zstream.next_out = png_ptr->zbuf;
  199837. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199838. }
  199839. png_ptr->flush_rows = 0;
  199840. png_flush(png_ptr);
  199841. }
  199842. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199843. /* free all memory used by the write */
  199844. void PNGAPI
  199845. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199846. {
  199847. png_structp png_ptr = NULL;
  199848. png_infop info_ptr = NULL;
  199849. #ifdef PNG_USER_MEM_SUPPORTED
  199850. png_free_ptr free_fn = NULL;
  199851. png_voidp mem_ptr = NULL;
  199852. #endif
  199853. png_debug(1, "in png_destroy_write_struct\n");
  199854. if (png_ptr_ptr != NULL)
  199855. {
  199856. png_ptr = *png_ptr_ptr;
  199857. #ifdef PNG_USER_MEM_SUPPORTED
  199858. free_fn = png_ptr->free_fn;
  199859. mem_ptr = png_ptr->mem_ptr;
  199860. #endif
  199861. }
  199862. if (info_ptr_ptr != NULL)
  199863. info_ptr = *info_ptr_ptr;
  199864. if (info_ptr != NULL)
  199865. {
  199866. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199867. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199868. if (png_ptr->num_chunk_list)
  199869. {
  199870. png_free(png_ptr, png_ptr->chunk_list);
  199871. png_ptr->chunk_list=NULL;
  199872. png_ptr->num_chunk_list=0;
  199873. }
  199874. #endif
  199875. #ifdef PNG_USER_MEM_SUPPORTED
  199876. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199877. (png_voidp)mem_ptr);
  199878. #else
  199879. png_destroy_struct((png_voidp)info_ptr);
  199880. #endif
  199881. *info_ptr_ptr = NULL;
  199882. }
  199883. if (png_ptr != NULL)
  199884. {
  199885. png_write_destroy(png_ptr);
  199886. #ifdef PNG_USER_MEM_SUPPORTED
  199887. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199888. (png_voidp)mem_ptr);
  199889. #else
  199890. png_destroy_struct((png_voidp)png_ptr);
  199891. #endif
  199892. *png_ptr_ptr = NULL;
  199893. }
  199894. }
  199895. /* Free any memory used in png_ptr struct (old method) */
  199896. void /* PRIVATE */
  199897. png_write_destroy(png_structp png_ptr)
  199898. {
  199899. #ifdef PNG_SETJMP_SUPPORTED
  199900. jmp_buf tmp_jmp; /* save jump buffer */
  199901. #endif
  199902. png_error_ptr error_fn;
  199903. png_error_ptr warning_fn;
  199904. png_voidp error_ptr;
  199905. #ifdef PNG_USER_MEM_SUPPORTED
  199906. png_free_ptr free_fn;
  199907. #endif
  199908. png_debug(1, "in png_write_destroy\n");
  199909. /* free any memory zlib uses */
  199910. deflateEnd(&png_ptr->zstream);
  199911. /* free our memory. png_free checks NULL for us. */
  199912. png_free(png_ptr, png_ptr->zbuf);
  199913. png_free(png_ptr, png_ptr->row_buf);
  199914. png_free(png_ptr, png_ptr->prev_row);
  199915. png_free(png_ptr, png_ptr->sub_row);
  199916. png_free(png_ptr, png_ptr->up_row);
  199917. png_free(png_ptr, png_ptr->avg_row);
  199918. png_free(png_ptr, png_ptr->paeth_row);
  199919. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199920. png_free(png_ptr, png_ptr->time_buffer);
  199921. #endif
  199922. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199923. png_free(png_ptr, png_ptr->prev_filters);
  199924. png_free(png_ptr, png_ptr->filter_weights);
  199925. png_free(png_ptr, png_ptr->inv_filter_weights);
  199926. png_free(png_ptr, png_ptr->filter_costs);
  199927. png_free(png_ptr, png_ptr->inv_filter_costs);
  199928. #endif
  199929. #ifdef PNG_SETJMP_SUPPORTED
  199930. /* reset structure */
  199931. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199932. #endif
  199933. error_fn = png_ptr->error_fn;
  199934. warning_fn = png_ptr->warning_fn;
  199935. error_ptr = png_ptr->error_ptr;
  199936. #ifdef PNG_USER_MEM_SUPPORTED
  199937. free_fn = png_ptr->free_fn;
  199938. #endif
  199939. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199940. png_ptr->error_fn = error_fn;
  199941. png_ptr->warning_fn = warning_fn;
  199942. png_ptr->error_ptr = error_ptr;
  199943. #ifdef PNG_USER_MEM_SUPPORTED
  199944. png_ptr->free_fn = free_fn;
  199945. #endif
  199946. #ifdef PNG_SETJMP_SUPPORTED
  199947. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199948. #endif
  199949. }
  199950. /* Allow the application to select one or more row filters to use. */
  199951. void PNGAPI
  199952. png_set_filter(png_structp png_ptr, int method, int filters)
  199953. {
  199954. png_debug(1, "in png_set_filter\n");
  199955. if (png_ptr == NULL)
  199956. return;
  199957. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199958. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199959. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199960. method = PNG_FILTER_TYPE_BASE;
  199961. #endif
  199962. if (method == PNG_FILTER_TYPE_BASE)
  199963. {
  199964. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199965. {
  199966. #ifndef PNG_NO_WRITE_FILTER
  199967. case 5:
  199968. case 6:
  199969. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199970. #endif /* PNG_NO_WRITE_FILTER */
  199971. case PNG_FILTER_VALUE_NONE:
  199972. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199973. #ifndef PNG_NO_WRITE_FILTER
  199974. case PNG_FILTER_VALUE_SUB:
  199975. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199976. case PNG_FILTER_VALUE_UP:
  199977. png_ptr->do_filter=PNG_FILTER_UP; break;
  199978. case PNG_FILTER_VALUE_AVG:
  199979. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199980. case PNG_FILTER_VALUE_PAETH:
  199981. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199982. default: png_ptr->do_filter = (png_byte)filters; break;
  199983. #else
  199984. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199985. #endif /* PNG_NO_WRITE_FILTER */
  199986. }
  199987. /* If we have allocated the row_buf, this means we have already started
  199988. * with the image and we should have allocated all of the filter buffers
  199989. * that have been selected. If prev_row isn't already allocated, then
  199990. * it is too late to start using the filters that need it, since we
  199991. * will be missing the data in the previous row. If an application
  199992. * wants to start and stop using particular filters during compression,
  199993. * it should start out with all of the filters, and then add and
  199994. * remove them after the start of compression.
  199995. */
  199996. if (png_ptr->row_buf != NULL)
  199997. {
  199998. #ifndef PNG_NO_WRITE_FILTER
  199999. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  200000. {
  200001. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  200002. (png_ptr->rowbytes + 1));
  200003. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  200004. }
  200005. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  200006. {
  200007. if (png_ptr->prev_row == NULL)
  200008. {
  200009. png_warning(png_ptr, "Can't add Up filter after starting");
  200010. png_ptr->do_filter &= ~PNG_FILTER_UP;
  200011. }
  200012. else
  200013. {
  200014. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  200015. (png_ptr->rowbytes + 1));
  200016. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  200017. }
  200018. }
  200019. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  200020. {
  200021. if (png_ptr->prev_row == NULL)
  200022. {
  200023. png_warning(png_ptr, "Can't add Average filter after starting");
  200024. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200025. }
  200026. else
  200027. {
  200028. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200029. (png_ptr->rowbytes + 1));
  200030. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200031. }
  200032. }
  200033. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200034. png_ptr->paeth_row == NULL)
  200035. {
  200036. if (png_ptr->prev_row == NULL)
  200037. {
  200038. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200039. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200040. }
  200041. else
  200042. {
  200043. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200044. (png_ptr->rowbytes + 1));
  200045. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200046. }
  200047. }
  200048. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200049. #endif /* PNG_NO_WRITE_FILTER */
  200050. png_ptr->do_filter = PNG_FILTER_NONE;
  200051. }
  200052. }
  200053. else
  200054. png_error(png_ptr, "Unknown custom filter method");
  200055. }
  200056. /* This allows us to influence the way in which libpng chooses the "best"
  200057. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200058. * differences metric is relatively fast and effective, there is some
  200059. * question as to whether it can be improved upon by trying to keep the
  200060. * filtered data going to zlib more consistent, hopefully resulting in
  200061. * better compression.
  200062. */
  200063. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200064. void PNGAPI
  200065. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200066. int num_weights, png_doublep filter_weights,
  200067. png_doublep filter_costs)
  200068. {
  200069. int i;
  200070. png_debug(1, "in png_set_filter_heuristics\n");
  200071. if (png_ptr == NULL)
  200072. return;
  200073. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200074. {
  200075. png_warning(png_ptr, "Unknown filter heuristic method");
  200076. return;
  200077. }
  200078. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200079. {
  200080. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200081. }
  200082. if (num_weights < 0 || filter_weights == NULL ||
  200083. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200084. {
  200085. num_weights = 0;
  200086. }
  200087. png_ptr->num_prev_filters = (png_byte)num_weights;
  200088. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200089. if (num_weights > 0)
  200090. {
  200091. if (png_ptr->prev_filters == NULL)
  200092. {
  200093. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200094. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200095. /* To make sure that the weighting starts out fairly */
  200096. for (i = 0; i < num_weights; i++)
  200097. {
  200098. png_ptr->prev_filters[i] = 255;
  200099. }
  200100. }
  200101. if (png_ptr->filter_weights == NULL)
  200102. {
  200103. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200104. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200105. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200106. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200107. for (i = 0; i < num_weights; i++)
  200108. {
  200109. png_ptr->inv_filter_weights[i] =
  200110. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200111. }
  200112. }
  200113. for (i = 0; i < num_weights; i++)
  200114. {
  200115. if (filter_weights[i] < 0.0)
  200116. {
  200117. png_ptr->inv_filter_weights[i] =
  200118. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200119. }
  200120. else
  200121. {
  200122. png_ptr->inv_filter_weights[i] =
  200123. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200124. png_ptr->filter_weights[i] =
  200125. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200126. }
  200127. }
  200128. }
  200129. /* If, in the future, there are other filter methods, this would
  200130. * need to be based on png_ptr->filter.
  200131. */
  200132. if (png_ptr->filter_costs == NULL)
  200133. {
  200134. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200135. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200136. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200137. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200138. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200139. {
  200140. png_ptr->inv_filter_costs[i] =
  200141. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200142. }
  200143. }
  200144. /* Here is where we set the relative costs of the different filters. We
  200145. * should take the desired compression level into account when setting
  200146. * the costs, so that Paeth, for instance, has a high relative cost at low
  200147. * compression levels, while it has a lower relative cost at higher
  200148. * compression settings. The filter types are in order of increasing
  200149. * relative cost, so it would be possible to do this with an algorithm.
  200150. */
  200151. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200152. {
  200153. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200154. {
  200155. png_ptr->inv_filter_costs[i] =
  200156. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200157. }
  200158. else if (filter_costs[i] >= 1.0)
  200159. {
  200160. png_ptr->inv_filter_costs[i] =
  200161. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200162. png_ptr->filter_costs[i] =
  200163. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200164. }
  200165. }
  200166. }
  200167. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200168. void PNGAPI
  200169. png_set_compression_level(png_structp png_ptr, int level)
  200170. {
  200171. png_debug(1, "in png_set_compression_level\n");
  200172. if (png_ptr == NULL)
  200173. return;
  200174. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200175. png_ptr->zlib_level = level;
  200176. }
  200177. void PNGAPI
  200178. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200179. {
  200180. png_debug(1, "in png_set_compression_mem_level\n");
  200181. if (png_ptr == NULL)
  200182. return;
  200183. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200184. png_ptr->zlib_mem_level = mem_level;
  200185. }
  200186. void PNGAPI
  200187. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200188. {
  200189. png_debug(1, "in png_set_compression_strategy\n");
  200190. if (png_ptr == NULL)
  200191. return;
  200192. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200193. png_ptr->zlib_strategy = strategy;
  200194. }
  200195. void PNGAPI
  200196. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200197. {
  200198. if (png_ptr == NULL)
  200199. return;
  200200. if (window_bits > 15)
  200201. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200202. else if (window_bits < 8)
  200203. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200204. #ifndef WBITS_8_OK
  200205. /* avoid libpng bug with 256-byte windows */
  200206. if (window_bits == 8)
  200207. {
  200208. png_warning(png_ptr, "Compression window is being reset to 512");
  200209. window_bits=9;
  200210. }
  200211. #endif
  200212. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200213. png_ptr->zlib_window_bits = window_bits;
  200214. }
  200215. void PNGAPI
  200216. png_set_compression_method(png_structp png_ptr, int method)
  200217. {
  200218. png_debug(1, "in png_set_compression_method\n");
  200219. if (png_ptr == NULL)
  200220. return;
  200221. if (method != 8)
  200222. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200223. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200224. png_ptr->zlib_method = method;
  200225. }
  200226. void PNGAPI
  200227. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200228. {
  200229. if (png_ptr == NULL)
  200230. return;
  200231. png_ptr->write_row_fn = write_row_fn;
  200232. }
  200233. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200234. void PNGAPI
  200235. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200236. write_user_transform_fn)
  200237. {
  200238. png_debug(1, "in png_set_write_user_transform_fn\n");
  200239. if (png_ptr == NULL)
  200240. return;
  200241. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200242. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200243. }
  200244. #endif
  200245. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200246. void PNGAPI
  200247. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200248. int transforms, voidp params)
  200249. {
  200250. if (png_ptr == NULL || info_ptr == NULL)
  200251. return;
  200252. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200253. /* invert the alpha channel from opacity to transparency */
  200254. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200255. png_set_invert_alpha(png_ptr);
  200256. #endif
  200257. /* Write the file header information. */
  200258. png_write_info(png_ptr, info_ptr);
  200259. /* ------ these transformations don't touch the info structure ------- */
  200260. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200261. /* invert monochrome pixels */
  200262. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200263. png_set_invert_mono(png_ptr);
  200264. #endif
  200265. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200266. /* Shift the pixels up to a legal bit depth and fill in
  200267. * as appropriate to correctly scale the image.
  200268. */
  200269. if ((transforms & PNG_TRANSFORM_SHIFT)
  200270. && (info_ptr->valid & PNG_INFO_sBIT))
  200271. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200272. #endif
  200273. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200274. /* pack pixels into bytes */
  200275. if (transforms & PNG_TRANSFORM_PACKING)
  200276. png_set_packing(png_ptr);
  200277. #endif
  200278. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200279. /* swap location of alpha bytes from ARGB to RGBA */
  200280. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200281. png_set_swap_alpha(png_ptr);
  200282. #endif
  200283. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200284. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200285. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200286. */
  200287. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200288. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200289. #endif
  200290. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200291. /* flip BGR pixels to RGB */
  200292. if (transforms & PNG_TRANSFORM_BGR)
  200293. png_set_bgr(png_ptr);
  200294. #endif
  200295. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200296. /* swap bytes of 16-bit files to most significant byte first */
  200297. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200298. png_set_swap(png_ptr);
  200299. #endif
  200300. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200301. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200302. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200303. png_set_packswap(png_ptr);
  200304. #endif
  200305. /* ----------------------- end of transformations ------------------- */
  200306. /* write the bits */
  200307. if (info_ptr->valid & PNG_INFO_IDAT)
  200308. png_write_image(png_ptr, info_ptr->row_pointers);
  200309. /* It is REQUIRED to call this to finish writing the rest of the file */
  200310. png_write_end(png_ptr, info_ptr);
  200311. transforms = transforms; /* quiet compiler warnings */
  200312. params = params;
  200313. }
  200314. #endif
  200315. #endif /* PNG_WRITE_SUPPORTED */
  200316. /*** End of inlined file: pngwrite.c ***/
  200317. /*** Start of inlined file: pngwtran.c ***/
  200318. /* pngwtran.c - transforms the data in a row for PNG writers
  200319. *
  200320. * Last changed in libpng 1.2.9 April 14, 2006
  200321. * For conditions of distribution and use, see copyright notice in png.h
  200322. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200323. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200324. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200325. */
  200326. #define PNG_INTERNAL
  200327. #ifdef PNG_WRITE_SUPPORTED
  200328. /* Transform the data according to the user's wishes. The order of
  200329. * transformations is significant.
  200330. */
  200331. void /* PRIVATE */
  200332. png_do_write_transformations(png_structp png_ptr)
  200333. {
  200334. png_debug(1, "in png_do_write_transformations\n");
  200335. if (png_ptr == NULL)
  200336. return;
  200337. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200338. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200339. if(png_ptr->write_user_transform_fn != NULL)
  200340. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200341. (png_ptr, /* png_ptr */
  200342. &(png_ptr->row_info), /* row_info: */
  200343. /* png_uint_32 width; width of row */
  200344. /* png_uint_32 rowbytes; number of bytes in row */
  200345. /* png_byte color_type; color type of pixels */
  200346. /* png_byte bit_depth; bit depth of samples */
  200347. /* png_byte channels; number of channels (1-4) */
  200348. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200349. png_ptr->row_buf + 1); /* start of pixel data for row */
  200350. #endif
  200351. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200352. if (png_ptr->transformations & PNG_FILLER)
  200353. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200354. png_ptr->flags);
  200355. #endif
  200356. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200357. if (png_ptr->transformations & PNG_PACKSWAP)
  200358. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200359. #endif
  200360. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200361. if (png_ptr->transformations & PNG_PACK)
  200362. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200363. (png_uint_32)png_ptr->bit_depth);
  200364. #endif
  200365. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200366. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200367. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200368. #endif
  200369. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200370. if (png_ptr->transformations & PNG_SHIFT)
  200371. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200372. &(png_ptr->shift));
  200373. #endif
  200374. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200375. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200376. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200377. #endif
  200378. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200379. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200380. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200381. #endif
  200382. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200383. if (png_ptr->transformations & PNG_BGR)
  200384. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200385. #endif
  200386. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200387. if (png_ptr->transformations & PNG_INVERT_MONO)
  200388. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200389. #endif
  200390. }
  200391. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200392. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200393. * row_info bit depth should be 8 (one pixel per byte). The channels
  200394. * should be 1 (this only happens on grayscale and paletted images).
  200395. */
  200396. void /* PRIVATE */
  200397. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200398. {
  200399. png_debug(1, "in png_do_pack\n");
  200400. if (row_info->bit_depth == 8 &&
  200401. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200402. row != NULL && row_info != NULL &&
  200403. #endif
  200404. row_info->channels == 1)
  200405. {
  200406. switch ((int)bit_depth)
  200407. {
  200408. case 1:
  200409. {
  200410. png_bytep sp, dp;
  200411. int mask, v;
  200412. png_uint_32 i;
  200413. png_uint_32 row_width = row_info->width;
  200414. sp = row;
  200415. dp = row;
  200416. mask = 0x80;
  200417. v = 0;
  200418. for (i = 0; i < row_width; i++)
  200419. {
  200420. if (*sp != 0)
  200421. v |= mask;
  200422. sp++;
  200423. if (mask > 1)
  200424. mask >>= 1;
  200425. else
  200426. {
  200427. mask = 0x80;
  200428. *dp = (png_byte)v;
  200429. dp++;
  200430. v = 0;
  200431. }
  200432. }
  200433. if (mask != 0x80)
  200434. *dp = (png_byte)v;
  200435. break;
  200436. }
  200437. case 2:
  200438. {
  200439. png_bytep sp, dp;
  200440. int shift, v;
  200441. png_uint_32 i;
  200442. png_uint_32 row_width = row_info->width;
  200443. sp = row;
  200444. dp = row;
  200445. shift = 6;
  200446. v = 0;
  200447. for (i = 0; i < row_width; i++)
  200448. {
  200449. png_byte value;
  200450. value = (png_byte)(*sp & 0x03);
  200451. v |= (value << shift);
  200452. if (shift == 0)
  200453. {
  200454. shift = 6;
  200455. *dp = (png_byte)v;
  200456. dp++;
  200457. v = 0;
  200458. }
  200459. else
  200460. shift -= 2;
  200461. sp++;
  200462. }
  200463. if (shift != 6)
  200464. *dp = (png_byte)v;
  200465. break;
  200466. }
  200467. case 4:
  200468. {
  200469. png_bytep sp, dp;
  200470. int shift, v;
  200471. png_uint_32 i;
  200472. png_uint_32 row_width = row_info->width;
  200473. sp = row;
  200474. dp = row;
  200475. shift = 4;
  200476. v = 0;
  200477. for (i = 0; i < row_width; i++)
  200478. {
  200479. png_byte value;
  200480. value = (png_byte)(*sp & 0x0f);
  200481. v |= (value << shift);
  200482. if (shift == 0)
  200483. {
  200484. shift = 4;
  200485. *dp = (png_byte)v;
  200486. dp++;
  200487. v = 0;
  200488. }
  200489. else
  200490. shift -= 4;
  200491. sp++;
  200492. }
  200493. if (shift != 4)
  200494. *dp = (png_byte)v;
  200495. break;
  200496. }
  200497. }
  200498. row_info->bit_depth = (png_byte)bit_depth;
  200499. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200500. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200501. row_info->width);
  200502. }
  200503. }
  200504. #endif
  200505. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200506. /* Shift pixel values to take advantage of whole range. Pass the
  200507. * true number of bits in bit_depth. The row should be packed
  200508. * according to row_info->bit_depth. Thus, if you had a row of
  200509. * bit depth 4, but the pixels only had values from 0 to 7, you
  200510. * would pass 3 as bit_depth, and this routine would translate the
  200511. * data to 0 to 15.
  200512. */
  200513. void /* PRIVATE */
  200514. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200515. {
  200516. png_debug(1, "in png_do_shift\n");
  200517. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200518. if (row != NULL && row_info != NULL &&
  200519. #else
  200520. if (
  200521. #endif
  200522. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200523. {
  200524. int shift_start[4], shift_dec[4];
  200525. int channels = 0;
  200526. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200527. {
  200528. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200529. shift_dec[channels] = bit_depth->red;
  200530. channels++;
  200531. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200532. shift_dec[channels] = bit_depth->green;
  200533. channels++;
  200534. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200535. shift_dec[channels] = bit_depth->blue;
  200536. channels++;
  200537. }
  200538. else
  200539. {
  200540. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200541. shift_dec[channels] = bit_depth->gray;
  200542. channels++;
  200543. }
  200544. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200545. {
  200546. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200547. shift_dec[channels] = bit_depth->alpha;
  200548. channels++;
  200549. }
  200550. /* with low row depths, could only be grayscale, so one channel */
  200551. if (row_info->bit_depth < 8)
  200552. {
  200553. png_bytep bp = row;
  200554. png_uint_32 i;
  200555. png_byte mask;
  200556. png_uint_32 row_bytes = row_info->rowbytes;
  200557. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200558. mask = 0x55;
  200559. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200560. mask = 0x11;
  200561. else
  200562. mask = 0xff;
  200563. for (i = 0; i < row_bytes; i++, bp++)
  200564. {
  200565. png_uint_16 v;
  200566. int j;
  200567. v = *bp;
  200568. *bp = 0;
  200569. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200570. {
  200571. if (j > 0)
  200572. *bp |= (png_byte)((v << j) & 0xff);
  200573. else
  200574. *bp |= (png_byte)((v >> (-j)) & mask);
  200575. }
  200576. }
  200577. }
  200578. else if (row_info->bit_depth == 8)
  200579. {
  200580. png_bytep bp = row;
  200581. png_uint_32 i;
  200582. png_uint_32 istop = channels * row_info->width;
  200583. for (i = 0; i < istop; i++, bp++)
  200584. {
  200585. png_uint_16 v;
  200586. int j;
  200587. int c = (int)(i%channels);
  200588. v = *bp;
  200589. *bp = 0;
  200590. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200591. {
  200592. if (j > 0)
  200593. *bp |= (png_byte)((v << j) & 0xff);
  200594. else
  200595. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200596. }
  200597. }
  200598. }
  200599. else
  200600. {
  200601. png_bytep bp;
  200602. png_uint_32 i;
  200603. png_uint_32 istop = channels * row_info->width;
  200604. for (bp = row, i = 0; i < istop; i++)
  200605. {
  200606. int c = (int)(i%channels);
  200607. png_uint_16 value, v;
  200608. int j;
  200609. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200610. value = 0;
  200611. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200612. {
  200613. if (j > 0)
  200614. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200615. else
  200616. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200617. }
  200618. *bp++ = (png_byte)(value >> 8);
  200619. *bp++ = (png_byte)(value & 0xff);
  200620. }
  200621. }
  200622. }
  200623. }
  200624. #endif
  200625. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200626. void /* PRIVATE */
  200627. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200628. {
  200629. png_debug(1, "in png_do_write_swap_alpha\n");
  200630. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200631. if (row != NULL && row_info != NULL)
  200632. #endif
  200633. {
  200634. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200635. {
  200636. /* This converts from ARGB to RGBA */
  200637. if (row_info->bit_depth == 8)
  200638. {
  200639. png_bytep sp, dp;
  200640. png_uint_32 i;
  200641. png_uint_32 row_width = row_info->width;
  200642. for (i = 0, sp = dp = row; i < row_width; i++)
  200643. {
  200644. png_byte save = *(sp++);
  200645. *(dp++) = *(sp++);
  200646. *(dp++) = *(sp++);
  200647. *(dp++) = *(sp++);
  200648. *(dp++) = save;
  200649. }
  200650. }
  200651. /* This converts from AARRGGBB to RRGGBBAA */
  200652. else
  200653. {
  200654. png_bytep sp, dp;
  200655. png_uint_32 i;
  200656. png_uint_32 row_width = row_info->width;
  200657. for (i = 0, sp = dp = row; i < row_width; i++)
  200658. {
  200659. png_byte save[2];
  200660. save[0] = *(sp++);
  200661. save[1] = *(sp++);
  200662. *(dp++) = *(sp++);
  200663. *(dp++) = *(sp++);
  200664. *(dp++) = *(sp++);
  200665. *(dp++) = *(sp++);
  200666. *(dp++) = *(sp++);
  200667. *(dp++) = *(sp++);
  200668. *(dp++) = save[0];
  200669. *(dp++) = save[1];
  200670. }
  200671. }
  200672. }
  200673. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200674. {
  200675. /* This converts from AG to GA */
  200676. if (row_info->bit_depth == 8)
  200677. {
  200678. png_bytep sp, dp;
  200679. png_uint_32 i;
  200680. png_uint_32 row_width = row_info->width;
  200681. for (i = 0, sp = dp = row; i < row_width; i++)
  200682. {
  200683. png_byte save = *(sp++);
  200684. *(dp++) = *(sp++);
  200685. *(dp++) = save;
  200686. }
  200687. }
  200688. /* This converts from AAGG to GGAA */
  200689. else
  200690. {
  200691. png_bytep sp, dp;
  200692. png_uint_32 i;
  200693. png_uint_32 row_width = row_info->width;
  200694. for (i = 0, sp = dp = row; i < row_width; i++)
  200695. {
  200696. png_byte save[2];
  200697. save[0] = *(sp++);
  200698. save[1] = *(sp++);
  200699. *(dp++) = *(sp++);
  200700. *(dp++) = *(sp++);
  200701. *(dp++) = save[0];
  200702. *(dp++) = save[1];
  200703. }
  200704. }
  200705. }
  200706. }
  200707. }
  200708. #endif
  200709. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200710. void /* PRIVATE */
  200711. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200712. {
  200713. png_debug(1, "in png_do_write_invert_alpha\n");
  200714. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200715. if (row != NULL && row_info != NULL)
  200716. #endif
  200717. {
  200718. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200719. {
  200720. /* This inverts the alpha channel in RGBA */
  200721. if (row_info->bit_depth == 8)
  200722. {
  200723. png_bytep sp, dp;
  200724. png_uint_32 i;
  200725. png_uint_32 row_width = row_info->width;
  200726. for (i = 0, sp = dp = row; i < row_width; i++)
  200727. {
  200728. /* does nothing
  200729. *(dp++) = *(sp++);
  200730. *(dp++) = *(sp++);
  200731. *(dp++) = *(sp++);
  200732. */
  200733. sp+=3; dp = sp;
  200734. *(dp++) = (png_byte)(255 - *(sp++));
  200735. }
  200736. }
  200737. /* This inverts the alpha channel in RRGGBBAA */
  200738. else
  200739. {
  200740. png_bytep sp, dp;
  200741. png_uint_32 i;
  200742. png_uint_32 row_width = row_info->width;
  200743. for (i = 0, sp = dp = row; i < row_width; i++)
  200744. {
  200745. /* does nothing
  200746. *(dp++) = *(sp++);
  200747. *(dp++) = *(sp++);
  200748. *(dp++) = *(sp++);
  200749. *(dp++) = *(sp++);
  200750. *(dp++) = *(sp++);
  200751. *(dp++) = *(sp++);
  200752. */
  200753. sp+=6; dp = sp;
  200754. *(dp++) = (png_byte)(255 - *(sp++));
  200755. *(dp++) = (png_byte)(255 - *(sp++));
  200756. }
  200757. }
  200758. }
  200759. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200760. {
  200761. /* This inverts the alpha channel in GA */
  200762. if (row_info->bit_depth == 8)
  200763. {
  200764. png_bytep sp, dp;
  200765. png_uint_32 i;
  200766. png_uint_32 row_width = row_info->width;
  200767. for (i = 0, sp = dp = row; i < row_width; i++)
  200768. {
  200769. *(dp++) = *(sp++);
  200770. *(dp++) = (png_byte)(255 - *(sp++));
  200771. }
  200772. }
  200773. /* This inverts the alpha channel in GGAA */
  200774. else
  200775. {
  200776. png_bytep sp, dp;
  200777. png_uint_32 i;
  200778. png_uint_32 row_width = row_info->width;
  200779. for (i = 0, sp = dp = row; i < row_width; i++)
  200780. {
  200781. /* does nothing
  200782. *(dp++) = *(sp++);
  200783. *(dp++) = *(sp++);
  200784. */
  200785. sp+=2; dp = sp;
  200786. *(dp++) = (png_byte)(255 - *(sp++));
  200787. *(dp++) = (png_byte)(255 - *(sp++));
  200788. }
  200789. }
  200790. }
  200791. }
  200792. }
  200793. #endif
  200794. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200795. /* undoes intrapixel differencing */
  200796. void /* PRIVATE */
  200797. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200798. {
  200799. png_debug(1, "in png_do_write_intrapixel\n");
  200800. if (
  200801. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200802. row != NULL && row_info != NULL &&
  200803. #endif
  200804. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200805. {
  200806. int bytes_per_pixel;
  200807. png_uint_32 row_width = row_info->width;
  200808. if (row_info->bit_depth == 8)
  200809. {
  200810. png_bytep rp;
  200811. png_uint_32 i;
  200812. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200813. bytes_per_pixel = 3;
  200814. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200815. bytes_per_pixel = 4;
  200816. else
  200817. return;
  200818. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200819. {
  200820. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200821. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200822. }
  200823. }
  200824. else if (row_info->bit_depth == 16)
  200825. {
  200826. png_bytep rp;
  200827. png_uint_32 i;
  200828. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200829. bytes_per_pixel = 6;
  200830. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200831. bytes_per_pixel = 8;
  200832. else
  200833. return;
  200834. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200835. {
  200836. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200837. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200838. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200839. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200840. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200841. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200842. *(rp+1) = (png_byte)(red & 0xff);
  200843. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200844. *(rp+5) = (png_byte)(blue & 0xff);
  200845. }
  200846. }
  200847. }
  200848. }
  200849. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200850. #endif /* PNG_WRITE_SUPPORTED */
  200851. /*** End of inlined file: pngwtran.c ***/
  200852. /*** Start of inlined file: pngwutil.c ***/
  200853. /* pngwutil.c - utilities to write a PNG file
  200854. *
  200855. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200856. * For conditions of distribution and use, see copyright notice in png.h
  200857. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200858. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200859. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200860. */
  200861. #define PNG_INTERNAL
  200862. #ifdef PNG_WRITE_SUPPORTED
  200863. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200864. * with unsigned numbers for convenience, although one supported
  200865. * ancillary chunk uses signed (two's complement) numbers.
  200866. */
  200867. void PNGAPI
  200868. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200869. {
  200870. buf[0] = (png_byte)((i >> 24) & 0xff);
  200871. buf[1] = (png_byte)((i >> 16) & 0xff);
  200872. buf[2] = (png_byte)((i >> 8) & 0xff);
  200873. buf[3] = (png_byte)(i & 0xff);
  200874. }
  200875. /* The png_save_int_32 function assumes integers are stored in two's
  200876. * complement format. If this isn't the case, then this routine needs to
  200877. * be modified to write data in two's complement format.
  200878. */
  200879. void PNGAPI
  200880. png_save_int_32(png_bytep buf, png_int_32 i)
  200881. {
  200882. buf[0] = (png_byte)((i >> 24) & 0xff);
  200883. buf[1] = (png_byte)((i >> 16) & 0xff);
  200884. buf[2] = (png_byte)((i >> 8) & 0xff);
  200885. buf[3] = (png_byte)(i & 0xff);
  200886. }
  200887. /* Place a 16-bit number into a buffer in PNG byte order.
  200888. * The parameter is declared unsigned int, not png_uint_16,
  200889. * just to avoid potential problems on pre-ANSI C compilers.
  200890. */
  200891. void PNGAPI
  200892. png_save_uint_16(png_bytep buf, unsigned int i)
  200893. {
  200894. buf[0] = (png_byte)((i >> 8) & 0xff);
  200895. buf[1] = (png_byte)(i & 0xff);
  200896. }
  200897. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200898. * representing the chunk name. The array must be at least 4 bytes in
  200899. * length, and does not need to be null terminated. To be safe, pass the
  200900. * pre-defined chunk names here, and if you need a new one, define it
  200901. * where the others are defined. The length is the length of the data.
  200902. * All the data must be present. If that is not possible, use the
  200903. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200904. * functions instead.
  200905. */
  200906. void PNGAPI
  200907. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200908. png_bytep data, png_size_t length)
  200909. {
  200910. if(png_ptr == NULL) return;
  200911. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200912. png_write_chunk_data(png_ptr, data, length);
  200913. png_write_chunk_end(png_ptr);
  200914. }
  200915. /* Write the start of a PNG chunk. The type is the chunk type.
  200916. * The total_length is the sum of the lengths of all the data you will be
  200917. * passing in png_write_chunk_data().
  200918. */
  200919. void PNGAPI
  200920. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200921. png_uint_32 length)
  200922. {
  200923. png_byte buf[4];
  200924. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200925. if(png_ptr == NULL) return;
  200926. /* write the length */
  200927. png_save_uint_32(buf, length);
  200928. png_write_data(png_ptr, buf, (png_size_t)4);
  200929. /* write the chunk name */
  200930. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200931. /* reset the crc and run it over the chunk name */
  200932. png_reset_crc(png_ptr);
  200933. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200934. }
  200935. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200936. * Note that multiple calls to this function are allowed, and that the
  200937. * sum of the lengths from these calls *must* add up to the total_length
  200938. * given to png_write_chunk_start().
  200939. */
  200940. void PNGAPI
  200941. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200942. {
  200943. /* write the data, and run the CRC over it */
  200944. if(png_ptr == NULL) return;
  200945. if (data != NULL && length > 0)
  200946. {
  200947. png_calculate_crc(png_ptr, data, length);
  200948. png_write_data(png_ptr, data, length);
  200949. }
  200950. }
  200951. /* Finish a chunk started with png_write_chunk_start(). */
  200952. void PNGAPI
  200953. png_write_chunk_end(png_structp png_ptr)
  200954. {
  200955. png_byte buf[4];
  200956. if(png_ptr == NULL) return;
  200957. /* write the crc */
  200958. png_save_uint_32(buf, png_ptr->crc);
  200959. png_write_data(png_ptr, buf, (png_size_t)4);
  200960. }
  200961. /* Simple function to write the signature. If we have already written
  200962. * the magic bytes of the signature, or more likely, the PNG stream is
  200963. * being embedded into another stream and doesn't need its own signature,
  200964. * we should call png_set_sig_bytes() to tell libpng how many of the
  200965. * bytes have already been written.
  200966. */
  200967. void /* PRIVATE */
  200968. png_write_sig(png_structp png_ptr)
  200969. {
  200970. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200971. /* write the rest of the 8 byte signature */
  200972. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200973. (png_size_t)8 - png_ptr->sig_bytes);
  200974. if(png_ptr->sig_bytes < 3)
  200975. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200976. }
  200977. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200978. /*
  200979. * This pair of functions encapsulates the operation of (a) compressing a
  200980. * text string, and (b) issuing it later as a series of chunk data writes.
  200981. * The compression_state structure is shared context for these functions
  200982. * set up by the caller in order to make the whole mess thread-safe.
  200983. */
  200984. typedef struct
  200985. {
  200986. char *input; /* the uncompressed input data */
  200987. int input_len; /* its length */
  200988. int num_output_ptr; /* number of output pointers used */
  200989. int max_output_ptr; /* size of output_ptr */
  200990. png_charpp output_ptr; /* array of pointers to output */
  200991. } compression_state;
  200992. /* compress given text into storage in the png_ptr structure */
  200993. static int /* PRIVATE */
  200994. png_text_compress(png_structp png_ptr,
  200995. png_charp text, png_size_t text_len, int compression,
  200996. compression_state *comp)
  200997. {
  200998. int ret;
  200999. comp->num_output_ptr = 0;
  201000. comp->max_output_ptr = 0;
  201001. comp->output_ptr = NULL;
  201002. comp->input = NULL;
  201003. comp->input_len = 0;
  201004. /* we may just want to pass the text right through */
  201005. if (compression == PNG_TEXT_COMPRESSION_NONE)
  201006. {
  201007. comp->input = text;
  201008. comp->input_len = text_len;
  201009. return((int)text_len);
  201010. }
  201011. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  201012. {
  201013. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201014. char msg[50];
  201015. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  201016. png_warning(png_ptr, msg);
  201017. #else
  201018. png_warning(png_ptr, "Unknown compression type");
  201019. #endif
  201020. }
  201021. /* We can't write the chunk until we find out how much data we have,
  201022. * which means we need to run the compressor first and save the
  201023. * output. This shouldn't be a problem, as the vast majority of
  201024. * comments should be reasonable, but we will set up an array of
  201025. * malloc'd pointers to be sure.
  201026. *
  201027. * If we knew the application was well behaved, we could simplify this
  201028. * greatly by assuming we can always malloc an output buffer large
  201029. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201030. * and malloc this directly. The only time this would be a bad idea is
  201031. * if we can't malloc more than 64K and we have 64K of random input
  201032. * data, or if the input string is incredibly large (although this
  201033. * wouldn't cause a failure, just a slowdown due to swapping).
  201034. */
  201035. /* set up the compression buffers */
  201036. png_ptr->zstream.avail_in = (uInt)text_len;
  201037. png_ptr->zstream.next_in = (Bytef *)text;
  201038. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201039. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201040. /* this is the same compression loop as in png_write_row() */
  201041. do
  201042. {
  201043. /* compress the data */
  201044. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201045. if (ret != Z_OK)
  201046. {
  201047. /* error */
  201048. if (png_ptr->zstream.msg != NULL)
  201049. png_error(png_ptr, png_ptr->zstream.msg);
  201050. else
  201051. png_error(png_ptr, "zlib error");
  201052. }
  201053. /* check to see if we need more room */
  201054. if (!(png_ptr->zstream.avail_out))
  201055. {
  201056. /* make sure the output array has room */
  201057. if (comp->num_output_ptr >= comp->max_output_ptr)
  201058. {
  201059. int old_max;
  201060. old_max = comp->max_output_ptr;
  201061. comp->max_output_ptr = comp->num_output_ptr + 4;
  201062. if (comp->output_ptr != NULL)
  201063. {
  201064. png_charpp old_ptr;
  201065. old_ptr = comp->output_ptr;
  201066. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201067. (png_uint_32)(comp->max_output_ptr *
  201068. png_sizeof (png_charpp)));
  201069. png_memcpy(comp->output_ptr, old_ptr, old_max
  201070. * png_sizeof (png_charp));
  201071. png_free(png_ptr, old_ptr);
  201072. }
  201073. else
  201074. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201075. (png_uint_32)(comp->max_output_ptr *
  201076. png_sizeof (png_charp)));
  201077. }
  201078. /* save the data */
  201079. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201080. (png_uint_32)png_ptr->zbuf_size);
  201081. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201082. png_ptr->zbuf_size);
  201083. comp->num_output_ptr++;
  201084. /* and reset the buffer */
  201085. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201086. png_ptr->zstream.next_out = png_ptr->zbuf;
  201087. }
  201088. /* continue until we don't have any more to compress */
  201089. } while (png_ptr->zstream.avail_in);
  201090. /* finish the compression */
  201091. do
  201092. {
  201093. /* tell zlib we are finished */
  201094. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201095. if (ret == Z_OK)
  201096. {
  201097. /* check to see if we need more room */
  201098. if (!(png_ptr->zstream.avail_out))
  201099. {
  201100. /* check to make sure our output array has room */
  201101. if (comp->num_output_ptr >= comp->max_output_ptr)
  201102. {
  201103. int old_max;
  201104. old_max = comp->max_output_ptr;
  201105. comp->max_output_ptr = comp->num_output_ptr + 4;
  201106. if (comp->output_ptr != NULL)
  201107. {
  201108. png_charpp old_ptr;
  201109. old_ptr = comp->output_ptr;
  201110. /* This could be optimized to realloc() */
  201111. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201112. (png_uint_32)(comp->max_output_ptr *
  201113. png_sizeof (png_charpp)));
  201114. png_memcpy(comp->output_ptr, old_ptr,
  201115. old_max * png_sizeof (png_charp));
  201116. png_free(png_ptr, old_ptr);
  201117. }
  201118. else
  201119. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201120. (png_uint_32)(comp->max_output_ptr *
  201121. png_sizeof (png_charp)));
  201122. }
  201123. /* save off the data */
  201124. comp->output_ptr[comp->num_output_ptr] =
  201125. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201126. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201127. png_ptr->zbuf_size);
  201128. comp->num_output_ptr++;
  201129. /* and reset the buffer pointers */
  201130. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201131. png_ptr->zstream.next_out = png_ptr->zbuf;
  201132. }
  201133. }
  201134. else if (ret != Z_STREAM_END)
  201135. {
  201136. /* we got an error */
  201137. if (png_ptr->zstream.msg != NULL)
  201138. png_error(png_ptr, png_ptr->zstream.msg);
  201139. else
  201140. png_error(png_ptr, "zlib error");
  201141. }
  201142. } while (ret != Z_STREAM_END);
  201143. /* text length is number of buffers plus last buffer */
  201144. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201145. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201146. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201147. return((int)text_len);
  201148. }
  201149. /* ship the compressed text out via chunk writes */
  201150. static void /* PRIVATE */
  201151. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201152. {
  201153. int i;
  201154. /* handle the no-compression case */
  201155. if (comp->input)
  201156. {
  201157. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201158. (png_size_t)comp->input_len);
  201159. return;
  201160. }
  201161. /* write saved output buffers, if any */
  201162. for (i = 0; i < comp->num_output_ptr; i++)
  201163. {
  201164. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201165. png_ptr->zbuf_size);
  201166. png_free(png_ptr, comp->output_ptr[i]);
  201167. comp->output_ptr[i]=NULL;
  201168. }
  201169. if (comp->max_output_ptr != 0)
  201170. png_free(png_ptr, comp->output_ptr);
  201171. comp->output_ptr=NULL;
  201172. /* write anything left in zbuf */
  201173. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201174. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201175. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201176. /* reset zlib for another zTXt/iTXt or image data */
  201177. deflateReset(&png_ptr->zstream);
  201178. png_ptr->zstream.data_type = Z_BINARY;
  201179. }
  201180. #endif
  201181. /* Write the IHDR chunk, and update the png_struct with the necessary
  201182. * information. Note that the rest of this code depends upon this
  201183. * information being correct.
  201184. */
  201185. void /* PRIVATE */
  201186. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201187. int bit_depth, int color_type, int compression_type, int filter_type,
  201188. int interlace_type)
  201189. {
  201190. #ifdef PNG_USE_LOCAL_ARRAYS
  201191. PNG_IHDR;
  201192. #endif
  201193. png_byte buf[13]; /* buffer to store the IHDR info */
  201194. png_debug(1, "in png_write_IHDR\n");
  201195. /* Check that we have valid input data from the application info */
  201196. switch (color_type)
  201197. {
  201198. case PNG_COLOR_TYPE_GRAY:
  201199. switch (bit_depth)
  201200. {
  201201. case 1:
  201202. case 2:
  201203. case 4:
  201204. case 8:
  201205. case 16: png_ptr->channels = 1; break;
  201206. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201207. }
  201208. break;
  201209. case PNG_COLOR_TYPE_RGB:
  201210. if (bit_depth != 8 && bit_depth != 16)
  201211. png_error(png_ptr, "Invalid bit depth for RGB image");
  201212. png_ptr->channels = 3;
  201213. break;
  201214. case PNG_COLOR_TYPE_PALETTE:
  201215. switch (bit_depth)
  201216. {
  201217. case 1:
  201218. case 2:
  201219. case 4:
  201220. case 8: png_ptr->channels = 1; break;
  201221. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201222. }
  201223. break;
  201224. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201225. if (bit_depth != 8 && bit_depth != 16)
  201226. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201227. png_ptr->channels = 2;
  201228. break;
  201229. case PNG_COLOR_TYPE_RGB_ALPHA:
  201230. if (bit_depth != 8 && bit_depth != 16)
  201231. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201232. png_ptr->channels = 4;
  201233. break;
  201234. default:
  201235. png_error(png_ptr, "Invalid image color type specified");
  201236. }
  201237. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201238. {
  201239. png_warning(png_ptr, "Invalid compression type specified");
  201240. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201241. }
  201242. /* Write filter_method 64 (intrapixel differencing) only if
  201243. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201244. * 2. Libpng did not write a PNG signature (this filter_method is only
  201245. * used in PNG datastreams that are embedded in MNG datastreams) and
  201246. * 3. The application called png_permit_mng_features with a mask that
  201247. * included PNG_FLAG_MNG_FILTER_64 and
  201248. * 4. The filter_method is 64 and
  201249. * 5. The color_type is RGB or RGBA
  201250. */
  201251. if (
  201252. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201253. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201254. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201255. (color_type == PNG_COLOR_TYPE_RGB ||
  201256. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201257. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201258. #endif
  201259. filter_type != PNG_FILTER_TYPE_BASE)
  201260. {
  201261. png_warning(png_ptr, "Invalid filter type specified");
  201262. filter_type = PNG_FILTER_TYPE_BASE;
  201263. }
  201264. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201265. if (interlace_type != PNG_INTERLACE_NONE &&
  201266. interlace_type != PNG_INTERLACE_ADAM7)
  201267. {
  201268. png_warning(png_ptr, "Invalid interlace type specified");
  201269. interlace_type = PNG_INTERLACE_ADAM7;
  201270. }
  201271. #else
  201272. interlace_type=PNG_INTERLACE_NONE;
  201273. #endif
  201274. /* save off the relevent information */
  201275. png_ptr->bit_depth = (png_byte)bit_depth;
  201276. png_ptr->color_type = (png_byte)color_type;
  201277. png_ptr->interlaced = (png_byte)interlace_type;
  201278. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201279. png_ptr->filter_type = (png_byte)filter_type;
  201280. #endif
  201281. png_ptr->compression_type = (png_byte)compression_type;
  201282. png_ptr->width = width;
  201283. png_ptr->height = height;
  201284. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201285. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201286. /* set the usr info, so any transformations can modify it */
  201287. png_ptr->usr_width = png_ptr->width;
  201288. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201289. png_ptr->usr_channels = png_ptr->channels;
  201290. /* pack the header information into the buffer */
  201291. png_save_uint_32(buf, width);
  201292. png_save_uint_32(buf + 4, height);
  201293. buf[8] = (png_byte)bit_depth;
  201294. buf[9] = (png_byte)color_type;
  201295. buf[10] = (png_byte)compression_type;
  201296. buf[11] = (png_byte)filter_type;
  201297. buf[12] = (png_byte)interlace_type;
  201298. /* write the chunk */
  201299. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201300. /* initialize zlib with PNG info */
  201301. png_ptr->zstream.zalloc = png_zalloc;
  201302. png_ptr->zstream.zfree = png_zfree;
  201303. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201304. if (!(png_ptr->do_filter))
  201305. {
  201306. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201307. png_ptr->bit_depth < 8)
  201308. png_ptr->do_filter = PNG_FILTER_NONE;
  201309. else
  201310. png_ptr->do_filter = PNG_ALL_FILTERS;
  201311. }
  201312. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201313. {
  201314. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201315. png_ptr->zlib_strategy = Z_FILTERED;
  201316. else
  201317. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201318. }
  201319. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201320. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201321. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201322. png_ptr->zlib_mem_level = 8;
  201323. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201324. png_ptr->zlib_window_bits = 15;
  201325. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201326. png_ptr->zlib_method = 8;
  201327. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201328. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201329. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201330. png_error(png_ptr, "zlib failed to initialize compressor");
  201331. png_ptr->zstream.next_out = png_ptr->zbuf;
  201332. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201333. /* libpng is not interested in zstream.data_type */
  201334. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201335. png_ptr->zstream.data_type = Z_BINARY;
  201336. png_ptr->mode = PNG_HAVE_IHDR;
  201337. }
  201338. /* write the palette. We are careful not to trust png_color to be in the
  201339. * correct order for PNG, so people can redefine it to any convenient
  201340. * structure.
  201341. */
  201342. void /* PRIVATE */
  201343. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201344. {
  201345. #ifdef PNG_USE_LOCAL_ARRAYS
  201346. PNG_PLTE;
  201347. #endif
  201348. png_uint_32 i;
  201349. png_colorp pal_ptr;
  201350. png_byte buf[3];
  201351. png_debug(1, "in png_write_PLTE\n");
  201352. if ((
  201353. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201354. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201355. #endif
  201356. num_pal == 0) || num_pal > 256)
  201357. {
  201358. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201359. {
  201360. png_error(png_ptr, "Invalid number of colors in palette");
  201361. }
  201362. else
  201363. {
  201364. png_warning(png_ptr, "Invalid number of colors in palette");
  201365. return;
  201366. }
  201367. }
  201368. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201369. {
  201370. png_warning(png_ptr,
  201371. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201372. return;
  201373. }
  201374. png_ptr->num_palette = (png_uint_16)num_pal;
  201375. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201376. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201377. #ifndef PNG_NO_POINTER_INDEXING
  201378. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201379. {
  201380. buf[0] = pal_ptr->red;
  201381. buf[1] = pal_ptr->green;
  201382. buf[2] = pal_ptr->blue;
  201383. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201384. }
  201385. #else
  201386. /* This is a little slower but some buggy compilers need to do this instead */
  201387. pal_ptr=palette;
  201388. for (i = 0; i < num_pal; i++)
  201389. {
  201390. buf[0] = pal_ptr[i].red;
  201391. buf[1] = pal_ptr[i].green;
  201392. buf[2] = pal_ptr[i].blue;
  201393. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201394. }
  201395. #endif
  201396. png_write_chunk_end(png_ptr);
  201397. png_ptr->mode |= PNG_HAVE_PLTE;
  201398. }
  201399. /* write an IDAT chunk */
  201400. void /* PRIVATE */
  201401. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201402. {
  201403. #ifdef PNG_USE_LOCAL_ARRAYS
  201404. PNG_IDAT;
  201405. #endif
  201406. png_debug(1, "in png_write_IDAT\n");
  201407. /* Optimize the CMF field in the zlib stream. */
  201408. /* This hack of the zlib stream is compliant to the stream specification. */
  201409. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201410. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201411. {
  201412. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201413. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201414. {
  201415. /* Avoid memory underflows and multiplication overflows. */
  201416. /* The conditions below are practically always satisfied;
  201417. however, they still must be checked. */
  201418. if (length >= 2 &&
  201419. png_ptr->height < 16384 && png_ptr->width < 16384)
  201420. {
  201421. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201422. ((png_ptr->width *
  201423. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201424. unsigned int z_cinfo = z_cmf >> 4;
  201425. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201426. while (uncompressed_idat_size <= half_z_window_size &&
  201427. half_z_window_size >= 256)
  201428. {
  201429. z_cinfo--;
  201430. half_z_window_size >>= 1;
  201431. }
  201432. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201433. if (data[0] != (png_byte)z_cmf)
  201434. {
  201435. data[0] = (png_byte)z_cmf;
  201436. data[1] &= 0xe0;
  201437. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201438. }
  201439. }
  201440. }
  201441. else
  201442. png_error(png_ptr,
  201443. "Invalid zlib compression method or flags in IDAT");
  201444. }
  201445. png_write_chunk(png_ptr, png_IDAT, data, length);
  201446. png_ptr->mode |= PNG_HAVE_IDAT;
  201447. }
  201448. /* write an IEND chunk */
  201449. void /* PRIVATE */
  201450. png_write_IEND(png_structp png_ptr)
  201451. {
  201452. #ifdef PNG_USE_LOCAL_ARRAYS
  201453. PNG_IEND;
  201454. #endif
  201455. png_debug(1, "in png_write_IEND\n");
  201456. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201457. (png_size_t)0);
  201458. png_ptr->mode |= PNG_HAVE_IEND;
  201459. }
  201460. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201461. /* write a gAMA chunk */
  201462. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201463. void /* PRIVATE */
  201464. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201465. {
  201466. #ifdef PNG_USE_LOCAL_ARRAYS
  201467. PNG_gAMA;
  201468. #endif
  201469. png_uint_32 igamma;
  201470. png_byte buf[4];
  201471. png_debug(1, "in png_write_gAMA\n");
  201472. /* file_gamma is saved in 1/100,000ths */
  201473. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201474. png_save_uint_32(buf, igamma);
  201475. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201476. }
  201477. #endif
  201478. #ifdef PNG_FIXED_POINT_SUPPORTED
  201479. void /* PRIVATE */
  201480. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201481. {
  201482. #ifdef PNG_USE_LOCAL_ARRAYS
  201483. PNG_gAMA;
  201484. #endif
  201485. png_byte buf[4];
  201486. png_debug(1, "in png_write_gAMA\n");
  201487. /* file_gamma is saved in 1/100,000ths */
  201488. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201489. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201490. }
  201491. #endif
  201492. #endif
  201493. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201494. /* write a sRGB chunk */
  201495. void /* PRIVATE */
  201496. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201497. {
  201498. #ifdef PNG_USE_LOCAL_ARRAYS
  201499. PNG_sRGB;
  201500. #endif
  201501. png_byte buf[1];
  201502. png_debug(1, "in png_write_sRGB\n");
  201503. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201504. png_warning(png_ptr,
  201505. "Invalid sRGB rendering intent specified");
  201506. buf[0]=(png_byte)srgb_intent;
  201507. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201508. }
  201509. #endif
  201510. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201511. /* write an iCCP chunk */
  201512. void /* PRIVATE */
  201513. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201514. png_charp profile, int profile_len)
  201515. {
  201516. #ifdef PNG_USE_LOCAL_ARRAYS
  201517. PNG_iCCP;
  201518. #endif
  201519. png_size_t name_len;
  201520. png_charp new_name;
  201521. compression_state comp;
  201522. int embedded_profile_len = 0;
  201523. png_debug(1, "in png_write_iCCP\n");
  201524. comp.num_output_ptr = 0;
  201525. comp.max_output_ptr = 0;
  201526. comp.output_ptr = NULL;
  201527. comp.input = NULL;
  201528. comp.input_len = 0;
  201529. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201530. &new_name)) == 0)
  201531. {
  201532. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201533. return;
  201534. }
  201535. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201536. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201537. if (profile == NULL)
  201538. profile_len = 0;
  201539. if (profile_len > 3)
  201540. embedded_profile_len =
  201541. ((*( (png_bytep)profile ))<<24) |
  201542. ((*( (png_bytep)profile+1))<<16) |
  201543. ((*( (png_bytep)profile+2))<< 8) |
  201544. ((*( (png_bytep)profile+3)) );
  201545. if (profile_len < embedded_profile_len)
  201546. {
  201547. png_warning(png_ptr,
  201548. "Embedded profile length too large in iCCP chunk");
  201549. return;
  201550. }
  201551. if (profile_len > embedded_profile_len)
  201552. {
  201553. png_warning(png_ptr,
  201554. "Truncating profile to actual length in iCCP chunk");
  201555. profile_len = embedded_profile_len;
  201556. }
  201557. if (profile_len)
  201558. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201559. PNG_COMPRESSION_TYPE_BASE, &comp);
  201560. /* make sure we include the NULL after the name and the compression type */
  201561. png_write_chunk_start(png_ptr, png_iCCP,
  201562. (png_uint_32)name_len+profile_len+2);
  201563. new_name[name_len+1]=0x00;
  201564. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201565. if (profile_len)
  201566. png_write_compressed_data_out(png_ptr, &comp);
  201567. png_write_chunk_end(png_ptr);
  201568. png_free(png_ptr, new_name);
  201569. }
  201570. #endif
  201571. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201572. /* write a sPLT chunk */
  201573. void /* PRIVATE */
  201574. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201575. {
  201576. #ifdef PNG_USE_LOCAL_ARRAYS
  201577. PNG_sPLT;
  201578. #endif
  201579. png_size_t name_len;
  201580. png_charp new_name;
  201581. png_byte entrybuf[10];
  201582. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201583. int palette_size = entry_size * spalette->nentries;
  201584. png_sPLT_entryp ep;
  201585. #ifdef PNG_NO_POINTER_INDEXING
  201586. int i;
  201587. #endif
  201588. png_debug(1, "in png_write_sPLT\n");
  201589. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201590. spalette->name, &new_name))==0)
  201591. {
  201592. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201593. return;
  201594. }
  201595. /* make sure we include the NULL after the name */
  201596. png_write_chunk_start(png_ptr, png_sPLT,
  201597. (png_uint_32)(name_len + 2 + palette_size));
  201598. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201599. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201600. /* loop through each palette entry, writing appropriately */
  201601. #ifndef PNG_NO_POINTER_INDEXING
  201602. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201603. {
  201604. if (spalette->depth == 8)
  201605. {
  201606. entrybuf[0] = (png_byte)ep->red;
  201607. entrybuf[1] = (png_byte)ep->green;
  201608. entrybuf[2] = (png_byte)ep->blue;
  201609. entrybuf[3] = (png_byte)ep->alpha;
  201610. png_save_uint_16(entrybuf + 4, ep->frequency);
  201611. }
  201612. else
  201613. {
  201614. png_save_uint_16(entrybuf + 0, ep->red);
  201615. png_save_uint_16(entrybuf + 2, ep->green);
  201616. png_save_uint_16(entrybuf + 4, ep->blue);
  201617. png_save_uint_16(entrybuf + 6, ep->alpha);
  201618. png_save_uint_16(entrybuf + 8, ep->frequency);
  201619. }
  201620. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201621. }
  201622. #else
  201623. ep=spalette->entries;
  201624. for (i=0; i>spalette->nentries; i++)
  201625. {
  201626. if (spalette->depth == 8)
  201627. {
  201628. entrybuf[0] = (png_byte)ep[i].red;
  201629. entrybuf[1] = (png_byte)ep[i].green;
  201630. entrybuf[2] = (png_byte)ep[i].blue;
  201631. entrybuf[3] = (png_byte)ep[i].alpha;
  201632. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201633. }
  201634. else
  201635. {
  201636. png_save_uint_16(entrybuf + 0, ep[i].red);
  201637. png_save_uint_16(entrybuf + 2, ep[i].green);
  201638. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201639. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201640. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201641. }
  201642. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201643. }
  201644. #endif
  201645. png_write_chunk_end(png_ptr);
  201646. png_free(png_ptr, new_name);
  201647. }
  201648. #endif
  201649. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201650. /* write the sBIT chunk */
  201651. void /* PRIVATE */
  201652. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201653. {
  201654. #ifdef PNG_USE_LOCAL_ARRAYS
  201655. PNG_sBIT;
  201656. #endif
  201657. png_byte buf[4];
  201658. png_size_t size;
  201659. png_debug(1, "in png_write_sBIT\n");
  201660. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201661. if (color_type & PNG_COLOR_MASK_COLOR)
  201662. {
  201663. png_byte maxbits;
  201664. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201665. png_ptr->usr_bit_depth);
  201666. if (sbit->red == 0 || sbit->red > maxbits ||
  201667. sbit->green == 0 || sbit->green > maxbits ||
  201668. sbit->blue == 0 || sbit->blue > maxbits)
  201669. {
  201670. png_warning(png_ptr, "Invalid sBIT depth specified");
  201671. return;
  201672. }
  201673. buf[0] = sbit->red;
  201674. buf[1] = sbit->green;
  201675. buf[2] = sbit->blue;
  201676. size = 3;
  201677. }
  201678. else
  201679. {
  201680. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201681. {
  201682. png_warning(png_ptr, "Invalid sBIT depth specified");
  201683. return;
  201684. }
  201685. buf[0] = sbit->gray;
  201686. size = 1;
  201687. }
  201688. if (color_type & PNG_COLOR_MASK_ALPHA)
  201689. {
  201690. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201691. {
  201692. png_warning(png_ptr, "Invalid sBIT depth specified");
  201693. return;
  201694. }
  201695. buf[size++] = sbit->alpha;
  201696. }
  201697. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201698. }
  201699. #endif
  201700. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201701. /* write the cHRM chunk */
  201702. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201703. void /* PRIVATE */
  201704. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201705. double red_x, double red_y, double green_x, double green_y,
  201706. double blue_x, double blue_y)
  201707. {
  201708. #ifdef PNG_USE_LOCAL_ARRAYS
  201709. PNG_cHRM;
  201710. #endif
  201711. png_byte buf[32];
  201712. png_uint_32 itemp;
  201713. png_debug(1, "in png_write_cHRM\n");
  201714. /* each value is saved in 1/100,000ths */
  201715. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201716. white_x + white_y > 1.0)
  201717. {
  201718. png_warning(png_ptr, "Invalid cHRM white point specified");
  201719. #if !defined(PNG_NO_CONSOLE_IO)
  201720. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201721. #endif
  201722. return;
  201723. }
  201724. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201725. png_save_uint_32(buf, itemp);
  201726. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201727. png_save_uint_32(buf + 4, itemp);
  201728. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201729. {
  201730. png_warning(png_ptr, "Invalid cHRM red point specified");
  201731. return;
  201732. }
  201733. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201734. png_save_uint_32(buf + 8, itemp);
  201735. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201736. png_save_uint_32(buf + 12, itemp);
  201737. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201738. {
  201739. png_warning(png_ptr, "Invalid cHRM green point specified");
  201740. return;
  201741. }
  201742. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201743. png_save_uint_32(buf + 16, itemp);
  201744. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201745. png_save_uint_32(buf + 20, itemp);
  201746. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201747. {
  201748. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201749. return;
  201750. }
  201751. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201752. png_save_uint_32(buf + 24, itemp);
  201753. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201754. png_save_uint_32(buf + 28, itemp);
  201755. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201756. }
  201757. #endif
  201758. #ifdef PNG_FIXED_POINT_SUPPORTED
  201759. void /* PRIVATE */
  201760. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201761. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201762. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201763. png_fixed_point blue_y)
  201764. {
  201765. #ifdef PNG_USE_LOCAL_ARRAYS
  201766. PNG_cHRM;
  201767. #endif
  201768. png_byte buf[32];
  201769. png_debug(1, "in png_write_cHRM\n");
  201770. /* each value is saved in 1/100,000ths */
  201771. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201772. {
  201773. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201774. #if !defined(PNG_NO_CONSOLE_IO)
  201775. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201776. #endif
  201777. return;
  201778. }
  201779. png_save_uint_32(buf, (png_uint_32)white_x);
  201780. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201781. if (red_x + red_y > 100000L)
  201782. {
  201783. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201784. return;
  201785. }
  201786. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201787. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201788. if (green_x + green_y > 100000L)
  201789. {
  201790. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201791. return;
  201792. }
  201793. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201794. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201795. if (blue_x + blue_y > 100000L)
  201796. {
  201797. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201798. return;
  201799. }
  201800. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201801. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201802. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201803. }
  201804. #endif
  201805. #endif
  201806. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201807. /* write the tRNS chunk */
  201808. void /* PRIVATE */
  201809. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201810. int num_trans, int color_type)
  201811. {
  201812. #ifdef PNG_USE_LOCAL_ARRAYS
  201813. PNG_tRNS;
  201814. #endif
  201815. png_byte buf[6];
  201816. png_debug(1, "in png_write_tRNS\n");
  201817. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201818. {
  201819. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201820. {
  201821. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201822. return;
  201823. }
  201824. /* write the chunk out as it is */
  201825. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201826. }
  201827. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201828. {
  201829. /* one 16 bit value */
  201830. if(tran->gray >= (1 << png_ptr->bit_depth))
  201831. {
  201832. png_warning(png_ptr,
  201833. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201834. return;
  201835. }
  201836. png_save_uint_16(buf, tran->gray);
  201837. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201838. }
  201839. else if (color_type == PNG_COLOR_TYPE_RGB)
  201840. {
  201841. /* three 16 bit values */
  201842. png_save_uint_16(buf, tran->red);
  201843. png_save_uint_16(buf + 2, tran->green);
  201844. png_save_uint_16(buf + 4, tran->blue);
  201845. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201846. {
  201847. png_warning(png_ptr,
  201848. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201849. return;
  201850. }
  201851. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201852. }
  201853. else
  201854. {
  201855. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201856. }
  201857. }
  201858. #endif
  201859. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201860. /* write the background chunk */
  201861. void /* PRIVATE */
  201862. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201863. {
  201864. #ifdef PNG_USE_LOCAL_ARRAYS
  201865. PNG_bKGD;
  201866. #endif
  201867. png_byte buf[6];
  201868. png_debug(1, "in png_write_bKGD\n");
  201869. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201870. {
  201871. if (
  201872. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201873. (png_ptr->num_palette ||
  201874. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201875. #endif
  201876. back->index > png_ptr->num_palette)
  201877. {
  201878. png_warning(png_ptr, "Invalid background palette index");
  201879. return;
  201880. }
  201881. buf[0] = back->index;
  201882. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201883. }
  201884. else if (color_type & PNG_COLOR_MASK_COLOR)
  201885. {
  201886. png_save_uint_16(buf, back->red);
  201887. png_save_uint_16(buf + 2, back->green);
  201888. png_save_uint_16(buf + 4, back->blue);
  201889. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201890. {
  201891. png_warning(png_ptr,
  201892. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201893. return;
  201894. }
  201895. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201896. }
  201897. else
  201898. {
  201899. if(back->gray >= (1 << png_ptr->bit_depth))
  201900. {
  201901. png_warning(png_ptr,
  201902. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201903. return;
  201904. }
  201905. png_save_uint_16(buf, back->gray);
  201906. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201907. }
  201908. }
  201909. #endif
  201910. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201911. /* write the histogram */
  201912. void /* PRIVATE */
  201913. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201914. {
  201915. #ifdef PNG_USE_LOCAL_ARRAYS
  201916. PNG_hIST;
  201917. #endif
  201918. int i;
  201919. png_byte buf[3];
  201920. png_debug(1, "in png_write_hIST\n");
  201921. if (num_hist > (int)png_ptr->num_palette)
  201922. {
  201923. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201924. png_ptr->num_palette);
  201925. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201926. return;
  201927. }
  201928. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201929. for (i = 0; i < num_hist; i++)
  201930. {
  201931. png_save_uint_16(buf, hist[i]);
  201932. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201933. }
  201934. png_write_chunk_end(png_ptr);
  201935. }
  201936. #endif
  201937. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201938. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201939. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201940. * and if invalid, correct the keyword rather than discarding the entire
  201941. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201942. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201943. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201944. *
  201945. * The new_key is allocated to hold the corrected keyword and must be freed
  201946. * by the calling routine. This avoids problems with trying to write to
  201947. * static keywords without having to have duplicate copies of the strings.
  201948. */
  201949. png_size_t /* PRIVATE */
  201950. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201951. {
  201952. png_size_t key_len;
  201953. png_charp kp, dp;
  201954. int kflag;
  201955. int kwarn=0;
  201956. png_debug(1, "in png_check_keyword\n");
  201957. *new_key = NULL;
  201958. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201959. {
  201960. png_warning(png_ptr, "zero length keyword");
  201961. return ((png_size_t)0);
  201962. }
  201963. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201964. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201965. if (*new_key == NULL)
  201966. {
  201967. png_warning(png_ptr, "Out of memory while procesing keyword");
  201968. return ((png_size_t)0);
  201969. }
  201970. /* Replace non-printing characters with a blank and print a warning */
  201971. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201972. {
  201973. if ((png_byte)*kp < 0x20 ||
  201974. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201975. {
  201976. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201977. char msg[40];
  201978. png_snprintf(msg, 40,
  201979. "invalid keyword character 0x%02X", (png_byte)*kp);
  201980. png_warning(png_ptr, msg);
  201981. #else
  201982. png_warning(png_ptr, "invalid character in keyword");
  201983. #endif
  201984. *dp = ' ';
  201985. }
  201986. else
  201987. {
  201988. *dp = *kp;
  201989. }
  201990. }
  201991. *dp = '\0';
  201992. /* Remove any trailing white space. */
  201993. kp = *new_key + key_len - 1;
  201994. if (*kp == ' ')
  201995. {
  201996. png_warning(png_ptr, "trailing spaces removed from keyword");
  201997. while (*kp == ' ')
  201998. {
  201999. *(kp--) = '\0';
  202000. key_len--;
  202001. }
  202002. }
  202003. /* Remove any leading white space. */
  202004. kp = *new_key;
  202005. if (*kp == ' ')
  202006. {
  202007. png_warning(png_ptr, "leading spaces removed from keyword");
  202008. while (*kp == ' ')
  202009. {
  202010. kp++;
  202011. key_len--;
  202012. }
  202013. }
  202014. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  202015. /* Remove multiple internal spaces. */
  202016. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  202017. {
  202018. if (*kp == ' ' && kflag == 0)
  202019. {
  202020. *(dp++) = *kp;
  202021. kflag = 1;
  202022. }
  202023. else if (*kp == ' ')
  202024. {
  202025. key_len--;
  202026. kwarn=1;
  202027. }
  202028. else
  202029. {
  202030. *(dp++) = *kp;
  202031. kflag = 0;
  202032. }
  202033. }
  202034. *dp = '\0';
  202035. if(kwarn)
  202036. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202037. if (key_len == 0)
  202038. {
  202039. png_free(png_ptr, *new_key);
  202040. *new_key=NULL;
  202041. png_warning(png_ptr, "Zero length keyword");
  202042. }
  202043. if (key_len > 79)
  202044. {
  202045. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202046. new_key[79] = '\0';
  202047. key_len = 79;
  202048. }
  202049. return (key_len);
  202050. }
  202051. #endif
  202052. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202053. /* write a tEXt chunk */
  202054. void /* PRIVATE */
  202055. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202056. png_size_t text_len)
  202057. {
  202058. #ifdef PNG_USE_LOCAL_ARRAYS
  202059. PNG_tEXt;
  202060. #endif
  202061. png_size_t key_len;
  202062. png_charp new_key;
  202063. png_debug(1, "in png_write_tEXt\n");
  202064. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202065. {
  202066. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202067. return;
  202068. }
  202069. if (text == NULL || *text == '\0')
  202070. text_len = 0;
  202071. else
  202072. text_len = png_strlen(text);
  202073. /* make sure we include the 0 after the key */
  202074. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202075. /*
  202076. * We leave it to the application to meet PNG-1.0 requirements on the
  202077. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202078. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202079. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202080. */
  202081. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202082. if (text_len)
  202083. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202084. png_write_chunk_end(png_ptr);
  202085. png_free(png_ptr, new_key);
  202086. }
  202087. #endif
  202088. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202089. /* write a compressed text chunk */
  202090. void /* PRIVATE */
  202091. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202092. png_size_t text_len, int compression)
  202093. {
  202094. #ifdef PNG_USE_LOCAL_ARRAYS
  202095. PNG_zTXt;
  202096. #endif
  202097. png_size_t key_len;
  202098. char buf[1];
  202099. png_charp new_key;
  202100. compression_state comp;
  202101. png_debug(1, "in png_write_zTXt\n");
  202102. comp.num_output_ptr = 0;
  202103. comp.max_output_ptr = 0;
  202104. comp.output_ptr = NULL;
  202105. comp.input = NULL;
  202106. comp.input_len = 0;
  202107. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202108. {
  202109. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202110. return;
  202111. }
  202112. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202113. {
  202114. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202115. png_free(png_ptr, new_key);
  202116. return;
  202117. }
  202118. text_len = png_strlen(text);
  202119. /* compute the compressed data; do it now for the length */
  202120. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202121. &comp);
  202122. /* write start of chunk */
  202123. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202124. (key_len+text_len+2));
  202125. /* write key */
  202126. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202127. png_free(png_ptr, new_key);
  202128. buf[0] = (png_byte)compression;
  202129. /* write compression */
  202130. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202131. /* write the compressed data */
  202132. png_write_compressed_data_out(png_ptr, &comp);
  202133. /* close the chunk */
  202134. png_write_chunk_end(png_ptr);
  202135. }
  202136. #endif
  202137. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202138. /* write an iTXt chunk */
  202139. void /* PRIVATE */
  202140. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202141. png_charp lang, png_charp lang_key, png_charp text)
  202142. {
  202143. #ifdef PNG_USE_LOCAL_ARRAYS
  202144. PNG_iTXt;
  202145. #endif
  202146. png_size_t lang_len, key_len, lang_key_len, text_len;
  202147. png_charp new_lang, new_key;
  202148. png_byte cbuf[2];
  202149. compression_state comp;
  202150. png_debug(1, "in png_write_iTXt\n");
  202151. comp.num_output_ptr = 0;
  202152. comp.max_output_ptr = 0;
  202153. comp.output_ptr = NULL;
  202154. comp.input = NULL;
  202155. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202156. {
  202157. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202158. return;
  202159. }
  202160. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202161. {
  202162. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202163. new_lang = NULL;
  202164. lang_len = 0;
  202165. }
  202166. if (lang_key == NULL)
  202167. lang_key_len = 0;
  202168. else
  202169. lang_key_len = png_strlen(lang_key);
  202170. if (text == NULL)
  202171. text_len = 0;
  202172. else
  202173. text_len = png_strlen(text);
  202174. /* compute the compressed data; do it now for the length */
  202175. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202176. &comp);
  202177. /* make sure we include the compression flag, the compression byte,
  202178. * and the NULs after the key, lang, and lang_key parts */
  202179. png_write_chunk_start(png_ptr, png_iTXt,
  202180. (png_uint_32)(
  202181. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202182. + key_len
  202183. + lang_len
  202184. + lang_key_len
  202185. + text_len));
  202186. /*
  202187. * We leave it to the application to meet PNG-1.0 requirements on the
  202188. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202189. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202190. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202191. */
  202192. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202193. /* set the compression flag */
  202194. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202195. compression == PNG_TEXT_COMPRESSION_NONE)
  202196. cbuf[0] = 0;
  202197. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202198. cbuf[0] = 1;
  202199. /* set the compression method */
  202200. cbuf[1] = 0;
  202201. png_write_chunk_data(png_ptr, cbuf, 2);
  202202. cbuf[0] = 0;
  202203. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202204. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202205. png_write_compressed_data_out(png_ptr, &comp);
  202206. png_write_chunk_end(png_ptr);
  202207. png_free(png_ptr, new_key);
  202208. if (new_lang)
  202209. png_free(png_ptr, new_lang);
  202210. }
  202211. #endif
  202212. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202213. /* write the oFFs chunk */
  202214. void /* PRIVATE */
  202215. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202216. int unit_type)
  202217. {
  202218. #ifdef PNG_USE_LOCAL_ARRAYS
  202219. PNG_oFFs;
  202220. #endif
  202221. png_byte buf[9];
  202222. png_debug(1, "in png_write_oFFs\n");
  202223. if (unit_type >= PNG_OFFSET_LAST)
  202224. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202225. png_save_int_32(buf, x_offset);
  202226. png_save_int_32(buf + 4, y_offset);
  202227. buf[8] = (png_byte)unit_type;
  202228. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202229. }
  202230. #endif
  202231. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202232. /* write the pCAL chunk (described in the PNG extensions document) */
  202233. void /* PRIVATE */
  202234. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202235. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202236. {
  202237. #ifdef PNG_USE_LOCAL_ARRAYS
  202238. PNG_pCAL;
  202239. #endif
  202240. png_size_t purpose_len, units_len, total_len;
  202241. png_uint_32p params_len;
  202242. png_byte buf[10];
  202243. png_charp new_purpose;
  202244. int i;
  202245. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202246. if (type >= PNG_EQUATION_LAST)
  202247. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202248. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202249. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202250. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202251. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202252. total_len = purpose_len + units_len + 10;
  202253. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202254. *png_sizeof(png_uint_32)));
  202255. /* Find the length of each parameter, making sure we don't count the
  202256. null terminator for the last parameter. */
  202257. for (i = 0; i < nparams; i++)
  202258. {
  202259. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202260. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202261. total_len += (png_size_t)params_len[i];
  202262. }
  202263. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202264. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202265. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202266. png_save_int_32(buf, X0);
  202267. png_save_int_32(buf + 4, X1);
  202268. buf[8] = (png_byte)type;
  202269. buf[9] = (png_byte)nparams;
  202270. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202271. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202272. png_free(png_ptr, new_purpose);
  202273. for (i = 0; i < nparams; i++)
  202274. {
  202275. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202276. (png_size_t)params_len[i]);
  202277. }
  202278. png_free(png_ptr, params_len);
  202279. png_write_chunk_end(png_ptr);
  202280. }
  202281. #endif
  202282. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202283. /* write the sCAL chunk */
  202284. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202285. void /* PRIVATE */
  202286. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202287. {
  202288. #ifdef PNG_USE_LOCAL_ARRAYS
  202289. PNG_sCAL;
  202290. #endif
  202291. char buf[64];
  202292. png_size_t total_len;
  202293. png_debug(1, "in png_write_sCAL\n");
  202294. buf[0] = (char)unit;
  202295. #if defined(_WIN32_WCE)
  202296. /* sprintf() function is not supported on WindowsCE */
  202297. {
  202298. wchar_t wc_buf[32];
  202299. size_t wc_len;
  202300. swprintf(wc_buf, TEXT("%12.12e"), width);
  202301. wc_len = wcslen(wc_buf);
  202302. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202303. total_len = wc_len + 2;
  202304. swprintf(wc_buf, TEXT("%12.12e"), height);
  202305. wc_len = wcslen(wc_buf);
  202306. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202307. NULL, NULL);
  202308. total_len += wc_len;
  202309. }
  202310. #else
  202311. png_snprintf(buf + 1, 63, "%12.12e", width);
  202312. total_len = 1 + png_strlen(buf + 1) + 1;
  202313. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202314. total_len += png_strlen(buf + total_len);
  202315. #endif
  202316. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202317. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202318. }
  202319. #else
  202320. #ifdef PNG_FIXED_POINT_SUPPORTED
  202321. void /* PRIVATE */
  202322. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202323. png_charp height)
  202324. {
  202325. #ifdef PNG_USE_LOCAL_ARRAYS
  202326. PNG_sCAL;
  202327. #endif
  202328. png_byte buf[64];
  202329. png_size_t wlen, hlen, total_len;
  202330. png_debug(1, "in png_write_sCAL_s\n");
  202331. wlen = png_strlen(width);
  202332. hlen = png_strlen(height);
  202333. total_len = wlen + hlen + 2;
  202334. if (total_len > 64)
  202335. {
  202336. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202337. return;
  202338. }
  202339. buf[0] = (png_byte)unit;
  202340. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202341. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202342. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202343. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202344. }
  202345. #endif
  202346. #endif
  202347. #endif
  202348. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202349. /* write the pHYs chunk */
  202350. void /* PRIVATE */
  202351. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202352. png_uint_32 y_pixels_per_unit,
  202353. int unit_type)
  202354. {
  202355. #ifdef PNG_USE_LOCAL_ARRAYS
  202356. PNG_pHYs;
  202357. #endif
  202358. png_byte buf[9];
  202359. png_debug(1, "in png_write_pHYs\n");
  202360. if (unit_type >= PNG_RESOLUTION_LAST)
  202361. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202362. png_save_uint_32(buf, x_pixels_per_unit);
  202363. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202364. buf[8] = (png_byte)unit_type;
  202365. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202366. }
  202367. #endif
  202368. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202369. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202370. * or png_convert_from_time_t(), or fill in the structure yourself.
  202371. */
  202372. void /* PRIVATE */
  202373. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202374. {
  202375. #ifdef PNG_USE_LOCAL_ARRAYS
  202376. PNG_tIME;
  202377. #endif
  202378. png_byte buf[7];
  202379. png_debug(1, "in png_write_tIME\n");
  202380. if (mod_time->month > 12 || mod_time->month < 1 ||
  202381. mod_time->day > 31 || mod_time->day < 1 ||
  202382. mod_time->hour > 23 || mod_time->second > 60)
  202383. {
  202384. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202385. return;
  202386. }
  202387. png_save_uint_16(buf, mod_time->year);
  202388. buf[2] = mod_time->month;
  202389. buf[3] = mod_time->day;
  202390. buf[4] = mod_time->hour;
  202391. buf[5] = mod_time->minute;
  202392. buf[6] = mod_time->second;
  202393. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202394. }
  202395. #endif
  202396. /* initializes the row writing capability of libpng */
  202397. void /* PRIVATE */
  202398. png_write_start_row(png_structp png_ptr)
  202399. {
  202400. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202401. #ifdef PNG_USE_LOCAL_ARRAYS
  202402. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202403. /* start of interlace block */
  202404. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202405. /* offset to next interlace block */
  202406. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202407. /* start of interlace block in the y direction */
  202408. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202409. /* offset to next interlace block in the y direction */
  202410. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202411. #endif
  202412. #endif
  202413. png_size_t buf_size;
  202414. png_debug(1, "in png_write_start_row\n");
  202415. buf_size = (png_size_t)(PNG_ROWBYTES(
  202416. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202417. /* set up row buffer */
  202418. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202419. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202420. #ifndef PNG_NO_WRITE_FILTERING
  202421. /* set up filtering buffer, if using this filter */
  202422. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202423. {
  202424. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202425. (png_ptr->rowbytes + 1));
  202426. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202427. }
  202428. /* We only need to keep the previous row if we are using one of these. */
  202429. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202430. {
  202431. /* set up previous row buffer */
  202432. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202433. png_memset(png_ptr->prev_row, 0, buf_size);
  202434. if (png_ptr->do_filter & PNG_FILTER_UP)
  202435. {
  202436. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202437. (png_ptr->rowbytes + 1));
  202438. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202439. }
  202440. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202441. {
  202442. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202443. (png_ptr->rowbytes + 1));
  202444. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202445. }
  202446. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202447. {
  202448. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202449. (png_ptr->rowbytes + 1));
  202450. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202451. }
  202452. #endif /* PNG_NO_WRITE_FILTERING */
  202453. }
  202454. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202455. /* if interlaced, we need to set up width and height of pass */
  202456. if (png_ptr->interlaced)
  202457. {
  202458. if (!(png_ptr->transformations & PNG_INTERLACE))
  202459. {
  202460. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202461. png_pass_ystart[0]) / png_pass_yinc[0];
  202462. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202463. png_pass_start[0]) / png_pass_inc[0];
  202464. }
  202465. else
  202466. {
  202467. png_ptr->num_rows = png_ptr->height;
  202468. png_ptr->usr_width = png_ptr->width;
  202469. }
  202470. }
  202471. else
  202472. #endif
  202473. {
  202474. png_ptr->num_rows = png_ptr->height;
  202475. png_ptr->usr_width = png_ptr->width;
  202476. }
  202477. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202478. png_ptr->zstream.next_out = png_ptr->zbuf;
  202479. }
  202480. /* Internal use only. Called when finished processing a row of data. */
  202481. void /* PRIVATE */
  202482. png_write_finish_row(png_structp png_ptr)
  202483. {
  202484. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202485. #ifdef PNG_USE_LOCAL_ARRAYS
  202486. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202487. /* start of interlace block */
  202488. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202489. /* offset to next interlace block */
  202490. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202491. /* start of interlace block in the y direction */
  202492. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202493. /* offset to next interlace block in the y direction */
  202494. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202495. #endif
  202496. #endif
  202497. int ret;
  202498. png_debug(1, "in png_write_finish_row\n");
  202499. /* next row */
  202500. png_ptr->row_number++;
  202501. /* see if we are done */
  202502. if (png_ptr->row_number < png_ptr->num_rows)
  202503. return;
  202504. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202505. /* if interlaced, go to next pass */
  202506. if (png_ptr->interlaced)
  202507. {
  202508. png_ptr->row_number = 0;
  202509. if (png_ptr->transformations & PNG_INTERLACE)
  202510. {
  202511. png_ptr->pass++;
  202512. }
  202513. else
  202514. {
  202515. /* loop until we find a non-zero width or height pass */
  202516. do
  202517. {
  202518. png_ptr->pass++;
  202519. if (png_ptr->pass >= 7)
  202520. break;
  202521. png_ptr->usr_width = (png_ptr->width +
  202522. png_pass_inc[png_ptr->pass] - 1 -
  202523. png_pass_start[png_ptr->pass]) /
  202524. png_pass_inc[png_ptr->pass];
  202525. png_ptr->num_rows = (png_ptr->height +
  202526. png_pass_yinc[png_ptr->pass] - 1 -
  202527. png_pass_ystart[png_ptr->pass]) /
  202528. png_pass_yinc[png_ptr->pass];
  202529. if (png_ptr->transformations & PNG_INTERLACE)
  202530. break;
  202531. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202532. }
  202533. /* reset the row above the image for the next pass */
  202534. if (png_ptr->pass < 7)
  202535. {
  202536. if (png_ptr->prev_row != NULL)
  202537. png_memset(png_ptr->prev_row, 0,
  202538. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202539. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202540. return;
  202541. }
  202542. }
  202543. #endif
  202544. /* if we get here, we've just written the last row, so we need
  202545. to flush the compressor */
  202546. do
  202547. {
  202548. /* tell the compressor we are done */
  202549. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202550. /* check for an error */
  202551. if (ret == Z_OK)
  202552. {
  202553. /* check to see if we need more room */
  202554. if (!(png_ptr->zstream.avail_out))
  202555. {
  202556. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202557. png_ptr->zstream.next_out = png_ptr->zbuf;
  202558. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202559. }
  202560. }
  202561. else if (ret != Z_STREAM_END)
  202562. {
  202563. if (png_ptr->zstream.msg != NULL)
  202564. png_error(png_ptr, png_ptr->zstream.msg);
  202565. else
  202566. png_error(png_ptr, "zlib error");
  202567. }
  202568. } while (ret != Z_STREAM_END);
  202569. /* write any extra space */
  202570. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202571. {
  202572. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202573. png_ptr->zstream.avail_out);
  202574. }
  202575. deflateReset(&png_ptr->zstream);
  202576. png_ptr->zstream.data_type = Z_BINARY;
  202577. }
  202578. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202579. /* Pick out the correct pixels for the interlace pass.
  202580. * The basic idea here is to go through the row with a source
  202581. * pointer and a destination pointer (sp and dp), and copy the
  202582. * correct pixels for the pass. As the row gets compacted,
  202583. * sp will always be >= dp, so we should never overwrite anything.
  202584. * See the default: case for the easiest code to understand.
  202585. */
  202586. void /* PRIVATE */
  202587. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202588. {
  202589. #ifdef PNG_USE_LOCAL_ARRAYS
  202590. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202591. /* start of interlace block */
  202592. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202593. /* offset to next interlace block */
  202594. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202595. #endif
  202596. png_debug(1, "in png_do_write_interlace\n");
  202597. /* we don't have to do anything on the last pass (6) */
  202598. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202599. if (row != NULL && row_info != NULL && pass < 6)
  202600. #else
  202601. if (pass < 6)
  202602. #endif
  202603. {
  202604. /* each pixel depth is handled separately */
  202605. switch (row_info->pixel_depth)
  202606. {
  202607. case 1:
  202608. {
  202609. png_bytep sp;
  202610. png_bytep dp;
  202611. int shift;
  202612. int d;
  202613. int value;
  202614. png_uint_32 i;
  202615. png_uint_32 row_width = row_info->width;
  202616. dp = row;
  202617. d = 0;
  202618. shift = 7;
  202619. for (i = png_pass_start[pass]; i < row_width;
  202620. i += png_pass_inc[pass])
  202621. {
  202622. sp = row + (png_size_t)(i >> 3);
  202623. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202624. d |= (value << shift);
  202625. if (shift == 0)
  202626. {
  202627. shift = 7;
  202628. *dp++ = (png_byte)d;
  202629. d = 0;
  202630. }
  202631. else
  202632. shift--;
  202633. }
  202634. if (shift != 7)
  202635. *dp = (png_byte)d;
  202636. break;
  202637. }
  202638. case 2:
  202639. {
  202640. png_bytep sp;
  202641. png_bytep dp;
  202642. int shift;
  202643. int d;
  202644. int value;
  202645. png_uint_32 i;
  202646. png_uint_32 row_width = row_info->width;
  202647. dp = row;
  202648. shift = 6;
  202649. d = 0;
  202650. for (i = png_pass_start[pass]; i < row_width;
  202651. i += png_pass_inc[pass])
  202652. {
  202653. sp = row + (png_size_t)(i >> 2);
  202654. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202655. d |= (value << shift);
  202656. if (shift == 0)
  202657. {
  202658. shift = 6;
  202659. *dp++ = (png_byte)d;
  202660. d = 0;
  202661. }
  202662. else
  202663. shift -= 2;
  202664. }
  202665. if (shift != 6)
  202666. *dp = (png_byte)d;
  202667. break;
  202668. }
  202669. case 4:
  202670. {
  202671. png_bytep sp;
  202672. png_bytep dp;
  202673. int shift;
  202674. int d;
  202675. int value;
  202676. png_uint_32 i;
  202677. png_uint_32 row_width = row_info->width;
  202678. dp = row;
  202679. shift = 4;
  202680. d = 0;
  202681. for (i = png_pass_start[pass]; i < row_width;
  202682. i += png_pass_inc[pass])
  202683. {
  202684. sp = row + (png_size_t)(i >> 1);
  202685. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202686. d |= (value << shift);
  202687. if (shift == 0)
  202688. {
  202689. shift = 4;
  202690. *dp++ = (png_byte)d;
  202691. d = 0;
  202692. }
  202693. else
  202694. shift -= 4;
  202695. }
  202696. if (shift != 4)
  202697. *dp = (png_byte)d;
  202698. break;
  202699. }
  202700. default:
  202701. {
  202702. png_bytep sp;
  202703. png_bytep dp;
  202704. png_uint_32 i;
  202705. png_uint_32 row_width = row_info->width;
  202706. png_size_t pixel_bytes;
  202707. /* start at the beginning */
  202708. dp = row;
  202709. /* find out how many bytes each pixel takes up */
  202710. pixel_bytes = (row_info->pixel_depth >> 3);
  202711. /* loop through the row, only looking at the pixels that
  202712. matter */
  202713. for (i = png_pass_start[pass]; i < row_width;
  202714. i += png_pass_inc[pass])
  202715. {
  202716. /* find out where the original pixel is */
  202717. sp = row + (png_size_t)i * pixel_bytes;
  202718. /* move the pixel */
  202719. if (dp != sp)
  202720. png_memcpy(dp, sp, pixel_bytes);
  202721. /* next pixel */
  202722. dp += pixel_bytes;
  202723. }
  202724. break;
  202725. }
  202726. }
  202727. /* set new row width */
  202728. row_info->width = (row_info->width +
  202729. png_pass_inc[pass] - 1 -
  202730. png_pass_start[pass]) /
  202731. png_pass_inc[pass];
  202732. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202733. row_info->width);
  202734. }
  202735. }
  202736. #endif
  202737. /* This filters the row, chooses which filter to use, if it has not already
  202738. * been specified by the application, and then writes the row out with the
  202739. * chosen filter.
  202740. */
  202741. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202742. #define PNG_HISHIFT 10
  202743. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202744. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202745. void /* PRIVATE */
  202746. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202747. {
  202748. png_bytep best_row;
  202749. #ifndef PNG_NO_WRITE_FILTER
  202750. png_bytep prev_row, row_buf;
  202751. png_uint_32 mins, bpp;
  202752. png_byte filter_to_do = png_ptr->do_filter;
  202753. png_uint_32 row_bytes = row_info->rowbytes;
  202754. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202755. int num_p_filters = (int)png_ptr->num_prev_filters;
  202756. #endif
  202757. png_debug(1, "in png_write_find_filter\n");
  202758. /* find out how many bytes offset each pixel is */
  202759. bpp = (row_info->pixel_depth + 7) >> 3;
  202760. prev_row = png_ptr->prev_row;
  202761. #endif
  202762. best_row = png_ptr->row_buf;
  202763. #ifndef PNG_NO_WRITE_FILTER
  202764. row_buf = best_row;
  202765. mins = PNG_MAXSUM;
  202766. /* The prediction method we use is to find which method provides the
  202767. * smallest value when summing the absolute values of the distances
  202768. * from zero, using anything >= 128 as negative numbers. This is known
  202769. * as the "minimum sum of absolute differences" heuristic. Other
  202770. * heuristics are the "weighted minimum sum of absolute differences"
  202771. * (experimental and can in theory improve compression), and the "zlib
  202772. * predictive" method (not implemented yet), which does test compressions
  202773. * of lines using different filter methods, and then chooses the
  202774. * (series of) filter(s) that give minimum compressed data size (VERY
  202775. * computationally expensive).
  202776. *
  202777. * GRR 980525: consider also
  202778. * (1) minimum sum of absolute differences from running average (i.e.,
  202779. * keep running sum of non-absolute differences & count of bytes)
  202780. * [track dispersion, too? restart average if dispersion too large?]
  202781. * (1b) minimum sum of absolute differences from sliding average, probably
  202782. * with window size <= deflate window (usually 32K)
  202783. * (2) minimum sum of squared differences from zero or running average
  202784. * (i.e., ~ root-mean-square approach)
  202785. */
  202786. /* We don't need to test the 'no filter' case if this is the only filter
  202787. * that has been chosen, as it doesn't actually do anything to the data.
  202788. */
  202789. if ((filter_to_do & PNG_FILTER_NONE) &&
  202790. filter_to_do != PNG_FILTER_NONE)
  202791. {
  202792. png_bytep rp;
  202793. png_uint_32 sum = 0;
  202794. png_uint_32 i;
  202795. int v;
  202796. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202797. {
  202798. v = *rp;
  202799. sum += (v < 128) ? v : 256 - v;
  202800. }
  202801. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202802. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202803. {
  202804. png_uint_32 sumhi, sumlo;
  202805. int j;
  202806. sumlo = sum & PNG_LOMASK;
  202807. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202808. /* Reduce the sum if we match any of the previous rows */
  202809. for (j = 0; j < num_p_filters; j++)
  202810. {
  202811. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202812. {
  202813. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202814. PNG_WEIGHT_SHIFT;
  202815. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202816. PNG_WEIGHT_SHIFT;
  202817. }
  202818. }
  202819. /* Factor in the cost of this filter (this is here for completeness,
  202820. * but it makes no sense to have a "cost" for the NONE filter, as
  202821. * it has the minimum possible computational cost - none).
  202822. */
  202823. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202824. PNG_COST_SHIFT;
  202825. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202826. PNG_COST_SHIFT;
  202827. if (sumhi > PNG_HIMASK)
  202828. sum = PNG_MAXSUM;
  202829. else
  202830. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202831. }
  202832. #endif
  202833. mins = sum;
  202834. }
  202835. /* sub filter */
  202836. if (filter_to_do == PNG_FILTER_SUB)
  202837. /* it's the only filter so no testing is needed */
  202838. {
  202839. png_bytep rp, lp, dp;
  202840. png_uint_32 i;
  202841. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202842. i++, rp++, dp++)
  202843. {
  202844. *dp = *rp;
  202845. }
  202846. for (lp = row_buf + 1; i < row_bytes;
  202847. i++, rp++, lp++, dp++)
  202848. {
  202849. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202850. }
  202851. best_row = png_ptr->sub_row;
  202852. }
  202853. else if (filter_to_do & PNG_FILTER_SUB)
  202854. {
  202855. png_bytep rp, dp, lp;
  202856. png_uint_32 sum = 0, lmins = mins;
  202857. png_uint_32 i;
  202858. int v;
  202859. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202860. /* We temporarily increase the "minimum sum" by the factor we
  202861. * would reduce the sum of this filter, so that we can do the
  202862. * early exit comparison without scaling the sum each time.
  202863. */
  202864. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202865. {
  202866. int j;
  202867. png_uint_32 lmhi, lmlo;
  202868. lmlo = lmins & PNG_LOMASK;
  202869. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202870. for (j = 0; j < num_p_filters; j++)
  202871. {
  202872. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202873. {
  202874. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202875. PNG_WEIGHT_SHIFT;
  202876. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202877. PNG_WEIGHT_SHIFT;
  202878. }
  202879. }
  202880. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202881. PNG_COST_SHIFT;
  202882. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202883. PNG_COST_SHIFT;
  202884. if (lmhi > PNG_HIMASK)
  202885. lmins = PNG_MAXSUM;
  202886. else
  202887. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202888. }
  202889. #endif
  202890. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202891. i++, rp++, dp++)
  202892. {
  202893. v = *dp = *rp;
  202894. sum += (v < 128) ? v : 256 - v;
  202895. }
  202896. for (lp = row_buf + 1; i < row_bytes;
  202897. i++, rp++, lp++, dp++)
  202898. {
  202899. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202900. sum += (v < 128) ? v : 256 - v;
  202901. if (sum > lmins) /* We are already worse, don't continue. */
  202902. break;
  202903. }
  202904. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202905. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202906. {
  202907. int j;
  202908. png_uint_32 sumhi, sumlo;
  202909. sumlo = sum & PNG_LOMASK;
  202910. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202911. for (j = 0; j < num_p_filters; j++)
  202912. {
  202913. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202914. {
  202915. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202916. PNG_WEIGHT_SHIFT;
  202917. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202918. PNG_WEIGHT_SHIFT;
  202919. }
  202920. }
  202921. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202922. PNG_COST_SHIFT;
  202923. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202924. PNG_COST_SHIFT;
  202925. if (sumhi > PNG_HIMASK)
  202926. sum = PNG_MAXSUM;
  202927. else
  202928. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202929. }
  202930. #endif
  202931. if (sum < mins)
  202932. {
  202933. mins = sum;
  202934. best_row = png_ptr->sub_row;
  202935. }
  202936. }
  202937. /* up filter */
  202938. if (filter_to_do == PNG_FILTER_UP)
  202939. {
  202940. png_bytep rp, dp, pp;
  202941. png_uint_32 i;
  202942. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202943. pp = prev_row + 1; i < row_bytes;
  202944. i++, rp++, pp++, dp++)
  202945. {
  202946. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202947. }
  202948. best_row = png_ptr->up_row;
  202949. }
  202950. else if (filter_to_do & PNG_FILTER_UP)
  202951. {
  202952. png_bytep rp, dp, pp;
  202953. png_uint_32 sum = 0, lmins = mins;
  202954. png_uint_32 i;
  202955. int v;
  202956. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202957. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202958. {
  202959. int j;
  202960. png_uint_32 lmhi, lmlo;
  202961. lmlo = lmins & PNG_LOMASK;
  202962. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202963. for (j = 0; j < num_p_filters; j++)
  202964. {
  202965. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202966. {
  202967. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202968. PNG_WEIGHT_SHIFT;
  202969. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202970. PNG_WEIGHT_SHIFT;
  202971. }
  202972. }
  202973. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202974. PNG_COST_SHIFT;
  202975. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202976. PNG_COST_SHIFT;
  202977. if (lmhi > PNG_HIMASK)
  202978. lmins = PNG_MAXSUM;
  202979. else
  202980. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202981. }
  202982. #endif
  202983. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202984. pp = prev_row + 1; i < row_bytes; i++)
  202985. {
  202986. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202987. sum += (v < 128) ? v : 256 - v;
  202988. if (sum > lmins) /* We are already worse, don't continue. */
  202989. break;
  202990. }
  202991. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202992. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202993. {
  202994. int j;
  202995. png_uint_32 sumhi, sumlo;
  202996. sumlo = sum & PNG_LOMASK;
  202997. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202998. for (j = 0; j < num_p_filters; j++)
  202999. {
  203000. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  203001. {
  203002. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203003. PNG_WEIGHT_SHIFT;
  203004. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203005. PNG_WEIGHT_SHIFT;
  203006. }
  203007. }
  203008. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203009. PNG_COST_SHIFT;
  203010. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203011. PNG_COST_SHIFT;
  203012. if (sumhi > PNG_HIMASK)
  203013. sum = PNG_MAXSUM;
  203014. else
  203015. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203016. }
  203017. #endif
  203018. if (sum < mins)
  203019. {
  203020. mins = sum;
  203021. best_row = png_ptr->up_row;
  203022. }
  203023. }
  203024. /* avg filter */
  203025. if (filter_to_do == PNG_FILTER_AVG)
  203026. {
  203027. png_bytep rp, dp, pp, lp;
  203028. png_uint_32 i;
  203029. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203030. pp = prev_row + 1; i < bpp; i++)
  203031. {
  203032. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203033. }
  203034. for (lp = row_buf + 1; i < row_bytes; i++)
  203035. {
  203036. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203037. & 0xff);
  203038. }
  203039. best_row = png_ptr->avg_row;
  203040. }
  203041. else if (filter_to_do & PNG_FILTER_AVG)
  203042. {
  203043. png_bytep rp, dp, pp, lp;
  203044. png_uint_32 sum = 0, lmins = mins;
  203045. png_uint_32 i;
  203046. int v;
  203047. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203048. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203049. {
  203050. int j;
  203051. png_uint_32 lmhi, lmlo;
  203052. lmlo = lmins & PNG_LOMASK;
  203053. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203054. for (j = 0; j < num_p_filters; j++)
  203055. {
  203056. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203057. {
  203058. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203059. PNG_WEIGHT_SHIFT;
  203060. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203061. PNG_WEIGHT_SHIFT;
  203062. }
  203063. }
  203064. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203065. PNG_COST_SHIFT;
  203066. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203067. PNG_COST_SHIFT;
  203068. if (lmhi > PNG_HIMASK)
  203069. lmins = PNG_MAXSUM;
  203070. else
  203071. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203072. }
  203073. #endif
  203074. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203075. pp = prev_row + 1; i < bpp; i++)
  203076. {
  203077. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203078. sum += (v < 128) ? v : 256 - v;
  203079. }
  203080. for (lp = row_buf + 1; i < row_bytes; i++)
  203081. {
  203082. v = *dp++ =
  203083. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203084. sum += (v < 128) ? v : 256 - v;
  203085. if (sum > lmins) /* We are already worse, don't continue. */
  203086. break;
  203087. }
  203088. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203089. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203090. {
  203091. int j;
  203092. png_uint_32 sumhi, sumlo;
  203093. sumlo = sum & PNG_LOMASK;
  203094. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203095. for (j = 0; j < num_p_filters; j++)
  203096. {
  203097. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203098. {
  203099. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203100. PNG_WEIGHT_SHIFT;
  203101. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203102. PNG_WEIGHT_SHIFT;
  203103. }
  203104. }
  203105. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203106. PNG_COST_SHIFT;
  203107. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203108. PNG_COST_SHIFT;
  203109. if (sumhi > PNG_HIMASK)
  203110. sum = PNG_MAXSUM;
  203111. else
  203112. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203113. }
  203114. #endif
  203115. if (sum < mins)
  203116. {
  203117. mins = sum;
  203118. best_row = png_ptr->avg_row;
  203119. }
  203120. }
  203121. /* Paeth filter */
  203122. if (filter_to_do == PNG_FILTER_PAETH)
  203123. {
  203124. png_bytep rp, dp, pp, cp, lp;
  203125. png_uint_32 i;
  203126. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203127. pp = prev_row + 1; i < bpp; i++)
  203128. {
  203129. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203130. }
  203131. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203132. {
  203133. int a, b, c, pa, pb, pc, p;
  203134. b = *pp++;
  203135. c = *cp++;
  203136. a = *lp++;
  203137. p = b - c;
  203138. pc = a - c;
  203139. #ifdef PNG_USE_ABS
  203140. pa = abs(p);
  203141. pb = abs(pc);
  203142. pc = abs(p + pc);
  203143. #else
  203144. pa = p < 0 ? -p : p;
  203145. pb = pc < 0 ? -pc : pc;
  203146. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203147. #endif
  203148. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203149. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203150. }
  203151. best_row = png_ptr->paeth_row;
  203152. }
  203153. else if (filter_to_do & PNG_FILTER_PAETH)
  203154. {
  203155. png_bytep rp, dp, pp, cp, lp;
  203156. png_uint_32 sum = 0, lmins = mins;
  203157. png_uint_32 i;
  203158. int v;
  203159. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203160. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203161. {
  203162. int j;
  203163. png_uint_32 lmhi, lmlo;
  203164. lmlo = lmins & PNG_LOMASK;
  203165. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203166. for (j = 0; j < num_p_filters; j++)
  203167. {
  203168. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203169. {
  203170. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203171. PNG_WEIGHT_SHIFT;
  203172. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203173. PNG_WEIGHT_SHIFT;
  203174. }
  203175. }
  203176. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203177. PNG_COST_SHIFT;
  203178. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203179. PNG_COST_SHIFT;
  203180. if (lmhi > PNG_HIMASK)
  203181. lmins = PNG_MAXSUM;
  203182. else
  203183. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203184. }
  203185. #endif
  203186. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203187. pp = prev_row + 1; i < bpp; i++)
  203188. {
  203189. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203190. sum += (v < 128) ? v : 256 - v;
  203191. }
  203192. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203193. {
  203194. int a, b, c, pa, pb, pc, p;
  203195. b = *pp++;
  203196. c = *cp++;
  203197. a = *lp++;
  203198. #ifndef PNG_SLOW_PAETH
  203199. p = b - c;
  203200. pc = a - c;
  203201. #ifdef PNG_USE_ABS
  203202. pa = abs(p);
  203203. pb = abs(pc);
  203204. pc = abs(p + pc);
  203205. #else
  203206. pa = p < 0 ? -p : p;
  203207. pb = pc < 0 ? -pc : pc;
  203208. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203209. #endif
  203210. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203211. #else /* PNG_SLOW_PAETH */
  203212. p = a + b - c;
  203213. pa = abs(p - a);
  203214. pb = abs(p - b);
  203215. pc = abs(p - c);
  203216. if (pa <= pb && pa <= pc)
  203217. p = a;
  203218. else if (pb <= pc)
  203219. p = b;
  203220. else
  203221. p = c;
  203222. #endif /* PNG_SLOW_PAETH */
  203223. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203224. sum += (v < 128) ? v : 256 - v;
  203225. if (sum > lmins) /* We are already worse, don't continue. */
  203226. break;
  203227. }
  203228. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203229. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203230. {
  203231. int j;
  203232. png_uint_32 sumhi, sumlo;
  203233. sumlo = sum & PNG_LOMASK;
  203234. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203235. for (j = 0; j < num_p_filters; j++)
  203236. {
  203237. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203238. {
  203239. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203240. PNG_WEIGHT_SHIFT;
  203241. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203242. PNG_WEIGHT_SHIFT;
  203243. }
  203244. }
  203245. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203246. PNG_COST_SHIFT;
  203247. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203248. PNG_COST_SHIFT;
  203249. if (sumhi > PNG_HIMASK)
  203250. sum = PNG_MAXSUM;
  203251. else
  203252. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203253. }
  203254. #endif
  203255. if (sum < mins)
  203256. {
  203257. best_row = png_ptr->paeth_row;
  203258. }
  203259. }
  203260. #endif /* PNG_NO_WRITE_FILTER */
  203261. /* Do the actual writing of the filtered row data from the chosen filter. */
  203262. png_write_filtered_row(png_ptr, best_row);
  203263. #ifndef PNG_NO_WRITE_FILTER
  203264. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203265. /* Save the type of filter we picked this time for future calculations */
  203266. if (png_ptr->num_prev_filters > 0)
  203267. {
  203268. int j;
  203269. for (j = 1; j < num_p_filters; j++)
  203270. {
  203271. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203272. }
  203273. png_ptr->prev_filters[j] = best_row[0];
  203274. }
  203275. #endif
  203276. #endif /* PNG_NO_WRITE_FILTER */
  203277. }
  203278. /* Do the actual writing of a previously filtered row. */
  203279. void /* PRIVATE */
  203280. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203281. {
  203282. png_debug(1, "in png_write_filtered_row\n");
  203283. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203284. /* set up the zlib input buffer */
  203285. png_ptr->zstream.next_in = filtered_row;
  203286. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203287. /* repeat until we have compressed all the data */
  203288. do
  203289. {
  203290. int ret; /* return of zlib */
  203291. /* compress the data */
  203292. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203293. /* check for compression errors */
  203294. if (ret != Z_OK)
  203295. {
  203296. if (png_ptr->zstream.msg != NULL)
  203297. png_error(png_ptr, png_ptr->zstream.msg);
  203298. else
  203299. png_error(png_ptr, "zlib error");
  203300. }
  203301. /* see if it is time to write another IDAT */
  203302. if (!(png_ptr->zstream.avail_out))
  203303. {
  203304. /* write the IDAT and reset the zlib output buffer */
  203305. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203306. png_ptr->zstream.next_out = png_ptr->zbuf;
  203307. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203308. }
  203309. /* repeat until all data has been compressed */
  203310. } while (png_ptr->zstream.avail_in);
  203311. /* swap the current and previous rows */
  203312. if (png_ptr->prev_row != NULL)
  203313. {
  203314. png_bytep tptr;
  203315. tptr = png_ptr->prev_row;
  203316. png_ptr->prev_row = png_ptr->row_buf;
  203317. png_ptr->row_buf = tptr;
  203318. }
  203319. /* finish row - updates counters and flushes zlib if last row */
  203320. png_write_finish_row(png_ptr);
  203321. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203322. png_ptr->flush_rows++;
  203323. if (png_ptr->flush_dist > 0 &&
  203324. png_ptr->flush_rows >= png_ptr->flush_dist)
  203325. {
  203326. png_write_flush(png_ptr);
  203327. }
  203328. #endif
  203329. }
  203330. #endif /* PNG_WRITE_SUPPORTED */
  203331. /*** End of inlined file: pngwutil.c ***/
  203332. #else
  203333. extern "C"
  203334. {
  203335. #include <png.h>
  203336. #include <pngconf.h>
  203337. }
  203338. #endif
  203339. }
  203340. #undef max
  203341. #undef min
  203342. #if JUCE_MSVC
  203343. #pragma warning (pop)
  203344. #endif
  203345. BEGIN_JUCE_NAMESPACE
  203346. using ::calloc;
  203347. using ::malloc;
  203348. using ::free;
  203349. namespace PNGHelpers
  203350. {
  203351. using namespace pnglibNamespace;
  203352. static void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203353. {
  203354. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203355. }
  203356. static void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203357. {
  203358. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203359. }
  203360. struct PNGErrorStruct {};
  203361. static void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203362. {
  203363. throw PNGErrorStruct();
  203364. }
  203365. }
  203366. PNGImageFormat::PNGImageFormat() {}
  203367. PNGImageFormat::~PNGImageFormat() {}
  203368. const String PNGImageFormat::getFormatName()
  203369. {
  203370. return "PNG";
  203371. }
  203372. bool PNGImageFormat::canUnderstand (InputStream& in)
  203373. {
  203374. const int bytesNeeded = 4;
  203375. char header [bytesNeeded];
  203376. return in.read (header, bytesNeeded) == bytesNeeded
  203377. && header[1] == 'P'
  203378. && header[2] == 'N'
  203379. && header[3] == 'G';
  203380. }
  203381. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203382. const Image juce_loadWithCoreImage (InputStream& input);
  203383. #endif
  203384. const Image PNGImageFormat::decodeImage (InputStream& in)
  203385. {
  203386. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203387. return juce_loadWithCoreImage (in);
  203388. #else
  203389. using namespace pnglibNamespace;
  203390. Image image;
  203391. png_structp pngReadStruct;
  203392. png_infop pngInfoStruct;
  203393. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203394. if (pngReadStruct != 0)
  203395. {
  203396. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203397. if (pngInfoStruct == 0)
  203398. {
  203399. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203400. return Image::null;
  203401. }
  203402. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203403. // read the header..
  203404. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203405. png_uint_32 width, height;
  203406. int bitDepth, colorType, interlaceType;
  203407. png_read_info (pngReadStruct, pngInfoStruct);
  203408. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203409. &width, &height,
  203410. &bitDepth, &colorType,
  203411. &interlaceType, 0, 0);
  203412. if (bitDepth == 16)
  203413. png_set_strip_16 (pngReadStruct);
  203414. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203415. png_set_expand (pngReadStruct);
  203416. if (bitDepth < 8)
  203417. png_set_expand (pngReadStruct);
  203418. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203419. png_set_expand (pngReadStruct);
  203420. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203421. png_set_gray_to_rgb (pngReadStruct);
  203422. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203423. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203424. || pngInfoStruct->num_trans > 0;
  203425. // Load the image into a temp buffer in the pnglib format..
  203426. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203427. {
  203428. HeapBlock <png_bytep> rows (height);
  203429. for (int y = (int) height; --y >= 0;)
  203430. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203431. png_read_image (pngReadStruct, rows);
  203432. png_read_end (pngReadStruct, pngInfoStruct);
  203433. }
  203434. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203435. // now convert the data to a juce image format..
  203436. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203437. (int) width, (int) height, hasAlphaChan);
  203438. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203439. const Image::BitmapData destData (image, true);
  203440. uint8* srcRow = tempBuffer;
  203441. uint8* destRow = destData.data;
  203442. for (int y = 0; y < (int) height; ++y)
  203443. {
  203444. const uint8* src = srcRow;
  203445. srcRow += (width << 2);
  203446. uint8* dest = destRow;
  203447. destRow += destData.lineStride;
  203448. if (hasAlphaChan)
  203449. {
  203450. for (int i = (int) width; --i >= 0;)
  203451. {
  203452. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203453. ((PixelARGB*) dest)->premultiply();
  203454. dest += destData.pixelStride;
  203455. src += 4;
  203456. }
  203457. }
  203458. else
  203459. {
  203460. for (int i = (int) width; --i >= 0;)
  203461. {
  203462. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203463. dest += destData.pixelStride;
  203464. src += 4;
  203465. }
  203466. }
  203467. }
  203468. }
  203469. return image;
  203470. #endif
  203471. }
  203472. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203473. {
  203474. using namespace pnglibNamespace;
  203475. const int width = image.getWidth();
  203476. const int height = image.getHeight();
  203477. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203478. if (pngWriteStruct == 0)
  203479. return false;
  203480. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203481. if (pngInfoStruct == 0)
  203482. {
  203483. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203484. return false;
  203485. }
  203486. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203487. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203488. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203489. : PNG_COLOR_TYPE_RGB,
  203490. PNG_INTERLACE_NONE,
  203491. PNG_COMPRESSION_TYPE_BASE,
  203492. PNG_FILTER_TYPE_BASE);
  203493. HeapBlock <uint8> rowData (width * 4);
  203494. png_color_8 sig_bit;
  203495. sig_bit.red = 8;
  203496. sig_bit.green = 8;
  203497. sig_bit.blue = 8;
  203498. sig_bit.alpha = 8;
  203499. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203500. png_write_info (pngWriteStruct, pngInfoStruct);
  203501. png_set_shift (pngWriteStruct, &sig_bit);
  203502. png_set_packing (pngWriteStruct);
  203503. const Image::BitmapData srcData (image, false);
  203504. for (int y = 0; y < height; ++y)
  203505. {
  203506. uint8* dst = rowData;
  203507. const uint8* src = srcData.getLinePointer (y);
  203508. if (image.hasAlphaChannel())
  203509. {
  203510. for (int i = width; --i >= 0;)
  203511. {
  203512. PixelARGB p (*(const PixelARGB*) src);
  203513. p.unpremultiply();
  203514. *dst++ = p.getRed();
  203515. *dst++ = p.getGreen();
  203516. *dst++ = p.getBlue();
  203517. *dst++ = p.getAlpha();
  203518. src += srcData.pixelStride;
  203519. }
  203520. }
  203521. else
  203522. {
  203523. for (int i = width; --i >= 0;)
  203524. {
  203525. *dst++ = ((const PixelRGB*) src)->getRed();
  203526. *dst++ = ((const PixelRGB*) src)->getGreen();
  203527. *dst++ = ((const PixelRGB*) src)->getBlue();
  203528. src += srcData.pixelStride;
  203529. }
  203530. }
  203531. png_bytep rowPtr = rowData;
  203532. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203533. }
  203534. png_write_end (pngWriteStruct, pngInfoStruct);
  203535. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203536. out.flush();
  203537. return true;
  203538. }
  203539. END_JUCE_NAMESPACE
  203540. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203541. #endif
  203542. //==============================================================================
  203543. #if JUCE_BUILD_NATIVE
  203544. // Non-public headers that are needed by more than one platform must be included
  203545. // before the platform-specific sections..
  203546. BEGIN_JUCE_NAMESPACE
  203547. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203548. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203549. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203550. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203551. /**
  203552. Helper class that takes chunks of incoming midi bytes, packages them into
  203553. messages, and dispatches them to a midi callback.
  203554. */
  203555. class MidiDataConcatenator
  203556. {
  203557. public:
  203558. MidiDataConcatenator (const int initialBufferSize)
  203559. : pendingData (initialBufferSize),
  203560. pendingBytes (0), pendingDataTime (0)
  203561. {
  203562. }
  203563. void reset()
  203564. {
  203565. pendingBytes = 0;
  203566. pendingDataTime = 0;
  203567. }
  203568. void pushMidiData (const void* data, int numBytes, double time,
  203569. MidiInput* input, MidiInputCallback& callback)
  203570. {
  203571. const uint8* d = static_cast <const uint8*> (data);
  203572. while (numBytes > 0)
  203573. {
  203574. if (pendingBytes > 0 || d[0] == 0xf0)
  203575. {
  203576. processSysex (d, numBytes, time, input, callback);
  203577. }
  203578. else
  203579. {
  203580. int used = 0;
  203581. const MidiMessage m (d, numBytes, used, 0, time);
  203582. if (used <= 0)
  203583. break; // malformed message..
  203584. callback.handleIncomingMidiMessage (input, m);
  203585. numBytes -= used;
  203586. d += used;
  203587. }
  203588. }
  203589. }
  203590. private:
  203591. void processSysex (const uint8*& d, int& numBytes, double time,
  203592. MidiInput* input, MidiInputCallback& callback)
  203593. {
  203594. if (*d == 0xf0)
  203595. {
  203596. pendingBytes = 0;
  203597. pendingDataTime = time;
  203598. }
  203599. pendingData.ensureSize (pendingBytes + numBytes, false);
  203600. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203601. uint8* dest = totalMessage + pendingBytes;
  203602. do
  203603. {
  203604. if (pendingBytes > 0 && *d >= 0x80)
  203605. {
  203606. if (*d >= 0xfa || *d == 0xf8)
  203607. {
  203608. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203609. ++d;
  203610. --numBytes;
  203611. }
  203612. else
  203613. {
  203614. if (*d == 0xf7)
  203615. {
  203616. *dest++ = *d++;
  203617. pendingBytes++;
  203618. --numBytes;
  203619. }
  203620. break;
  203621. }
  203622. }
  203623. else
  203624. {
  203625. *dest++ = *d++;
  203626. pendingBytes++;
  203627. --numBytes;
  203628. }
  203629. }
  203630. while (numBytes > 0);
  203631. if (pendingBytes > 0)
  203632. {
  203633. if (totalMessage [pendingBytes - 1] == 0xf7)
  203634. {
  203635. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203636. pendingBytes = 0;
  203637. }
  203638. else
  203639. {
  203640. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203641. }
  203642. }
  203643. }
  203644. MemoryBlock pendingData;
  203645. int pendingBytes;
  203646. double pendingDataTime;
  203647. MidiDataConcatenator (const MidiDataConcatenator&);
  203648. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203649. };
  203650. #endif
  203651. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203652. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203653. END_JUCE_NAMESPACE
  203654. #if JUCE_WINDOWS
  203655. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203656. /*
  203657. This file wraps together all the win32-specific code, so that
  203658. we can include all the native headers just once, and compile all our
  203659. platform-specific stuff in one big lump, keeping it out of the way of
  203660. the rest of the codebase.
  203661. */
  203662. #if JUCE_WINDOWS
  203663. BEGIN_JUCE_NAMESPACE
  203664. #define JUCE_INCLUDED_FILE 1
  203665. // Now include the actual code files..
  203666. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203667. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203668. // compiled on its own).
  203669. #if JUCE_INCLUDED_FILE
  203670. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203671. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203672. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203673. #ifndef DOXYGEN
  203674. // use with DynamicLibraryLoader to simplify importing functions
  203675. //
  203676. // functionName: function to import
  203677. // localFunctionName: name you want to use to actually call it (must be different)
  203678. // returnType: the return type
  203679. // object: the DynamicLibraryLoader to use
  203680. // params: list of params (bracketed)
  203681. //
  203682. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203683. typedef returnType (WINAPI *type##localFunctionName) params; \
  203684. type##localFunctionName localFunctionName \
  203685. = (type##localFunctionName)object.findProcAddress (#functionName);
  203686. // loads and unloads a DLL automatically
  203687. class JUCE_API DynamicLibraryLoader
  203688. {
  203689. public:
  203690. DynamicLibraryLoader (const String& name);
  203691. ~DynamicLibraryLoader();
  203692. void* findProcAddress (const String& functionName);
  203693. private:
  203694. void* libHandle;
  203695. };
  203696. #endif
  203697. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203698. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203699. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203700. {
  203701. libHandle = LoadLibrary (name);
  203702. }
  203703. DynamicLibraryLoader::~DynamicLibraryLoader()
  203704. {
  203705. FreeLibrary ((HMODULE) libHandle);
  203706. }
  203707. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203708. {
  203709. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203710. }
  203711. #endif
  203712. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203713. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203714. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203715. // compiled on its own).
  203716. #if JUCE_INCLUDED_FILE
  203717. extern void juce_initialiseThreadEvents();
  203718. void Logger::outputDebugString (const String& text)
  203719. {
  203720. OutputDebugString (text + "\n");
  203721. }
  203722. static int64 hiResTicksPerSecond;
  203723. static double hiResTicksScaleFactor;
  203724. #if JUCE_USE_INTRINSICS
  203725. // CPU info functions using intrinsics...
  203726. #pragma intrinsic (__cpuid)
  203727. #pragma intrinsic (__rdtsc)
  203728. const String SystemStats::getCpuVendor()
  203729. {
  203730. int info [4];
  203731. __cpuid (info, 0);
  203732. char v [12];
  203733. memcpy (v, info + 1, 4);
  203734. memcpy (v + 4, info + 3, 4);
  203735. memcpy (v + 8, info + 2, 4);
  203736. return String (v, 12);
  203737. }
  203738. #else
  203739. // CPU info functions using old fashioned inline asm...
  203740. static void juce_getCpuVendor (char* const v)
  203741. {
  203742. int vendor[4];
  203743. zeromem (vendor, 16);
  203744. #ifdef JUCE_64BIT
  203745. #else
  203746. #ifndef __MINGW32__
  203747. __try
  203748. #endif
  203749. {
  203750. #if JUCE_GCC
  203751. unsigned int dummy = 0;
  203752. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203753. #else
  203754. __asm
  203755. {
  203756. mov eax, 0
  203757. cpuid
  203758. mov [vendor], ebx
  203759. mov [vendor + 4], edx
  203760. mov [vendor + 8], ecx
  203761. }
  203762. #endif
  203763. }
  203764. #ifndef __MINGW32__
  203765. __except (EXCEPTION_EXECUTE_HANDLER)
  203766. {
  203767. *v = 0;
  203768. }
  203769. #endif
  203770. #endif
  203771. memcpy (v, vendor, 16);
  203772. }
  203773. const String SystemStats::getCpuVendor()
  203774. {
  203775. char v [16];
  203776. juce_getCpuVendor (v);
  203777. return String (v, 16);
  203778. }
  203779. #endif
  203780. void SystemStats::initialiseStats()
  203781. {
  203782. juce_initialiseThreadEvents();
  203783. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203784. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203785. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203786. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203787. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203788. #else
  203789. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203790. #endif
  203791. {
  203792. SYSTEM_INFO systemInfo;
  203793. GetSystemInfo (&systemInfo);
  203794. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203795. }
  203796. LARGE_INTEGER f;
  203797. QueryPerformanceFrequency (&f);
  203798. hiResTicksPerSecond = f.QuadPart;
  203799. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203800. String s (SystemStats::getJUCEVersion());
  203801. const MMRESULT res = timeBeginPeriod (1);
  203802. (void) res;
  203803. jassert (res == TIMERR_NOERROR);
  203804. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203805. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203806. #endif
  203807. }
  203808. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203809. {
  203810. OSVERSIONINFO info;
  203811. info.dwOSVersionInfoSize = sizeof (info);
  203812. GetVersionEx (&info);
  203813. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203814. {
  203815. switch (info.dwMajorVersion)
  203816. {
  203817. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203818. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203819. default: jassertfalse; break; // !! not a supported OS!
  203820. }
  203821. }
  203822. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203823. {
  203824. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203825. return Win98;
  203826. }
  203827. return UnknownOS;
  203828. }
  203829. const String SystemStats::getOperatingSystemName()
  203830. {
  203831. const char* name = "Unknown OS";
  203832. switch (getOperatingSystemType())
  203833. {
  203834. case Windows7: name = "Windows 7"; break;
  203835. case WinVista: name = "Windows Vista"; break;
  203836. case WinXP: name = "Windows XP"; break;
  203837. case Win2000: name = "Windows 2000"; break;
  203838. case Win98: name = "Windows 98"; break;
  203839. default: jassertfalse; break; // !! new type of OS?
  203840. }
  203841. return name;
  203842. }
  203843. bool SystemStats::isOperatingSystem64Bit()
  203844. {
  203845. #ifdef _WIN64
  203846. return true;
  203847. #else
  203848. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203849. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203850. BOOL isWow64 = FALSE;
  203851. return (fnIsWow64Process != 0)
  203852. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203853. && (isWow64 != FALSE);
  203854. #endif
  203855. }
  203856. int SystemStats::getMemorySizeInMegabytes()
  203857. {
  203858. MEMORYSTATUSEX mem;
  203859. mem.dwLength = sizeof (mem);
  203860. GlobalMemoryStatusEx (&mem);
  203861. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203862. }
  203863. uint32 juce_millisecondsSinceStartup() throw()
  203864. {
  203865. return (uint32) timeGetTime();
  203866. }
  203867. int64 Time::getHighResolutionTicks() throw()
  203868. {
  203869. LARGE_INTEGER ticks;
  203870. QueryPerformanceCounter (&ticks);
  203871. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203872. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203873. // fix for a very obscure PCI hardware bug that can make the counter
  203874. // sometimes jump forwards by a few seconds..
  203875. static int64 hiResTicksOffset = 0;
  203876. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203877. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203878. hiResTicksOffset = newOffset;
  203879. return ticks.QuadPart + hiResTicksOffset;
  203880. }
  203881. double Time::getMillisecondCounterHiRes() throw()
  203882. {
  203883. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203884. }
  203885. int64 Time::getHighResolutionTicksPerSecond() throw()
  203886. {
  203887. return hiResTicksPerSecond;
  203888. }
  203889. static int64 juce_getClockCycleCounter() throw()
  203890. {
  203891. #if JUCE_USE_INTRINSICS
  203892. // MS intrinsics version...
  203893. return __rdtsc();
  203894. #elif JUCE_GCC
  203895. // GNU inline asm version...
  203896. unsigned int hi = 0, lo = 0;
  203897. __asm__ __volatile__ (
  203898. "xor %%eax, %%eax \n\
  203899. xor %%edx, %%edx \n\
  203900. rdtsc \n\
  203901. movl %%eax, %[lo] \n\
  203902. movl %%edx, %[hi]"
  203903. :
  203904. : [hi] "m" (hi),
  203905. [lo] "m" (lo)
  203906. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203907. return (int64) ((((uint64) hi) << 32) | lo);
  203908. #else
  203909. // MSVC inline asm version...
  203910. unsigned int hi = 0, lo = 0;
  203911. __asm
  203912. {
  203913. xor eax, eax
  203914. xor edx, edx
  203915. rdtsc
  203916. mov lo, eax
  203917. mov hi, edx
  203918. }
  203919. return (int64) ((((uint64) hi) << 32) | lo);
  203920. #endif
  203921. }
  203922. int SystemStats::getCpuSpeedInMegaherz()
  203923. {
  203924. const int64 cycles = juce_getClockCycleCounter();
  203925. const uint32 millis = Time::getMillisecondCounter();
  203926. int lastResult = 0;
  203927. for (;;)
  203928. {
  203929. int n = 1000000;
  203930. while (--n > 0) {}
  203931. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203932. const int64 cyclesNow = juce_getClockCycleCounter();
  203933. if (millisElapsed > 80)
  203934. {
  203935. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203936. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203937. return newResult;
  203938. lastResult = newResult;
  203939. }
  203940. }
  203941. }
  203942. bool Time::setSystemTimeToThisTime() const
  203943. {
  203944. SYSTEMTIME st;
  203945. st.wDayOfWeek = 0;
  203946. st.wYear = (WORD) getYear();
  203947. st.wMonth = (WORD) (getMonth() + 1);
  203948. st.wDay = (WORD) getDayOfMonth();
  203949. st.wHour = (WORD) getHours();
  203950. st.wMinute = (WORD) getMinutes();
  203951. st.wSecond = (WORD) getSeconds();
  203952. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203953. // do this twice because of daylight saving conversion problems - the
  203954. // first one sets it up, the second one kicks it in.
  203955. return SetLocalTime (&st) != 0
  203956. && SetLocalTime (&st) != 0;
  203957. }
  203958. int SystemStats::getPageSize()
  203959. {
  203960. SYSTEM_INFO systemInfo;
  203961. GetSystemInfo (&systemInfo);
  203962. return systemInfo.dwPageSize;
  203963. }
  203964. const String SystemStats::getLogonName()
  203965. {
  203966. TCHAR text [256];
  203967. DWORD len = numElementsInArray (text) - 2;
  203968. zerostruct (text);
  203969. GetUserName (text, &len);
  203970. return String (text, len);
  203971. }
  203972. const String SystemStats::getFullUserName()
  203973. {
  203974. return getLogonName();
  203975. }
  203976. #endif
  203977. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203978. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203979. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203980. // compiled on its own).
  203981. #if JUCE_INCLUDED_FILE
  203982. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203983. extern HWND juce_messageWindowHandle;
  203984. #endif
  203985. #if ! JUCE_USE_INTRINSICS
  203986. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203987. // older ones we have to actually call the ops as win32 functions..
  203988. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203989. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203990. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203991. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203992. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203993. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203994. {
  203995. jassertfalse; // This operation isn't available in old MS compiler versions!
  203996. __int64 oldValue = *value;
  203997. if (oldValue == valueToCompare)
  203998. *value = newValue;
  203999. return oldValue;
  204000. }
  204001. #endif
  204002. CriticalSection::CriticalSection() throw()
  204003. {
  204004. // (just to check the MS haven't changed this structure and broken things...)
  204005. #if _MSC_VER >= 1400
  204006. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  204007. #else
  204008. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  204009. #endif
  204010. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  204011. }
  204012. CriticalSection::~CriticalSection() throw()
  204013. {
  204014. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  204015. }
  204016. void CriticalSection::enter() const throw()
  204017. {
  204018. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  204019. }
  204020. bool CriticalSection::tryEnter() const throw()
  204021. {
  204022. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  204023. }
  204024. void CriticalSection::exit() const throw()
  204025. {
  204026. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  204027. }
  204028. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  204029. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  204030. {
  204031. }
  204032. WaitableEvent::~WaitableEvent() throw()
  204033. {
  204034. CloseHandle (internal);
  204035. }
  204036. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  204037. {
  204038. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  204039. }
  204040. void WaitableEvent::signal() const throw()
  204041. {
  204042. SetEvent (internal);
  204043. }
  204044. void WaitableEvent::reset() const throw()
  204045. {
  204046. ResetEvent (internal);
  204047. }
  204048. void JUCE_API juce_threadEntryPoint (void*);
  204049. static unsigned int __stdcall threadEntryProc (void* userData)
  204050. {
  204051. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204052. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204053. GetCurrentThreadId(), TRUE);
  204054. #endif
  204055. juce_threadEntryPoint (userData);
  204056. _endthreadex (0);
  204057. return 0;
  204058. }
  204059. void juce_CloseThreadHandle (void* handle)
  204060. {
  204061. CloseHandle ((HANDLE) handle);
  204062. }
  204063. void* juce_createThread (void* userData)
  204064. {
  204065. unsigned int threadId;
  204066. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  204067. }
  204068. void juce_killThread (void* handle)
  204069. {
  204070. if (handle != 0)
  204071. {
  204072. #if JUCE_DEBUG
  204073. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204074. #endif
  204075. TerminateThread (handle, 0);
  204076. }
  204077. }
  204078. void juce_setCurrentThreadName (const String& name)
  204079. {
  204080. #if JUCE_DEBUG && JUCE_MSVC
  204081. struct
  204082. {
  204083. DWORD dwType;
  204084. LPCSTR szName;
  204085. DWORD dwThreadID;
  204086. DWORD dwFlags;
  204087. } info;
  204088. info.dwType = 0x1000;
  204089. info.szName = name.toCString();
  204090. info.dwThreadID = GetCurrentThreadId();
  204091. info.dwFlags = 0;
  204092. __try
  204093. {
  204094. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204095. }
  204096. __except (EXCEPTION_CONTINUE_EXECUTION)
  204097. {}
  204098. #else
  204099. (void) name;
  204100. #endif
  204101. }
  204102. Thread::ThreadID Thread::getCurrentThreadId()
  204103. {
  204104. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  204105. }
  204106. // priority 1 to 10 where 5=normal, 1=low
  204107. bool juce_setThreadPriority (void* threadHandle, int priority)
  204108. {
  204109. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204110. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  204111. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  204112. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  204113. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  204114. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204115. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  204116. if (threadHandle == 0)
  204117. threadHandle = GetCurrentThread();
  204118. return SetThreadPriority (threadHandle, pri) != FALSE;
  204119. }
  204120. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  204121. {
  204122. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204123. }
  204124. static HANDLE sleepEvent = 0;
  204125. void juce_initialiseThreadEvents()
  204126. {
  204127. if (sleepEvent == 0)
  204128. #if JUCE_DEBUG
  204129. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  204130. #else
  204131. sleepEvent = CreateEvent (0, 0, 0, 0);
  204132. #endif
  204133. }
  204134. void Thread::yield()
  204135. {
  204136. Sleep (0);
  204137. }
  204138. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204139. {
  204140. if (millisecs >= 10)
  204141. {
  204142. Sleep (millisecs);
  204143. }
  204144. else
  204145. {
  204146. jassert (sleepEvent != 0);
  204147. // unlike Sleep() this is guaranteed to return to the current thread after
  204148. // the time expires, so we'll use this for short waits, which are more likely
  204149. // to need to be accurate
  204150. WaitForSingleObject (sleepEvent, millisecs);
  204151. }
  204152. }
  204153. static int lastProcessPriority = -1;
  204154. // called by WindowDriver because Windows does wierd things to process priority
  204155. // when you swap apps, and this forces an update when the app is brought to the front.
  204156. void juce_repeatLastProcessPriority()
  204157. {
  204158. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204159. {
  204160. DWORD p;
  204161. switch (lastProcessPriority)
  204162. {
  204163. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204164. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204165. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204166. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204167. default: jassertfalse; return; // bad priority value
  204168. }
  204169. SetPriorityClass (GetCurrentProcess(), p);
  204170. }
  204171. }
  204172. void Process::setPriority (ProcessPriority prior)
  204173. {
  204174. if (lastProcessPriority != (int) prior)
  204175. {
  204176. lastProcessPriority = (int) prior;
  204177. juce_repeatLastProcessPriority();
  204178. }
  204179. }
  204180. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  204181. {
  204182. return IsDebuggerPresent() != FALSE;
  204183. }
  204184. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204185. {
  204186. return juce_isRunningUnderDebugger();
  204187. }
  204188. void Process::raisePrivilege()
  204189. {
  204190. jassertfalse; // xxx not implemented
  204191. }
  204192. void Process::lowerPrivilege()
  204193. {
  204194. jassertfalse; // xxx not implemented
  204195. }
  204196. void Process::terminate()
  204197. {
  204198. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204199. _CrtDumpMemoryLeaks();
  204200. #endif
  204201. // bullet in the head in case there's a problem shutting down..
  204202. ExitProcess (0);
  204203. }
  204204. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204205. {
  204206. void* result = 0;
  204207. JUCE_TRY
  204208. {
  204209. result = LoadLibrary (name);
  204210. }
  204211. JUCE_CATCH_ALL
  204212. return result;
  204213. }
  204214. void PlatformUtilities::freeDynamicLibrary (void* h)
  204215. {
  204216. JUCE_TRY
  204217. {
  204218. if (h != 0)
  204219. FreeLibrary ((HMODULE) h);
  204220. }
  204221. JUCE_CATCH_ALL
  204222. }
  204223. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204224. {
  204225. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204226. }
  204227. class InterProcessLock::Pimpl
  204228. {
  204229. public:
  204230. Pimpl (const String& name, const int timeOutMillisecs)
  204231. : handle (0), refCount (1)
  204232. {
  204233. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204234. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204235. {
  204236. if (timeOutMillisecs == 0)
  204237. {
  204238. close();
  204239. return;
  204240. }
  204241. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204242. {
  204243. case WAIT_OBJECT_0:
  204244. case WAIT_ABANDONED:
  204245. break;
  204246. case WAIT_TIMEOUT:
  204247. default:
  204248. close();
  204249. break;
  204250. }
  204251. }
  204252. }
  204253. ~Pimpl()
  204254. {
  204255. close();
  204256. }
  204257. void close()
  204258. {
  204259. if (handle != 0)
  204260. {
  204261. ReleaseMutex (handle);
  204262. CloseHandle (handle);
  204263. handle = 0;
  204264. }
  204265. }
  204266. HANDLE handle;
  204267. int refCount;
  204268. };
  204269. InterProcessLock::InterProcessLock (const String& name_)
  204270. : name (name_)
  204271. {
  204272. }
  204273. InterProcessLock::~InterProcessLock()
  204274. {
  204275. }
  204276. bool InterProcessLock::enter (const int timeOutMillisecs)
  204277. {
  204278. const ScopedLock sl (lock);
  204279. if (pimpl == 0)
  204280. {
  204281. pimpl = new Pimpl (name, timeOutMillisecs);
  204282. if (pimpl->handle == 0)
  204283. pimpl = 0;
  204284. }
  204285. else
  204286. {
  204287. pimpl->refCount++;
  204288. }
  204289. return pimpl != 0;
  204290. }
  204291. void InterProcessLock::exit()
  204292. {
  204293. const ScopedLock sl (lock);
  204294. // Trying to release the lock too many times!
  204295. jassert (pimpl != 0);
  204296. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204297. pimpl = 0;
  204298. }
  204299. #endif
  204300. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204301. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204302. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204303. // compiled on its own).
  204304. #if JUCE_INCLUDED_FILE
  204305. #ifndef CSIDL_MYMUSIC
  204306. #define CSIDL_MYMUSIC 0x000d
  204307. #endif
  204308. #ifndef CSIDL_MYVIDEO
  204309. #define CSIDL_MYVIDEO 0x000e
  204310. #endif
  204311. #ifndef INVALID_FILE_ATTRIBUTES
  204312. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204313. #endif
  204314. const juce_wchar File::separator = '\\';
  204315. const String File::separatorString ("\\");
  204316. bool File::exists() const
  204317. {
  204318. return fullPath.isNotEmpty()
  204319. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204320. }
  204321. bool File::existsAsFile() const
  204322. {
  204323. return fullPath.isNotEmpty()
  204324. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204325. }
  204326. bool File::isDirectory() const
  204327. {
  204328. const DWORD attr = GetFileAttributes (fullPath);
  204329. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204330. }
  204331. bool File::hasWriteAccess() const
  204332. {
  204333. if (exists())
  204334. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204335. // on windows, it seems that even read-only directories can still be written into,
  204336. // so checking the parent directory's permissions would return the wrong result..
  204337. return true;
  204338. }
  204339. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204340. {
  204341. DWORD attr = GetFileAttributes (fullPath);
  204342. if (attr == INVALID_FILE_ATTRIBUTES)
  204343. return false;
  204344. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204345. return true;
  204346. if (shouldBeReadOnly)
  204347. attr |= FILE_ATTRIBUTE_READONLY;
  204348. else
  204349. attr &= ~FILE_ATTRIBUTE_READONLY;
  204350. return SetFileAttributes (fullPath, attr) != FALSE;
  204351. }
  204352. bool File::isHidden() const
  204353. {
  204354. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204355. }
  204356. bool File::deleteFile() const
  204357. {
  204358. if (! exists())
  204359. return true;
  204360. else if (isDirectory())
  204361. return RemoveDirectory (fullPath) != 0;
  204362. else
  204363. return DeleteFile (fullPath) != 0;
  204364. }
  204365. bool File::moveToTrash() const
  204366. {
  204367. if (! exists())
  204368. return true;
  204369. SHFILEOPSTRUCT fos;
  204370. zerostruct (fos);
  204371. // The string we pass in must be double null terminated..
  204372. String doubleNullTermPath (getFullPathName() + " ");
  204373. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204374. p [getFullPathName().length()] = 0;
  204375. fos.wFunc = FO_DELETE;
  204376. fos.pFrom = p;
  204377. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204378. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204379. return SHFileOperation (&fos) == 0;
  204380. }
  204381. bool File::copyInternal (const File& dest) const
  204382. {
  204383. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204384. }
  204385. bool File::moveInternal (const File& dest) const
  204386. {
  204387. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204388. }
  204389. void File::createDirectoryInternal (const String& fileName) const
  204390. {
  204391. CreateDirectory (fileName, 0);
  204392. }
  204393. int64 juce_fileSetPosition (void* handle, int64 pos)
  204394. {
  204395. LARGE_INTEGER li;
  204396. li.QuadPart = pos;
  204397. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204398. return li.QuadPart;
  204399. }
  204400. void FileInputStream::openHandle()
  204401. {
  204402. totalSize = file.getSize();
  204403. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204404. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204405. if (h != INVALID_HANDLE_VALUE)
  204406. fileHandle = (void*) h;
  204407. }
  204408. void FileInputStream::closeHandle()
  204409. {
  204410. CloseHandle ((HANDLE) fileHandle);
  204411. }
  204412. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204413. {
  204414. if (fileHandle != 0)
  204415. {
  204416. DWORD actualNum = 0;
  204417. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204418. return (size_t) actualNum;
  204419. }
  204420. return 0;
  204421. }
  204422. void FileOutputStream::openHandle()
  204423. {
  204424. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204425. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204426. if (h != INVALID_HANDLE_VALUE)
  204427. {
  204428. LARGE_INTEGER li;
  204429. li.QuadPart = 0;
  204430. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204431. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204432. {
  204433. fileHandle = (void*) h;
  204434. currentPosition = li.QuadPart;
  204435. }
  204436. }
  204437. }
  204438. void FileOutputStream::closeHandle()
  204439. {
  204440. CloseHandle ((HANDLE) fileHandle);
  204441. }
  204442. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204443. {
  204444. if (fileHandle != 0)
  204445. {
  204446. DWORD actualNum = 0;
  204447. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204448. return (int) actualNum;
  204449. }
  204450. return 0;
  204451. }
  204452. void FileOutputStream::flushInternal()
  204453. {
  204454. if (fileHandle != 0)
  204455. FlushFileBuffers ((HANDLE) fileHandle);
  204456. }
  204457. int64 File::getSize() const
  204458. {
  204459. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204460. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204461. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204462. return 0;
  204463. }
  204464. static int64 fileTimeToTime (const FILETIME* const ft)
  204465. {
  204466. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204467. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204468. }
  204469. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204470. {
  204471. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204472. }
  204473. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204474. {
  204475. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204476. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204477. {
  204478. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204479. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204480. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204481. }
  204482. else
  204483. {
  204484. creationTime = accessTime = modificationTime = 0;
  204485. }
  204486. }
  204487. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204488. {
  204489. bool ok = false;
  204490. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204491. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204492. if (h != INVALID_HANDLE_VALUE)
  204493. {
  204494. FILETIME m, a, c;
  204495. timeToFileTime (modificationTime, &m);
  204496. timeToFileTime (accessTime, &a);
  204497. timeToFileTime (creationTime, &c);
  204498. ok = SetFileTime (h,
  204499. creationTime > 0 ? &c : 0,
  204500. accessTime > 0 ? &a : 0,
  204501. modificationTime > 0 ? &m : 0) != 0;
  204502. CloseHandle (h);
  204503. }
  204504. return ok;
  204505. }
  204506. void File::findFileSystemRoots (Array<File>& destArray)
  204507. {
  204508. TCHAR buffer [2048];
  204509. buffer[0] = 0;
  204510. buffer[1] = 0;
  204511. GetLogicalDriveStrings (2048, buffer);
  204512. const TCHAR* n = buffer;
  204513. StringArray roots;
  204514. while (*n != 0)
  204515. {
  204516. roots.add (String (n));
  204517. while (*n++ != 0)
  204518. {}
  204519. }
  204520. roots.sort (true);
  204521. for (int i = 0; i < roots.size(); ++i)
  204522. destArray.add (roots [i]);
  204523. }
  204524. static const String getDriveFromPath (const String& path)
  204525. {
  204526. if (path.isNotEmpty() && path[1] == ':')
  204527. return path.substring (0, 2) + '\\';
  204528. return path;
  204529. }
  204530. const String File::getVolumeLabel() const
  204531. {
  204532. TCHAR dest[64];
  204533. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204534. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204535. dest[0] = 0;
  204536. return dest;
  204537. }
  204538. int File::getVolumeSerialNumber() const
  204539. {
  204540. TCHAR dest[64];
  204541. DWORD serialNum;
  204542. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204543. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204544. return 0;
  204545. return (int) serialNum;
  204546. }
  204547. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204548. {
  204549. ULARGE_INTEGER spc, tot, totFree;
  204550. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204551. return total ? (int64) tot.QuadPart
  204552. : (int64) spc.QuadPart;
  204553. return 0;
  204554. }
  204555. int64 File::getBytesFreeOnVolume() const
  204556. {
  204557. return getDiskSpaceInfo (getFullPathName(), false);
  204558. }
  204559. int64 File::getVolumeTotalSize() const
  204560. {
  204561. return getDiskSpaceInfo (getFullPathName(), true);
  204562. }
  204563. static unsigned int getWindowsDriveType (const String& path)
  204564. {
  204565. return GetDriveType (getDriveFromPath (path));
  204566. }
  204567. bool File::isOnCDRomDrive() const
  204568. {
  204569. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204570. }
  204571. bool File::isOnHardDisk() const
  204572. {
  204573. if (fullPath.isEmpty())
  204574. return false;
  204575. const unsigned int n = getWindowsDriveType (getFullPathName());
  204576. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204577. return n != DRIVE_REMOVABLE;
  204578. else
  204579. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204580. }
  204581. bool File::isOnRemovableDrive() const
  204582. {
  204583. if (fullPath.isEmpty())
  204584. return false;
  204585. const unsigned int n = getWindowsDriveType (getFullPathName());
  204586. return n == DRIVE_CDROM
  204587. || n == DRIVE_REMOTE
  204588. || n == DRIVE_REMOVABLE
  204589. || n == DRIVE_RAMDISK;
  204590. }
  204591. static const File juce_getSpecialFolderPath (int type)
  204592. {
  204593. WCHAR path [MAX_PATH + 256];
  204594. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204595. return File (String (path));
  204596. return File::nonexistent;
  204597. }
  204598. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204599. {
  204600. int csidlType = 0;
  204601. switch (type)
  204602. {
  204603. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204604. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204605. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204606. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204607. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204608. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204609. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204610. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204611. case tempDirectory:
  204612. {
  204613. WCHAR dest [2048];
  204614. dest[0] = 0;
  204615. GetTempPath (numElementsInArray (dest), dest);
  204616. return File (String (dest));
  204617. }
  204618. case invokedExecutableFile:
  204619. case currentExecutableFile:
  204620. case currentApplicationFile:
  204621. {
  204622. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204623. WCHAR dest [MAX_PATH + 256];
  204624. dest[0] = 0;
  204625. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204626. return File (String (dest));
  204627. }
  204628. case hostApplicationPath:
  204629. {
  204630. WCHAR dest [MAX_PATH + 256];
  204631. dest[0] = 0;
  204632. GetModuleFileName (0, dest, numElementsInArray (dest));
  204633. return File (String (dest));
  204634. }
  204635. default:
  204636. jassertfalse; // unknown type?
  204637. return File::nonexistent;
  204638. }
  204639. return juce_getSpecialFolderPath (csidlType);
  204640. }
  204641. const File File::getCurrentWorkingDirectory()
  204642. {
  204643. WCHAR dest [MAX_PATH + 256];
  204644. dest[0] = 0;
  204645. GetCurrentDirectory (numElementsInArray (dest), dest);
  204646. return File (String (dest));
  204647. }
  204648. bool File::setAsCurrentWorkingDirectory() const
  204649. {
  204650. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204651. }
  204652. const String File::getVersion() const
  204653. {
  204654. String result;
  204655. DWORD handle = 0;
  204656. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204657. HeapBlock<char> buffer;
  204658. buffer.calloc (bufferSize);
  204659. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204660. {
  204661. VS_FIXEDFILEINFO* vffi;
  204662. UINT len = 0;
  204663. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204664. {
  204665. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204666. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204667. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204668. << (int) LOWORD (vffi->dwFileVersionLS);
  204669. }
  204670. }
  204671. return result;
  204672. }
  204673. const File File::getLinkedTarget() const
  204674. {
  204675. File result (*this);
  204676. String p (getFullPathName());
  204677. if (! exists())
  204678. p += ".lnk";
  204679. else if (getFileExtension() != ".lnk")
  204680. return result;
  204681. ComSmartPtr <IShellLink> shellLink;
  204682. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204683. {
  204684. ComSmartPtr <IPersistFile> persistFile;
  204685. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204686. {
  204687. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204688. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204689. {
  204690. WIN32_FIND_DATA winFindData;
  204691. WCHAR resolvedPath [MAX_PATH];
  204692. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204693. result = File (resolvedPath);
  204694. }
  204695. }
  204696. }
  204697. return result;
  204698. }
  204699. class DirectoryIterator::NativeIterator::Pimpl
  204700. {
  204701. public:
  204702. Pimpl (const File& directory, const String& wildCard)
  204703. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204704. handle (INVALID_HANDLE_VALUE)
  204705. {
  204706. }
  204707. ~Pimpl()
  204708. {
  204709. if (handle != INVALID_HANDLE_VALUE)
  204710. FindClose (handle);
  204711. }
  204712. bool next (String& filenameFound,
  204713. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204714. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204715. {
  204716. WIN32_FIND_DATA findData;
  204717. if (handle == INVALID_HANDLE_VALUE)
  204718. {
  204719. handle = FindFirstFile (directoryWithWildCard, &findData);
  204720. if (handle == INVALID_HANDLE_VALUE)
  204721. return false;
  204722. }
  204723. else
  204724. {
  204725. if (FindNextFile (handle, &findData) == 0)
  204726. return false;
  204727. }
  204728. filenameFound = findData.cFileName;
  204729. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204730. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204731. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204732. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204733. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204734. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204735. return true;
  204736. }
  204737. juce_UseDebuggingNewOperator
  204738. private:
  204739. const String directoryWithWildCard;
  204740. HANDLE handle;
  204741. Pimpl (const Pimpl&);
  204742. Pimpl& operator= (const Pimpl&);
  204743. };
  204744. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204745. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204746. {
  204747. }
  204748. DirectoryIterator::NativeIterator::~NativeIterator()
  204749. {
  204750. }
  204751. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204752. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204753. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204754. {
  204755. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204756. }
  204757. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204758. {
  204759. HINSTANCE hInstance = 0;
  204760. JUCE_TRY
  204761. {
  204762. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204763. }
  204764. JUCE_CATCH_ALL
  204765. return hInstance > (HINSTANCE) 32;
  204766. }
  204767. void File::revealToUser() const
  204768. {
  204769. if (isDirectory())
  204770. startAsProcess();
  204771. else if (getParentDirectory().exists())
  204772. getParentDirectory().startAsProcess();
  204773. }
  204774. class NamedPipeInternal
  204775. {
  204776. public:
  204777. NamedPipeInternal (const String& file, const bool isPipe_)
  204778. : pipeH (0),
  204779. cancelEvent (0),
  204780. connected (false),
  204781. isPipe (isPipe_)
  204782. {
  204783. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204784. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204785. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204786. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204787. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204788. }
  204789. ~NamedPipeInternal()
  204790. {
  204791. disconnectPipe();
  204792. if (pipeH != 0)
  204793. CloseHandle (pipeH);
  204794. CloseHandle (cancelEvent);
  204795. }
  204796. bool connect (const int timeOutMs)
  204797. {
  204798. if (! isPipe)
  204799. return true;
  204800. if (! connected)
  204801. {
  204802. OVERLAPPED over;
  204803. zerostruct (over);
  204804. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204805. if (ConnectNamedPipe (pipeH, &over))
  204806. {
  204807. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204808. }
  204809. else
  204810. {
  204811. const int err = GetLastError();
  204812. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204813. {
  204814. HANDLE handles[] = { over.hEvent, cancelEvent };
  204815. if (WaitForMultipleObjects (2, handles, FALSE,
  204816. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204817. connected = true;
  204818. }
  204819. else if (err == ERROR_PIPE_CONNECTED)
  204820. {
  204821. connected = true;
  204822. }
  204823. }
  204824. CloseHandle (over.hEvent);
  204825. }
  204826. return connected;
  204827. }
  204828. void disconnectPipe()
  204829. {
  204830. if (connected)
  204831. {
  204832. DisconnectNamedPipe (pipeH);
  204833. connected = false;
  204834. }
  204835. }
  204836. HANDLE pipeH;
  204837. HANDLE cancelEvent;
  204838. bool connected, isPipe;
  204839. };
  204840. void NamedPipe::close()
  204841. {
  204842. cancelPendingReads();
  204843. const ScopedLock sl (lock);
  204844. delete static_cast<NamedPipeInternal*> (internal);
  204845. internal = 0;
  204846. }
  204847. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204848. {
  204849. close();
  204850. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204851. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204852. {
  204853. internal = intern.release();
  204854. return true;
  204855. }
  204856. return false;
  204857. }
  204858. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204859. {
  204860. const ScopedLock sl (lock);
  204861. int bytesRead = -1;
  204862. bool waitAgain = true;
  204863. while (waitAgain && internal != 0)
  204864. {
  204865. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204866. waitAgain = false;
  204867. if (! intern->connect (timeOutMilliseconds))
  204868. break;
  204869. if (maxBytesToRead <= 0)
  204870. return 0;
  204871. OVERLAPPED over;
  204872. zerostruct (over);
  204873. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204874. unsigned long numRead;
  204875. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204876. {
  204877. bytesRead = (int) numRead;
  204878. }
  204879. else if (GetLastError() == ERROR_IO_PENDING)
  204880. {
  204881. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204882. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204883. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204884. : INFINITE);
  204885. if (waitResult != WAIT_OBJECT_0)
  204886. {
  204887. // if the operation timed out, let's cancel it...
  204888. CancelIo (intern->pipeH);
  204889. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204890. }
  204891. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204892. {
  204893. bytesRead = (int) numRead;
  204894. }
  204895. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204896. {
  204897. intern->disconnectPipe();
  204898. waitAgain = true;
  204899. }
  204900. }
  204901. else
  204902. {
  204903. waitAgain = internal != 0;
  204904. Sleep (5);
  204905. }
  204906. CloseHandle (over.hEvent);
  204907. }
  204908. return bytesRead;
  204909. }
  204910. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204911. {
  204912. int bytesWritten = -1;
  204913. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204914. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204915. {
  204916. if (numBytesToWrite <= 0)
  204917. return 0;
  204918. OVERLAPPED over;
  204919. zerostruct (over);
  204920. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204921. unsigned long numWritten;
  204922. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204923. {
  204924. bytesWritten = (int) numWritten;
  204925. }
  204926. else if (GetLastError() == ERROR_IO_PENDING)
  204927. {
  204928. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204929. DWORD waitResult;
  204930. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204931. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204932. : INFINITE);
  204933. if (waitResult != WAIT_OBJECT_0)
  204934. {
  204935. CancelIo (intern->pipeH);
  204936. WaitForSingleObject (over.hEvent, INFINITE);
  204937. }
  204938. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204939. {
  204940. bytesWritten = (int) numWritten;
  204941. }
  204942. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204943. {
  204944. intern->disconnectPipe();
  204945. }
  204946. }
  204947. CloseHandle (over.hEvent);
  204948. }
  204949. return bytesWritten;
  204950. }
  204951. void NamedPipe::cancelPendingReads()
  204952. {
  204953. if (internal != 0)
  204954. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204955. }
  204956. #endif
  204957. /*** End of inlined file: juce_win32_Files.cpp ***/
  204958. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204959. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204960. // compiled on its own).
  204961. #if JUCE_INCLUDED_FILE
  204962. #ifndef INTERNET_FLAG_NEED_FILE
  204963. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204964. #endif
  204965. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204966. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204967. #endif
  204968. struct ConnectionAndRequestStruct
  204969. {
  204970. HINTERNET connection, request;
  204971. };
  204972. static HINTERNET sessionHandle = 0;
  204973. #ifndef WORKAROUND_TIMEOUT_BUG
  204974. //#define WORKAROUND_TIMEOUT_BUG 1
  204975. #endif
  204976. #if WORKAROUND_TIMEOUT_BUG
  204977. // Required because of a Microsoft bug in setting a timeout
  204978. class InternetConnectThread : public Thread
  204979. {
  204980. public:
  204981. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204982. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204983. {
  204984. startThread();
  204985. }
  204986. ~InternetConnectThread()
  204987. {
  204988. stopThread (60000);
  204989. }
  204990. void run()
  204991. {
  204992. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204993. uc.nPort, _T(""), _T(""),
  204994. isFtp ? INTERNET_SERVICE_FTP
  204995. : INTERNET_SERVICE_HTTP,
  204996. 0, 0);
  204997. notify();
  204998. }
  204999. juce_UseDebuggingNewOperator
  205000. private:
  205001. URL_COMPONENTS& uc;
  205002. HINTERNET& connection;
  205003. const bool isFtp;
  205004. InternetConnectThread (const InternetConnectThread&);
  205005. InternetConnectThread& operator= (const InternetConnectThread&);
  205006. };
  205007. #endif
  205008. void* juce_openInternetFile (const String& url,
  205009. const String& headers,
  205010. const MemoryBlock& postData,
  205011. const bool isPost,
  205012. URL::OpenStreamProgressCallback* callback,
  205013. void* callbackContext,
  205014. int timeOutMs)
  205015. {
  205016. if (sessionHandle == 0)
  205017. sessionHandle = InternetOpen (_T("juce"),
  205018. INTERNET_OPEN_TYPE_PRECONFIG,
  205019. 0, 0, 0);
  205020. if (sessionHandle != 0)
  205021. {
  205022. // break up the url..
  205023. TCHAR file[1024], server[1024];
  205024. URL_COMPONENTS uc;
  205025. zerostruct (uc);
  205026. uc.dwStructSize = sizeof (uc);
  205027. uc.dwUrlPathLength = sizeof (file);
  205028. uc.dwHostNameLength = sizeof (server);
  205029. uc.lpszUrlPath = file;
  205030. uc.lpszHostName = server;
  205031. if (InternetCrackUrl (url, 0, 0, &uc))
  205032. {
  205033. int disable = 1;
  205034. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  205035. if (timeOutMs == 0)
  205036. timeOutMs = 30000;
  205037. else if (timeOutMs < 0)
  205038. timeOutMs = -1;
  205039. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  205040. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  205041. #if WORKAROUND_TIMEOUT_BUG
  205042. HINTERNET connection = 0;
  205043. {
  205044. InternetConnectThread connectThread (uc, connection, isFtp);
  205045. connectThread.wait (timeOutMs);
  205046. if (connection == 0)
  205047. {
  205048. InternetCloseHandle (sessionHandle);
  205049. sessionHandle = 0;
  205050. }
  205051. }
  205052. #else
  205053. HINTERNET connection = InternetConnect (sessionHandle,
  205054. uc.lpszHostName,
  205055. uc.nPort,
  205056. _T(""), _T(""),
  205057. isFtp ? INTERNET_SERVICE_FTP
  205058. : INTERNET_SERVICE_HTTP,
  205059. 0, 0);
  205060. #endif
  205061. if (connection != 0)
  205062. {
  205063. if (isFtp)
  205064. {
  205065. HINTERNET request = FtpOpenFile (connection,
  205066. uc.lpszUrlPath,
  205067. GENERIC_READ,
  205068. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  205069. 0);
  205070. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  205071. result->connection = connection;
  205072. result->request = request;
  205073. return result;
  205074. }
  205075. else
  205076. {
  205077. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205078. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  205079. if (url.startsWithIgnoreCase ("https:"))
  205080. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205081. // IE7 seems to automatically work out when it's https)
  205082. HINTERNET request = HttpOpenRequest (connection,
  205083. isPost ? _T("POST")
  205084. : _T("GET"),
  205085. uc.lpszUrlPath,
  205086. 0, 0, mimeTypes, flags, 0);
  205087. if (request != 0)
  205088. {
  205089. INTERNET_BUFFERS buffers;
  205090. zerostruct (buffers);
  205091. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205092. buffers.lpcszHeader = (LPCTSTR) headers;
  205093. buffers.dwHeadersLength = headers.length();
  205094. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205095. ConnectionAndRequestStruct* result = 0;
  205096. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205097. {
  205098. int bytesSent = 0;
  205099. for (;;)
  205100. {
  205101. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  205102. DWORD bytesDone = 0;
  205103. if (bytesToDo > 0
  205104. && ! InternetWriteFile (request,
  205105. static_cast <const char*> (postData.getData()) + bytesSent,
  205106. bytesToDo, &bytesDone))
  205107. {
  205108. break;
  205109. }
  205110. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205111. {
  205112. result = new ConnectionAndRequestStruct();
  205113. result->connection = connection;
  205114. result->request = request;
  205115. if (! HttpEndRequest (request, 0, 0, 0))
  205116. break;
  205117. return result;
  205118. }
  205119. bytesSent += bytesDone;
  205120. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  205121. break;
  205122. }
  205123. }
  205124. InternetCloseHandle (request);
  205125. }
  205126. InternetCloseHandle (connection);
  205127. }
  205128. }
  205129. }
  205130. }
  205131. return 0;
  205132. }
  205133. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  205134. {
  205135. DWORD bytesRead = 0;
  205136. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205137. if (crs != 0)
  205138. InternetReadFile (crs->request,
  205139. buffer, bytesToRead,
  205140. &bytesRead);
  205141. return bytesRead;
  205142. }
  205143. int juce_seekInInternetFile (void* handle, int newPosition)
  205144. {
  205145. if (handle != 0)
  205146. {
  205147. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205148. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  205149. }
  205150. return -1;
  205151. }
  205152. int64 juce_getInternetFileContentLength (void* handle)
  205153. {
  205154. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205155. if (crs != 0)
  205156. {
  205157. DWORD index = 0, result = 0, size = sizeof (result);
  205158. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205159. return (int64) result;
  205160. }
  205161. return -1;
  205162. }
  205163. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  205164. {
  205165. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205166. if (crs != 0)
  205167. {
  205168. DWORD bufferSizeBytes = 4096;
  205169. for (;;)
  205170. {
  205171. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205172. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205173. {
  205174. StringArray headersArray;
  205175. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205176. for (int i = 0; i < headersArray.size(); ++i)
  205177. {
  205178. const String& header = headersArray[i];
  205179. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205180. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205181. const String previousValue (headers [key]);
  205182. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205183. }
  205184. break;
  205185. }
  205186. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205187. break;
  205188. }
  205189. }
  205190. }
  205191. void juce_closeInternetFile (void* handle)
  205192. {
  205193. if (handle != 0)
  205194. {
  205195. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  205196. InternetCloseHandle (crs->request);
  205197. InternetCloseHandle (crs->connection);
  205198. }
  205199. }
  205200. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  205201. {
  205202. int numFound = 0;
  205203. DynamicLibraryLoader dll ("iphlpapi.dll");
  205204. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205205. if (getAdaptersInfo != 0)
  205206. {
  205207. ULONG len = sizeof (IP_ADAPTER_INFO);
  205208. MemoryBlock mb;
  205209. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205210. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205211. {
  205212. mb.setSize (len);
  205213. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205214. }
  205215. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205216. {
  205217. PIP_ADAPTER_INFO adapter = adapterInfo;
  205218. while (adapter != 0)
  205219. {
  205220. int64 mac = 0;
  205221. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  205222. mac = (mac << 8) | adapter->Address[i];
  205223. if (littleEndian)
  205224. mac = (int64) ByteOrder::swap ((uint64) mac);
  205225. if (numFound < maxNum && mac != 0)
  205226. addresses [numFound++] = mac;
  205227. adapter = adapter->Next;
  205228. }
  205229. }
  205230. }
  205231. return numFound;
  205232. }
  205233. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205234. {
  205235. int numFound = 0;
  205236. DynamicLibraryLoader dll ("netapi32.dll");
  205237. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205238. if (NetbiosCall != 0)
  205239. {
  205240. NCB ncb;
  205241. zerostruct (ncb);
  205242. struct ASTAT
  205243. {
  205244. ADAPTER_STATUS adapt;
  205245. NAME_BUFFER NameBuff [30];
  205246. };
  205247. ASTAT astat;
  205248. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205249. LANA_ENUM enums;
  205250. zerostruct (enums);
  205251. ncb.ncb_command = NCBENUM;
  205252. ncb.ncb_buffer = (unsigned char*) &enums;
  205253. ncb.ncb_length = sizeof (LANA_ENUM);
  205254. NetbiosCall (&ncb);
  205255. for (int i = 0; i < enums.length; ++i)
  205256. {
  205257. zerostruct (ncb);
  205258. ncb.ncb_command = NCBRESET;
  205259. ncb.ncb_lana_num = enums.lana[i];
  205260. if (NetbiosCall (&ncb) == 0)
  205261. {
  205262. zerostruct (ncb);
  205263. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205264. ncb.ncb_command = NCBASTAT;
  205265. ncb.ncb_lana_num = enums.lana[i];
  205266. ncb.ncb_buffer = (unsigned char*) &astat;
  205267. ncb.ncb_length = sizeof (ASTAT);
  205268. if (NetbiosCall (&ncb) == 0)
  205269. {
  205270. if (astat.adapt.adapter_type == 0xfe)
  205271. {
  205272. uint64 mac = 0;
  205273. for (int i = 6; --i >= 0;)
  205274. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205275. if (numFound < maxNum && mac != 0)
  205276. addresses [numFound++] = mac;
  205277. }
  205278. }
  205279. }
  205280. }
  205281. }
  205282. return numFound;
  205283. }
  205284. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205285. {
  205286. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205287. if (numFound == 0)
  205288. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205289. return numFound;
  205290. }
  205291. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205292. const String& emailSubject,
  205293. const String& bodyText,
  205294. const StringArray& filesToAttach)
  205295. {
  205296. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205297. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205298. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205299. bool ok = false;
  205300. if (mapiSendMail != 0)
  205301. {
  205302. MapiMessage message;
  205303. zerostruct (message);
  205304. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205305. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205306. MapiRecipDesc recip;
  205307. zerostruct (recip);
  205308. recip.ulRecipClass = MAPI_TO;
  205309. String targetEmailAddress_ (targetEmailAddress);
  205310. if (targetEmailAddress_.isEmpty())
  205311. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205312. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205313. message.nRecipCount = 1;
  205314. message.lpRecips = &recip;
  205315. HeapBlock <MapiFileDesc> files;
  205316. files.calloc (filesToAttach.size());
  205317. message.nFileCount = filesToAttach.size();
  205318. message.lpFiles = files;
  205319. for (int i = 0; i < filesToAttach.size(); ++i)
  205320. {
  205321. files[i].nPosition = (ULONG) -1;
  205322. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205323. }
  205324. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205325. }
  205326. FreeLibrary (h);
  205327. return ok;
  205328. }
  205329. #endif
  205330. /*** End of inlined file: juce_win32_Network.cpp ***/
  205331. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205332. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205333. // compiled on its own).
  205334. #if JUCE_INCLUDED_FILE
  205335. static HKEY findKeyForPath (String name,
  205336. const bool createForWriting,
  205337. String& valueName)
  205338. {
  205339. HKEY rootKey = 0;
  205340. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205341. rootKey = HKEY_CURRENT_USER;
  205342. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205343. rootKey = HKEY_LOCAL_MACHINE;
  205344. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205345. rootKey = HKEY_CLASSES_ROOT;
  205346. if (rootKey != 0)
  205347. {
  205348. name = name.substring (name.indexOfChar ('\\') + 1);
  205349. const int lastSlash = name.lastIndexOfChar ('\\');
  205350. valueName = name.substring (lastSlash + 1);
  205351. name = name.substring (0, lastSlash);
  205352. HKEY key;
  205353. DWORD result;
  205354. if (createForWriting)
  205355. {
  205356. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205357. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205358. return key;
  205359. }
  205360. else
  205361. {
  205362. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205363. return key;
  205364. }
  205365. }
  205366. return 0;
  205367. }
  205368. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205369. const String& defaultValue)
  205370. {
  205371. String valueName, result (defaultValue);
  205372. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205373. if (k != 0)
  205374. {
  205375. WCHAR buffer [2048];
  205376. unsigned long bufferSize = sizeof (buffer);
  205377. DWORD type = REG_SZ;
  205378. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205379. {
  205380. if (type == REG_SZ)
  205381. result = buffer;
  205382. else if (type == REG_DWORD)
  205383. result = String ((int) *(DWORD*) buffer);
  205384. }
  205385. RegCloseKey (k);
  205386. }
  205387. return result;
  205388. }
  205389. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205390. const String& value)
  205391. {
  205392. String valueName;
  205393. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205394. if (k != 0)
  205395. {
  205396. RegSetValueEx (k, valueName, 0, REG_SZ,
  205397. (const BYTE*) (const WCHAR*) value,
  205398. sizeof (WCHAR) * (value.length() + 1));
  205399. RegCloseKey (k);
  205400. }
  205401. }
  205402. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205403. {
  205404. bool exists = false;
  205405. String valueName;
  205406. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205407. if (k != 0)
  205408. {
  205409. unsigned char buffer [2048];
  205410. unsigned long bufferSize = sizeof (buffer);
  205411. DWORD type = 0;
  205412. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205413. exists = true;
  205414. RegCloseKey (k);
  205415. }
  205416. return exists;
  205417. }
  205418. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205419. {
  205420. String valueName;
  205421. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205422. if (k != 0)
  205423. {
  205424. RegDeleteValue (k, valueName);
  205425. RegCloseKey (k);
  205426. }
  205427. }
  205428. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205429. {
  205430. String valueName;
  205431. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205432. if (k != 0)
  205433. {
  205434. RegDeleteKey (k, valueName);
  205435. RegCloseKey (k);
  205436. }
  205437. }
  205438. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205439. const String& symbolicDescription,
  205440. const String& fullDescription,
  205441. const File& targetExecutable,
  205442. int iconResourceNumber)
  205443. {
  205444. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205445. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205446. if (iconResourceNumber != 0)
  205447. setRegistryValue (key + "\\DefaultIcon\\",
  205448. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205449. setRegistryValue (key + "\\", fullDescription);
  205450. setRegistryValue (key + "\\shell\\open\\command\\",
  205451. targetExecutable.getFullPathName() + " %1");
  205452. }
  205453. bool juce_IsRunningInWine()
  205454. {
  205455. HKEY key;
  205456. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205457. {
  205458. RegCloseKey (key);
  205459. return true;
  205460. }
  205461. return false;
  205462. }
  205463. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205464. {
  205465. String s (::GetCommandLineW());
  205466. StringArray tokens;
  205467. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205468. return tokens.joinIntoString (" ", 1);
  205469. }
  205470. static void* currentModuleHandle = 0;
  205471. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205472. {
  205473. if (currentModuleHandle == 0)
  205474. currentModuleHandle = GetModuleHandle (0);
  205475. return currentModuleHandle;
  205476. }
  205477. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205478. {
  205479. currentModuleHandle = newHandle;
  205480. }
  205481. void PlatformUtilities::fpuReset()
  205482. {
  205483. #if JUCE_MSVC
  205484. _clearfp();
  205485. #endif
  205486. }
  205487. void PlatformUtilities::beep()
  205488. {
  205489. MessageBeep (MB_OK);
  205490. }
  205491. #endif
  205492. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205493. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205494. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205495. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205496. // compiled on its own).
  205497. #if JUCE_INCLUDED_FILE
  205498. static const unsigned int specialId = WM_APP + 0x4400;
  205499. static const unsigned int broadcastId = WM_APP + 0x4403;
  205500. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205501. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205502. HWND juce_messageWindowHandle = 0;
  205503. extern long improbableWindowNumber; // defined in windowing.cpp
  205504. #ifndef WM_APPCOMMAND
  205505. #define WM_APPCOMMAND 0x0319
  205506. #endif
  205507. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205508. const UINT message,
  205509. const WPARAM wParam,
  205510. const LPARAM lParam) throw()
  205511. {
  205512. JUCE_TRY
  205513. {
  205514. if (h == juce_messageWindowHandle)
  205515. {
  205516. if (message == specialCallbackId)
  205517. {
  205518. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205519. return (LRESULT) (*func) ((void*) lParam);
  205520. }
  205521. else if (message == specialId)
  205522. {
  205523. // these are trapped early in the dispatch call, but must also be checked
  205524. // here in case there are windows modal dialog boxes doing their own
  205525. // dispatch loop and not calling our version
  205526. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205527. return 0;
  205528. }
  205529. else if (message == broadcastId)
  205530. {
  205531. const ScopedPointer <String> messageString ((String*) lParam);
  205532. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205533. return 0;
  205534. }
  205535. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205536. {
  205537. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205538. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205539. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205540. return 0;
  205541. }
  205542. }
  205543. }
  205544. JUCE_CATCH_EXCEPTION
  205545. return DefWindowProc (h, message, wParam, lParam);
  205546. }
  205547. static bool isEventBlockedByModalComps (MSG& m)
  205548. {
  205549. if (Component::getNumCurrentlyModalComponents() == 0
  205550. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205551. return false;
  205552. switch (m.message)
  205553. {
  205554. case WM_MOUSEMOVE:
  205555. case WM_NCMOUSEMOVE:
  205556. case 0x020A: /* WM_MOUSEWHEEL */
  205557. case 0x020E: /* WM_MOUSEHWHEEL */
  205558. case WM_KEYUP:
  205559. case WM_SYSKEYUP:
  205560. case WM_CHAR:
  205561. case WM_APPCOMMAND:
  205562. case WM_LBUTTONUP:
  205563. case WM_MBUTTONUP:
  205564. case WM_RBUTTONUP:
  205565. case WM_MOUSEACTIVATE:
  205566. case WM_NCMOUSEHOVER:
  205567. case WM_MOUSEHOVER:
  205568. return true;
  205569. case WM_NCLBUTTONDOWN:
  205570. case WM_NCLBUTTONDBLCLK:
  205571. case WM_NCRBUTTONDOWN:
  205572. case WM_NCRBUTTONDBLCLK:
  205573. case WM_NCMBUTTONDOWN:
  205574. case WM_NCMBUTTONDBLCLK:
  205575. case WM_LBUTTONDOWN:
  205576. case WM_LBUTTONDBLCLK:
  205577. case WM_MBUTTONDOWN:
  205578. case WM_MBUTTONDBLCLK:
  205579. case WM_RBUTTONDOWN:
  205580. case WM_RBUTTONDBLCLK:
  205581. case WM_KEYDOWN:
  205582. case WM_SYSKEYDOWN:
  205583. {
  205584. Component* const modal = Component::getCurrentlyModalComponent (0);
  205585. if (modal != 0)
  205586. modal->inputAttemptWhenModal();
  205587. return true;
  205588. }
  205589. default:
  205590. break;
  205591. }
  205592. return false;
  205593. }
  205594. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205595. {
  205596. MSG m;
  205597. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205598. return false;
  205599. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205600. {
  205601. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205602. {
  205603. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205604. }
  205605. else if (m.message == WM_QUIT)
  205606. {
  205607. if (JUCEApplication::getInstance() != 0)
  205608. JUCEApplication::getInstance()->systemRequestedQuit();
  205609. }
  205610. else if (! isEventBlockedByModalComps (m))
  205611. {
  205612. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205613. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205614. {
  205615. // if it's someone else's window being clicked on, and the focus is
  205616. // currently on a juce window, pass the kb focus over..
  205617. HWND currentFocus = GetFocus();
  205618. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205619. SetFocus (m.hwnd);
  205620. }
  205621. TranslateMessage (&m);
  205622. DispatchMessage (&m);
  205623. }
  205624. }
  205625. return true;
  205626. }
  205627. bool juce_postMessageToSystemQueue (Message* message)
  205628. {
  205629. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205630. }
  205631. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205632. void* userData)
  205633. {
  205634. if (MessageManager::getInstance()->isThisTheMessageThread())
  205635. {
  205636. return (*callback) (userData);
  205637. }
  205638. else
  205639. {
  205640. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205641. // deadlock because the message manager is blocked from running, and can't
  205642. // call your function..
  205643. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205644. return (void*) SendMessage (juce_messageWindowHandle,
  205645. specialCallbackId,
  205646. (WPARAM) callback,
  205647. (LPARAM) userData);
  205648. }
  205649. }
  205650. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205651. {
  205652. if (hwnd != juce_messageWindowHandle)
  205653. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205654. return TRUE;
  205655. }
  205656. void MessageManager::broadcastMessage (const String& value)
  205657. {
  205658. Array<void*> windows;
  205659. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205660. const String localCopy (value);
  205661. COPYDATASTRUCT data;
  205662. data.dwData = broadcastId;
  205663. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205664. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205665. for (int i = windows.size(); --i >= 0;)
  205666. {
  205667. HWND hwnd = (HWND) windows.getUnchecked(i);
  205668. TCHAR windowName [64]; // no need to read longer strings than this
  205669. GetWindowText (hwnd, windowName, 64);
  205670. windowName [63] = 0;
  205671. if (String (windowName) == messageWindowName)
  205672. {
  205673. DWORD_PTR result;
  205674. SendMessageTimeout (hwnd, WM_COPYDATA,
  205675. (WPARAM) juce_messageWindowHandle,
  205676. (LPARAM) &data,
  205677. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205678. 8000,
  205679. &result);
  205680. }
  205681. }
  205682. }
  205683. static const String getMessageWindowClassName()
  205684. {
  205685. // this name has to be different for each app/dll instance because otherwise
  205686. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205687. // window class).
  205688. static int number = 0;
  205689. if (number == 0)
  205690. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205691. return "JUCEcs_" + String (number);
  205692. }
  205693. void MessageManager::doPlatformSpecificInitialisation()
  205694. {
  205695. OleInitialize (0);
  205696. const String className (getMessageWindowClassName());
  205697. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205698. WNDCLASSEX wc;
  205699. zerostruct (wc);
  205700. wc.cbSize = sizeof (wc);
  205701. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205702. wc.cbWndExtra = 4;
  205703. wc.hInstance = hmod;
  205704. wc.lpszClassName = className;
  205705. RegisterClassEx (&wc);
  205706. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205707. messageWindowName,
  205708. 0, 0, 0, 0, 0, 0, 0,
  205709. hmod, 0);
  205710. }
  205711. void MessageManager::doPlatformSpecificShutdown()
  205712. {
  205713. DestroyWindow (juce_messageWindowHandle);
  205714. UnregisterClass (getMessageWindowClassName(), 0);
  205715. OleUninitialize();
  205716. }
  205717. #endif
  205718. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205719. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205720. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205721. // compiled on its own).
  205722. #if JUCE_INCLUDED_FILE
  205723. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205724. NEWTEXTMETRICEXW*,
  205725. int type,
  205726. LPARAM lParam)
  205727. {
  205728. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205729. {
  205730. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205731. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205732. }
  205733. return 1;
  205734. }
  205735. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205736. NEWTEXTMETRICEXW*,
  205737. int type,
  205738. LPARAM lParam)
  205739. {
  205740. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205741. {
  205742. LOGFONTW lf;
  205743. zerostruct (lf);
  205744. lf.lfWeight = FW_DONTCARE;
  205745. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205746. lf.lfQuality = DEFAULT_QUALITY;
  205747. lf.lfCharSet = DEFAULT_CHARSET;
  205748. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205749. lf.lfPitchAndFamily = FF_DONTCARE;
  205750. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205751. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205752. HDC dc = CreateCompatibleDC (0);
  205753. EnumFontFamiliesEx (dc, &lf,
  205754. (FONTENUMPROCW) &wfontEnum2,
  205755. lParam, 0);
  205756. DeleteDC (dc);
  205757. }
  205758. return 1;
  205759. }
  205760. const StringArray Font::findAllTypefaceNames()
  205761. {
  205762. StringArray results;
  205763. HDC dc = CreateCompatibleDC (0);
  205764. {
  205765. LOGFONTW lf;
  205766. zerostruct (lf);
  205767. lf.lfWeight = FW_DONTCARE;
  205768. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205769. lf.lfQuality = DEFAULT_QUALITY;
  205770. lf.lfCharSet = DEFAULT_CHARSET;
  205771. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205772. lf.lfPitchAndFamily = FF_DONTCARE;
  205773. lf.lfFaceName[0] = 0;
  205774. EnumFontFamiliesEx (dc, &lf,
  205775. (FONTENUMPROCW) &wfontEnum1,
  205776. (LPARAM) &results, 0);
  205777. }
  205778. DeleteDC (dc);
  205779. results.sort (true);
  205780. return results;
  205781. }
  205782. extern bool juce_IsRunningInWine();
  205783. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205784. {
  205785. if (juce_IsRunningInWine())
  205786. {
  205787. // If we're running in Wine, then use fonts that might be available on Linux..
  205788. defaultSans = "Bitstream Vera Sans";
  205789. defaultSerif = "Bitstream Vera Serif";
  205790. defaultFixed = "Bitstream Vera Sans Mono";
  205791. }
  205792. else
  205793. {
  205794. defaultSans = "Verdana";
  205795. defaultSerif = "Times";
  205796. defaultFixed = "Lucida Console";
  205797. }
  205798. }
  205799. class FontDCHolder : private DeletedAtShutdown
  205800. {
  205801. public:
  205802. FontDCHolder()
  205803. : dc (0), numKPs (0), size (0),
  205804. bold (false), italic (false)
  205805. {
  205806. }
  205807. ~FontDCHolder()
  205808. {
  205809. if (dc != 0)
  205810. {
  205811. DeleteDC (dc);
  205812. DeleteObject (fontH);
  205813. }
  205814. clearSingletonInstance();
  205815. }
  205816. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205817. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205818. {
  205819. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205820. {
  205821. fontName = fontName_;
  205822. bold = bold_;
  205823. italic = italic_;
  205824. size = size_;
  205825. if (dc != 0)
  205826. {
  205827. DeleteDC (dc);
  205828. DeleteObject (fontH);
  205829. kps.free();
  205830. }
  205831. fontH = 0;
  205832. dc = CreateCompatibleDC (0);
  205833. SetMapperFlags (dc, 0);
  205834. SetMapMode (dc, MM_TEXT);
  205835. LOGFONTW lfw;
  205836. zerostruct (lfw);
  205837. lfw.lfCharSet = DEFAULT_CHARSET;
  205838. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205839. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205840. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205841. lfw.lfQuality = PROOF_QUALITY;
  205842. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205843. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205844. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205845. lfw.lfHeight = size > 0 ? size : -256;
  205846. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205847. if (standardSizedFont != 0)
  205848. {
  205849. if (SelectObject (dc, standardSizedFont) != 0)
  205850. {
  205851. fontH = standardSizedFont;
  205852. if (size == 0)
  205853. {
  205854. OUTLINETEXTMETRIC otm;
  205855. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205856. {
  205857. lfw.lfHeight = -(int) otm.otmEMSquare;
  205858. fontH = CreateFontIndirect (&lfw);
  205859. SelectObject (dc, fontH);
  205860. DeleteObject (standardSizedFont);
  205861. }
  205862. }
  205863. }
  205864. else
  205865. {
  205866. jassertfalse;
  205867. }
  205868. }
  205869. else
  205870. {
  205871. jassertfalse;
  205872. }
  205873. }
  205874. return dc;
  205875. }
  205876. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205877. {
  205878. if (kps == 0)
  205879. {
  205880. numKPs = GetKerningPairs (dc, 0, 0);
  205881. kps.calloc (numKPs);
  205882. GetKerningPairs (dc, numKPs, kps);
  205883. }
  205884. numKPs_ = numKPs;
  205885. return kps;
  205886. }
  205887. private:
  205888. HFONT fontH;
  205889. HDC dc;
  205890. String fontName;
  205891. HeapBlock <KERNINGPAIR> kps;
  205892. int numKPs, size;
  205893. bool bold, italic;
  205894. FontDCHolder (const FontDCHolder&);
  205895. FontDCHolder& operator= (const FontDCHolder&);
  205896. };
  205897. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205898. class WindowsTypeface : public CustomTypeface
  205899. {
  205900. public:
  205901. WindowsTypeface (const Font& font)
  205902. {
  205903. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205904. font.isBold(), font.isItalic(), 0);
  205905. TEXTMETRIC tm;
  205906. tm.tmAscent = tm.tmHeight = 1;
  205907. tm.tmDefaultChar = 0;
  205908. GetTextMetrics (dc, &tm);
  205909. setCharacteristics (font.getTypefaceName(),
  205910. tm.tmAscent / (float) tm.tmHeight,
  205911. font.isBold(), font.isItalic(),
  205912. tm.tmDefaultChar);
  205913. }
  205914. bool loadGlyphIfPossible (juce_wchar character)
  205915. {
  205916. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205917. GLYPHMETRICS gm;
  205918. {
  205919. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205920. WORD index = 0;
  205921. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205922. && index == 0xffff)
  205923. {
  205924. return false;
  205925. }
  205926. }
  205927. Path glyphPath;
  205928. TEXTMETRIC tm;
  205929. if (! GetTextMetrics (dc, &tm))
  205930. {
  205931. addGlyph (character, glyphPath, 0);
  205932. return true;
  205933. }
  205934. const float height = (float) tm.tmHeight;
  205935. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205936. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205937. &gm, 0, 0, &identityMatrix);
  205938. if (bufSize > 0)
  205939. {
  205940. HeapBlock<char> data (bufSize);
  205941. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205942. bufSize, data, &identityMatrix);
  205943. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205944. const float scaleX = 1.0f / height;
  205945. const float scaleY = -1.0f / height;
  205946. while ((char*) pheader < data + bufSize)
  205947. {
  205948. float x = scaleX * pheader->pfxStart.x.value;
  205949. float y = scaleY * pheader->pfxStart.y.value;
  205950. glyphPath.startNewSubPath (x, y);
  205951. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205952. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205953. while ((const char*) curve < curveEnd)
  205954. {
  205955. if (curve->wType == TT_PRIM_LINE)
  205956. {
  205957. for (int i = 0; i < curve->cpfx; ++i)
  205958. {
  205959. x = scaleX * curve->apfx[i].x.value;
  205960. y = scaleY * curve->apfx[i].y.value;
  205961. glyphPath.lineTo (x, y);
  205962. }
  205963. }
  205964. else if (curve->wType == TT_PRIM_QSPLINE)
  205965. {
  205966. for (int i = 0; i < curve->cpfx - 1; ++i)
  205967. {
  205968. const float x2 = scaleX * curve->apfx[i].x.value;
  205969. const float y2 = scaleY * curve->apfx[i].y.value;
  205970. float x3, y3;
  205971. if (i < curve->cpfx - 2)
  205972. {
  205973. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205974. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205975. }
  205976. else
  205977. {
  205978. x3 = scaleX * curve->apfx[i + 1].x.value;
  205979. y3 = scaleY * curve->apfx[i + 1].y.value;
  205980. }
  205981. glyphPath.quadraticTo (x2, y2, x3, y3);
  205982. x = x3;
  205983. y = y3;
  205984. }
  205985. }
  205986. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205987. }
  205988. pheader = (const TTPOLYGONHEADER*) curve;
  205989. glyphPath.closeSubPath();
  205990. }
  205991. }
  205992. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205993. int numKPs;
  205994. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205995. for (int i = 0; i < numKPs; ++i)
  205996. {
  205997. if (kps[i].wFirst == character)
  205998. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205999. kps[i].iKernAmount / height);
  206000. }
  206001. return true;
  206002. }
  206003. juce_UseDebuggingNewOperator
  206004. };
  206005. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206006. {
  206007. return new WindowsTypeface (font);
  206008. }
  206009. #endif
  206010. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206011. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206012. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206013. // compiled on its own).
  206014. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  206015. class SharedD2DFactory : public DeletedAtShutdown
  206016. {
  206017. public:
  206018. SharedD2DFactory()
  206019. {
  206020. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  206021. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  206022. if (directWriteFactory != 0)
  206023. directWriteFactory->GetSystemFontCollection (&systemFonts);
  206024. }
  206025. ~SharedD2DFactory()
  206026. {
  206027. clearSingletonInstance();
  206028. }
  206029. juce_DeclareSingleton (SharedD2DFactory, false);
  206030. ComSmartPtr <ID2D1Factory> d2dFactory;
  206031. ComSmartPtr <IDWriteFactory> directWriteFactory;
  206032. ComSmartPtr <IDWriteFontCollection> systemFonts;
  206033. };
  206034. juce_ImplementSingleton (SharedD2DFactory)
  206035. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  206036. {
  206037. public:
  206038. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  206039. : hwnd (hwnd_),
  206040. currentState (0)
  206041. {
  206042. RECT windowRect;
  206043. GetClientRect (hwnd, &windowRect);
  206044. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206045. bounds.setSize (size.width, size.height);
  206046. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  206047. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  206048. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  206049. // xxx check for error
  206050. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  206051. }
  206052. ~Direct2DLowLevelGraphicsContext()
  206053. {
  206054. states.clear();
  206055. }
  206056. void resized()
  206057. {
  206058. RECT windowRect;
  206059. GetClientRect (hwnd, &windowRect);
  206060. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206061. renderingTarget->Resize (size);
  206062. bounds.setSize (size.width, size.height);
  206063. }
  206064. void clear()
  206065. {
  206066. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  206067. }
  206068. void start()
  206069. {
  206070. renderingTarget->BeginDraw();
  206071. saveState();
  206072. }
  206073. void end()
  206074. {
  206075. states.clear();
  206076. currentState = 0;
  206077. renderingTarget->EndDraw();
  206078. renderingTarget->CheckWindowState();
  206079. }
  206080. bool isVectorDevice() const { return false; }
  206081. void setOrigin (int x, int y)
  206082. {
  206083. currentState->origin.addXY (x, y);
  206084. }
  206085. bool clipToRectangle (const Rectangle<int>& r)
  206086. {
  206087. currentState->clipToRectangle (r);
  206088. return ! isClipEmpty();
  206089. }
  206090. bool clipToRectangleList (const RectangleList& clipRegion)
  206091. {
  206092. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  206093. return ! isClipEmpty();
  206094. }
  206095. void excludeClipRectangle (const Rectangle<int>&)
  206096. {
  206097. //xxx
  206098. }
  206099. void clipToPath (const Path& path, const AffineTransform& transform)
  206100. {
  206101. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  206102. }
  206103. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  206104. {
  206105. currentState->clipToImage (sourceImage,transform);
  206106. }
  206107. bool clipRegionIntersects (const Rectangle<int>& r)
  206108. {
  206109. const Rectangle<int> r2 (r + currentState->origin);
  206110. return currentState->clipRect.intersects (r2);
  206111. }
  206112. const Rectangle<int> getClipBounds() const
  206113. {
  206114. // xxx could this take into account complex clip regions?
  206115. return currentState->clipRect - currentState->origin;
  206116. }
  206117. bool isClipEmpty() const
  206118. {
  206119. return currentState->clipRect.isEmpty();
  206120. }
  206121. void saveState()
  206122. {
  206123. states.add (new SavedState (*this));
  206124. currentState = states.getLast();
  206125. }
  206126. void restoreState()
  206127. {
  206128. jassert (states.size() > 1) //you should never pop the last state!
  206129. states.removeLast (1);
  206130. currentState = states.getLast();
  206131. }
  206132. void setFill (const FillType& fillType)
  206133. {
  206134. currentState->setFill (fillType);
  206135. }
  206136. void setOpacity (float newOpacity)
  206137. {
  206138. currentState->setOpacity (newOpacity);
  206139. }
  206140. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206141. {
  206142. }
  206143. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206144. {
  206145. currentState->createBrush();
  206146. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206147. }
  206148. void fillPath (const Path& p, const AffineTransform& transform)
  206149. {
  206150. currentState->createBrush();
  206151. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206152. if (renderingTarget != 0)
  206153. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206154. }
  206155. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206156. {
  206157. const int x = currentState->origin.getX();
  206158. const int y = currentState->origin.getY();
  206159. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206160. D2D1_SIZE_U size;
  206161. size.width = image.getWidth();
  206162. size.height = image.getHeight();
  206163. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206164. Image img (image.convertedToFormat (Image::ARGB));
  206165. Image::BitmapData bd (img, false);
  206166. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206167. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206168. {
  206169. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206170. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206171. if (tempBitmap != 0)
  206172. renderingTarget->DrawBitmap (tempBitmap);
  206173. }
  206174. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206175. }
  206176. void drawLine (const Line <float>& line)
  206177. {
  206178. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206179. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206180. line.getEnd() + currentState->origin.toFloat());
  206181. currentState->createBrush();
  206182. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206183. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206184. currentState->currentBrush);
  206185. }
  206186. void drawVerticalLine (int x, float top, float bottom)
  206187. {
  206188. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206189. currentState->createBrush();
  206190. x += currentState->origin.getX();
  206191. const int y = currentState->origin.getY();
  206192. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206193. D2D1::Point2F (x, y + bottom),
  206194. currentState->currentBrush);
  206195. }
  206196. void drawHorizontalLine (int y, float left, float right)
  206197. {
  206198. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206199. currentState->createBrush();
  206200. y += currentState->origin.getY();
  206201. const int x = currentState->origin.getX();
  206202. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206203. D2D1::Point2F (x + right, y),
  206204. currentState->currentBrush);
  206205. }
  206206. void setFont (const Font& newFont)
  206207. {
  206208. currentState->setFont (newFont);
  206209. }
  206210. const Font getFont()
  206211. {
  206212. return currentState->font;
  206213. }
  206214. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206215. {
  206216. const float x = currentState->origin.getX();
  206217. const float y = currentState->origin.getY();
  206218. currentState->createBrush();
  206219. currentState->createFont();
  206220. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206221. float hScale = currentState->font.getHorizontalScale();
  206222. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206223. float dpiX = 0, dpiY = 0;
  206224. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206225. UINT32 glyphNum = glyphNumber;
  206226. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206227. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206228. DWRITE_GLYPH_OFFSET offset;
  206229. offset.advanceOffset = 0;
  206230. offset.ascenderOffset = 0;
  206231. float glyphAdvances = 0;
  206232. DWRITE_GLYPH_RUN glyph;
  206233. glyph.fontFace = currentState->currentFontFace;
  206234. glyph.glyphCount = 1;
  206235. glyph.glyphIndices = &glyphNum1;
  206236. glyph.isSideways = FALSE;
  206237. glyph.glyphAdvances = &glyphAdvances;
  206238. glyph.glyphOffsets = &offset;
  206239. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206240. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206241. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206242. }
  206243. class SavedState
  206244. {
  206245. public:
  206246. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206247. : owner (owner_), currentBrush (0),
  206248. fontScaling (1.0f), currentFontFace (0),
  206249. clipsRect (false), shouldClipRect (false),
  206250. clipsRectList (false), shouldClipRectList (false),
  206251. clipsComplex (false), shouldClipComplex (false),
  206252. clipsBitmap (false), shouldClipBitmap (false)
  206253. {
  206254. if (owner.currentState != 0)
  206255. {
  206256. // xxx seems like a very slow way to create one of these, and this is a performance
  206257. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206258. setFill (owner.currentState->fillType);
  206259. currentBrush = owner.currentState->currentBrush;
  206260. origin = owner.currentState->origin;
  206261. clipRect = owner.currentState->clipRect;
  206262. font = owner.currentState->font;
  206263. currentFontFace = owner.currentState->currentFontFace;
  206264. }
  206265. else
  206266. {
  206267. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206268. clipRect.setSize (size.width, size.height);
  206269. setFill (FillType (Colours::black));
  206270. }
  206271. }
  206272. ~SavedState()
  206273. {
  206274. clearClip();
  206275. clearFont();
  206276. clearFill();
  206277. clearPathClip();
  206278. clearImageClip();
  206279. complexClipLayer = 0;
  206280. bitmapMaskLayer = 0;
  206281. }
  206282. void clearClip()
  206283. {
  206284. popClips();
  206285. shouldClipRect = false;
  206286. }
  206287. void clipToRectangle (const Rectangle<int>& r)
  206288. {
  206289. clearClip();
  206290. clipRect = r + origin;
  206291. shouldClipRect = true;
  206292. pushClips();
  206293. }
  206294. void clearPathClip()
  206295. {
  206296. popClips();
  206297. if (shouldClipComplex)
  206298. {
  206299. complexClipGeometry = 0;
  206300. shouldClipComplex = false;
  206301. }
  206302. }
  206303. void clipToPath (ID2D1Geometry* geometry)
  206304. {
  206305. clearPathClip();
  206306. if (complexClipLayer == 0)
  206307. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206308. complexClipGeometry = geometry;
  206309. shouldClipComplex = true;
  206310. pushClips();
  206311. }
  206312. void clearRectListClip()
  206313. {
  206314. popClips();
  206315. if (shouldClipRectList)
  206316. {
  206317. rectListGeometry = 0;
  206318. shouldClipRectList = false;
  206319. }
  206320. }
  206321. void clipToRectList (ID2D1Geometry* geometry)
  206322. {
  206323. clearRectListClip();
  206324. if (rectListLayer == 0)
  206325. owner.renderingTarget->CreateLayer (&rectListLayer);
  206326. rectListGeometry = geometry;
  206327. shouldClipRectList = true;
  206328. pushClips();
  206329. }
  206330. void clearImageClip()
  206331. {
  206332. popClips();
  206333. if (shouldClipBitmap)
  206334. {
  206335. maskBitmap = 0;
  206336. bitmapMaskBrush = 0;
  206337. shouldClipBitmap = false;
  206338. }
  206339. }
  206340. void clipToImage (const Image& image, const AffineTransform& transform)
  206341. {
  206342. clearImageClip();
  206343. if (bitmapMaskLayer == 0)
  206344. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206345. D2D1_BRUSH_PROPERTIES brushProps;
  206346. brushProps.opacity = 1;
  206347. brushProps.transform = transfromToMatrix (transform);
  206348. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206349. D2D1_SIZE_U size;
  206350. size.width = image.getWidth();
  206351. size.height = image.getHeight();
  206352. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206353. maskImage = image.convertedToFormat (Image::ARGB);
  206354. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206355. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206356. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206357. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206358. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206359. imageMaskLayerParams = D2D1::LayerParameters();
  206360. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206361. shouldClipBitmap = true;
  206362. pushClips();
  206363. }
  206364. void popClips()
  206365. {
  206366. if (clipsBitmap)
  206367. {
  206368. owner.renderingTarget->PopLayer();
  206369. clipsBitmap = false;
  206370. }
  206371. if (clipsComplex)
  206372. {
  206373. owner.renderingTarget->PopLayer();
  206374. clipsComplex = false;
  206375. }
  206376. if (clipsRectList)
  206377. {
  206378. owner.renderingTarget->PopLayer();
  206379. clipsRectList = false;
  206380. }
  206381. if (clipsRect)
  206382. {
  206383. owner.renderingTarget->PopAxisAlignedClip();
  206384. clipsRect = false;
  206385. }
  206386. }
  206387. void pushClips()
  206388. {
  206389. if (shouldClipRect && ! clipsRect)
  206390. {
  206391. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206392. clipsRect = true;
  206393. }
  206394. if (shouldClipRectList && ! clipsRectList)
  206395. {
  206396. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206397. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206398. layerParams.geometricMask = rectListGeometry;
  206399. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206400. clipsRectList = true;
  206401. }
  206402. if (shouldClipComplex && ! clipsComplex)
  206403. {
  206404. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206405. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206406. layerParams.geometricMask = complexClipGeometry;
  206407. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206408. clipsComplex = true;
  206409. }
  206410. if (shouldClipBitmap && ! clipsBitmap)
  206411. {
  206412. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206413. clipsBitmap = true;
  206414. }
  206415. }
  206416. void setFill (const FillType& newFillType)
  206417. {
  206418. if (fillType != newFillType)
  206419. {
  206420. fillType = newFillType;
  206421. clearFill();
  206422. }
  206423. }
  206424. void clearFont()
  206425. {
  206426. currentFontFace = localFontFace = 0;
  206427. }
  206428. void setFont (const Font& newFont)
  206429. {
  206430. if (font != newFont)
  206431. {
  206432. font = newFont;
  206433. clearFont();
  206434. }
  206435. }
  206436. void createFont()
  206437. {
  206438. // xxx The font shouldn't be managed by the graphics context.
  206439. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206440. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206441. // WindowsTypeface class.
  206442. if (currentFontFace == 0)
  206443. {
  206444. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206445. fontScaling = systemType->getAscent();
  206446. BOOL fontFound;
  206447. uint32 fontIndex;
  206448. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206449. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206450. if (! fontFound)
  206451. fontIndex = 0;
  206452. ComSmartPtr <IDWriteFontFamily> fontFam;
  206453. fonts->GetFontFamily (fontIndex, &fontFam);
  206454. ComSmartPtr <IDWriteFont> font;
  206455. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206456. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206457. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206458. font->CreateFontFace (&localFontFace);
  206459. currentFontFace = localFontFace;
  206460. }
  206461. }
  206462. void setOpacity (float newOpacity)
  206463. {
  206464. fillType.setOpacity (newOpacity);
  206465. if (currentBrush != 0)
  206466. currentBrush->SetOpacity (newOpacity);
  206467. }
  206468. void clearFill()
  206469. {
  206470. gradientStops = 0;
  206471. linearGradient = 0;
  206472. radialGradient = 0;
  206473. bitmap = 0;
  206474. bitmapBrush = 0;
  206475. currentBrush = 0;
  206476. }
  206477. void createBrush()
  206478. {
  206479. if (currentBrush == 0)
  206480. {
  206481. const int x = origin.getX();
  206482. const int y = origin.getY();
  206483. if (fillType.isColour())
  206484. {
  206485. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206486. owner.colourBrush->SetColor (colour);
  206487. currentBrush = owner.colourBrush;
  206488. }
  206489. else if (fillType.isTiledImage())
  206490. {
  206491. D2D1_BRUSH_PROPERTIES brushProps;
  206492. brushProps.opacity = fillType.getOpacity();
  206493. brushProps.transform = transfromToMatrix (fillType.transform);
  206494. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206495. image = fillType.image;
  206496. D2D1_SIZE_U size;
  206497. size.width = image.getWidth();
  206498. size.height = image.getHeight();
  206499. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206500. this->image = image.convertedToFormat (Image::ARGB);
  206501. Image::BitmapData bd (this->image, false);
  206502. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206503. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206504. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206505. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206506. currentBrush = bitmapBrush;
  206507. }
  206508. else if (fillType.isGradient())
  206509. {
  206510. gradientStops = 0;
  206511. D2D1_BRUSH_PROPERTIES brushProps;
  206512. brushProps.opacity = fillType.getOpacity();
  206513. brushProps.transform = transfromToMatrix (fillType.transform);
  206514. const int numColors = fillType.gradient->getNumColours();
  206515. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206516. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206517. {
  206518. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206519. stops[i].position = fillType.gradient->getColourPosition(i);
  206520. }
  206521. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206522. if (fillType.gradient->isRadial)
  206523. {
  206524. radialGradient = 0;
  206525. const Point<float>& p1 = fillType.gradient->point1;
  206526. const Point<float>& p2 = fillType.gradient->point2;
  206527. float r = p1.getDistanceFrom (p2);
  206528. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206529. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206530. D2D1::Point2F (0, 0),
  206531. r, r);
  206532. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206533. currentBrush = radialGradient;
  206534. }
  206535. else
  206536. {
  206537. linearGradient = 0;
  206538. const Point<float>& p1 = fillType.gradient->point1;
  206539. const Point<float>& p2 = fillType.gradient->point2;
  206540. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206541. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206542. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206543. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206544. currentBrush = linearGradient;
  206545. }
  206546. }
  206547. }
  206548. }
  206549. juce_UseDebuggingNewOperator
  206550. //xxx most of these members should probably be private...
  206551. Direct2DLowLevelGraphicsContext& owner;
  206552. Point<int> origin;
  206553. Font font;
  206554. float fontScaling;
  206555. IDWriteFontFace* currentFontFace;
  206556. ComSmartPtr <IDWriteFontFace> localFontFace;
  206557. FillType fillType;
  206558. Image image;
  206559. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206560. Rectangle<int> clipRect;
  206561. bool clipsRect, shouldClipRect;
  206562. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206563. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206564. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206565. bool clipsComplex, shouldClipComplex;
  206566. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206567. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206568. ComSmartPtr <ID2D1Layer> rectListLayer;
  206569. bool clipsRectList, shouldClipRectList;
  206570. Image maskImage;
  206571. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206572. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206573. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206574. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206575. bool clipsBitmap, shouldClipBitmap;
  206576. ID2D1Brush* currentBrush;
  206577. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206578. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206579. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206580. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206581. private:
  206582. SavedState (const SavedState&);
  206583. SavedState& operator= (const SavedState& other);
  206584. };
  206585. juce_UseDebuggingNewOperator
  206586. private:
  206587. HWND hwnd;
  206588. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206589. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206590. Rectangle<int> bounds;
  206591. SavedState* currentState;
  206592. OwnedArray<SavedState> states;
  206593. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206594. {
  206595. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206596. }
  206597. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206598. {
  206599. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206600. }
  206601. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206602. {
  206603. transform.transformPoint (x, y);
  206604. return D2D1::Point2F (x, y);
  206605. }
  206606. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206607. {
  206608. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206609. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206610. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206611. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206612. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206613. }
  206614. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206615. {
  206616. ID2D1PathGeometry* p = 0;
  206617. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206618. ComSmartPtr <ID2D1GeometrySink> sink;
  206619. HRESULT hr = p->Open (&sink); // xxx handle error
  206620. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206621. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206622. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206623. hr = sink->Close();
  206624. return p;
  206625. }
  206626. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206627. {
  206628. Path::Iterator it (path);
  206629. while (it.next())
  206630. {
  206631. switch (it.elementType)
  206632. {
  206633. case Path::Iterator::cubicTo:
  206634. {
  206635. D2D1_BEZIER_SEGMENT seg;
  206636. transform.transformPoint (it.x1, it.y1);
  206637. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206638. transform.transformPoint (it.x2, it.y2);
  206639. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206640. transform.transformPoint(it.x3, it.y3);
  206641. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206642. sink->AddBezier (seg);
  206643. break;
  206644. }
  206645. case Path::Iterator::lineTo:
  206646. {
  206647. transform.transformPoint (it.x1, it.y1);
  206648. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206649. break;
  206650. }
  206651. case Path::Iterator::quadraticTo:
  206652. {
  206653. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206654. transform.transformPoint (it.x1, it.y1);
  206655. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206656. transform.transformPoint (it.x2, it.y2);
  206657. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206658. sink->AddQuadraticBezier (seg);
  206659. break;
  206660. }
  206661. case Path::Iterator::closePath:
  206662. {
  206663. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206664. break;
  206665. }
  206666. case Path::Iterator::startNewSubPath:
  206667. {
  206668. transform.transformPoint (it.x1, it.y1);
  206669. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206670. break;
  206671. }
  206672. }
  206673. }
  206674. }
  206675. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206676. {
  206677. ID2D1PathGeometry* p = 0;
  206678. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206679. ComSmartPtr <ID2D1GeometrySink> sink;
  206680. HRESULT hr = p->Open (&sink);
  206681. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206682. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206683. hr = sink->Close();
  206684. return p;
  206685. }
  206686. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206687. {
  206688. D2D1::Matrix3x2F matrix;
  206689. matrix._11 = transform.mat00;
  206690. matrix._12 = transform.mat10;
  206691. matrix._21 = transform.mat01;
  206692. matrix._22 = transform.mat11;
  206693. matrix._31 = transform.mat02;
  206694. matrix._32 = transform.mat12;
  206695. return matrix;
  206696. }
  206697. };
  206698. #endif
  206699. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206700. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206701. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206702. // compiled on its own).
  206703. #if JUCE_INCLUDED_FILE
  206704. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206705. // these are in the windows SDK, but need to be repeated here for GCC..
  206706. #ifndef GET_APPCOMMAND_LPARAM
  206707. #define FAPPCOMMAND_MASK 0xF000
  206708. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206709. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206710. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206711. #define APPCOMMAND_MEDIA_STOP 13
  206712. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206713. #define WM_APPCOMMAND 0x0319
  206714. #endif
  206715. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206716. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206717. extern bool juce_IsRunningInWine();
  206718. #ifndef ULW_ALPHA
  206719. #define ULW_ALPHA 0x00000002
  206720. #endif
  206721. #ifndef AC_SRC_ALPHA
  206722. #define AC_SRC_ALPHA 0x01
  206723. #endif
  206724. static HPALETTE palette = 0;
  206725. static bool createPaletteIfNeeded = true;
  206726. static bool shouldDeactivateTitleBar = true;
  206727. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206728. #define WM_TRAYNOTIFY WM_USER + 100
  206729. using ::abs;
  206730. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206731. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206732. bool Desktop::canUseSemiTransparentWindows() throw()
  206733. {
  206734. if (updateLayeredWindow == 0)
  206735. {
  206736. if (! juce_IsRunningInWine())
  206737. {
  206738. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206739. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206740. }
  206741. }
  206742. return updateLayeredWindow != 0;
  206743. }
  206744. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206745. {
  206746. return upright;
  206747. }
  206748. const int extendedKeyModifier = 0x10000;
  206749. const int KeyPress::spaceKey = VK_SPACE;
  206750. const int KeyPress::returnKey = VK_RETURN;
  206751. const int KeyPress::escapeKey = VK_ESCAPE;
  206752. const int KeyPress::backspaceKey = VK_BACK;
  206753. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206754. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206755. const int KeyPress::tabKey = VK_TAB;
  206756. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206757. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206758. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206759. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206760. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206761. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206762. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206763. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206764. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206765. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206766. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206767. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206768. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206769. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206770. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206771. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206772. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206773. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206774. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206775. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206776. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206777. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206778. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206779. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206780. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206781. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206782. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206783. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206784. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206785. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206786. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206787. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206788. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206789. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206790. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206791. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206792. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206793. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206794. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206795. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206796. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206797. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206798. const int KeyPress::playKey = 0x30000;
  206799. const int KeyPress::stopKey = 0x30001;
  206800. const int KeyPress::fastForwardKey = 0x30002;
  206801. const int KeyPress::rewindKey = 0x30003;
  206802. class WindowsBitmapImage : public Image::SharedImage
  206803. {
  206804. public:
  206805. HBITMAP hBitmap;
  206806. BITMAPV4HEADER bitmapInfo;
  206807. HDC hdc;
  206808. unsigned char* bitmapData;
  206809. WindowsBitmapImage (const Image::PixelFormat format_,
  206810. const int w, const int h, const bool clearImage)
  206811. : Image::SharedImage (format_, w, h)
  206812. {
  206813. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206814. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206815. zerostruct (bitmapInfo);
  206816. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206817. bitmapInfo.bV4Width = w;
  206818. bitmapInfo.bV4Height = h;
  206819. bitmapInfo.bV4Planes = 1;
  206820. bitmapInfo.bV4CSType = 1;
  206821. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206822. if (format_ == Image::ARGB)
  206823. {
  206824. bitmapInfo.bV4AlphaMask = 0xff000000;
  206825. bitmapInfo.bV4RedMask = 0xff0000;
  206826. bitmapInfo.bV4GreenMask = 0xff00;
  206827. bitmapInfo.bV4BlueMask = 0xff;
  206828. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206829. }
  206830. else
  206831. {
  206832. bitmapInfo.bV4V4Compression = BI_RGB;
  206833. }
  206834. lineStride = -((w * pixelStride + 3) & ~3);
  206835. HDC dc = GetDC (0);
  206836. hdc = CreateCompatibleDC (dc);
  206837. ReleaseDC (0, dc);
  206838. SetMapMode (hdc, MM_TEXT);
  206839. hBitmap = CreateDIBSection (hdc,
  206840. (BITMAPINFO*) &(bitmapInfo),
  206841. DIB_RGB_COLORS,
  206842. (void**) &bitmapData,
  206843. 0, 0);
  206844. SelectObject (hdc, hBitmap);
  206845. if (format_ == Image::ARGB && clearImage)
  206846. zeromem (bitmapData, abs (h * lineStride));
  206847. imageData = bitmapData - (lineStride * (h - 1));
  206848. }
  206849. ~WindowsBitmapImage()
  206850. {
  206851. DeleteDC (hdc);
  206852. DeleteObject (hBitmap);
  206853. }
  206854. Image::ImageType getType() const { return Image::NativeImage; }
  206855. LowLevelGraphicsContext* createLowLevelContext()
  206856. {
  206857. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206858. }
  206859. SharedImage* clone()
  206860. {
  206861. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206862. for (int i = 0; i < height; ++i)
  206863. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206864. return im;
  206865. }
  206866. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206867. const int x, const int y,
  206868. const RectangleList& maskedRegion) throw()
  206869. {
  206870. static HDRAWDIB hdd = 0;
  206871. static bool needToCreateDrawDib = true;
  206872. if (needToCreateDrawDib)
  206873. {
  206874. needToCreateDrawDib = false;
  206875. HDC dc = GetDC (0);
  206876. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206877. ReleaseDC (0, dc);
  206878. // only open if we're not palettised
  206879. if (n > 8)
  206880. hdd = DrawDibOpen();
  206881. }
  206882. if (createPaletteIfNeeded)
  206883. {
  206884. HDC dc = GetDC (0);
  206885. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206886. ReleaseDC (0, dc);
  206887. if (n <= 8)
  206888. palette = CreateHalftonePalette (dc);
  206889. createPaletteIfNeeded = false;
  206890. }
  206891. if (palette != 0)
  206892. {
  206893. SelectPalette (dc, palette, FALSE);
  206894. RealizePalette (dc);
  206895. SetStretchBltMode (dc, HALFTONE);
  206896. }
  206897. SetMapMode (dc, MM_TEXT);
  206898. if (transparent)
  206899. {
  206900. POINT p, pos;
  206901. SIZE size;
  206902. RECT windowBounds;
  206903. GetWindowRect (hwnd, &windowBounds);
  206904. p.x = -x;
  206905. p.y = -y;
  206906. pos.x = windowBounds.left;
  206907. pos.y = windowBounds.top;
  206908. size.cx = windowBounds.right - windowBounds.left;
  206909. size.cy = windowBounds.bottom - windowBounds.top;
  206910. BLENDFUNCTION bf;
  206911. bf.AlphaFormat = AC_SRC_ALPHA;
  206912. bf.BlendFlags = 0;
  206913. bf.BlendOp = AC_SRC_OVER;
  206914. bf.SourceConstantAlpha = 0xff;
  206915. if (! maskedRegion.isEmpty())
  206916. {
  206917. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206918. {
  206919. const Rectangle<int>& r = *i.getRectangle();
  206920. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206921. }
  206922. }
  206923. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206924. }
  206925. else
  206926. {
  206927. int savedDC = 0;
  206928. if (! maskedRegion.isEmpty())
  206929. {
  206930. savedDC = SaveDC (dc);
  206931. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206932. {
  206933. const Rectangle<int>& r = *i.getRectangle();
  206934. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206935. }
  206936. }
  206937. if (hdd == 0)
  206938. {
  206939. StretchDIBits (dc,
  206940. x, y, width, height,
  206941. 0, 0, width, height,
  206942. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206943. DIB_RGB_COLORS, SRCCOPY);
  206944. }
  206945. else
  206946. {
  206947. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206948. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206949. 0, 0, width, height, 0);
  206950. }
  206951. if (! maskedRegion.isEmpty())
  206952. RestoreDC (dc, savedDC);
  206953. }
  206954. }
  206955. juce_UseDebuggingNewOperator
  206956. private:
  206957. WindowsBitmapImage (const WindowsBitmapImage&);
  206958. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206959. };
  206960. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206961. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206962. {
  206963. SHORT k = (SHORT) keyCode;
  206964. if ((keyCode & extendedKeyModifier) == 0
  206965. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206966. k += (SHORT) 'A' - (SHORT) 'a';
  206967. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206968. (SHORT) '+', VK_OEM_PLUS,
  206969. (SHORT) '-', VK_OEM_MINUS,
  206970. (SHORT) '.', VK_OEM_PERIOD,
  206971. (SHORT) ';', VK_OEM_1,
  206972. (SHORT) ':', VK_OEM_1,
  206973. (SHORT) '/', VK_OEM_2,
  206974. (SHORT) '?', VK_OEM_2,
  206975. (SHORT) '[', VK_OEM_4,
  206976. (SHORT) ']', VK_OEM_6 };
  206977. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206978. if (k == translatedValues [i])
  206979. k = translatedValues [i + 1];
  206980. return (GetKeyState (k) & 0x8000) != 0;
  206981. }
  206982. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206983. {
  206984. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206985. return callback (userData);
  206986. else
  206987. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206988. }
  206989. class Win32ComponentPeer : public ComponentPeer
  206990. {
  206991. public:
  206992. enum RenderingEngineType
  206993. {
  206994. softwareRenderingEngine = 0,
  206995. direct2DRenderingEngine
  206996. };
  206997. Win32ComponentPeer (Component* const component,
  206998. const int windowStyleFlags,
  206999. HWND parentToAddTo_)
  207000. : ComponentPeer (component, windowStyleFlags),
  207001. dontRepaint (false),
  207002. #if JUCE_DIRECT2D
  207003. currentRenderingEngine (direct2DRenderingEngine),
  207004. #else
  207005. currentRenderingEngine (softwareRenderingEngine),
  207006. #endif
  207007. fullScreen (false),
  207008. isDragging (false),
  207009. isMouseOver (false),
  207010. hasCreatedCaret (false),
  207011. currentWindowIcon (0),
  207012. dropTarget (0),
  207013. parentToAddTo (parentToAddTo_)
  207014. {
  207015. callFunctionIfNotLocked (&createWindowCallback, this);
  207016. setTitle (component->getName());
  207017. if ((windowStyleFlags & windowHasDropShadow) != 0
  207018. && Desktop::canUseSemiTransparentWindows())
  207019. {
  207020. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  207021. if (shadower != 0)
  207022. shadower->setOwner (component);
  207023. }
  207024. }
  207025. ~Win32ComponentPeer()
  207026. {
  207027. setTaskBarIcon (Image());
  207028. shadower = 0;
  207029. // do this before the next bit to avoid messages arriving for this window
  207030. // before it's destroyed
  207031. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  207032. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  207033. if (currentWindowIcon != 0)
  207034. DestroyIcon (currentWindowIcon);
  207035. if (dropTarget != 0)
  207036. {
  207037. dropTarget->Release();
  207038. dropTarget = 0;
  207039. }
  207040. #if JUCE_DIRECT2D
  207041. direct2DContext = 0;
  207042. #endif
  207043. }
  207044. void* getNativeHandle() const
  207045. {
  207046. return hwnd;
  207047. }
  207048. void setVisible (bool shouldBeVisible)
  207049. {
  207050. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207051. if (shouldBeVisible)
  207052. InvalidateRect (hwnd, 0, 0);
  207053. else
  207054. lastPaintTime = 0;
  207055. }
  207056. void setTitle (const String& title)
  207057. {
  207058. SetWindowText (hwnd, title);
  207059. }
  207060. void setPosition (int x, int y)
  207061. {
  207062. offsetWithinParent (x, y);
  207063. SetWindowPos (hwnd, 0,
  207064. x - windowBorder.getLeft(),
  207065. y - windowBorder.getTop(),
  207066. 0, 0,
  207067. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207068. }
  207069. void repaintNowIfTransparent()
  207070. {
  207071. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  207072. handlePaintMessage();
  207073. }
  207074. void updateBorderSize()
  207075. {
  207076. WINDOWINFO info;
  207077. info.cbSize = sizeof (info);
  207078. if (GetWindowInfo (hwnd, &info))
  207079. {
  207080. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  207081. info.rcClient.left - info.rcWindow.left,
  207082. info.rcWindow.bottom - info.rcClient.bottom,
  207083. info.rcWindow.right - info.rcClient.right);
  207084. }
  207085. #if JUCE_DIRECT2D
  207086. if (direct2DContext != 0)
  207087. direct2DContext->resized();
  207088. #endif
  207089. }
  207090. void setSize (int w, int h)
  207091. {
  207092. SetWindowPos (hwnd, 0, 0, 0,
  207093. w + windowBorder.getLeftAndRight(),
  207094. h + windowBorder.getTopAndBottom(),
  207095. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207096. updateBorderSize();
  207097. repaintNowIfTransparent();
  207098. }
  207099. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207100. {
  207101. fullScreen = isNowFullScreen;
  207102. offsetWithinParent (x, y);
  207103. SetWindowPos (hwnd, 0,
  207104. x - windowBorder.getLeft(),
  207105. y - windowBorder.getTop(),
  207106. w + windowBorder.getLeftAndRight(),
  207107. h + windowBorder.getTopAndBottom(),
  207108. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207109. updateBorderSize();
  207110. repaintNowIfTransparent();
  207111. }
  207112. const Rectangle<int> getBounds() const
  207113. {
  207114. RECT r;
  207115. GetWindowRect (hwnd, &r);
  207116. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207117. HWND parentH = GetParent (hwnd);
  207118. if (parentH != 0)
  207119. {
  207120. GetWindowRect (parentH, &r);
  207121. bounds.translate (-r.left, -r.top);
  207122. }
  207123. return windowBorder.subtractedFrom (bounds);
  207124. }
  207125. const Point<int> getScreenPosition() const
  207126. {
  207127. RECT r;
  207128. GetWindowRect (hwnd, &r);
  207129. return Point<int> (r.left + windowBorder.getLeft(),
  207130. r.top + windowBorder.getTop());
  207131. }
  207132. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  207133. {
  207134. return relativePosition + getScreenPosition();
  207135. }
  207136. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  207137. {
  207138. return screenPosition - getScreenPosition();
  207139. }
  207140. void setMinimised (bool shouldBeMinimised)
  207141. {
  207142. if (shouldBeMinimised != isMinimised())
  207143. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207144. }
  207145. bool isMinimised() const
  207146. {
  207147. WINDOWPLACEMENT wp;
  207148. wp.length = sizeof (WINDOWPLACEMENT);
  207149. GetWindowPlacement (hwnd, &wp);
  207150. return wp.showCmd == SW_SHOWMINIMIZED;
  207151. }
  207152. void setFullScreen (bool shouldBeFullScreen)
  207153. {
  207154. setMinimised (false);
  207155. if (fullScreen != shouldBeFullScreen)
  207156. {
  207157. fullScreen = shouldBeFullScreen;
  207158. const Component::SafePointer<Component> deletionChecker (component);
  207159. if (! fullScreen)
  207160. {
  207161. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207162. if (hasTitleBar())
  207163. ShowWindow (hwnd, SW_SHOWNORMAL);
  207164. if (! boundsCopy.isEmpty())
  207165. {
  207166. setBounds (boundsCopy.getX(),
  207167. boundsCopy.getY(),
  207168. boundsCopy.getWidth(),
  207169. boundsCopy.getHeight(),
  207170. false);
  207171. }
  207172. }
  207173. else
  207174. {
  207175. if (hasTitleBar())
  207176. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207177. else
  207178. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207179. }
  207180. if (deletionChecker != 0)
  207181. handleMovedOrResized();
  207182. }
  207183. }
  207184. bool isFullScreen() const
  207185. {
  207186. if (! hasTitleBar())
  207187. return fullScreen;
  207188. WINDOWPLACEMENT wp;
  207189. wp.length = sizeof (wp);
  207190. GetWindowPlacement (hwnd, &wp);
  207191. return wp.showCmd == SW_SHOWMAXIMIZED;
  207192. }
  207193. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207194. {
  207195. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  207196. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  207197. return false;
  207198. RECT r;
  207199. GetWindowRect (hwnd, &r);
  207200. POINT p;
  207201. p.x = position.getX() + r.left + windowBorder.getLeft();
  207202. p.y = position.getY() + r.top + windowBorder.getTop();
  207203. HWND w = WindowFromPoint (p);
  207204. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207205. }
  207206. const BorderSize getFrameSize() const
  207207. {
  207208. return windowBorder;
  207209. }
  207210. bool setAlwaysOnTop (bool alwaysOnTop)
  207211. {
  207212. const bool oldDeactivate = shouldDeactivateTitleBar;
  207213. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207214. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207215. 0, 0, 0, 0,
  207216. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207217. shouldDeactivateTitleBar = oldDeactivate;
  207218. if (shadower != 0)
  207219. shadower->componentBroughtToFront (*component);
  207220. return true;
  207221. }
  207222. void toFront (bool makeActive)
  207223. {
  207224. setMinimised (false);
  207225. const bool oldDeactivate = shouldDeactivateTitleBar;
  207226. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207227. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207228. shouldDeactivateTitleBar = oldDeactivate;
  207229. if (! makeActive)
  207230. {
  207231. // in this case a broughttofront call won't have occured, so do it now..
  207232. handleBroughtToFront();
  207233. }
  207234. }
  207235. void toBehind (ComponentPeer* other)
  207236. {
  207237. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207238. jassert (otherPeer != 0); // wrong type of window?
  207239. if (otherPeer != 0)
  207240. {
  207241. setMinimised (false);
  207242. // must be careful not to try to put a topmost window behind a normal one, or win32
  207243. // promotes the normal one to be topmost!
  207244. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207245. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207246. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207247. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207248. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207249. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207250. }
  207251. }
  207252. bool isFocused() const
  207253. {
  207254. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207255. }
  207256. void grabFocus()
  207257. {
  207258. const bool oldDeactivate = shouldDeactivateTitleBar;
  207259. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207260. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207261. shouldDeactivateTitleBar = oldDeactivate;
  207262. }
  207263. void textInputRequired (const Point<int>&)
  207264. {
  207265. if (! hasCreatedCaret)
  207266. {
  207267. hasCreatedCaret = true;
  207268. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207269. }
  207270. ShowCaret (hwnd);
  207271. SetCaretPos (0, 0);
  207272. }
  207273. void repaint (const Rectangle<int>& area)
  207274. {
  207275. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207276. InvalidateRect (hwnd, &r, FALSE);
  207277. }
  207278. void performAnyPendingRepaintsNow()
  207279. {
  207280. MSG m;
  207281. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207282. DispatchMessage (&m);
  207283. }
  207284. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207285. {
  207286. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207287. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207288. return 0;
  207289. }
  207290. void setTaskBarIcon (const Image& image)
  207291. {
  207292. if (image.isValid())
  207293. {
  207294. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  207295. if (taskBarIcon == 0)
  207296. {
  207297. taskBarIcon = new NOTIFYICONDATA();
  207298. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207299. taskBarIcon->hWnd = (HWND) hwnd;
  207300. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207301. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207302. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207303. taskBarIcon->hIcon = hicon;
  207304. taskBarIcon->szTip[0] = 0;
  207305. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207306. }
  207307. else
  207308. {
  207309. HICON oldIcon = taskBarIcon->hIcon;
  207310. taskBarIcon->hIcon = hicon;
  207311. taskBarIcon->uFlags = NIF_ICON;
  207312. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207313. DestroyIcon (oldIcon);
  207314. }
  207315. DestroyIcon (hicon);
  207316. }
  207317. else if (taskBarIcon != 0)
  207318. {
  207319. taskBarIcon->uFlags = 0;
  207320. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207321. DestroyIcon (taskBarIcon->hIcon);
  207322. taskBarIcon = 0;
  207323. }
  207324. }
  207325. void setTaskBarIconToolTip (const String& toolTip) const
  207326. {
  207327. if (taskBarIcon != 0)
  207328. {
  207329. taskBarIcon->uFlags = NIF_TIP;
  207330. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207331. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207332. }
  207333. }
  207334. bool isInside (HWND h) const
  207335. {
  207336. return GetAncestor (hwnd, GA_ROOT) == h;
  207337. }
  207338. static void updateKeyModifiers() throw()
  207339. {
  207340. int keyMods = 0;
  207341. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207342. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207343. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207344. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207345. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207346. }
  207347. static void updateModifiersFromWParam (const WPARAM wParam)
  207348. {
  207349. int mouseMods = 0;
  207350. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207351. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207352. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207353. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207354. updateKeyModifiers();
  207355. }
  207356. static int64 getMouseEventTime()
  207357. {
  207358. static int64 eventTimeOffset = 0;
  207359. static DWORD lastMessageTime = 0;
  207360. const DWORD thisMessageTime = GetMessageTime();
  207361. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207362. {
  207363. lastMessageTime = thisMessageTime;
  207364. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207365. }
  207366. return eventTimeOffset + thisMessageTime;
  207367. }
  207368. juce_UseDebuggingNewOperator
  207369. bool dontRepaint;
  207370. static ModifierKeys currentModifiers;
  207371. static ModifierKeys modifiersAtLastCallback;
  207372. private:
  207373. HWND hwnd, parentToAddTo;
  207374. ScopedPointer<DropShadower> shadower;
  207375. RenderingEngineType currentRenderingEngine;
  207376. #if JUCE_DIRECT2D
  207377. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207378. #endif
  207379. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207380. BorderSize windowBorder;
  207381. HICON currentWindowIcon;
  207382. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207383. IDropTarget* dropTarget;
  207384. class TemporaryImage : public Timer
  207385. {
  207386. public:
  207387. TemporaryImage() {}
  207388. ~TemporaryImage() {}
  207389. const Image& getImage (const bool transparent, const int w, const int h)
  207390. {
  207391. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207392. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207393. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207394. startTimer (3000);
  207395. return image;
  207396. }
  207397. void timerCallback()
  207398. {
  207399. stopTimer();
  207400. image = Image::null;
  207401. }
  207402. private:
  207403. Image image;
  207404. TemporaryImage (const TemporaryImage&);
  207405. TemporaryImage& operator= (const TemporaryImage&);
  207406. };
  207407. TemporaryImage offscreenImageGenerator;
  207408. class WindowClassHolder : public DeletedAtShutdown
  207409. {
  207410. public:
  207411. WindowClassHolder()
  207412. : windowClassName ("JUCE_")
  207413. {
  207414. // this name has to be different for each app/dll instance because otherwise
  207415. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207416. // window class).
  207417. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207418. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207419. TCHAR moduleFile [1024];
  207420. moduleFile[0] = 0;
  207421. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207422. WORD iconNum = 0;
  207423. WNDCLASSEX wcex;
  207424. wcex.cbSize = sizeof (wcex);
  207425. wcex.style = CS_OWNDC;
  207426. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207427. wcex.lpszClassName = windowClassName;
  207428. wcex.cbClsExtra = 0;
  207429. wcex.cbWndExtra = 32;
  207430. wcex.hInstance = moduleHandle;
  207431. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207432. iconNum = 1;
  207433. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207434. wcex.hCursor = 0;
  207435. wcex.hbrBackground = 0;
  207436. wcex.lpszMenuName = 0;
  207437. RegisterClassEx (&wcex);
  207438. }
  207439. ~WindowClassHolder()
  207440. {
  207441. if (ComponentPeer::getNumPeers() == 0)
  207442. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207443. clearSingletonInstance();
  207444. }
  207445. String windowClassName;
  207446. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207447. };
  207448. static void* createWindowCallback (void* userData)
  207449. {
  207450. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207451. return 0;
  207452. }
  207453. void createWindow()
  207454. {
  207455. DWORD exstyle = WS_EX_ACCEPTFILES;
  207456. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207457. if (hasTitleBar())
  207458. {
  207459. type |= WS_OVERLAPPED;
  207460. if ((styleFlags & windowHasCloseButton) != 0)
  207461. {
  207462. type |= WS_SYSMENU;
  207463. }
  207464. else
  207465. {
  207466. // annoyingly, windows won't let you have a min/max button without a close button
  207467. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207468. }
  207469. if ((styleFlags & windowIsResizable) != 0)
  207470. type |= WS_THICKFRAME;
  207471. }
  207472. else if (parentToAddTo != 0)
  207473. {
  207474. type |= WS_CHILD;
  207475. }
  207476. else
  207477. {
  207478. type |= WS_POPUP | WS_SYSMENU;
  207479. }
  207480. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207481. exstyle |= WS_EX_TOOLWINDOW;
  207482. else
  207483. exstyle |= WS_EX_APPWINDOW;
  207484. if ((styleFlags & windowHasMinimiseButton) != 0)
  207485. type |= WS_MINIMIZEBOX;
  207486. if ((styleFlags & windowHasMaximiseButton) != 0)
  207487. type |= WS_MAXIMIZEBOX;
  207488. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207489. exstyle |= WS_EX_TRANSPARENT;
  207490. if ((styleFlags & windowIsSemiTransparent) != 0
  207491. && Desktop::canUseSemiTransparentWindows())
  207492. exstyle |= WS_EX_LAYERED;
  207493. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207494. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207495. #if JUCE_DIRECT2D
  207496. updateDirect2DContext();
  207497. #endif
  207498. if (hwnd != 0)
  207499. {
  207500. SetWindowLongPtr (hwnd, 0, 0);
  207501. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207502. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207503. if (dropTarget == 0)
  207504. dropTarget = new JuceDropTarget (this);
  207505. RegisterDragDrop (hwnd, dropTarget);
  207506. updateBorderSize();
  207507. // Calling this function here is (for some reason) necessary to make Windows
  207508. // correctly enable the menu items that we specify in the wm_initmenu message.
  207509. GetSystemMenu (hwnd, false);
  207510. }
  207511. else
  207512. {
  207513. jassertfalse;
  207514. }
  207515. }
  207516. static void* destroyWindowCallback (void* handle)
  207517. {
  207518. RevokeDragDrop ((HWND) handle);
  207519. DestroyWindow ((HWND) handle);
  207520. return 0;
  207521. }
  207522. static void* toFrontCallback1 (void* h)
  207523. {
  207524. SetForegroundWindow ((HWND) h);
  207525. return 0;
  207526. }
  207527. static void* toFrontCallback2 (void* h)
  207528. {
  207529. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207530. return 0;
  207531. }
  207532. static void* setFocusCallback (void* h)
  207533. {
  207534. SetFocus ((HWND) h);
  207535. return 0;
  207536. }
  207537. static void* getFocusCallback (void*)
  207538. {
  207539. return GetFocus();
  207540. }
  207541. void offsetWithinParent (int& x, int& y) const
  207542. {
  207543. if (isTransparent())
  207544. {
  207545. HWND parentHwnd = GetParent (hwnd);
  207546. if (parentHwnd != 0)
  207547. {
  207548. RECT parentRect;
  207549. GetWindowRect (parentHwnd, &parentRect);
  207550. x += parentRect.left;
  207551. y += parentRect.top;
  207552. }
  207553. }
  207554. }
  207555. bool isTransparent() const
  207556. {
  207557. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207558. }
  207559. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207560. void setIcon (const Image& newIcon)
  207561. {
  207562. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207563. if (hicon != 0)
  207564. {
  207565. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207566. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207567. if (currentWindowIcon != 0)
  207568. DestroyIcon (currentWindowIcon);
  207569. currentWindowIcon = hicon;
  207570. }
  207571. }
  207572. void handlePaintMessage()
  207573. {
  207574. #if JUCE_DIRECT2D
  207575. if (direct2DContext != 0)
  207576. {
  207577. RECT r;
  207578. if (GetUpdateRect (hwnd, &r, false))
  207579. {
  207580. direct2DContext->start();
  207581. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207582. handlePaint (*direct2DContext);
  207583. direct2DContext->end();
  207584. }
  207585. }
  207586. else
  207587. #endif
  207588. {
  207589. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207590. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207591. PAINTSTRUCT paintStruct;
  207592. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207593. // message and become re-entrant, but that's OK
  207594. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207595. // corrupt the image it's using to paint into, so do a check here.
  207596. static bool reentrant = false;
  207597. if (reentrant)
  207598. {
  207599. DeleteObject (rgn);
  207600. EndPaint (hwnd, &paintStruct);
  207601. return;
  207602. }
  207603. reentrant = true;
  207604. // this is the rectangle to update..
  207605. int x = paintStruct.rcPaint.left;
  207606. int y = paintStruct.rcPaint.top;
  207607. int w = paintStruct.rcPaint.right - x;
  207608. int h = paintStruct.rcPaint.bottom - y;
  207609. const bool transparent = isTransparent();
  207610. if (transparent)
  207611. {
  207612. // it's not possible to have a transparent window with a title bar at the moment!
  207613. jassert (! hasTitleBar());
  207614. RECT r;
  207615. GetWindowRect (hwnd, &r);
  207616. x = y = 0;
  207617. w = r.right - r.left;
  207618. h = r.bottom - r.top;
  207619. }
  207620. if (w > 0 && h > 0)
  207621. {
  207622. clearMaskedRegion();
  207623. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207624. RectangleList contextClip;
  207625. const Rectangle<int> clipBounds (0, 0, w, h);
  207626. bool needToPaintAll = true;
  207627. if (regionType == COMPLEXREGION && ! transparent)
  207628. {
  207629. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207630. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207631. DeleteObject (clipRgn);
  207632. char rgnData [8192];
  207633. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207634. if (res > 0 && res <= sizeof (rgnData))
  207635. {
  207636. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207637. if (hdr->iType == RDH_RECTANGLES
  207638. && hdr->rcBound.right - hdr->rcBound.left >= w
  207639. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207640. {
  207641. needToPaintAll = false;
  207642. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207643. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207644. while (--num >= 0)
  207645. {
  207646. if (rects->right <= x + w && rects->bottom <= y + h)
  207647. {
  207648. const int cx = jmax (x, (int) rects->left);
  207649. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207650. .getIntersection (clipBounds));
  207651. }
  207652. else
  207653. {
  207654. needToPaintAll = true;
  207655. break;
  207656. }
  207657. ++rects;
  207658. }
  207659. }
  207660. }
  207661. }
  207662. if (needToPaintAll)
  207663. {
  207664. contextClip.clear();
  207665. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207666. }
  207667. if (transparent)
  207668. {
  207669. RectangleList::Iterator i (contextClip);
  207670. while (i.next())
  207671. offscreenImage.clear (*i.getRectangle());
  207672. }
  207673. // if the component's not opaque, this won't draw properly unless the platform can support this
  207674. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207675. updateCurrentModifiers();
  207676. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207677. handlePaint (context);
  207678. if (! dontRepaint)
  207679. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207680. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207681. }
  207682. DeleteObject (rgn);
  207683. EndPaint (hwnd, &paintStruct);
  207684. reentrant = false;
  207685. }
  207686. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207687. _fpreset(); // because some graphics cards can unmask FP exceptions
  207688. #endif
  207689. lastPaintTime = Time::getMillisecondCounter();
  207690. }
  207691. void doMouseEvent (const Point<int>& position)
  207692. {
  207693. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207694. }
  207695. const StringArray getAvailableRenderingEngines()
  207696. {
  207697. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207698. #if JUCE_DIRECT2D
  207699. // xxx is this correct? Seems to enable it on Vista too??
  207700. OSVERSIONINFO info;
  207701. zerostruct (info);
  207702. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207703. GetVersionEx (&info);
  207704. if (info.dwMajorVersion >= 6)
  207705. s.add ("Direct2D");
  207706. #endif
  207707. return s;
  207708. }
  207709. int getCurrentRenderingEngine() throw()
  207710. {
  207711. return currentRenderingEngine;
  207712. }
  207713. #if JUCE_DIRECT2D
  207714. void updateDirect2DContext()
  207715. {
  207716. if (currentRenderingEngine != direct2DRenderingEngine)
  207717. direct2DContext = 0;
  207718. else if (direct2DContext == 0)
  207719. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207720. }
  207721. #endif
  207722. void setCurrentRenderingEngine (int index)
  207723. {
  207724. (void) index;
  207725. #if JUCE_DIRECT2D
  207726. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207727. updateDirect2DContext();
  207728. repaint (component->getLocalBounds());
  207729. #endif
  207730. }
  207731. void doMouseMove (const Point<int>& position)
  207732. {
  207733. if (! isMouseOver)
  207734. {
  207735. isMouseOver = true;
  207736. updateKeyModifiers();
  207737. TRACKMOUSEEVENT tme;
  207738. tme.cbSize = sizeof (tme);
  207739. tme.dwFlags = TME_LEAVE;
  207740. tme.hwndTrack = hwnd;
  207741. tme.dwHoverTime = 0;
  207742. if (! TrackMouseEvent (&tme))
  207743. jassertfalse;
  207744. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207745. }
  207746. else if (! isDragging)
  207747. {
  207748. if (! contains (position, false))
  207749. return;
  207750. }
  207751. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207752. static uint32 lastMouseTime = 0;
  207753. const uint32 now = Time::getMillisecondCounter();
  207754. const int maxMouseMovesPerSecond = 60;
  207755. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207756. {
  207757. lastMouseTime = now;
  207758. doMouseEvent (position);
  207759. }
  207760. }
  207761. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207762. {
  207763. if (GetCapture() != hwnd)
  207764. SetCapture (hwnd);
  207765. doMouseMove (position);
  207766. updateModifiersFromWParam (wParam);
  207767. isDragging = true;
  207768. doMouseEvent (position);
  207769. }
  207770. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207771. {
  207772. updateModifiersFromWParam (wParam);
  207773. isDragging = false;
  207774. // release the mouse capture if the user has released all buttons
  207775. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207776. ReleaseCapture();
  207777. doMouseEvent (position);
  207778. }
  207779. void doCaptureChanged()
  207780. {
  207781. if (isDragging)
  207782. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207783. }
  207784. void doMouseExit()
  207785. {
  207786. isMouseOver = false;
  207787. doMouseEvent (getCurrentMousePos());
  207788. }
  207789. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207790. {
  207791. updateKeyModifiers();
  207792. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207793. handleMouseWheel (0, position, getMouseEventTime(),
  207794. isVertical ? 0.0f : amount,
  207795. isVertical ? amount : 0.0f);
  207796. }
  207797. void sendModifierKeyChangeIfNeeded()
  207798. {
  207799. if (modifiersAtLastCallback != currentModifiers)
  207800. {
  207801. modifiersAtLastCallback = currentModifiers;
  207802. handleModifierKeysChange();
  207803. }
  207804. }
  207805. bool doKeyUp (const WPARAM key)
  207806. {
  207807. updateKeyModifiers();
  207808. switch (key)
  207809. {
  207810. case VK_SHIFT:
  207811. case VK_CONTROL:
  207812. case VK_MENU:
  207813. case VK_CAPITAL:
  207814. case VK_LWIN:
  207815. case VK_RWIN:
  207816. case VK_APPS:
  207817. case VK_NUMLOCK:
  207818. case VK_SCROLL:
  207819. case VK_LSHIFT:
  207820. case VK_RSHIFT:
  207821. case VK_LCONTROL:
  207822. case VK_LMENU:
  207823. case VK_RCONTROL:
  207824. case VK_RMENU:
  207825. sendModifierKeyChangeIfNeeded();
  207826. }
  207827. return handleKeyUpOrDown (false)
  207828. || Component::getCurrentlyModalComponent() != 0;
  207829. }
  207830. bool doKeyDown (const WPARAM key)
  207831. {
  207832. updateKeyModifiers();
  207833. bool used = false;
  207834. switch (key)
  207835. {
  207836. case VK_SHIFT:
  207837. case VK_LSHIFT:
  207838. case VK_RSHIFT:
  207839. case VK_CONTROL:
  207840. case VK_LCONTROL:
  207841. case VK_RCONTROL:
  207842. case VK_MENU:
  207843. case VK_LMENU:
  207844. case VK_RMENU:
  207845. case VK_LWIN:
  207846. case VK_RWIN:
  207847. case VK_CAPITAL:
  207848. case VK_NUMLOCK:
  207849. case VK_SCROLL:
  207850. case VK_APPS:
  207851. sendModifierKeyChangeIfNeeded();
  207852. break;
  207853. case VK_LEFT:
  207854. case VK_RIGHT:
  207855. case VK_UP:
  207856. case VK_DOWN:
  207857. case VK_PRIOR:
  207858. case VK_NEXT:
  207859. case VK_HOME:
  207860. case VK_END:
  207861. case VK_DELETE:
  207862. case VK_INSERT:
  207863. case VK_F1:
  207864. case VK_F2:
  207865. case VK_F3:
  207866. case VK_F4:
  207867. case VK_F5:
  207868. case VK_F6:
  207869. case VK_F7:
  207870. case VK_F8:
  207871. case VK_F9:
  207872. case VK_F10:
  207873. case VK_F11:
  207874. case VK_F12:
  207875. case VK_F13:
  207876. case VK_F14:
  207877. case VK_F15:
  207878. case VK_F16:
  207879. used = handleKeyUpOrDown (true);
  207880. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207881. break;
  207882. case VK_ADD:
  207883. case VK_SUBTRACT:
  207884. case VK_MULTIPLY:
  207885. case VK_DIVIDE:
  207886. case VK_SEPARATOR:
  207887. case VK_DECIMAL:
  207888. used = handleKeyUpOrDown (true);
  207889. break;
  207890. default:
  207891. used = handleKeyUpOrDown (true);
  207892. {
  207893. MSG msg;
  207894. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207895. {
  207896. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207897. // manually generate the key-press event that matches this key-down.
  207898. const UINT keyChar = MapVirtualKey (key, 2);
  207899. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207900. }
  207901. }
  207902. break;
  207903. }
  207904. if (Component::getCurrentlyModalComponent() != 0)
  207905. used = true;
  207906. return used;
  207907. }
  207908. bool doKeyChar (int key, const LPARAM flags)
  207909. {
  207910. updateKeyModifiers();
  207911. juce_wchar textChar = (juce_wchar) key;
  207912. const int virtualScanCode = (flags >> 16) & 0xff;
  207913. if (key >= '0' && key <= '9')
  207914. {
  207915. switch (virtualScanCode) // check for a numeric keypad scan-code
  207916. {
  207917. case 0x52:
  207918. case 0x4f:
  207919. case 0x50:
  207920. case 0x51:
  207921. case 0x4b:
  207922. case 0x4c:
  207923. case 0x4d:
  207924. case 0x47:
  207925. case 0x48:
  207926. case 0x49:
  207927. key = (key - '0') + KeyPress::numberPad0;
  207928. break;
  207929. default:
  207930. break;
  207931. }
  207932. }
  207933. else
  207934. {
  207935. // convert the scan code to an unmodified character code..
  207936. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207937. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207938. keyChar = LOWORD (keyChar);
  207939. if (keyChar != 0)
  207940. key = (int) keyChar;
  207941. // avoid sending junk text characters for some control-key combinations
  207942. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207943. textChar = 0;
  207944. }
  207945. return handleKeyPress (key, textChar);
  207946. }
  207947. bool doAppCommand (const LPARAM lParam)
  207948. {
  207949. int key = 0;
  207950. switch (GET_APPCOMMAND_LPARAM (lParam))
  207951. {
  207952. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207953. key = KeyPress::playKey;
  207954. break;
  207955. case APPCOMMAND_MEDIA_STOP:
  207956. key = KeyPress::stopKey;
  207957. break;
  207958. case APPCOMMAND_MEDIA_NEXTTRACK:
  207959. key = KeyPress::fastForwardKey;
  207960. break;
  207961. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207962. key = KeyPress::rewindKey;
  207963. break;
  207964. }
  207965. if (key != 0)
  207966. {
  207967. updateKeyModifiers();
  207968. if (hwnd == GetActiveWindow())
  207969. {
  207970. handleKeyPress (key, 0);
  207971. return true;
  207972. }
  207973. }
  207974. return false;
  207975. }
  207976. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207977. {
  207978. public:
  207979. JuceDropTarget (Win32ComponentPeer* const owner_)
  207980. : owner (owner_)
  207981. {
  207982. }
  207983. ~JuceDropTarget() {}
  207984. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207985. {
  207986. updateFileList (pDataObject);
  207987. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207988. *pdwEffect = DROPEFFECT_COPY;
  207989. return S_OK;
  207990. }
  207991. HRESULT __stdcall DragLeave()
  207992. {
  207993. owner->handleFileDragExit (files);
  207994. return S_OK;
  207995. }
  207996. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207997. {
  207998. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207999. *pdwEffect = DROPEFFECT_COPY;
  208000. return S_OK;
  208001. }
  208002. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208003. {
  208004. updateFileList (pDataObject);
  208005. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  208006. *pdwEffect = DROPEFFECT_COPY;
  208007. return S_OK;
  208008. }
  208009. private:
  208010. Win32ComponentPeer* const owner;
  208011. StringArray files;
  208012. void updateFileList (IDataObject* const pDataObject)
  208013. {
  208014. files.clear();
  208015. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208016. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208017. if (pDataObject->GetData (&format, &medium) == S_OK)
  208018. {
  208019. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  208020. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  208021. unsigned int i = 0;
  208022. if (pDropFiles->fWide)
  208023. {
  208024. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  208025. for (;;)
  208026. {
  208027. unsigned int len = 0;
  208028. while (i + len < totalLen && fname [i + len] != 0)
  208029. ++len;
  208030. if (len == 0)
  208031. break;
  208032. files.add (String (fname + i, len));
  208033. i += len + 1;
  208034. }
  208035. }
  208036. else
  208037. {
  208038. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  208039. for (;;)
  208040. {
  208041. unsigned int len = 0;
  208042. while (i + len < totalLen && fname [i + len] != 0)
  208043. ++len;
  208044. if (len == 0)
  208045. break;
  208046. files.add (String (fname + i, len));
  208047. i += len + 1;
  208048. }
  208049. }
  208050. GlobalUnlock (medium.hGlobal);
  208051. }
  208052. }
  208053. JuceDropTarget (const JuceDropTarget&);
  208054. JuceDropTarget& operator= (const JuceDropTarget&);
  208055. };
  208056. void doSettingChange()
  208057. {
  208058. Desktop::getInstance().refreshMonitorSizes();
  208059. if (fullScreen && ! isMinimised())
  208060. {
  208061. const Rectangle<int> r (component->getParentMonitorArea());
  208062. SetWindowPos (hwnd, 0,
  208063. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208064. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208065. }
  208066. }
  208067. public:
  208068. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208069. {
  208070. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208071. if (peer != 0)
  208072. return peer->peerWindowProc (h, message, wParam, lParam);
  208073. return DefWindowProcW (h, message, wParam, lParam);
  208074. }
  208075. private:
  208076. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208077. {
  208078. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208079. }
  208080. const Point<int> getCurrentMousePos() throw()
  208081. {
  208082. RECT wr;
  208083. GetWindowRect (hwnd, &wr);
  208084. const DWORD mp = GetMessagePos();
  208085. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208086. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208087. }
  208088. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208089. {
  208090. if (isValidPeer (this))
  208091. {
  208092. switch (message)
  208093. {
  208094. case WM_NCHITTEST:
  208095. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208096. return HTTRANSPARENT;
  208097. if (hasTitleBar())
  208098. break;
  208099. return HTCLIENT;
  208100. case WM_PAINT:
  208101. handlePaintMessage();
  208102. return 0;
  208103. case WM_NCPAINT:
  208104. if (wParam != 1)
  208105. handlePaintMessage();
  208106. if (hasTitleBar())
  208107. break;
  208108. return 0;
  208109. case WM_ERASEBKGND:
  208110. case WM_NCCALCSIZE:
  208111. if (hasTitleBar())
  208112. break;
  208113. return 1;
  208114. case WM_MOUSEMOVE:
  208115. doMouseMove (getPointFromLParam (lParam));
  208116. return 0;
  208117. case WM_MOUSELEAVE:
  208118. doMouseExit();
  208119. return 0;
  208120. case WM_LBUTTONDOWN:
  208121. case WM_MBUTTONDOWN:
  208122. case WM_RBUTTONDOWN:
  208123. doMouseDown (getPointFromLParam (lParam), wParam);
  208124. return 0;
  208125. case WM_LBUTTONUP:
  208126. case WM_MBUTTONUP:
  208127. case WM_RBUTTONUP:
  208128. doMouseUp (getPointFromLParam (lParam), wParam);
  208129. return 0;
  208130. case WM_CAPTURECHANGED:
  208131. doCaptureChanged();
  208132. return 0;
  208133. case WM_NCMOUSEMOVE:
  208134. if (hasTitleBar())
  208135. break;
  208136. return 0;
  208137. case 0x020A: /* WM_MOUSEWHEEL */
  208138. doMouseWheel (getCurrentMousePos(), wParam, true);
  208139. return 0;
  208140. case 0x020E: /* WM_MOUSEHWHEEL */
  208141. doMouseWheel (getCurrentMousePos(), wParam, false);
  208142. return 0;
  208143. case WM_SIZING:
  208144. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208145. {
  208146. RECT* const r = (RECT*) lParam;
  208147. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  208148. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  208149. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208150. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  208151. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  208152. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  208153. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  208154. r->left = pos.getX();
  208155. r->top = pos.getY();
  208156. r->right = pos.getRight();
  208157. r->bottom = pos.getBottom();
  208158. }
  208159. return TRUE;
  208160. case WM_WINDOWPOSCHANGING:
  208161. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208162. {
  208163. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  208164. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  208165. && ! Component::isMouseButtonDownAnywhere())
  208166. {
  208167. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208168. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  208169. constrainer->checkBounds (pos, current,
  208170. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208171. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208172. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208173. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208174. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208175. wp->x = pos.getX();
  208176. wp->y = pos.getY();
  208177. wp->cx = pos.getWidth();
  208178. wp->cy = pos.getHeight();
  208179. }
  208180. }
  208181. return 0;
  208182. case WM_WINDOWPOSCHANGED:
  208183. doMouseEvent (getCurrentMousePos());
  208184. handleMovedOrResized();
  208185. if (dontRepaint)
  208186. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208187. return 0;
  208188. case WM_KEYDOWN:
  208189. case WM_SYSKEYDOWN:
  208190. if (doKeyDown (wParam))
  208191. return 0;
  208192. break;
  208193. case WM_KEYUP:
  208194. case WM_SYSKEYUP:
  208195. if (doKeyUp (wParam))
  208196. return 0;
  208197. break;
  208198. case WM_CHAR:
  208199. if (doKeyChar ((int) wParam, lParam))
  208200. return 0;
  208201. break;
  208202. case WM_APPCOMMAND:
  208203. if (doAppCommand (lParam))
  208204. return TRUE;
  208205. break;
  208206. case WM_SETFOCUS:
  208207. updateKeyModifiers();
  208208. handleFocusGain();
  208209. break;
  208210. case WM_KILLFOCUS:
  208211. if (hasCreatedCaret)
  208212. {
  208213. hasCreatedCaret = false;
  208214. DestroyCaret();
  208215. }
  208216. handleFocusLoss();
  208217. break;
  208218. case WM_ACTIVATEAPP:
  208219. // Windows does weird things to process priority when you swap apps,
  208220. // so this forces an update when the app is brought to the front
  208221. if (wParam != FALSE)
  208222. juce_repeatLastProcessPriority();
  208223. else
  208224. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208225. juce_CheckCurrentlyFocusedTopLevelWindow();
  208226. modifiersAtLastCallback = -1;
  208227. return 0;
  208228. case WM_ACTIVATE:
  208229. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208230. {
  208231. modifiersAtLastCallback = -1;
  208232. updateKeyModifiers();
  208233. if (isMinimised())
  208234. {
  208235. component->repaint();
  208236. handleMovedOrResized();
  208237. if (! ComponentPeer::isValidPeer (this))
  208238. return 0;
  208239. }
  208240. if (LOWORD (wParam) == WA_CLICKACTIVE
  208241. && component->isCurrentlyBlockedByAnotherModalComponent())
  208242. {
  208243. const Point<int> mousePos (component->getMouseXYRelative());
  208244. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208245. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208246. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208247. return 0;
  208248. }
  208249. handleBroughtToFront();
  208250. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208251. Component::getCurrentlyModalComponent()->toFront (true);
  208252. return 0;
  208253. }
  208254. break;
  208255. case WM_NCACTIVATE:
  208256. // while a temporary window is being shown, prevent Windows from deactivating the
  208257. // title bars of our main windows.
  208258. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208259. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208260. break;
  208261. case WM_MOUSEACTIVATE:
  208262. if (! component->getMouseClickGrabsKeyboardFocus())
  208263. return MA_NOACTIVATE;
  208264. break;
  208265. case WM_SHOWWINDOW:
  208266. if (wParam != 0)
  208267. handleBroughtToFront();
  208268. break;
  208269. case WM_CLOSE:
  208270. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208271. handleUserClosingWindow();
  208272. return 0;
  208273. case WM_QUERYENDSESSION:
  208274. if (JUCEApplication::getInstance() != 0)
  208275. {
  208276. JUCEApplication::getInstance()->systemRequestedQuit();
  208277. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208278. }
  208279. return TRUE;
  208280. case WM_TRAYNOTIFY:
  208281. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208282. {
  208283. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208284. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208285. {
  208286. Component* const current = Component::getCurrentlyModalComponent();
  208287. if (current != 0)
  208288. current->inputAttemptWhenModal();
  208289. }
  208290. }
  208291. else
  208292. {
  208293. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208294. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208295. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208296. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208297. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208298. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208299. eventMods = eventMods.withoutMouseButtons();
  208300. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208301. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208302. Point<int>(), getMouseEventTime(), 1, false);
  208303. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208304. {
  208305. SetFocus (hwnd);
  208306. SetForegroundWindow (hwnd);
  208307. component->mouseDown (e);
  208308. }
  208309. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208310. {
  208311. component->mouseUp (e);
  208312. }
  208313. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208314. {
  208315. component->mouseDoubleClick (e);
  208316. }
  208317. else if (lParam == WM_MOUSEMOVE)
  208318. {
  208319. component->mouseMove (e);
  208320. }
  208321. }
  208322. break;
  208323. case WM_SYNCPAINT:
  208324. return 0;
  208325. case WM_PALETTECHANGED:
  208326. InvalidateRect (h, 0, 0);
  208327. break;
  208328. case WM_DISPLAYCHANGE:
  208329. InvalidateRect (h, 0, 0);
  208330. createPaletteIfNeeded = true;
  208331. // intentional fall-through...
  208332. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208333. doSettingChange();
  208334. break;
  208335. case WM_INITMENU:
  208336. if (! hasTitleBar())
  208337. {
  208338. if (isFullScreen())
  208339. {
  208340. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208341. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208342. }
  208343. else if (! isMinimised())
  208344. {
  208345. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208346. }
  208347. }
  208348. break;
  208349. case WM_SYSCOMMAND:
  208350. switch (wParam & 0xfff0)
  208351. {
  208352. case SC_CLOSE:
  208353. if (sendInputAttemptWhenModalMessage())
  208354. return 0;
  208355. if (hasTitleBar())
  208356. {
  208357. PostMessage (h, WM_CLOSE, 0, 0);
  208358. return 0;
  208359. }
  208360. break;
  208361. case SC_KEYMENU:
  208362. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208363. // obscure situations that can arise if a modal loop is started from an alt-key
  208364. // keypress).
  208365. if (hasTitleBar() && h == GetCapture())
  208366. ReleaseCapture();
  208367. break;
  208368. case SC_MAXIMIZE:
  208369. if (sendInputAttemptWhenModalMessage())
  208370. return 0;
  208371. setFullScreen (true);
  208372. return 0;
  208373. case SC_MINIMIZE:
  208374. if (sendInputAttemptWhenModalMessage())
  208375. return 0;
  208376. if (! hasTitleBar())
  208377. {
  208378. setMinimised (true);
  208379. return 0;
  208380. }
  208381. break;
  208382. case SC_RESTORE:
  208383. if (sendInputAttemptWhenModalMessage())
  208384. return 0;
  208385. if (hasTitleBar())
  208386. {
  208387. if (isFullScreen())
  208388. {
  208389. setFullScreen (false);
  208390. return 0;
  208391. }
  208392. }
  208393. else
  208394. {
  208395. if (isMinimised())
  208396. setMinimised (false);
  208397. else if (isFullScreen())
  208398. setFullScreen (false);
  208399. return 0;
  208400. }
  208401. break;
  208402. }
  208403. break;
  208404. case WM_NCLBUTTONDOWN:
  208405. case WM_NCRBUTTONDOWN:
  208406. case WM_NCMBUTTONDOWN:
  208407. sendInputAttemptWhenModalMessage();
  208408. break;
  208409. //case WM_IME_STARTCOMPOSITION;
  208410. // return 0;
  208411. case WM_GETDLGCODE:
  208412. return DLGC_WANTALLKEYS;
  208413. default:
  208414. break;
  208415. }
  208416. }
  208417. return DefWindowProcW (h, message, wParam, lParam);
  208418. }
  208419. bool sendInputAttemptWhenModalMessage()
  208420. {
  208421. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208422. {
  208423. Component* const current = Component::getCurrentlyModalComponent();
  208424. if (current != 0)
  208425. current->inputAttemptWhenModal();
  208426. return true;
  208427. }
  208428. return false;
  208429. }
  208430. Win32ComponentPeer (const Win32ComponentPeer&);
  208431. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208432. };
  208433. ModifierKeys Win32ComponentPeer::currentModifiers;
  208434. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208435. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208436. {
  208437. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208438. }
  208439. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208440. void ModifierKeys::updateCurrentModifiers() throw()
  208441. {
  208442. currentModifiers = Win32ComponentPeer::currentModifiers;
  208443. }
  208444. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208445. {
  208446. Win32ComponentPeer::updateKeyModifiers();
  208447. int keyMods = 0;
  208448. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208449. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208450. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208451. Win32ComponentPeer::currentModifiers
  208452. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208453. return Win32ComponentPeer::currentModifiers;
  208454. }
  208455. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208456. {
  208457. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208458. if (wp != 0)
  208459. wp->setTaskBarIcon (newImage);
  208460. }
  208461. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208462. {
  208463. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208464. if (wp != 0)
  208465. wp->setTaskBarIconToolTip (tooltip);
  208466. }
  208467. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208468. {
  208469. DWORD val = GetWindowLong (h, styleType);
  208470. if (bitIsSet)
  208471. val |= feature;
  208472. else
  208473. val &= ~feature;
  208474. SetWindowLongPtr (h, styleType, val);
  208475. SetWindowPos (h, 0, 0, 0, 0, 0,
  208476. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208477. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208478. }
  208479. bool Process::isForegroundProcess()
  208480. {
  208481. HWND fg = GetForegroundWindow();
  208482. if (fg == 0)
  208483. return true;
  208484. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208485. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208486. // have to see if any of our windows are children of the foreground window
  208487. fg = GetAncestor (fg, GA_ROOT);
  208488. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208489. {
  208490. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208491. if (wp != 0 && wp->isInside (fg))
  208492. return true;
  208493. }
  208494. return false;
  208495. }
  208496. bool AlertWindow::showNativeDialogBox (const String& title,
  208497. const String& bodyText,
  208498. bool isOkCancel)
  208499. {
  208500. return MessageBox (0, bodyText, title,
  208501. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208502. : MB_OK)) == IDOK;
  208503. }
  208504. void Desktop::createMouseInputSources()
  208505. {
  208506. mouseSources.add (new MouseInputSource (0, true));
  208507. }
  208508. const Point<int> Desktop::getMousePosition()
  208509. {
  208510. POINT mousePos;
  208511. GetCursorPos (&mousePos);
  208512. return Point<int> (mousePos.x, mousePos.y);
  208513. }
  208514. void Desktop::setMousePosition (const Point<int>& newPosition)
  208515. {
  208516. SetCursorPos (newPosition.getX(), newPosition.getY());
  208517. }
  208518. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208519. {
  208520. return createSoftwareImage (format, width, height, clearImage);
  208521. }
  208522. class ScreenSaverDefeater : public Timer,
  208523. public DeletedAtShutdown
  208524. {
  208525. public:
  208526. ScreenSaverDefeater()
  208527. {
  208528. startTimer (10000);
  208529. timerCallback();
  208530. }
  208531. ~ScreenSaverDefeater() {}
  208532. void timerCallback()
  208533. {
  208534. if (Process::isForegroundProcess())
  208535. {
  208536. // simulate a shift key getting pressed..
  208537. INPUT input[2];
  208538. input[0].type = INPUT_KEYBOARD;
  208539. input[0].ki.wVk = VK_SHIFT;
  208540. input[0].ki.dwFlags = 0;
  208541. input[0].ki.dwExtraInfo = 0;
  208542. input[1].type = INPUT_KEYBOARD;
  208543. input[1].ki.wVk = VK_SHIFT;
  208544. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208545. input[1].ki.dwExtraInfo = 0;
  208546. SendInput (2, input, sizeof (INPUT));
  208547. }
  208548. }
  208549. };
  208550. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208551. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208552. {
  208553. if (isEnabled)
  208554. deleteAndZero (screenSaverDefeater);
  208555. else if (screenSaverDefeater == 0)
  208556. screenSaverDefeater = new ScreenSaverDefeater();
  208557. }
  208558. bool Desktop::isScreenSaverEnabled()
  208559. {
  208560. return screenSaverDefeater == 0;
  208561. }
  208562. /* (The code below is the "correct" way to disable the screen saver, but it
  208563. completely fails on winXP when the saver is password-protected...)
  208564. static bool juce_screenSaverEnabled = true;
  208565. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208566. {
  208567. juce_screenSaverEnabled = isEnabled;
  208568. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208569. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208570. }
  208571. bool Desktop::isScreenSaverEnabled() throw()
  208572. {
  208573. return juce_screenSaverEnabled;
  208574. }
  208575. */
  208576. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208577. {
  208578. if (enableOrDisable)
  208579. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208580. }
  208581. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208582. {
  208583. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208584. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208585. return TRUE;
  208586. }
  208587. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208588. {
  208589. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208590. // make sure the first in the list is the main monitor
  208591. for (int i = 1; i < monitorCoords.size(); ++i)
  208592. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208593. monitorCoords.swap (i, 0);
  208594. if (monitorCoords.size() == 0)
  208595. {
  208596. RECT r;
  208597. GetWindowRect (GetDesktopWindow(), &r);
  208598. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208599. }
  208600. if (clipToWorkArea)
  208601. {
  208602. // clip the main monitor to the active non-taskbar area
  208603. RECT r;
  208604. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208605. Rectangle<int>& screen = monitorCoords.getReference (0);
  208606. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208607. jmax (screen.getY(), (int) r.top));
  208608. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208609. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208610. }
  208611. }
  208612. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208613. {
  208614. Image im;
  208615. if (bitmap != 0)
  208616. {
  208617. BITMAP bm;
  208618. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208619. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208620. {
  208621. HDC tempDC = GetDC (0);
  208622. HDC dc = CreateCompatibleDC (tempDC);
  208623. ReleaseDC (0, tempDC);
  208624. SelectObject (dc, bitmap);
  208625. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208626. Image::BitmapData imageData (im, true);
  208627. for (int y = bm.bmHeight; --y >= 0;)
  208628. {
  208629. for (int x = bm.bmWidth; --x >= 0;)
  208630. {
  208631. COLORREF col = GetPixel (dc, x, y);
  208632. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208633. (uint8) GetGValue (col),
  208634. (uint8) GetBValue (col)));
  208635. }
  208636. }
  208637. DeleteDC (dc);
  208638. }
  208639. }
  208640. return im;
  208641. }
  208642. static const Image createImageFromHICON (HICON icon)
  208643. {
  208644. ICONINFO info;
  208645. if (GetIconInfo (icon, &info))
  208646. {
  208647. Image mask (createImageFromHBITMAP (info.hbmMask));
  208648. Image image (createImageFromHBITMAP (info.hbmColor));
  208649. if (mask.isValid() && image.isValid())
  208650. {
  208651. for (int y = image.getHeight(); --y >= 0;)
  208652. {
  208653. for (int x = image.getWidth(); --x >= 0;)
  208654. {
  208655. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208656. if (brightness > 0.0f)
  208657. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208658. }
  208659. }
  208660. return image;
  208661. }
  208662. }
  208663. return Image::null;
  208664. }
  208665. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208666. {
  208667. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208668. Image bitmap (nativeBitmap);
  208669. {
  208670. Graphics g (bitmap);
  208671. g.drawImageAt (image, 0, 0);
  208672. }
  208673. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208674. ICONINFO info;
  208675. info.fIcon = isIcon;
  208676. info.xHotspot = hotspotX;
  208677. info.yHotspot = hotspotY;
  208678. info.hbmMask = mask;
  208679. info.hbmColor = nativeBitmap->hBitmap;
  208680. HICON hi = CreateIconIndirect (&info);
  208681. DeleteObject (mask);
  208682. return hi;
  208683. }
  208684. const Image juce_createIconForFile (const File& file)
  208685. {
  208686. Image image;
  208687. WCHAR filename [1024];
  208688. file.getFullPathName().copyToUnicode (filename, 1023);
  208689. WORD iconNum = 0;
  208690. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208691. filename, &iconNum);
  208692. if (icon != 0)
  208693. {
  208694. image = createImageFromHICON (icon);
  208695. DestroyIcon (icon);
  208696. }
  208697. return image;
  208698. }
  208699. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208700. {
  208701. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208702. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208703. Image im (image);
  208704. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208705. {
  208706. im = im.rescaled (maxW, maxH);
  208707. hotspotX = (hotspotX * maxW) / image.getWidth();
  208708. hotspotY = (hotspotY * maxH) / image.getHeight();
  208709. }
  208710. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208711. }
  208712. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208713. {
  208714. if (cursorHandle != 0 && ! isStandard)
  208715. DestroyCursor ((HCURSOR) cursorHandle);
  208716. }
  208717. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208718. {
  208719. LPCTSTR cursorName = IDC_ARROW;
  208720. switch (type)
  208721. {
  208722. case NormalCursor: break;
  208723. case NoCursor: return 0;
  208724. case WaitCursor: cursorName = IDC_WAIT; break;
  208725. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208726. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208727. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208728. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208729. case LeftRightResizeCursor:
  208730. case LeftEdgeResizeCursor:
  208731. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208732. case UpDownResizeCursor:
  208733. case TopEdgeResizeCursor:
  208734. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208735. case TopLeftCornerResizeCursor:
  208736. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208737. case TopRightCornerResizeCursor:
  208738. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208739. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208740. case DraggingHandCursor:
  208741. {
  208742. static void* dragHandCursor = 0;
  208743. if (dragHandCursor == 0)
  208744. {
  208745. static const unsigned char dragHandData[] =
  208746. { 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,
  208747. 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,
  208748. 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 };
  208749. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208750. }
  208751. return dragHandCursor;
  208752. }
  208753. default:
  208754. jassertfalse; break;
  208755. }
  208756. HCURSOR cursorH = LoadCursor (0, cursorName);
  208757. if (cursorH == 0)
  208758. cursorH = LoadCursor (0, IDC_ARROW);
  208759. return cursorH;
  208760. }
  208761. void MouseCursor::showInWindow (ComponentPeer*) const
  208762. {
  208763. SetCursor ((HCURSOR) getHandle());
  208764. }
  208765. void MouseCursor::showInAllWindows() const
  208766. {
  208767. showInWindow (0);
  208768. }
  208769. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208770. {
  208771. public:
  208772. JuceDropSource() {}
  208773. ~JuceDropSource() {}
  208774. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208775. {
  208776. if (escapePressed)
  208777. return DRAGDROP_S_CANCEL;
  208778. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208779. return DRAGDROP_S_DROP;
  208780. return S_OK;
  208781. }
  208782. HRESULT __stdcall GiveFeedback (DWORD)
  208783. {
  208784. return DRAGDROP_S_USEDEFAULTCURSORS;
  208785. }
  208786. };
  208787. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208788. {
  208789. public:
  208790. JuceEnumFormatEtc (const FORMATETC* const format_)
  208791. : format (format_),
  208792. index (0)
  208793. {
  208794. }
  208795. ~JuceEnumFormatEtc() {}
  208796. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208797. {
  208798. if (result == 0)
  208799. return E_POINTER;
  208800. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208801. newOne->index = index;
  208802. *result = newOne;
  208803. return S_OK;
  208804. }
  208805. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208806. {
  208807. if (pceltFetched != 0)
  208808. *pceltFetched = 0;
  208809. else if (celt != 1)
  208810. return S_FALSE;
  208811. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208812. {
  208813. copyFormatEtc (lpFormatEtc [0], *format);
  208814. ++index;
  208815. if (pceltFetched != 0)
  208816. *pceltFetched = 1;
  208817. return S_OK;
  208818. }
  208819. return S_FALSE;
  208820. }
  208821. HRESULT __stdcall Skip (ULONG celt)
  208822. {
  208823. if (index + (int) celt >= 1)
  208824. return S_FALSE;
  208825. index += celt;
  208826. return S_OK;
  208827. }
  208828. HRESULT __stdcall Reset()
  208829. {
  208830. index = 0;
  208831. return S_OK;
  208832. }
  208833. private:
  208834. const FORMATETC* const format;
  208835. int index;
  208836. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208837. {
  208838. dest = source;
  208839. if (source.ptd != 0)
  208840. {
  208841. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208842. *(dest.ptd) = *(source.ptd);
  208843. }
  208844. }
  208845. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208846. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208847. };
  208848. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208849. {
  208850. public:
  208851. JuceDataObject (JuceDropSource* const dropSource_,
  208852. const FORMATETC* const format_,
  208853. const STGMEDIUM* const medium_)
  208854. : dropSource (dropSource_),
  208855. format (format_),
  208856. medium (medium_)
  208857. {
  208858. }
  208859. ~JuceDataObject()
  208860. {
  208861. jassert (refCount == 0);
  208862. }
  208863. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208864. {
  208865. if ((pFormatEtc->tymed & format->tymed) != 0
  208866. && pFormatEtc->cfFormat == format->cfFormat
  208867. && pFormatEtc->dwAspect == format->dwAspect)
  208868. {
  208869. pMedium->tymed = format->tymed;
  208870. pMedium->pUnkForRelease = 0;
  208871. if (format->tymed == TYMED_HGLOBAL)
  208872. {
  208873. const SIZE_T len = GlobalSize (medium->hGlobal);
  208874. void* const src = GlobalLock (medium->hGlobal);
  208875. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208876. memcpy (dst, src, len);
  208877. GlobalUnlock (medium->hGlobal);
  208878. pMedium->hGlobal = dst;
  208879. return S_OK;
  208880. }
  208881. }
  208882. return DV_E_FORMATETC;
  208883. }
  208884. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208885. {
  208886. if (f == 0)
  208887. return E_INVALIDARG;
  208888. if (f->tymed == format->tymed
  208889. && f->cfFormat == format->cfFormat
  208890. && f->dwAspect == format->dwAspect)
  208891. return S_OK;
  208892. return DV_E_FORMATETC;
  208893. }
  208894. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208895. {
  208896. pFormatEtcOut->ptd = 0;
  208897. return E_NOTIMPL;
  208898. }
  208899. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208900. {
  208901. if (result == 0)
  208902. return E_POINTER;
  208903. if (direction == DATADIR_GET)
  208904. {
  208905. *result = new JuceEnumFormatEtc (format);
  208906. return S_OK;
  208907. }
  208908. *result = 0;
  208909. return E_NOTIMPL;
  208910. }
  208911. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208912. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208913. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208914. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208915. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208916. private:
  208917. JuceDropSource* const dropSource;
  208918. const FORMATETC* const format;
  208919. const STGMEDIUM* const medium;
  208920. JuceDataObject (const JuceDataObject&);
  208921. JuceDataObject& operator= (const JuceDataObject&);
  208922. };
  208923. static HDROP createHDrop (const StringArray& fileNames)
  208924. {
  208925. int totalChars = 0;
  208926. for (int i = fileNames.size(); --i >= 0;)
  208927. totalChars += fileNames[i].length() + 1;
  208928. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208929. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208930. if (hDrop != 0)
  208931. {
  208932. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208933. pDropFiles->pFiles = sizeof (DROPFILES);
  208934. pDropFiles->fWide = true;
  208935. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208936. for (int i = 0; i < fileNames.size(); ++i)
  208937. {
  208938. fileNames[i].copyToUnicode (fname, 2048);
  208939. fname += fileNames[i].length() + 1;
  208940. }
  208941. *fname = 0;
  208942. GlobalUnlock (hDrop);
  208943. }
  208944. return hDrop;
  208945. }
  208946. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208947. {
  208948. JuceDropSource* const source = new JuceDropSource();
  208949. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208950. DWORD effect;
  208951. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208952. data->Release();
  208953. source->Release();
  208954. return res == DRAGDROP_S_DROP;
  208955. }
  208956. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208957. {
  208958. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208959. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208960. medium.hGlobal = createHDrop (files);
  208961. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208962. : DROPEFFECT_COPY);
  208963. }
  208964. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208965. {
  208966. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208967. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208968. const int numChars = text.length();
  208969. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208970. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208971. text.copyToUnicode (data, numChars + 1);
  208972. format.cfFormat = CF_UNICODETEXT;
  208973. GlobalUnlock (medium.hGlobal);
  208974. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208975. }
  208976. #endif
  208977. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208978. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208979. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208980. // compiled on its own).
  208981. #if JUCE_INCLUDED_FILE
  208982. namespace FileChooserHelpers
  208983. {
  208984. static bool areThereAnyAlwaysOnTopWindows()
  208985. {
  208986. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208987. {
  208988. Component* c = Desktop::getInstance().getComponent (i);
  208989. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208990. return true;
  208991. }
  208992. return false;
  208993. }
  208994. struct FileChooserCallbackInfo
  208995. {
  208996. String initialPath;
  208997. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208998. ScopedPointer<Component> customComponent;
  208999. };
  209000. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  209001. {
  209002. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  209003. if (msg == BFFM_INITIALIZED)
  209004. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  209005. else if (msg == BFFM_VALIDATEFAILEDW)
  209006. info->returnedString = (LPCWSTR) lParam;
  209007. else if (msg == BFFM_VALIDATEFAILEDA)
  209008. info->returnedString = (const char*) lParam;
  209009. return 0;
  209010. }
  209011. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  209012. {
  209013. if (uiMsg == WM_INITDIALOG)
  209014. {
  209015. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  209016. HWND dialogH = GetParent (hdlg);
  209017. jassert (dialogH != 0);
  209018. if (dialogH == 0)
  209019. dialogH = hdlg;
  209020. RECT r, cr;
  209021. GetWindowRect (dialogH, &r);
  209022. GetClientRect (dialogH, &cr);
  209023. SetWindowPos (dialogH, 0,
  209024. r.left, r.top,
  209025. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  209026. jmax (150, (int) (r.bottom - r.top)),
  209027. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  209028. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  209029. customComp->addToDesktop (0, dialogH);
  209030. }
  209031. else if (uiMsg == WM_NOTIFY)
  209032. {
  209033. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  209034. if (ofn->hdr.code == CDN_SELCHANGE)
  209035. {
  209036. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  209037. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  209038. if (comp != 0)
  209039. {
  209040. WCHAR path [MAX_PATH * 2];
  209041. zerostruct (path);
  209042. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  209043. comp->selectedFileChanged (File (path));
  209044. }
  209045. }
  209046. }
  209047. return 0;
  209048. }
  209049. class CustomComponentHolder : public Component
  209050. {
  209051. public:
  209052. CustomComponentHolder (Component* customComp)
  209053. {
  209054. setVisible (true);
  209055. setOpaque (true);
  209056. addAndMakeVisible (customComp);
  209057. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  209058. }
  209059. void paint (Graphics& g)
  209060. {
  209061. g.fillAll (Colours::lightgrey);
  209062. }
  209063. void resized()
  209064. {
  209065. if (getNumChildComponents() > 0)
  209066. getChildComponent(0)->setBounds (getLocalBounds());
  209067. }
  209068. juce_UseDebuggingNewOperator
  209069. private:
  209070. CustomComponentHolder (const CustomComponentHolder&);
  209071. CustomComponentHolder& operator= (const CustomComponentHolder&);
  209072. };
  209073. }
  209074. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  209075. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  209076. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  209077. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  209078. {
  209079. using namespace FileChooserHelpers;
  209080. HeapBlock<WCHAR> files;
  209081. const int charsAvailableForResult = 32768;
  209082. files.calloc (charsAvailableForResult + 1);
  209083. int filenameOffset = 0;
  209084. FileChooserCallbackInfo info;
  209085. // use a modal window as the parent for this dialog box
  209086. // to block input from other app windows
  209087. Component parentWindow (String::empty);
  209088. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  209089. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209090. mainMon.getY() + mainMon.getHeight() / 4,
  209091. 0, 0);
  209092. parentWindow.setOpaque (true);
  209093. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209094. parentWindow.addToDesktop (0);
  209095. if (extraInfoComponent == 0)
  209096. parentWindow.enterModalState();
  209097. if (currentFileOrDirectory.isDirectory())
  209098. {
  209099. info.initialPath = currentFileOrDirectory.getFullPathName();
  209100. }
  209101. else
  209102. {
  209103. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  209104. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209105. }
  209106. if (selectsDirectory)
  209107. {
  209108. BROWSEINFO bi;
  209109. zerostruct (bi);
  209110. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209111. bi.pszDisplayName = files;
  209112. bi.lpszTitle = title;
  209113. bi.lParam = (LPARAM) &info;
  209114. bi.lpfn = browseCallbackProc;
  209115. #ifdef BIF_USENEWUI
  209116. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209117. #else
  209118. bi.ulFlags = 0x50;
  209119. #endif
  209120. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  209121. if (! SHGetPathFromIDListW (list, files))
  209122. {
  209123. files[0] = 0;
  209124. info.returnedString = String::empty;
  209125. }
  209126. LPMALLOC al;
  209127. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209128. al->Free (list);
  209129. if (info.returnedString.isNotEmpty())
  209130. {
  209131. results.add (File (String (files)).getSiblingFile (info.returnedString));
  209132. return;
  209133. }
  209134. }
  209135. else
  209136. {
  209137. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209138. if (warnAboutOverwritingExistingFiles)
  209139. flags |= OFN_OVERWRITEPROMPT;
  209140. if (selectMultipleFiles)
  209141. flags |= OFN_ALLOWMULTISELECT;
  209142. if (extraInfoComponent != 0)
  209143. {
  209144. flags |= OFN_ENABLEHOOK;
  209145. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209146. info.customComponent->enterModalState();
  209147. }
  209148. WCHAR filters [1024];
  209149. zerostruct (filters);
  209150. filter.copyToUnicode (filters, 1024);
  209151. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  209152. OPENFILENAMEW of;
  209153. zerostruct (of);
  209154. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209155. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209156. #else
  209157. of.lStructSize = sizeof (of);
  209158. #endif
  209159. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209160. of.lpstrFilter = filters;
  209161. of.nFilterIndex = 1;
  209162. of.lpstrFile = files;
  209163. of.nMaxFile = charsAvailableForResult;
  209164. of.lpstrInitialDir = info.initialPath;
  209165. of.lpstrTitle = title;
  209166. of.Flags = flags;
  209167. of.lCustData = (LPARAM) &info;
  209168. if (extraInfoComponent != 0)
  209169. of.lpfnHook = &openCallback;
  209170. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209171. : GetOpenFileName (&of)))
  209172. return;
  209173. filenameOffset = of.nFileOffset;
  209174. }
  209175. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209176. {
  209177. const WCHAR* filename = files + filenameOffset;
  209178. while (*filename != 0)
  209179. {
  209180. results.add (File (String (files) + "\\" + String (filename)));
  209181. filename += CharacterFunctions::length (filename) + 1;
  209182. }
  209183. }
  209184. else if (files[0] != 0)
  209185. {
  209186. results.add (File (String (files)));
  209187. }
  209188. }
  209189. #endif
  209190. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209191. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209192. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209193. // compiled on its own).
  209194. #if JUCE_INCLUDED_FILE
  209195. void SystemClipboard::copyTextToClipboard (const String& text)
  209196. {
  209197. if (OpenClipboard (0) != 0)
  209198. {
  209199. if (EmptyClipboard() != 0)
  209200. {
  209201. const int len = text.length();
  209202. if (len > 0)
  209203. {
  209204. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209205. (len + 1) * sizeof (wchar_t));
  209206. if (bufH != 0)
  209207. {
  209208. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209209. text.copyToUnicode (data, len);
  209210. GlobalUnlock (bufH);
  209211. SetClipboardData (CF_UNICODETEXT, bufH);
  209212. }
  209213. }
  209214. }
  209215. CloseClipboard();
  209216. }
  209217. }
  209218. const String SystemClipboard::getTextFromClipboard()
  209219. {
  209220. String result;
  209221. if (OpenClipboard (0) != 0)
  209222. {
  209223. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209224. if (bufH != 0)
  209225. {
  209226. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209227. if (data != 0)
  209228. {
  209229. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209230. GlobalUnlock (bufH);
  209231. }
  209232. }
  209233. CloseClipboard();
  209234. }
  209235. return result;
  209236. }
  209237. #endif
  209238. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209239. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209240. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209241. // compiled on its own).
  209242. #if JUCE_INCLUDED_FILE
  209243. namespace ActiveXHelpers
  209244. {
  209245. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209246. {
  209247. public:
  209248. JuceIStorage() {}
  209249. ~JuceIStorage() {}
  209250. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209251. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209252. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209253. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209254. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209255. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209256. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209257. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209258. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209259. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209260. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209261. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209262. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209263. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209264. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209265. juce_UseDebuggingNewOperator
  209266. };
  209267. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209268. {
  209269. HWND window;
  209270. public:
  209271. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209272. ~JuceOleInPlaceFrame() {}
  209273. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209274. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209275. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209276. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209277. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209278. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209279. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209280. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209281. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209282. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209283. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209284. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209285. juce_UseDebuggingNewOperator
  209286. };
  209287. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209288. {
  209289. HWND window;
  209290. JuceOleInPlaceFrame* frame;
  209291. public:
  209292. JuceIOleInPlaceSite (HWND window_)
  209293. : window (window_),
  209294. frame (new JuceOleInPlaceFrame (window))
  209295. {}
  209296. ~JuceIOleInPlaceSite()
  209297. {
  209298. frame->Release();
  209299. }
  209300. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209301. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209302. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209303. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209304. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209305. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209306. {
  209307. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209308. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209309. */
  209310. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209311. if (lplpDoc != 0) *lplpDoc = 0;
  209312. lpFrameInfo->fMDIApp = FALSE;
  209313. lpFrameInfo->hwndFrame = window;
  209314. lpFrameInfo->haccel = 0;
  209315. lpFrameInfo->cAccelEntries = 0;
  209316. return S_OK;
  209317. }
  209318. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209319. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209320. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209321. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209322. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209323. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209324. juce_UseDebuggingNewOperator
  209325. };
  209326. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209327. {
  209328. JuceIOleInPlaceSite* inplaceSite;
  209329. public:
  209330. JuceIOleClientSite (HWND window)
  209331. : inplaceSite (new JuceIOleInPlaceSite (window))
  209332. {}
  209333. ~JuceIOleClientSite()
  209334. {
  209335. inplaceSite->Release();
  209336. }
  209337. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209338. {
  209339. if (type == IID_IOleInPlaceSite)
  209340. {
  209341. inplaceSite->AddRef();
  209342. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209343. return S_OK;
  209344. }
  209345. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209346. }
  209347. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209348. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209349. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209350. HRESULT __stdcall ShowObject() { return S_OK; }
  209351. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209352. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209353. juce_UseDebuggingNewOperator
  209354. };
  209355. static Array<ActiveXControlComponent*> activeXComps;
  209356. static HWND getHWND (const ActiveXControlComponent* const component)
  209357. {
  209358. HWND hwnd = 0;
  209359. const IID iid = IID_IOleWindow;
  209360. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209361. if (window != 0)
  209362. {
  209363. window->GetWindow (&hwnd);
  209364. window->Release();
  209365. }
  209366. return hwnd;
  209367. }
  209368. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209369. {
  209370. RECT activeXRect, peerRect;
  209371. GetWindowRect (hwnd, &activeXRect);
  209372. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209373. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209374. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209375. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209376. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209377. switch (message)
  209378. {
  209379. case WM_MOUSEMOVE:
  209380. case WM_LBUTTONDOWN:
  209381. case WM_MBUTTONDOWN:
  209382. case WM_RBUTTONDOWN:
  209383. case WM_LBUTTONUP:
  209384. case WM_MBUTTONUP:
  209385. case WM_RBUTTONUP:
  209386. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209387. break;
  209388. default:
  209389. break;
  209390. }
  209391. }
  209392. }
  209393. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209394. {
  209395. ActiveXControlComponent& owner;
  209396. bool wasShowing;
  209397. public:
  209398. HWND controlHWND;
  209399. IStorage* storage;
  209400. IOleClientSite* clientSite;
  209401. IOleObject* control;
  209402. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209403. : ComponentMovementWatcher (&owner_),
  209404. owner (owner_),
  209405. wasShowing (owner_.isShowing()),
  209406. controlHWND (0),
  209407. storage (new ActiveXHelpers::JuceIStorage()),
  209408. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209409. control (0)
  209410. {
  209411. }
  209412. ~Pimpl()
  209413. {
  209414. if (control != 0)
  209415. {
  209416. control->Close (OLECLOSE_NOSAVE);
  209417. control->Release();
  209418. }
  209419. clientSite->Release();
  209420. storage->Release();
  209421. }
  209422. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209423. {
  209424. Component* const topComp = owner.getTopLevelComponent();
  209425. if (topComp->getPeer() != 0)
  209426. {
  209427. const Point<int> pos (owner.relativePositionToOtherComponent (topComp, Point<int>()));
  209428. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209429. }
  209430. }
  209431. void componentPeerChanged()
  209432. {
  209433. const bool isShowingNow = owner.isShowing();
  209434. if (wasShowing != isShowingNow)
  209435. {
  209436. wasShowing = isShowingNow;
  209437. owner.setControlVisible (isShowingNow);
  209438. }
  209439. componentMovedOrResized (true, true);
  209440. }
  209441. void componentVisibilityChanged (Component&)
  209442. {
  209443. componentPeerChanged();
  209444. }
  209445. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209446. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209447. {
  209448. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209449. {
  209450. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209451. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209452. {
  209453. switch (message)
  209454. {
  209455. case WM_MOUSEMOVE:
  209456. case WM_LBUTTONDOWN:
  209457. case WM_MBUTTONDOWN:
  209458. case WM_RBUTTONDOWN:
  209459. case WM_LBUTTONUP:
  209460. case WM_MBUTTONUP:
  209461. case WM_RBUTTONUP:
  209462. case WM_LBUTTONDBLCLK:
  209463. case WM_MBUTTONDBLCLK:
  209464. case WM_RBUTTONDBLCLK:
  209465. if (ax->isShowing())
  209466. {
  209467. ComponentPeer* const peer = ax->getPeer();
  209468. if (peer != 0)
  209469. {
  209470. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209471. if (! ax->areMouseEventsAllowed())
  209472. return 0;
  209473. }
  209474. }
  209475. break;
  209476. default:
  209477. break;
  209478. }
  209479. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209480. }
  209481. }
  209482. return DefWindowProc (hwnd, message, wParam, lParam);
  209483. }
  209484. };
  209485. ActiveXControlComponent::ActiveXControlComponent()
  209486. : originalWndProc (0),
  209487. mouseEventsAllowed (true)
  209488. {
  209489. ActiveXHelpers::activeXComps.add (this);
  209490. }
  209491. ActiveXControlComponent::~ActiveXControlComponent()
  209492. {
  209493. deleteControl();
  209494. ActiveXHelpers::activeXComps.removeValue (this);
  209495. }
  209496. void ActiveXControlComponent::paint (Graphics& g)
  209497. {
  209498. if (control == 0)
  209499. g.fillAll (Colours::lightgrey);
  209500. }
  209501. bool ActiveXControlComponent::createControl (const void* controlIID)
  209502. {
  209503. deleteControl();
  209504. ComponentPeer* const peer = getPeer();
  209505. // the component must have already been added to a real window when you call this!
  209506. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209507. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209508. {
  209509. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209510. HWND hwnd = (HWND) peer->getNativeHandle();
  209511. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209512. HRESULT hr;
  209513. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209514. newControl->clientSite, newControl->storage,
  209515. (void**) &(newControl->control))) == S_OK)
  209516. {
  209517. newControl->control->SetHostNames (L"Juce", 0);
  209518. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209519. {
  209520. RECT rect;
  209521. rect.left = pos.getX();
  209522. rect.top = pos.getY();
  209523. rect.right = pos.getX() + getWidth();
  209524. rect.bottom = pos.getY() + getHeight();
  209525. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209526. {
  209527. control = newControl;
  209528. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209529. control->controlHWND = ActiveXHelpers::getHWND (this);
  209530. if (control->controlHWND != 0)
  209531. {
  209532. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209533. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209534. }
  209535. return true;
  209536. }
  209537. }
  209538. }
  209539. }
  209540. return false;
  209541. }
  209542. void ActiveXControlComponent::deleteControl()
  209543. {
  209544. control = 0;
  209545. originalWndProc = 0;
  209546. }
  209547. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209548. {
  209549. void* result = 0;
  209550. if (control != 0 && control->control != 0
  209551. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209552. return result;
  209553. return 0;
  209554. }
  209555. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209556. {
  209557. if (control->controlHWND != 0)
  209558. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209559. }
  209560. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209561. {
  209562. if (control->controlHWND != 0)
  209563. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209564. }
  209565. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209566. {
  209567. mouseEventsAllowed = eventsCanReachControl;
  209568. }
  209569. #endif
  209570. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209571. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209572. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209573. // compiled on its own).
  209574. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209575. using namespace QTOLibrary;
  209576. using namespace QTOControlLib;
  209577. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209578. static bool isQTAvailable = false;
  209579. class QuickTimeMovieComponent::Pimpl
  209580. {
  209581. public:
  209582. Pimpl() : dataHandle (0)
  209583. {
  209584. }
  209585. ~Pimpl()
  209586. {
  209587. clearHandle();
  209588. }
  209589. void clearHandle()
  209590. {
  209591. if (dataHandle != 0)
  209592. {
  209593. DisposeHandle (dataHandle);
  209594. dataHandle = 0;
  209595. }
  209596. }
  209597. IQTControlPtr qtControl;
  209598. IQTMoviePtr qtMovie;
  209599. Handle dataHandle;
  209600. };
  209601. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209602. : movieLoaded (false),
  209603. controllerVisible (true)
  209604. {
  209605. pimpl = new Pimpl();
  209606. setMouseEventsAllowed (false);
  209607. }
  209608. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209609. {
  209610. closeMovie();
  209611. pimpl->qtControl = 0;
  209612. deleteControl();
  209613. pimpl = 0;
  209614. }
  209615. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209616. {
  209617. if (! isQTAvailable)
  209618. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209619. return isQTAvailable;
  209620. }
  209621. void QuickTimeMovieComponent::createControlIfNeeded()
  209622. {
  209623. if (isShowing() && ! isControlCreated())
  209624. {
  209625. const IID qtIID = __uuidof (QTControl);
  209626. if (createControl (&qtIID))
  209627. {
  209628. const IID qtInterfaceIID = __uuidof (IQTControl);
  209629. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209630. if (pimpl->qtControl != 0)
  209631. {
  209632. pimpl->qtControl->Release(); // it has one ref too many at this point
  209633. pimpl->qtControl->QuickTimeInitialize();
  209634. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209635. if (movieFile != File::nonexistent)
  209636. loadMovie (movieFile, controllerVisible);
  209637. }
  209638. }
  209639. }
  209640. }
  209641. bool QuickTimeMovieComponent::isControlCreated() const
  209642. {
  209643. return isControlOpen();
  209644. }
  209645. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209646. const bool isControllerVisible)
  209647. {
  209648. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209649. movieFile = File::nonexistent;
  209650. movieLoaded = false;
  209651. pimpl->qtMovie = 0;
  209652. controllerVisible = isControllerVisible;
  209653. createControlIfNeeded();
  209654. if (isControlCreated())
  209655. {
  209656. if (pimpl->qtControl != 0)
  209657. {
  209658. pimpl->qtControl->Put_MovieHandle (0);
  209659. pimpl->clearHandle();
  209660. Movie movie;
  209661. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209662. {
  209663. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209664. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209665. if (pimpl->qtMovie != 0)
  209666. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209667. : qtMovieControllerTypeNone);
  209668. }
  209669. if (movie == 0)
  209670. pimpl->clearHandle();
  209671. }
  209672. movieLoaded = (pimpl->qtMovie != 0);
  209673. }
  209674. else
  209675. {
  209676. // You're trying to open a movie when the control hasn't yet been created, probably because
  209677. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209678. jassertfalse;
  209679. }
  209680. return movieLoaded;
  209681. }
  209682. void QuickTimeMovieComponent::closeMovie()
  209683. {
  209684. stop();
  209685. movieFile = File::nonexistent;
  209686. movieLoaded = false;
  209687. pimpl->qtMovie = 0;
  209688. if (pimpl->qtControl != 0)
  209689. pimpl->qtControl->Put_MovieHandle (0);
  209690. pimpl->clearHandle();
  209691. }
  209692. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209693. {
  209694. return movieFile;
  209695. }
  209696. bool QuickTimeMovieComponent::isMovieOpen() const
  209697. {
  209698. return movieLoaded;
  209699. }
  209700. double QuickTimeMovieComponent::getMovieDuration() const
  209701. {
  209702. if (pimpl->qtMovie != 0)
  209703. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209704. return 0.0;
  209705. }
  209706. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209707. {
  209708. if (pimpl->qtMovie != 0)
  209709. {
  209710. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209711. width = r.right - r.left;
  209712. height = r.bottom - r.top;
  209713. }
  209714. else
  209715. {
  209716. width = height = 0;
  209717. }
  209718. }
  209719. void QuickTimeMovieComponent::play()
  209720. {
  209721. if (pimpl->qtMovie != 0)
  209722. pimpl->qtMovie->Play();
  209723. }
  209724. void QuickTimeMovieComponent::stop()
  209725. {
  209726. if (pimpl->qtMovie != 0)
  209727. pimpl->qtMovie->Stop();
  209728. }
  209729. bool QuickTimeMovieComponent::isPlaying() const
  209730. {
  209731. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209732. }
  209733. void QuickTimeMovieComponent::setPosition (const double seconds)
  209734. {
  209735. if (pimpl->qtMovie != 0)
  209736. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209737. }
  209738. double QuickTimeMovieComponent::getPosition() const
  209739. {
  209740. if (pimpl->qtMovie != 0)
  209741. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209742. return 0.0;
  209743. }
  209744. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209745. {
  209746. if (pimpl->qtMovie != 0)
  209747. pimpl->qtMovie->PutRate (newSpeed);
  209748. }
  209749. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209750. {
  209751. if (pimpl->qtMovie != 0)
  209752. {
  209753. pimpl->qtMovie->PutAudioVolume (newVolume);
  209754. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209755. }
  209756. }
  209757. float QuickTimeMovieComponent::getMovieVolume() const
  209758. {
  209759. if (pimpl->qtMovie != 0)
  209760. return pimpl->qtMovie->GetAudioVolume();
  209761. return 0.0f;
  209762. }
  209763. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209764. {
  209765. if (pimpl->qtMovie != 0)
  209766. pimpl->qtMovie->PutLoop (shouldLoop);
  209767. }
  209768. bool QuickTimeMovieComponent::isLooping() const
  209769. {
  209770. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209771. }
  209772. bool QuickTimeMovieComponent::isControllerVisible() const
  209773. {
  209774. return controllerVisible;
  209775. }
  209776. void QuickTimeMovieComponent::parentHierarchyChanged()
  209777. {
  209778. createControlIfNeeded();
  209779. QTCompBaseClass::parentHierarchyChanged();
  209780. }
  209781. void QuickTimeMovieComponent::visibilityChanged()
  209782. {
  209783. createControlIfNeeded();
  209784. QTCompBaseClass::visibilityChanged();
  209785. }
  209786. void QuickTimeMovieComponent::paint (Graphics& g)
  209787. {
  209788. if (! isControlCreated())
  209789. g.fillAll (Colours::black);
  209790. }
  209791. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209792. {
  209793. Handle dataRef = 0;
  209794. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209795. if (err == noErr)
  209796. {
  209797. Str255 suffix;
  209798. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209799. StringPtr name = suffix;
  209800. err = PtrAndHand (name, dataRef, name[0] + 1);
  209801. if (err == noErr)
  209802. {
  209803. long atoms[3];
  209804. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209805. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209806. atoms[2] = EndianU32_NtoB (MovieFileType);
  209807. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209808. if (err == noErr)
  209809. return dataRef;
  209810. }
  209811. DisposeHandle (dataRef);
  209812. }
  209813. return 0;
  209814. }
  209815. static CFStringRef juceStringToCFString (const String& s)
  209816. {
  209817. const int len = s.length();
  209818. const juce_wchar* const t = s;
  209819. HeapBlock <UniChar> temp (len + 2);
  209820. for (int i = 0; i <= len; ++i)
  209821. temp[i] = t[i];
  209822. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209823. }
  209824. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209825. {
  209826. Boolean trueBool = true;
  209827. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209828. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209829. props[prop].propValueSize = sizeof (trueBool);
  209830. props[prop].propValueAddress = &trueBool;
  209831. ++prop;
  209832. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209833. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209834. props[prop].propValueSize = sizeof (trueBool);
  209835. props[prop].propValueAddress = &trueBool;
  209836. ++prop;
  209837. Boolean isActive = true;
  209838. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209839. props[prop].propID = kQTNewMoviePropertyID_Active;
  209840. props[prop].propValueSize = sizeof (isActive);
  209841. props[prop].propValueAddress = &isActive;
  209842. ++prop;
  209843. MacSetPort (0);
  209844. jassert (prop <= 5);
  209845. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209846. return err == noErr;
  209847. }
  209848. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209849. {
  209850. if (input == 0)
  209851. return false;
  209852. dataHandle = 0;
  209853. bool ok = false;
  209854. QTNewMoviePropertyElement props[5];
  209855. zeromem (props, sizeof (props));
  209856. int prop = 0;
  209857. DataReferenceRecord dr;
  209858. props[prop].propClass = kQTPropertyClass_DataLocation;
  209859. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209860. props[prop].propValueSize = sizeof (dr);
  209861. props[prop].propValueAddress = &dr;
  209862. ++prop;
  209863. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209864. if (fin != 0)
  209865. {
  209866. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209867. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209868. &dr.dataRef, &dr.dataRefType);
  209869. ok = openMovie (props, prop, movie);
  209870. DisposeHandle (dr.dataRef);
  209871. CFRelease (filePath);
  209872. }
  209873. else
  209874. {
  209875. // sanity-check because this currently needs to load the whole stream into memory..
  209876. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209877. dataHandle = NewHandle ((Size) input->getTotalLength());
  209878. HLock (dataHandle);
  209879. // read the entire stream into memory - this is a pain, but can't get it to work
  209880. // properly using a custom callback to supply the data.
  209881. input->read (*dataHandle, (int) input->getTotalLength());
  209882. HUnlock (dataHandle);
  209883. // different types to get QT to try. (We should really be a bit smarter here by
  209884. // working out in advance which one the stream contains, rather than just trying
  209885. // each one)
  209886. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209887. "\04.avi", "\04.m4a" };
  209888. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209889. {
  209890. /* // this fails for some bizarre reason - it can be bodged to work with
  209891. // movies, but can't seem to do it for other file types..
  209892. QTNewMovieUserProcRecord procInfo;
  209893. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209894. procInfo.getMovieUserProcRefcon = this;
  209895. procInfo.defaultDataRef.dataRef = dataRef;
  209896. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209897. props[prop].propClass = kQTPropertyClass_DataLocation;
  209898. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209899. props[prop].propValueSize = sizeof (procInfo);
  209900. props[prop].propValueAddress = (void*) &procInfo;
  209901. ++prop; */
  209902. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209903. dr.dataRefType = HandleDataHandlerSubType;
  209904. ok = openMovie (props, prop, movie);
  209905. DisposeHandle (dr.dataRef);
  209906. }
  209907. }
  209908. return ok;
  209909. }
  209910. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209911. const bool isControllerVisible)
  209912. {
  209913. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209914. movieFile = movieFile_;
  209915. return ok;
  209916. }
  209917. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209918. const bool isControllerVisible)
  209919. {
  209920. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209921. }
  209922. void QuickTimeMovieComponent::goToStart()
  209923. {
  209924. setPosition (0.0);
  209925. }
  209926. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209927. const RectanglePlacement& placement)
  209928. {
  209929. int normalWidth, normalHeight;
  209930. getMovieNormalSize (normalWidth, normalHeight);
  209931. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209932. {
  209933. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209934. placement.applyTo (x, y, w, h,
  209935. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209936. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209937. if (w > 0 && h > 0)
  209938. {
  209939. setBounds (roundToInt (x), roundToInt (y),
  209940. roundToInt (w), roundToInt (h));
  209941. }
  209942. }
  209943. else
  209944. {
  209945. setBounds (spaceToFitWithin);
  209946. }
  209947. }
  209948. #endif
  209949. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209950. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209951. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209952. // compiled on its own).
  209953. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209954. class WebBrowserComponentInternal : public ActiveXControlComponent
  209955. {
  209956. public:
  209957. WebBrowserComponentInternal()
  209958. : browser (0),
  209959. connectionPoint (0),
  209960. adviseCookie (0)
  209961. {
  209962. }
  209963. ~WebBrowserComponentInternal()
  209964. {
  209965. if (connectionPoint != 0)
  209966. connectionPoint->Unadvise (adviseCookie);
  209967. if (browser != 0)
  209968. browser->Release();
  209969. }
  209970. void createBrowser()
  209971. {
  209972. createControl (&CLSID_WebBrowser);
  209973. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209974. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209975. if (connectionPointContainer != 0)
  209976. {
  209977. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209978. &connectionPoint);
  209979. if (connectionPoint != 0)
  209980. {
  209981. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209982. jassert (owner != 0);
  209983. EventHandler* handler = new EventHandler (owner);
  209984. connectionPoint->Advise (handler, &adviseCookie);
  209985. handler->Release();
  209986. }
  209987. }
  209988. }
  209989. void goToURL (const String& url,
  209990. const StringArray* headers,
  209991. const MemoryBlock* postData)
  209992. {
  209993. if (browser != 0)
  209994. {
  209995. LPSAFEARRAY sa = 0;
  209996. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209997. VariantInit (&flags);
  209998. VariantInit (&frame);
  209999. VariantInit (&postDataVar);
  210000. VariantInit (&headersVar);
  210001. if (headers != 0)
  210002. {
  210003. V_VT (&headersVar) = VT_BSTR;
  210004. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  210005. }
  210006. if (postData != 0 && postData->getSize() > 0)
  210007. {
  210008. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  210009. if (sa != 0)
  210010. {
  210011. void* data = 0;
  210012. SafeArrayAccessData (sa, &data);
  210013. jassert (data != 0);
  210014. if (data != 0)
  210015. {
  210016. postData->copyTo (data, 0, postData->getSize());
  210017. SafeArrayUnaccessData (sa);
  210018. VARIANT postDataVar2;
  210019. VariantInit (&postDataVar2);
  210020. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  210021. V_ARRAY (&postDataVar2) = sa;
  210022. postDataVar = postDataVar2;
  210023. }
  210024. }
  210025. }
  210026. browser->Navigate ((BSTR) (const OLECHAR*) url,
  210027. &flags, &frame,
  210028. &postDataVar, &headersVar);
  210029. if (sa != 0)
  210030. SafeArrayDestroy (sa);
  210031. VariantClear (&flags);
  210032. VariantClear (&frame);
  210033. VariantClear (&postDataVar);
  210034. VariantClear (&headersVar);
  210035. }
  210036. }
  210037. IWebBrowser2* browser;
  210038. juce_UseDebuggingNewOperator
  210039. private:
  210040. IConnectionPoint* connectionPoint;
  210041. DWORD adviseCookie;
  210042. class EventHandler : public ComBaseClassHelper <IDispatch>,
  210043. public ComponentMovementWatcher
  210044. {
  210045. public:
  210046. EventHandler (WebBrowserComponent* owner_)
  210047. : ComponentMovementWatcher (owner_),
  210048. owner (owner_)
  210049. {
  210050. }
  210051. ~EventHandler()
  210052. {
  210053. }
  210054. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  210055. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  210056. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  210057. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  210058. WORD /*wFlags*/, DISPPARAMS* pDispParams,
  210059. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/,
  210060. UINT* /*puArgErr*/)
  210061. {
  210062. switch (dispIdMember)
  210063. {
  210064. case DISPID_BEFORENAVIGATE2:
  210065. {
  210066. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210067. String url;
  210068. if ((vurl->vt & VT_BYREF) != 0)
  210069. url = *vurl->pbstrVal;
  210070. else
  210071. url = vurl->bstrVal;
  210072. *pDispParams->rgvarg->pboolVal
  210073. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  210074. : VARIANT_TRUE;
  210075. return S_OK;
  210076. }
  210077. default:
  210078. break;
  210079. }
  210080. return E_NOTIMPL;
  210081. }
  210082. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  210083. void componentPeerChanged() {}
  210084. void componentVisibilityChanged (Component&)
  210085. {
  210086. owner->visibilityChanged();
  210087. }
  210088. juce_UseDebuggingNewOperator
  210089. private:
  210090. WebBrowserComponent* const owner;
  210091. EventHandler (const EventHandler&);
  210092. EventHandler& operator= (const EventHandler&);
  210093. };
  210094. };
  210095. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  210096. : browser (0),
  210097. blankPageShown (false),
  210098. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  210099. {
  210100. setOpaque (true);
  210101. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210102. }
  210103. WebBrowserComponent::~WebBrowserComponent()
  210104. {
  210105. delete browser;
  210106. }
  210107. void WebBrowserComponent::goToURL (const String& url,
  210108. const StringArray* headers,
  210109. const MemoryBlock* postData)
  210110. {
  210111. lastURL = url;
  210112. lastHeaders.clear();
  210113. if (headers != 0)
  210114. lastHeaders = *headers;
  210115. lastPostData.setSize (0);
  210116. if (postData != 0)
  210117. lastPostData = *postData;
  210118. blankPageShown = false;
  210119. browser->goToURL (url, headers, postData);
  210120. }
  210121. void WebBrowserComponent::stop()
  210122. {
  210123. if (browser->browser != 0)
  210124. browser->browser->Stop();
  210125. }
  210126. void WebBrowserComponent::goBack()
  210127. {
  210128. lastURL = String::empty;
  210129. blankPageShown = false;
  210130. if (browser->browser != 0)
  210131. browser->browser->GoBack();
  210132. }
  210133. void WebBrowserComponent::goForward()
  210134. {
  210135. lastURL = String::empty;
  210136. if (browser->browser != 0)
  210137. browser->browser->GoForward();
  210138. }
  210139. void WebBrowserComponent::refresh()
  210140. {
  210141. if (browser->browser != 0)
  210142. browser->browser->Refresh();
  210143. }
  210144. void WebBrowserComponent::paint (Graphics& g)
  210145. {
  210146. if (browser->browser == 0)
  210147. g.fillAll (Colours::white);
  210148. }
  210149. void WebBrowserComponent::checkWindowAssociation()
  210150. {
  210151. if (isShowing())
  210152. {
  210153. if (browser->browser == 0 && getPeer() != 0)
  210154. {
  210155. browser->createBrowser();
  210156. reloadLastURL();
  210157. }
  210158. else
  210159. {
  210160. if (blankPageShown)
  210161. goBack();
  210162. }
  210163. }
  210164. else
  210165. {
  210166. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210167. {
  210168. // when the component becomes invisible, some stuff like flash
  210169. // carries on playing audio, so we need to force it onto a blank
  210170. // page to avoid this..
  210171. blankPageShown = true;
  210172. browser->goToURL ("about:blank", 0, 0);
  210173. }
  210174. }
  210175. }
  210176. void WebBrowserComponent::reloadLastURL()
  210177. {
  210178. if (lastURL.isNotEmpty())
  210179. {
  210180. goToURL (lastURL, &lastHeaders, &lastPostData);
  210181. lastURL = String::empty;
  210182. }
  210183. }
  210184. void WebBrowserComponent::parentHierarchyChanged()
  210185. {
  210186. checkWindowAssociation();
  210187. }
  210188. void WebBrowserComponent::resized()
  210189. {
  210190. browser->setSize (getWidth(), getHeight());
  210191. }
  210192. void WebBrowserComponent::visibilityChanged()
  210193. {
  210194. checkWindowAssociation();
  210195. }
  210196. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210197. {
  210198. return true;
  210199. }
  210200. #endif
  210201. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210202. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210203. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210204. // compiled on its own).
  210205. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210206. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210207. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210208. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210209. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210210. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210211. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210212. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210213. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210214. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210215. #define WGL_ACCELERATION_ARB 0x2003
  210216. #define WGL_SWAP_METHOD_ARB 0x2007
  210217. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210218. #define WGL_PIXEL_TYPE_ARB 0x2013
  210219. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210220. #define WGL_COLOR_BITS_ARB 0x2014
  210221. #define WGL_RED_BITS_ARB 0x2015
  210222. #define WGL_GREEN_BITS_ARB 0x2017
  210223. #define WGL_BLUE_BITS_ARB 0x2019
  210224. #define WGL_ALPHA_BITS_ARB 0x201B
  210225. #define WGL_DEPTH_BITS_ARB 0x2022
  210226. #define WGL_STENCIL_BITS_ARB 0x2023
  210227. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210228. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210229. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210230. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210231. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210232. #define WGL_STEREO_ARB 0x2012
  210233. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210234. #define WGL_SAMPLES_ARB 0x2042
  210235. #define WGL_TYPE_RGBA_ARB 0x202B
  210236. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210237. {
  210238. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210239. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210240. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210241. else
  210242. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210243. }
  210244. class WindowedGLContext : public OpenGLContext
  210245. {
  210246. public:
  210247. WindowedGLContext (Component* const component_,
  210248. HGLRC contextToShareWith,
  210249. const OpenGLPixelFormat& pixelFormat)
  210250. : renderContext (0),
  210251. dc (0),
  210252. component (component_)
  210253. {
  210254. jassert (component != 0);
  210255. createNativeWindow();
  210256. // Use a default pixel format that should be supported everywhere
  210257. PIXELFORMATDESCRIPTOR pfd;
  210258. zerostruct (pfd);
  210259. pfd.nSize = sizeof (pfd);
  210260. pfd.nVersion = 1;
  210261. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210262. pfd.iPixelType = PFD_TYPE_RGBA;
  210263. pfd.cColorBits = 24;
  210264. pfd.cDepthBits = 16;
  210265. const int format = ChoosePixelFormat (dc, &pfd);
  210266. if (format != 0)
  210267. SetPixelFormat (dc, format, &pfd);
  210268. renderContext = wglCreateContext (dc);
  210269. makeActive();
  210270. setPixelFormat (pixelFormat);
  210271. if (contextToShareWith != 0 && renderContext != 0)
  210272. wglShareLists (contextToShareWith, renderContext);
  210273. }
  210274. ~WindowedGLContext()
  210275. {
  210276. deleteContext();
  210277. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210278. nativeWindow = 0;
  210279. }
  210280. void deleteContext()
  210281. {
  210282. makeInactive();
  210283. if (renderContext != 0)
  210284. {
  210285. wglDeleteContext (renderContext);
  210286. renderContext = 0;
  210287. }
  210288. }
  210289. bool makeActive() const throw()
  210290. {
  210291. jassert (renderContext != 0);
  210292. return wglMakeCurrent (dc, renderContext) != 0;
  210293. }
  210294. bool makeInactive() const throw()
  210295. {
  210296. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210297. }
  210298. bool isActive() const throw()
  210299. {
  210300. return wglGetCurrentContext() == renderContext;
  210301. }
  210302. const OpenGLPixelFormat getPixelFormat() const
  210303. {
  210304. OpenGLPixelFormat pf;
  210305. makeActive();
  210306. StringArray availableExtensions;
  210307. getWglExtensions (dc, availableExtensions);
  210308. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210309. return pf;
  210310. }
  210311. void* getRawContext() const throw()
  210312. {
  210313. return renderContext;
  210314. }
  210315. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210316. {
  210317. makeActive();
  210318. PIXELFORMATDESCRIPTOR pfd;
  210319. zerostruct (pfd);
  210320. pfd.nSize = sizeof (pfd);
  210321. pfd.nVersion = 1;
  210322. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210323. pfd.iPixelType = PFD_TYPE_RGBA;
  210324. pfd.iLayerType = PFD_MAIN_PLANE;
  210325. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210326. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210327. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210328. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210329. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210330. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210331. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210332. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210333. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210334. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210335. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210336. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210337. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210338. int format = 0;
  210339. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210340. StringArray availableExtensions;
  210341. getWglExtensions (dc, availableExtensions);
  210342. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210343. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210344. {
  210345. int attributes[64];
  210346. int n = 0;
  210347. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210348. attributes[n++] = GL_TRUE;
  210349. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210350. attributes[n++] = GL_TRUE;
  210351. attributes[n++] = WGL_ACCELERATION_ARB;
  210352. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210353. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210354. attributes[n++] = GL_TRUE;
  210355. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210356. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210357. attributes[n++] = WGL_COLOR_BITS_ARB;
  210358. attributes[n++] = pfd.cColorBits;
  210359. attributes[n++] = WGL_RED_BITS_ARB;
  210360. attributes[n++] = pixelFormat.redBits;
  210361. attributes[n++] = WGL_GREEN_BITS_ARB;
  210362. attributes[n++] = pixelFormat.greenBits;
  210363. attributes[n++] = WGL_BLUE_BITS_ARB;
  210364. attributes[n++] = pixelFormat.blueBits;
  210365. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210366. attributes[n++] = pixelFormat.alphaBits;
  210367. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210368. attributes[n++] = pixelFormat.depthBufferBits;
  210369. if (pixelFormat.stencilBufferBits > 0)
  210370. {
  210371. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210372. attributes[n++] = pixelFormat.stencilBufferBits;
  210373. }
  210374. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210375. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210376. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210377. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210378. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210379. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210380. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210381. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210382. if (availableExtensions.contains ("WGL_ARB_multisample")
  210383. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210384. {
  210385. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210386. attributes[n++] = 1;
  210387. attributes[n++] = WGL_SAMPLES_ARB;
  210388. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210389. }
  210390. attributes[n++] = 0;
  210391. UINT formatsCount;
  210392. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210393. (void) ok;
  210394. jassert (ok);
  210395. }
  210396. else
  210397. {
  210398. format = ChoosePixelFormat (dc, &pfd);
  210399. }
  210400. if (format != 0)
  210401. {
  210402. makeInactive();
  210403. // win32 can't change the pixel format of a window, so need to delete the
  210404. // old one and create a new one..
  210405. jassert (nativeWindow != 0);
  210406. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210407. nativeWindow = 0;
  210408. createNativeWindow();
  210409. if (SetPixelFormat (dc, format, &pfd))
  210410. {
  210411. wglDeleteContext (renderContext);
  210412. renderContext = wglCreateContext (dc);
  210413. jassert (renderContext != 0);
  210414. return renderContext != 0;
  210415. }
  210416. }
  210417. return false;
  210418. }
  210419. void updateWindowPosition (int x, int y, int w, int h, int)
  210420. {
  210421. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210422. x, y, w, h,
  210423. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210424. }
  210425. void repaint()
  210426. {
  210427. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210428. }
  210429. void swapBuffers()
  210430. {
  210431. SwapBuffers (dc);
  210432. }
  210433. bool setSwapInterval (int numFramesPerSwap)
  210434. {
  210435. makeActive();
  210436. StringArray availableExtensions;
  210437. getWglExtensions (dc, availableExtensions);
  210438. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210439. return availableExtensions.contains ("WGL_EXT_swap_control")
  210440. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210441. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210442. }
  210443. int getSwapInterval() const
  210444. {
  210445. makeActive();
  210446. StringArray availableExtensions;
  210447. getWglExtensions (dc, availableExtensions);
  210448. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210449. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210450. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210451. return wglGetSwapIntervalEXT();
  210452. return 0;
  210453. }
  210454. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210455. {
  210456. jassert (isActive());
  210457. StringArray availableExtensions;
  210458. getWglExtensions (dc, availableExtensions);
  210459. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210460. int numTypes = 0;
  210461. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210462. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210463. {
  210464. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210465. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210466. jassertfalse;
  210467. }
  210468. else
  210469. {
  210470. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210471. }
  210472. OpenGLPixelFormat pf;
  210473. for (int i = 0; i < numTypes; ++i)
  210474. {
  210475. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210476. {
  210477. bool alreadyListed = false;
  210478. for (int j = results.size(); --j >= 0;)
  210479. if (pf == *results.getUnchecked(j))
  210480. alreadyListed = true;
  210481. if (! alreadyListed)
  210482. results.add (new OpenGLPixelFormat (pf));
  210483. }
  210484. }
  210485. }
  210486. void* getNativeWindowHandle() const
  210487. {
  210488. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210489. }
  210490. juce_UseDebuggingNewOperator
  210491. HGLRC renderContext;
  210492. private:
  210493. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210494. Component* const component;
  210495. HDC dc;
  210496. void createNativeWindow()
  210497. {
  210498. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210499. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210500. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210501. nativeWindow->dontRepaint = true;
  210502. nativeWindow->setVisible (true);
  210503. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210504. }
  210505. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210506. OpenGLPixelFormat& result,
  210507. const StringArray& availableExtensions) const throw()
  210508. {
  210509. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210510. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210511. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210512. {
  210513. int attributes[32];
  210514. int numAttributes = 0;
  210515. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210516. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210517. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210518. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210519. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210520. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210521. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210522. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210523. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210524. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210525. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210526. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210527. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210528. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210529. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210530. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210531. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210532. int values[32];
  210533. zeromem (values, sizeof (values));
  210534. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210535. {
  210536. int n = 0;
  210537. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210538. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210539. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210540. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210541. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210542. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210543. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210544. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210545. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210546. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210547. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210548. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210549. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210550. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210551. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210552. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210553. return isValidFormat;
  210554. }
  210555. else
  210556. {
  210557. jassertfalse;
  210558. }
  210559. }
  210560. else
  210561. {
  210562. PIXELFORMATDESCRIPTOR pfd;
  210563. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210564. {
  210565. result.redBits = pfd.cRedBits;
  210566. result.greenBits = pfd.cGreenBits;
  210567. result.blueBits = pfd.cBlueBits;
  210568. result.alphaBits = pfd.cAlphaBits;
  210569. result.depthBufferBits = pfd.cDepthBits;
  210570. result.stencilBufferBits = pfd.cStencilBits;
  210571. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210572. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210573. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210574. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210575. result.fullSceneAntiAliasingNumSamples = 0;
  210576. return true;
  210577. }
  210578. else
  210579. {
  210580. jassertfalse;
  210581. }
  210582. }
  210583. return false;
  210584. }
  210585. WindowedGLContext (const WindowedGLContext&);
  210586. WindowedGLContext& operator= (const WindowedGLContext&);
  210587. };
  210588. OpenGLContext* OpenGLComponent::createContext()
  210589. {
  210590. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210591. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210592. preferredPixelFormat));
  210593. return (c->renderContext != 0) ? c.release() : 0;
  210594. }
  210595. void* OpenGLComponent::getNativeWindowHandle() const
  210596. {
  210597. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210598. }
  210599. void juce_glViewport (const int w, const int h)
  210600. {
  210601. glViewport (0, 0, w, h);
  210602. }
  210603. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210604. OwnedArray <OpenGLPixelFormat>& results)
  210605. {
  210606. Component tempComp;
  210607. {
  210608. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210609. wc.makeActive();
  210610. wc.findAlternativeOpenGLPixelFormats (results);
  210611. }
  210612. }
  210613. #endif
  210614. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210615. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210616. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210617. // compiled on its own).
  210618. #if JUCE_INCLUDED_FILE
  210619. #if JUCE_USE_CDREADER
  210620. namespace CDReaderHelpers
  210621. {
  210622. //***************************************************************************
  210623. // %%% TARGET STATUS VALUES %%%
  210624. //***************************************************************************
  210625. #define STATUS_GOOD 0x00 // Status Good
  210626. #define STATUS_CHKCOND 0x02 // Check Condition
  210627. #define STATUS_CONDMET 0x04 // Condition Met
  210628. #define STATUS_BUSY 0x08 // Busy
  210629. #define STATUS_INTERM 0x10 // Intermediate
  210630. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210631. #define STATUS_RESCONF 0x18 // Reservation conflict
  210632. #define STATUS_COMTERM 0x22 // Command Terminated
  210633. #define STATUS_QFULL 0x28 // Queue full
  210634. //***************************************************************************
  210635. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210636. //***************************************************************************
  210637. #define MAXLUN 7 // Maximum Logical Unit Id
  210638. #define MAXTARG 7 // Maximum Target Id
  210639. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210640. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210641. //***************************************************************************
  210642. // %%% Commands for all Device Types %%%
  210643. //***************************************************************************
  210644. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210645. #define SCSI_COMPARE 0x39 // Compare (O)
  210646. #define SCSI_COPY 0x18 // Copy (O)
  210647. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210648. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210649. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210650. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210651. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210652. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210653. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210654. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210655. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210656. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210657. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210658. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210659. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210660. //***************************************************************************
  210661. // %%% Commands Unique to Direct Access Devices %%%
  210662. //***************************************************************************
  210663. #define SCSI_COMPARE 0x39 // Compare (O)
  210664. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210665. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210666. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210667. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210668. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210669. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210670. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210671. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210672. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210673. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210674. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210675. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210676. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210677. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210678. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210679. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210680. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210681. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210682. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210683. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210684. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210685. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210686. #define SCSI_VERIFY 0x2F // Verify (O)
  210687. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210688. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210689. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210690. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210691. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210692. //***************************************************************************
  210693. // %%% Commands Unique to Sequential Access Devices %%%
  210694. //***************************************************************************
  210695. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210696. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210697. #define SCSI_LOCATE 0x2B // Locate (O)
  210698. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210699. #define SCSI_READ_POS 0x34 // Read Position (O)
  210700. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210701. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210702. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210703. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210704. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210705. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210706. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210707. //***************************************************************************
  210708. // %%% Commands Unique to Printer Devices %%%
  210709. //***************************************************************************
  210710. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210711. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210712. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210713. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210714. //***************************************************************************
  210715. // %%% Commands Unique to Processor Devices %%%
  210716. //***************************************************************************
  210717. #define SCSI_RECEIVE 0x08 // Receive (O)
  210718. #define SCSI_SEND 0x0A // Send (O)
  210719. //***************************************************************************
  210720. // %%% Commands Unique to Write-Once Devices %%%
  210721. //***************************************************************************
  210722. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210723. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210724. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210725. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210726. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210727. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210728. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210729. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210730. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210731. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210732. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210733. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210734. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210735. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210736. //***************************************************************************
  210737. // %%% Commands Unique to CD-ROM Devices %%%
  210738. //***************************************************************************
  210739. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210740. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210741. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210742. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210743. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210744. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210745. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210746. #define SCSI_READHEADER 0x44 // Read Header (O)
  210747. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210748. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210749. //***************************************************************************
  210750. // %%% Commands Unique to Scanner Devices %%%
  210751. //***************************************************************************
  210752. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210753. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210754. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210755. #define SCSI_SCAN 0x1B // Scan (O)
  210756. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210757. //***************************************************************************
  210758. // %%% Commands Unique to Optical Memory Devices %%%
  210759. //***************************************************************************
  210760. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210761. //***************************************************************************
  210762. // %%% Commands Unique to Medium Changer Devices %%%
  210763. //***************************************************************************
  210764. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210765. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210766. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210767. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210768. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210769. //***************************************************************************
  210770. // %%% Commands Unique to Communication Devices %%%
  210771. //***************************************************************************
  210772. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210773. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210774. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210775. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210776. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210777. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210778. //***************************************************************************
  210779. // %%% Request Sense Data Format %%%
  210780. //***************************************************************************
  210781. typedef struct {
  210782. BYTE ErrorCode; // Error Code (70H or 71H)
  210783. BYTE SegmentNum; // Number of current segment descriptor
  210784. BYTE SenseKey; // Sense Key(See bit definitions too)
  210785. BYTE InfoByte0; // Information MSB
  210786. BYTE InfoByte1; // Information MID
  210787. BYTE InfoByte2; // Information MID
  210788. BYTE InfoByte3; // Information LSB
  210789. BYTE AddSenLen; // Additional Sense Length
  210790. BYTE ComSpecInf0; // Command Specific Information MSB
  210791. BYTE ComSpecInf1; // Command Specific Information MID
  210792. BYTE ComSpecInf2; // Command Specific Information MID
  210793. BYTE ComSpecInf3; // Command Specific Information LSB
  210794. BYTE AddSenseCode; // Additional Sense Code
  210795. BYTE AddSenQual; // Additional Sense Code Qualifier
  210796. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210797. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210798. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210799. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210800. BYTE AddSenseBytes; // Additional Sense Bytes
  210801. } SENSE_DATA_FMT;
  210802. //***************************************************************************
  210803. // %%% REQUEST SENSE ERROR CODE %%%
  210804. //***************************************************************************
  210805. #define SERROR_CURRENT 0x70 // Current Errors
  210806. #define SERROR_DEFERED 0x71 // Deferred Errors
  210807. //***************************************************************************
  210808. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210809. //***************************************************************************
  210810. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210811. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210812. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210813. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210814. //***************************************************************************
  210815. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210816. //***************************************************************************
  210817. #define KEY_NOSENSE 0x00 // No Sense
  210818. #define KEY_RECERROR 0x01 // Recovered Error
  210819. #define KEY_NOTREADY 0x02 // Not Ready
  210820. #define KEY_MEDIUMERR 0x03 // Medium Error
  210821. #define KEY_HARDERROR 0x04 // Hardware Error
  210822. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210823. #define KEY_UNITATT 0x06 // Unit Attention
  210824. #define KEY_DATAPROT 0x07 // Data Protect
  210825. #define KEY_BLANKCHK 0x08 // Blank Check
  210826. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210827. #define KEY_COPYABORT 0x0A // Copy Abort
  210828. #define KEY_EQUAL 0x0C // Equal (Search)
  210829. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210830. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210831. #define KEY_RESERVED 0x0F // Reserved
  210832. //***************************************************************************
  210833. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210834. //***************************************************************************
  210835. #define DTYPE_DASD 0x00 // Disk Device
  210836. #define DTYPE_SEQD 0x01 // Tape Device
  210837. #define DTYPE_PRNT 0x02 // Printer
  210838. #define DTYPE_PROC 0x03 // Processor
  210839. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210840. #define DTYPE_CROM 0x05 // CD-ROM device
  210841. #define DTYPE_SCAN 0x06 // Scanner device
  210842. #define DTYPE_OPTI 0x07 // Optical memory device
  210843. #define DTYPE_JUKE 0x08 // Medium Changer device
  210844. #define DTYPE_COMM 0x09 // Communications device
  210845. #define DTYPE_RESL 0x0A // Reserved (low)
  210846. #define DTYPE_RESH 0x1E // Reserved (high)
  210847. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210848. //***************************************************************************
  210849. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210850. //***************************************************************************
  210851. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210852. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210853. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210854. #define ANSI_RESLO 0x3 // Reserved (low)
  210855. #define ANSI_RESHI 0x7 // Reserved (high)
  210856. typedef struct
  210857. {
  210858. USHORT Length;
  210859. UCHAR ScsiStatus;
  210860. UCHAR PathId;
  210861. UCHAR TargetId;
  210862. UCHAR Lun;
  210863. UCHAR CdbLength;
  210864. UCHAR SenseInfoLength;
  210865. UCHAR DataIn;
  210866. ULONG DataTransferLength;
  210867. ULONG TimeOutValue;
  210868. ULONG DataBufferOffset;
  210869. ULONG SenseInfoOffset;
  210870. UCHAR Cdb[16];
  210871. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210872. typedef struct
  210873. {
  210874. USHORT Length;
  210875. UCHAR ScsiStatus;
  210876. UCHAR PathId;
  210877. UCHAR TargetId;
  210878. UCHAR Lun;
  210879. UCHAR CdbLength;
  210880. UCHAR SenseInfoLength;
  210881. UCHAR DataIn;
  210882. ULONG DataTransferLength;
  210883. ULONG TimeOutValue;
  210884. PVOID DataBuffer;
  210885. ULONG SenseInfoOffset;
  210886. UCHAR Cdb[16];
  210887. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210888. typedef struct
  210889. {
  210890. SCSI_PASS_THROUGH_DIRECT spt;
  210891. ULONG Filler;
  210892. UCHAR ucSenseBuf[32];
  210893. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210894. typedef struct
  210895. {
  210896. ULONG Length;
  210897. UCHAR PortNumber;
  210898. UCHAR PathId;
  210899. UCHAR TargetId;
  210900. UCHAR Lun;
  210901. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210902. #define METHOD_BUFFERED 0
  210903. #define METHOD_IN_DIRECT 1
  210904. #define METHOD_OUT_DIRECT 2
  210905. #define METHOD_NEITHER 3
  210906. #define FILE_ANY_ACCESS 0
  210907. #ifndef FILE_READ_ACCESS
  210908. #define FILE_READ_ACCESS (0x0001)
  210909. #endif
  210910. #ifndef FILE_WRITE_ACCESS
  210911. #define FILE_WRITE_ACCESS (0x0002)
  210912. #endif
  210913. #define IOCTL_SCSI_BASE 0x00000004
  210914. #define SCSI_IOCTL_DATA_OUT 0
  210915. #define SCSI_IOCTL_DATA_IN 1
  210916. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210917. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210918. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210919. )
  210920. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210921. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210922. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210923. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210924. #define SENSE_LEN 14
  210925. #define SRB_DIR_SCSI 0x00
  210926. #define SRB_POSTING 0x01
  210927. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210928. #define SRB_DIR_IN 0x08
  210929. #define SRB_DIR_OUT 0x10
  210930. #define SRB_EVENT_NOTIFY 0x40
  210931. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210932. #define MAX_SRB_TIMEOUT 1080001u
  210933. #define DEFAULT_SRB_TIMEOUT 1080001u
  210934. #define SC_HA_INQUIRY 0x00
  210935. #define SC_GET_DEV_TYPE 0x01
  210936. #define SC_EXEC_SCSI_CMD 0x02
  210937. #define SC_ABORT_SRB 0x03
  210938. #define SC_RESET_DEV 0x04
  210939. #define SC_SET_HA_PARMS 0x05
  210940. #define SC_GET_DISK_INFO 0x06
  210941. #define SC_RESCAN_SCSI_BUS 0x07
  210942. #define SC_GETSET_TIMEOUTS 0x08
  210943. #define SS_PENDING 0x00
  210944. #define SS_COMP 0x01
  210945. #define SS_ABORTED 0x02
  210946. #define SS_ABORT_FAIL 0x03
  210947. #define SS_ERR 0x04
  210948. #define SS_INVALID_CMD 0x80
  210949. #define SS_INVALID_HA 0x81
  210950. #define SS_NO_DEVICE 0x82
  210951. #define SS_INVALID_SRB 0xE0
  210952. #define SS_OLD_MANAGER 0xE1
  210953. #define SS_BUFFER_ALIGN 0xE1
  210954. #define SS_ILLEGAL_MODE 0xE2
  210955. #define SS_NO_ASPI 0xE3
  210956. #define SS_FAILED_INIT 0xE4
  210957. #define SS_ASPI_IS_BUSY 0xE5
  210958. #define SS_BUFFER_TO_BIG 0xE6
  210959. #define SS_BUFFER_TOO_BIG 0xE6
  210960. #define SS_MISMATCHED_COMPONENTS 0xE7
  210961. #define SS_NO_ADAPTERS 0xE8
  210962. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210963. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210964. #define SS_BAD_INSTALL 0xEB
  210965. #define HASTAT_OK 0x00
  210966. #define HASTAT_SEL_TO 0x11
  210967. #define HASTAT_DO_DU 0x12
  210968. #define HASTAT_BUS_FREE 0x13
  210969. #define HASTAT_PHASE_ERR 0x14
  210970. #define HASTAT_TIMEOUT 0x09
  210971. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210972. #define HASTAT_MESSAGE_REJECT 0x0D
  210973. #define HASTAT_BUS_RESET 0x0E
  210974. #define HASTAT_PARITY_ERROR 0x0F
  210975. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210976. #define PACKED
  210977. #pragma pack(1)
  210978. typedef struct
  210979. {
  210980. BYTE SRB_Cmd;
  210981. BYTE SRB_Status;
  210982. BYTE SRB_HaID;
  210983. BYTE SRB_Flags;
  210984. DWORD SRB_Hdr_Rsvd;
  210985. BYTE HA_Count;
  210986. BYTE HA_SCSI_ID;
  210987. BYTE HA_ManagerId[16];
  210988. BYTE HA_Identifier[16];
  210989. BYTE HA_Unique[16];
  210990. WORD HA_Rsvd1;
  210991. BYTE pad[20];
  210992. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210993. typedef struct
  210994. {
  210995. BYTE SRB_Cmd;
  210996. BYTE SRB_Status;
  210997. BYTE SRB_HaID;
  210998. BYTE SRB_Flags;
  210999. DWORD SRB_Hdr_Rsvd;
  211000. BYTE SRB_Target;
  211001. BYTE SRB_Lun;
  211002. BYTE SRB_DeviceType;
  211003. BYTE SRB_Rsvd1;
  211004. BYTE pad[68];
  211005. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  211006. typedef struct
  211007. {
  211008. BYTE SRB_Cmd;
  211009. BYTE SRB_Status;
  211010. BYTE SRB_HaID;
  211011. BYTE SRB_Flags;
  211012. DWORD SRB_Hdr_Rsvd;
  211013. BYTE SRB_Target;
  211014. BYTE SRB_Lun;
  211015. WORD SRB_Rsvd1;
  211016. DWORD SRB_BufLen;
  211017. BYTE FAR *SRB_BufPointer;
  211018. BYTE SRB_SenseLen;
  211019. BYTE SRB_CDBLen;
  211020. BYTE SRB_HaStat;
  211021. BYTE SRB_TargStat;
  211022. VOID FAR *SRB_PostProc;
  211023. BYTE SRB_Rsvd2[20];
  211024. BYTE CDBByte[16];
  211025. BYTE SenseArea[SENSE_LEN+2];
  211026. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  211027. typedef struct
  211028. {
  211029. BYTE SRB_Cmd;
  211030. BYTE SRB_Status;
  211031. BYTE SRB_HaId;
  211032. BYTE SRB_Flags;
  211033. DWORD SRB_Hdr_Rsvd;
  211034. } PACKED SRB, *PSRB, FAR *LPSRB;
  211035. #pragma pack()
  211036. struct CDDeviceInfo
  211037. {
  211038. char vendor[9];
  211039. char productId[17];
  211040. char rev[5];
  211041. char vendorSpec[21];
  211042. BYTE ha;
  211043. BYTE tgt;
  211044. BYTE lun;
  211045. char scsiDriveLetter; // will be 0 if not using scsi
  211046. };
  211047. class CDReadBuffer
  211048. {
  211049. public:
  211050. int startFrame;
  211051. int numFrames;
  211052. int dataStartOffset;
  211053. int dataLength;
  211054. int bufferSize;
  211055. HeapBlock<BYTE> buffer;
  211056. int index;
  211057. bool wantsIndex;
  211058. CDReadBuffer (const int numberOfFrames)
  211059. : startFrame (0),
  211060. numFrames (0),
  211061. dataStartOffset (0),
  211062. dataLength (0),
  211063. bufferSize (2352 * numberOfFrames),
  211064. buffer (bufferSize),
  211065. index (0),
  211066. wantsIndex (false)
  211067. {
  211068. }
  211069. bool isZero() const throw()
  211070. {
  211071. BYTE* p = buffer + dataStartOffset;
  211072. for (int i = dataLength; --i >= 0;)
  211073. if (*p++ != 0)
  211074. return false;
  211075. return true;
  211076. }
  211077. };
  211078. class CDDeviceHandle;
  211079. class CDController
  211080. {
  211081. public:
  211082. CDController();
  211083. virtual ~CDController();
  211084. virtual bool read (CDReadBuffer* t) = 0;
  211085. virtual void shutDown();
  211086. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  211087. int getLastIndex();
  211088. public:
  211089. bool initialised;
  211090. CDDeviceHandle* deviceInfo;
  211091. int framesToCheck, framesOverlap;
  211092. void prepare (SRB_ExecSCSICmd& s);
  211093. void perform (SRB_ExecSCSICmd& s);
  211094. void setPaused (bool paused);
  211095. };
  211096. #pragma pack(1)
  211097. struct TOCTRACK
  211098. {
  211099. BYTE rsvd;
  211100. BYTE ADR;
  211101. BYTE trackNumber;
  211102. BYTE rsvd2;
  211103. BYTE addr[4];
  211104. };
  211105. struct TOC
  211106. {
  211107. WORD tocLen;
  211108. BYTE firstTrack;
  211109. BYTE lastTrack;
  211110. TOCTRACK tracks[100];
  211111. };
  211112. #pragma pack()
  211113. enum
  211114. {
  211115. READTYPE_ANY = 0,
  211116. READTYPE_ATAPI1 = 1,
  211117. READTYPE_ATAPI2 = 2,
  211118. READTYPE_READ6 = 3,
  211119. READTYPE_READ10 = 4,
  211120. READTYPE_READ_D8 = 5,
  211121. READTYPE_READ_D4 = 6,
  211122. READTYPE_READ_D4_1 = 7,
  211123. READTYPE_READ10_2 = 8
  211124. };
  211125. class CDDeviceHandle
  211126. {
  211127. public:
  211128. CDDeviceHandle (const CDDeviceInfo* const device)
  211129. : scsiHandle (0),
  211130. readType (READTYPE_ANY),
  211131. controller (0)
  211132. {
  211133. memcpy (&info, device, sizeof (info));
  211134. }
  211135. ~CDDeviceHandle()
  211136. {
  211137. if (controller != 0)
  211138. {
  211139. controller->shutDown();
  211140. controller = 0;
  211141. }
  211142. if (scsiHandle != 0)
  211143. CloseHandle (scsiHandle);
  211144. }
  211145. bool readTOC (TOC* lpToc);
  211146. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  211147. void openDrawer (bool shouldBeOpen);
  211148. CDDeviceInfo info;
  211149. HANDLE scsiHandle;
  211150. BYTE readType;
  211151. private:
  211152. ScopedPointer<CDController> controller;
  211153. bool testController (const int readType,
  211154. CDController* const newController,
  211155. CDReadBuffer* const bufferToUse);
  211156. };
  211157. DWORD (*fGetASPI32SupportInfo)(void);
  211158. DWORD (*fSendASPI32Command)(LPSRB);
  211159. static HINSTANCE winAspiLib = 0;
  211160. static bool usingScsi = false;
  211161. static bool initialised = false;
  211162. static bool InitialiseCDRipper()
  211163. {
  211164. if (! initialised)
  211165. {
  211166. initialised = true;
  211167. OSVERSIONINFO info;
  211168. info.dwOSVersionInfoSize = sizeof (info);
  211169. GetVersionEx (&info);
  211170. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  211171. if (! usingScsi)
  211172. {
  211173. fGetASPI32SupportInfo = 0;
  211174. fSendASPI32Command = 0;
  211175. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  211176. if (winAspiLib != 0)
  211177. {
  211178. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  211179. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  211180. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  211181. return false;
  211182. }
  211183. else
  211184. {
  211185. usingScsi = true;
  211186. }
  211187. }
  211188. }
  211189. return true;
  211190. }
  211191. static void DeinitialiseCDRipper()
  211192. {
  211193. if (winAspiLib != 0)
  211194. {
  211195. fGetASPI32SupportInfo = 0;
  211196. fSendASPI32Command = 0;
  211197. FreeLibrary (winAspiLib);
  211198. winAspiLib = 0;
  211199. }
  211200. initialised = false;
  211201. }
  211202. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211203. {
  211204. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  211205. OSVERSIONINFO info;
  211206. info.dwOSVersionInfoSize = sizeof (info);
  211207. GetVersionEx (&info);
  211208. DWORD flags = GENERIC_READ;
  211209. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211210. flags = GENERIC_READ | GENERIC_WRITE;
  211211. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211212. if (h == INVALID_HANDLE_VALUE)
  211213. {
  211214. flags ^= GENERIC_WRITE;
  211215. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211216. }
  211217. return h;
  211218. }
  211219. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  211220. const char driveLetter,
  211221. HANDLE& deviceHandle,
  211222. const bool retryOnFailure = true)
  211223. {
  211224. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211225. zerostruct (s);
  211226. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211227. s.spt.CdbLength = srb->SRB_CDBLen;
  211228. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211229. ? SCSI_IOCTL_DATA_IN
  211230. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211231. ? SCSI_IOCTL_DATA_OUT
  211232. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211233. s.spt.DataTransferLength = srb->SRB_BufLen;
  211234. s.spt.TimeOutValue = 5;
  211235. s.spt.DataBuffer = srb->SRB_BufPointer;
  211236. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211237. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211238. srb->SRB_Status = SS_ERR;
  211239. srb->SRB_TargStat = 0x0004;
  211240. DWORD bytesReturned = 0;
  211241. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211242. &s, sizeof (s),
  211243. &s, sizeof (s),
  211244. &bytesReturned, 0) != 0)
  211245. {
  211246. srb->SRB_Status = SS_COMP;
  211247. }
  211248. else if (retryOnFailure)
  211249. {
  211250. const DWORD error = GetLastError();
  211251. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211252. {
  211253. if (error != ERROR_INVALID_HANDLE)
  211254. CloseHandle (deviceHandle);
  211255. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211256. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211257. }
  211258. }
  211259. return srb->SRB_Status;
  211260. }
  211261. // Controller types..
  211262. class ControllerType1 : public CDController
  211263. {
  211264. public:
  211265. ControllerType1() {}
  211266. ~ControllerType1() {}
  211267. bool read (CDReadBuffer* rb)
  211268. {
  211269. if (rb->numFrames * 2352 > rb->bufferSize)
  211270. return false;
  211271. SRB_ExecSCSICmd s;
  211272. prepare (s);
  211273. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211274. s.SRB_BufLen = rb->bufferSize;
  211275. s.SRB_BufPointer = rb->buffer;
  211276. s.SRB_CDBLen = 12;
  211277. s.CDBByte[0] = 0xBE;
  211278. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211279. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211280. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211281. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211282. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211283. perform (s);
  211284. if (s.SRB_Status != SS_COMP)
  211285. return false;
  211286. rb->dataLength = rb->numFrames * 2352;
  211287. rb->dataStartOffset = 0;
  211288. return true;
  211289. }
  211290. };
  211291. class ControllerType2 : public CDController
  211292. {
  211293. public:
  211294. ControllerType2() {}
  211295. ~ControllerType2() {}
  211296. void shutDown()
  211297. {
  211298. if (initialised)
  211299. {
  211300. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211301. SRB_ExecSCSICmd s;
  211302. prepare (s);
  211303. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211304. s.SRB_BufLen = 0x0C;
  211305. s.SRB_BufPointer = bufPointer;
  211306. s.SRB_CDBLen = 6;
  211307. s.CDBByte[0] = 0x15;
  211308. s.CDBByte[4] = 0x0C;
  211309. perform (s);
  211310. }
  211311. }
  211312. bool init()
  211313. {
  211314. SRB_ExecSCSICmd s;
  211315. s.SRB_Status = SS_ERR;
  211316. if (deviceInfo->readType == READTYPE_READ10_2)
  211317. {
  211318. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211319. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211320. for (int i = 0; i < 2; ++i)
  211321. {
  211322. prepare (s);
  211323. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211324. s.SRB_BufLen = 0x14;
  211325. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211326. s.SRB_CDBLen = 6;
  211327. s.CDBByte[0] = 0x15;
  211328. s.CDBByte[1] = 0x10;
  211329. s.CDBByte[4] = 0x14;
  211330. perform (s);
  211331. if (s.SRB_Status != SS_COMP)
  211332. return false;
  211333. }
  211334. }
  211335. else
  211336. {
  211337. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211338. prepare (s);
  211339. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211340. s.SRB_BufLen = 0x0C;
  211341. s.SRB_BufPointer = bufPointer;
  211342. s.SRB_CDBLen = 6;
  211343. s.CDBByte[0] = 0x15;
  211344. s.CDBByte[4] = 0x0C;
  211345. perform (s);
  211346. }
  211347. return s.SRB_Status == SS_COMP;
  211348. }
  211349. bool read (CDReadBuffer* rb)
  211350. {
  211351. if (rb->numFrames * 2352 > rb->bufferSize)
  211352. return false;
  211353. if (!initialised)
  211354. {
  211355. initialised = init();
  211356. if (!initialised)
  211357. return false;
  211358. }
  211359. SRB_ExecSCSICmd s;
  211360. prepare (s);
  211361. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211362. s.SRB_BufLen = rb->bufferSize;
  211363. s.SRB_BufPointer = rb->buffer;
  211364. s.SRB_CDBLen = 10;
  211365. s.CDBByte[0] = 0x28;
  211366. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211367. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211368. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211369. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211370. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211371. perform (s);
  211372. if (s.SRB_Status != SS_COMP)
  211373. return false;
  211374. rb->dataLength = rb->numFrames * 2352;
  211375. rb->dataStartOffset = 0;
  211376. return true;
  211377. }
  211378. };
  211379. class ControllerType3 : public CDController
  211380. {
  211381. public:
  211382. ControllerType3() {}
  211383. ~ControllerType3() {}
  211384. bool read (CDReadBuffer* rb)
  211385. {
  211386. if (rb->numFrames * 2352 > rb->bufferSize)
  211387. return false;
  211388. if (!initialised)
  211389. {
  211390. setPaused (false);
  211391. initialised = true;
  211392. }
  211393. SRB_ExecSCSICmd s;
  211394. prepare (s);
  211395. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211396. s.SRB_BufLen = rb->numFrames * 2352;
  211397. s.SRB_BufPointer = rb->buffer;
  211398. s.SRB_CDBLen = 12;
  211399. s.CDBByte[0] = 0xD8;
  211400. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211401. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211402. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211403. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211404. perform (s);
  211405. if (s.SRB_Status != SS_COMP)
  211406. return false;
  211407. rb->dataLength = rb->numFrames * 2352;
  211408. rb->dataStartOffset = 0;
  211409. return true;
  211410. }
  211411. };
  211412. class ControllerType4 : public CDController
  211413. {
  211414. public:
  211415. ControllerType4() {}
  211416. ~ControllerType4() {}
  211417. bool selectD4Mode()
  211418. {
  211419. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211420. SRB_ExecSCSICmd s;
  211421. prepare (s);
  211422. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211423. s.SRB_CDBLen = 6;
  211424. s.SRB_BufLen = 12;
  211425. s.SRB_BufPointer = bufPointer;
  211426. s.CDBByte[0] = 0x15;
  211427. s.CDBByte[1] = 0x10;
  211428. s.CDBByte[4] = 0x08;
  211429. perform (s);
  211430. return s.SRB_Status == SS_COMP;
  211431. }
  211432. bool read (CDReadBuffer* rb)
  211433. {
  211434. if (rb->numFrames * 2352 > rb->bufferSize)
  211435. return false;
  211436. if (!initialised)
  211437. {
  211438. setPaused (true);
  211439. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211440. selectD4Mode();
  211441. initialised = true;
  211442. }
  211443. SRB_ExecSCSICmd s;
  211444. prepare (s);
  211445. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211446. s.SRB_BufLen = rb->bufferSize;
  211447. s.SRB_BufPointer = rb->buffer;
  211448. s.SRB_CDBLen = 10;
  211449. s.CDBByte[0] = 0xD4;
  211450. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211451. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211452. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211453. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211454. perform (s);
  211455. if (s.SRB_Status != SS_COMP)
  211456. return false;
  211457. rb->dataLength = rb->numFrames * 2352;
  211458. rb->dataStartOffset = 0;
  211459. return true;
  211460. }
  211461. };
  211462. CDController::CDController() : initialised (false)
  211463. {
  211464. }
  211465. CDController::~CDController()
  211466. {
  211467. }
  211468. void CDController::prepare (SRB_ExecSCSICmd& s)
  211469. {
  211470. zerostruct (s);
  211471. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211472. s.SRB_HaID = deviceInfo->info.ha;
  211473. s.SRB_Target = deviceInfo->info.tgt;
  211474. s.SRB_Lun = deviceInfo->info.lun;
  211475. s.SRB_SenseLen = SENSE_LEN;
  211476. }
  211477. void CDController::perform (SRB_ExecSCSICmd& s)
  211478. {
  211479. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211480. s.SRB_PostProc = event;
  211481. ResetEvent (event);
  211482. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211483. deviceInfo->info.scsiDriveLetter,
  211484. deviceInfo->scsiHandle)
  211485. : fSendASPI32Command ((LPSRB)&s);
  211486. if (status == SS_PENDING)
  211487. WaitForSingleObject (event, 4000);
  211488. CloseHandle (event);
  211489. }
  211490. void CDController::setPaused (bool paused)
  211491. {
  211492. SRB_ExecSCSICmd s;
  211493. prepare (s);
  211494. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211495. s.SRB_CDBLen = 10;
  211496. s.CDBByte[0] = 0x4B;
  211497. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211498. perform (s);
  211499. }
  211500. void CDController::shutDown()
  211501. {
  211502. }
  211503. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211504. {
  211505. if (overlapBuffer != 0)
  211506. {
  211507. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211508. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211509. if (doJitter
  211510. && overlapBuffer->startFrame > 0
  211511. && overlapBuffer->numFrames > 0
  211512. && overlapBuffer->dataLength > 0)
  211513. {
  211514. const int numFrames = rb->numFrames;
  211515. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211516. {
  211517. rb->startFrame -= framesOverlap;
  211518. if (framesToCheck < framesOverlap
  211519. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211520. rb->numFrames += framesOverlap;
  211521. }
  211522. else
  211523. {
  211524. overlapBuffer->dataLength = 0;
  211525. overlapBuffer->startFrame = 0;
  211526. overlapBuffer->numFrames = 0;
  211527. }
  211528. }
  211529. if (! read (rb))
  211530. return false;
  211531. if (doJitter)
  211532. {
  211533. const int checkLen = framesToCheck * 2352;
  211534. const int maxToCheck = rb->dataLength - checkLen;
  211535. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211536. return true;
  211537. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211538. bool found = false;
  211539. for (int i = 0; i < maxToCheck; ++i)
  211540. {
  211541. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211542. {
  211543. i += checkLen;
  211544. rb->dataStartOffset = i;
  211545. rb->dataLength -= i;
  211546. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211547. found = true;
  211548. break;
  211549. }
  211550. }
  211551. rb->numFrames = rb->dataLength / 2352;
  211552. rb->dataLength = 2352 * rb->numFrames;
  211553. if (!found)
  211554. return false;
  211555. }
  211556. if (canDoJitter)
  211557. {
  211558. memcpy (overlapBuffer->buffer,
  211559. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211560. 2352 * framesToCheck);
  211561. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211562. overlapBuffer->numFrames = framesToCheck;
  211563. overlapBuffer->dataLength = 2352 * framesToCheck;
  211564. overlapBuffer->dataStartOffset = 0;
  211565. }
  211566. else
  211567. {
  211568. overlapBuffer->startFrame = 0;
  211569. overlapBuffer->numFrames = 0;
  211570. overlapBuffer->dataLength = 0;
  211571. }
  211572. return true;
  211573. }
  211574. else
  211575. {
  211576. return read (rb);
  211577. }
  211578. }
  211579. int CDController::getLastIndex()
  211580. {
  211581. char qdata[100];
  211582. SRB_ExecSCSICmd s;
  211583. prepare (s);
  211584. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211585. s.SRB_BufLen = sizeof (qdata);
  211586. s.SRB_BufPointer = (BYTE*)qdata;
  211587. s.SRB_CDBLen = 12;
  211588. s.CDBByte[0] = 0x42;
  211589. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211590. s.CDBByte[2] = 64;
  211591. s.CDBByte[3] = 1; // get current position
  211592. s.CDBByte[7] = 0;
  211593. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211594. perform (s);
  211595. if (s.SRB_Status == SS_COMP)
  211596. return qdata[7];
  211597. return 0;
  211598. }
  211599. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211600. {
  211601. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211602. SRB_ExecSCSICmd s;
  211603. zerostruct (s);
  211604. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211605. s.SRB_HaID = info.ha;
  211606. s.SRB_Target = info.tgt;
  211607. s.SRB_Lun = info.lun;
  211608. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211609. s.SRB_BufLen = 0x324;
  211610. s.SRB_BufPointer = (BYTE*)lpToc;
  211611. s.SRB_SenseLen = 0x0E;
  211612. s.SRB_CDBLen = 0x0A;
  211613. s.SRB_PostProc = event;
  211614. s.CDBByte[0] = 0x43;
  211615. s.CDBByte[1] = 0x00;
  211616. s.CDBByte[7] = 0x03;
  211617. s.CDBByte[8] = 0x24;
  211618. ResetEvent (event);
  211619. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211620. : fSendASPI32Command ((LPSRB)&s);
  211621. if (status == SS_PENDING)
  211622. WaitForSingleObject (event, 4000);
  211623. CloseHandle (event);
  211624. return (s.SRB_Status == SS_COMP);
  211625. }
  211626. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211627. CDReadBuffer* const overlapBuffer)
  211628. {
  211629. if (controller == 0)
  211630. {
  211631. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211632. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211633. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211634. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211635. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211636. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211637. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211638. }
  211639. buffer->index = 0;
  211640. if ((controller != 0)
  211641. && controller->readAudio (buffer, overlapBuffer))
  211642. {
  211643. if (buffer->wantsIndex)
  211644. buffer->index = controller->getLastIndex();
  211645. return true;
  211646. }
  211647. return false;
  211648. }
  211649. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211650. {
  211651. if (shouldBeOpen)
  211652. {
  211653. if (controller != 0)
  211654. {
  211655. controller->shutDown();
  211656. controller = 0;
  211657. }
  211658. if (scsiHandle != 0)
  211659. {
  211660. CloseHandle (scsiHandle);
  211661. scsiHandle = 0;
  211662. }
  211663. }
  211664. SRB_ExecSCSICmd s;
  211665. zerostruct (s);
  211666. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211667. s.SRB_HaID = info.ha;
  211668. s.SRB_Target = info.tgt;
  211669. s.SRB_Lun = info.lun;
  211670. s.SRB_SenseLen = SENSE_LEN;
  211671. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211672. s.SRB_BufLen = 0;
  211673. s.SRB_BufPointer = 0;
  211674. s.SRB_CDBLen = 12;
  211675. s.CDBByte[0] = 0x1b;
  211676. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211677. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211678. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211679. s.SRB_PostProc = event;
  211680. ResetEvent (event);
  211681. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211682. : fSendASPI32Command ((LPSRB)&s);
  211683. if (status == SS_PENDING)
  211684. WaitForSingleObject (event, 4000);
  211685. CloseHandle (event);
  211686. }
  211687. bool CDDeviceHandle::testController (const int type,
  211688. CDController* const newController,
  211689. CDReadBuffer* const rb)
  211690. {
  211691. controller = newController;
  211692. readType = (BYTE)type;
  211693. controller->deviceInfo = this;
  211694. controller->framesToCheck = 1;
  211695. controller->framesOverlap = 3;
  211696. bool passed = false;
  211697. memset (rb->buffer, 0xcd, rb->bufferSize);
  211698. if (controller->read (rb))
  211699. {
  211700. passed = true;
  211701. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211702. int wrong = 0;
  211703. for (int i = rb->dataLength / 4; --i >= 0;)
  211704. {
  211705. if (*p++ == (int) 0xcdcdcdcd)
  211706. {
  211707. if (++wrong == 4)
  211708. {
  211709. passed = false;
  211710. break;
  211711. }
  211712. }
  211713. else
  211714. {
  211715. wrong = 0;
  211716. }
  211717. }
  211718. }
  211719. if (! passed)
  211720. {
  211721. controller->shutDown();
  211722. controller = 0;
  211723. }
  211724. return passed;
  211725. }
  211726. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211727. {
  211728. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211729. const int bufSize = 128;
  211730. BYTE buffer[bufSize];
  211731. zeromem (buffer, bufSize);
  211732. SRB_ExecSCSICmd s;
  211733. zerostruct (s);
  211734. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211735. s.SRB_HaID = ha;
  211736. s.SRB_Target = tgt;
  211737. s.SRB_Lun = lun;
  211738. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211739. s.SRB_BufLen = bufSize;
  211740. s.SRB_BufPointer = buffer;
  211741. s.SRB_SenseLen = SENSE_LEN;
  211742. s.SRB_CDBLen = 6;
  211743. s.SRB_PostProc = event;
  211744. s.CDBByte[0] = SCSI_INQUIRY;
  211745. s.CDBByte[4] = 100;
  211746. ResetEvent (event);
  211747. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211748. WaitForSingleObject (event, 4000);
  211749. CloseHandle (event);
  211750. if (s.SRB_Status == SS_COMP)
  211751. {
  211752. memcpy (dev->vendor, &buffer[8], 8);
  211753. memcpy (dev->productId, &buffer[16], 16);
  211754. memcpy (dev->rev, &buffer[32], 4);
  211755. memcpy (dev->vendorSpec, &buffer[36], 20);
  211756. }
  211757. }
  211758. static int FindCDDevices (CDDeviceInfo* const list,
  211759. int maxItems)
  211760. {
  211761. int count = 0;
  211762. if (usingScsi)
  211763. {
  211764. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211765. {
  211766. TCHAR drivePath[8];
  211767. drivePath[0] = driveLetter;
  211768. drivePath[1] = ':';
  211769. drivePath[2] = '\\';
  211770. drivePath[3] = 0;
  211771. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211772. {
  211773. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211774. if (h != INVALID_HANDLE_VALUE)
  211775. {
  211776. BYTE buffer[100], passThroughStruct[1024];
  211777. zeromem (buffer, sizeof (buffer));
  211778. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211779. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211780. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211781. p->spt.CdbLength = 6;
  211782. p->spt.SenseInfoLength = 24;
  211783. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211784. p->spt.DataTransferLength = 100;
  211785. p->spt.TimeOutValue = 2;
  211786. p->spt.DataBuffer = buffer;
  211787. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211788. p->spt.Cdb[0] = 0x12;
  211789. p->spt.Cdb[4] = 100;
  211790. DWORD bytesReturned = 0;
  211791. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211792. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211793. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211794. &bytesReturned, 0) != 0)
  211795. {
  211796. zeromem (&list[count], sizeof (CDDeviceInfo));
  211797. list[count].scsiDriveLetter = driveLetter;
  211798. memcpy (list[count].vendor, &buffer[8], 8);
  211799. memcpy (list[count].productId, &buffer[16], 16);
  211800. memcpy (list[count].rev, &buffer[32], 4);
  211801. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211802. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211803. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211804. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211805. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211806. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211807. &bytesReturned, 0) != 0)
  211808. {
  211809. list[count].ha = scsiAddr->PortNumber;
  211810. list[count].tgt = scsiAddr->TargetId;
  211811. list[count].lun = scsiAddr->Lun;
  211812. ++count;
  211813. }
  211814. }
  211815. CloseHandle (h);
  211816. }
  211817. }
  211818. }
  211819. }
  211820. else
  211821. {
  211822. const DWORD d = fGetASPI32SupportInfo();
  211823. BYTE status = HIBYTE (LOWORD (d));
  211824. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211825. return 0;
  211826. const int numAdapters = LOBYTE (LOWORD (d));
  211827. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211828. {
  211829. SRB_HAInquiry s;
  211830. zerostruct (s);
  211831. s.SRB_Cmd = SC_HA_INQUIRY;
  211832. s.SRB_HaID = ha;
  211833. fSendASPI32Command ((LPSRB)&s);
  211834. if (s.SRB_Status == SS_COMP)
  211835. {
  211836. maxItems = (int)s.HA_Unique[3];
  211837. if (maxItems == 0)
  211838. maxItems = 8;
  211839. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211840. {
  211841. for (BYTE lun = 0; lun < 8; ++lun)
  211842. {
  211843. SRB_GDEVBlock sb;
  211844. zerostruct (sb);
  211845. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211846. sb.SRB_HaID = ha;
  211847. sb.SRB_Target = tgt;
  211848. sb.SRB_Lun = lun;
  211849. fSendASPI32Command ((LPSRB) &sb);
  211850. if (sb.SRB_Status == SS_COMP
  211851. && sb.SRB_DeviceType == DTYPE_CROM)
  211852. {
  211853. zeromem (&list[count], sizeof (CDDeviceInfo));
  211854. list[count].ha = ha;
  211855. list[count].tgt = tgt;
  211856. list[count].lun = lun;
  211857. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211858. ++count;
  211859. }
  211860. }
  211861. }
  211862. }
  211863. }
  211864. }
  211865. return count;
  211866. }
  211867. static int ripperUsers = 0;
  211868. static bool initialisedOk = false;
  211869. class DeinitialiseTimer : private Timer,
  211870. private DeletedAtShutdown
  211871. {
  211872. DeinitialiseTimer (const DeinitialiseTimer&);
  211873. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211874. public:
  211875. DeinitialiseTimer()
  211876. {
  211877. startTimer (4000);
  211878. }
  211879. ~DeinitialiseTimer()
  211880. {
  211881. if (--ripperUsers == 0)
  211882. DeinitialiseCDRipper();
  211883. }
  211884. void timerCallback()
  211885. {
  211886. delete this;
  211887. }
  211888. juce_UseDebuggingNewOperator
  211889. };
  211890. static void incUserCount()
  211891. {
  211892. if (ripperUsers++ == 0)
  211893. initialisedOk = InitialiseCDRipper();
  211894. }
  211895. static void decUserCount()
  211896. {
  211897. new DeinitialiseTimer();
  211898. }
  211899. struct CDDeviceWrapper
  211900. {
  211901. ScopedPointer<CDDeviceHandle> cdH;
  211902. ScopedPointer<CDReadBuffer> overlapBuffer;
  211903. bool jitter;
  211904. };
  211905. static int getAddressOf (const TOCTRACK* const t)
  211906. {
  211907. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211908. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211909. }
  211910. static const int samplesPerFrame = 44100 / 75;
  211911. static const int bytesPerFrame = samplesPerFrame * 4;
  211912. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211913. {
  211914. SRB_GDEVBlock s;
  211915. zerostruct (s);
  211916. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211917. s.SRB_HaID = device->ha;
  211918. s.SRB_Target = device->tgt;
  211919. s.SRB_Lun = device->lun;
  211920. if (usingScsi)
  211921. {
  211922. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211923. if (h != INVALID_HANDLE_VALUE)
  211924. {
  211925. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211926. cdh->scsiHandle = h;
  211927. return cdh;
  211928. }
  211929. }
  211930. else
  211931. {
  211932. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211933. && s.SRB_DeviceType == DTYPE_CROM)
  211934. {
  211935. return new CDDeviceHandle (device);
  211936. }
  211937. }
  211938. return 0;
  211939. }
  211940. }
  211941. const StringArray AudioCDReader::getAvailableCDNames()
  211942. {
  211943. using namespace CDReaderHelpers;
  211944. StringArray results;
  211945. incUserCount();
  211946. if (initialisedOk)
  211947. {
  211948. CDDeviceInfo list[8];
  211949. const int num = FindCDDevices (list, 8);
  211950. decUserCount();
  211951. for (int i = 0; i < num; ++i)
  211952. {
  211953. String s;
  211954. if (list[i].scsiDriveLetter > 0)
  211955. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211956. s << String (list[i].vendor).trim()
  211957. << ' ' << String (list[i].productId).trim()
  211958. << ' ' << String (list[i].rev).trim();
  211959. results.add (s);
  211960. }
  211961. }
  211962. return results;
  211963. }
  211964. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211965. {
  211966. using namespace CDReaderHelpers;
  211967. incUserCount();
  211968. if (initialisedOk)
  211969. {
  211970. CDDeviceInfo list[8];
  211971. const int num = FindCDDevices (list, 8);
  211972. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211973. {
  211974. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211975. if (handle != 0)
  211976. {
  211977. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211978. d->cdH = handle;
  211979. d->overlapBuffer = new CDReadBuffer(3);
  211980. return new AudioCDReader (d);
  211981. }
  211982. }
  211983. }
  211984. decUserCount();
  211985. return 0;
  211986. }
  211987. AudioCDReader::AudioCDReader (void* handle_)
  211988. : AudioFormatReader (0, "CD Audio"),
  211989. handle (handle_),
  211990. indexingEnabled (false),
  211991. lastIndex (0),
  211992. firstFrameInBuffer (0),
  211993. samplesInBuffer (0)
  211994. {
  211995. using namespace CDReaderHelpers;
  211996. jassert (handle_ != 0);
  211997. refreshTrackLengths();
  211998. sampleRate = 44100.0;
  211999. bitsPerSample = 16;
  212000. numChannels = 2;
  212001. usesFloatingPointData = false;
  212002. buffer.setSize (4 * bytesPerFrame, true);
  212003. }
  212004. AudioCDReader::~AudioCDReader()
  212005. {
  212006. using namespace CDReaderHelpers;
  212007. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212008. delete device;
  212009. decUserCount();
  212010. }
  212011. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  212012. int64 startSampleInFile, int numSamples)
  212013. {
  212014. using namespace CDReaderHelpers;
  212015. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212016. bool ok = true;
  212017. while (numSamples > 0)
  212018. {
  212019. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  212020. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  212021. if (startSampleInFile >= bufferStartSample
  212022. && startSampleInFile < bufferEndSample)
  212023. {
  212024. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  212025. int* const l = destSamples[0] + startOffsetInDestBuffer;
  212026. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  212027. const short* src = (const short*) buffer.getData();
  212028. src += 2 * (startSampleInFile - bufferStartSample);
  212029. for (int i = 0; i < toDo; ++i)
  212030. {
  212031. l[i] = src [i << 1] << 16;
  212032. if (r != 0)
  212033. r[i] = src [(i << 1) + 1] << 16;
  212034. }
  212035. startOffsetInDestBuffer += toDo;
  212036. startSampleInFile += toDo;
  212037. numSamples -= toDo;
  212038. }
  212039. else
  212040. {
  212041. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  212042. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  212043. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  212044. {
  212045. device->overlapBuffer->dataLength = 0;
  212046. device->overlapBuffer->startFrame = 0;
  212047. device->overlapBuffer->numFrames = 0;
  212048. device->jitter = false;
  212049. }
  212050. firstFrameInBuffer = frameNeeded;
  212051. lastIndex = 0;
  212052. CDReadBuffer readBuffer (framesInBuffer + 4);
  212053. readBuffer.wantsIndex = indexingEnabled;
  212054. int i;
  212055. for (i = 5; --i >= 0;)
  212056. {
  212057. readBuffer.startFrame = frameNeeded;
  212058. readBuffer.numFrames = framesInBuffer;
  212059. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  212060. break;
  212061. else
  212062. device->overlapBuffer->dataLength = 0;
  212063. }
  212064. if (i >= 0)
  212065. {
  212066. memcpy ((char*) buffer.getData(),
  212067. readBuffer.buffer + readBuffer.dataStartOffset,
  212068. readBuffer.dataLength);
  212069. samplesInBuffer = readBuffer.dataLength >> 2;
  212070. lastIndex = readBuffer.index;
  212071. }
  212072. else
  212073. {
  212074. int* l = destSamples[0] + startOffsetInDestBuffer;
  212075. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  212076. while (--numSamples >= 0)
  212077. {
  212078. *l++ = 0;
  212079. if (r != 0)
  212080. *r++ = 0;
  212081. }
  212082. // sometimes the read fails for just the very last couple of blocks, so
  212083. // we'll ignore and errors in the last half-second of the disk..
  212084. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  212085. break;
  212086. }
  212087. }
  212088. }
  212089. return ok;
  212090. }
  212091. bool AudioCDReader::isCDStillPresent() const
  212092. {
  212093. using namespace CDReaderHelpers;
  212094. TOC toc;
  212095. zerostruct (toc);
  212096. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  212097. }
  212098. void AudioCDReader::refreshTrackLengths()
  212099. {
  212100. using namespace CDReaderHelpers;
  212101. trackStartSamples.clear();
  212102. zeromem (audioTracks, sizeof (audioTracks));
  212103. TOC toc;
  212104. zerostruct (toc);
  212105. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  212106. {
  212107. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  212108. for (int i = 0; i <= numTracks; ++i)
  212109. {
  212110. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  212111. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  212112. }
  212113. }
  212114. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  212115. }
  212116. bool AudioCDReader::isTrackAudio (int trackNum) const
  212117. {
  212118. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  212119. }
  212120. void AudioCDReader::enableIndexScanning (bool b)
  212121. {
  212122. indexingEnabled = b;
  212123. }
  212124. int AudioCDReader::getLastIndex() const
  212125. {
  212126. return lastIndex;
  212127. }
  212128. const int framesPerIndexRead = 4;
  212129. int AudioCDReader::getIndexAt (int samplePos)
  212130. {
  212131. using namespace CDReaderHelpers;
  212132. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212133. const int frameNeeded = samplePos / samplesPerFrame;
  212134. device->overlapBuffer->dataLength = 0;
  212135. device->overlapBuffer->startFrame = 0;
  212136. device->overlapBuffer->numFrames = 0;
  212137. device->jitter = false;
  212138. firstFrameInBuffer = 0;
  212139. lastIndex = 0;
  212140. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  212141. readBuffer.wantsIndex = true;
  212142. int i;
  212143. for (i = 5; --i >= 0;)
  212144. {
  212145. readBuffer.startFrame = frameNeeded;
  212146. readBuffer.numFrames = framesPerIndexRead;
  212147. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212148. break;
  212149. }
  212150. if (i >= 0)
  212151. return readBuffer.index;
  212152. return -1;
  212153. }
  212154. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  212155. {
  212156. using namespace CDReaderHelpers;
  212157. Array <int> indexes;
  212158. const int trackStart = getPositionOfTrackStart (trackNumber);
  212159. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  212160. bool needToScan = true;
  212161. if (trackEnd - trackStart > 20 * 44100)
  212162. {
  212163. // check the end of the track for indexes before scanning the whole thing
  212164. needToScan = false;
  212165. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  212166. bool seenAnIndex = false;
  212167. while (pos <= trackEnd - samplesPerFrame)
  212168. {
  212169. const int index = getIndexAt (pos);
  212170. if (index == 0)
  212171. {
  212172. // lead-out, so skip back a bit if we've not found any indexes yet..
  212173. if (seenAnIndex)
  212174. break;
  212175. pos -= 44100 * 5;
  212176. if (pos < trackStart)
  212177. break;
  212178. }
  212179. else
  212180. {
  212181. if (index > 0)
  212182. seenAnIndex = true;
  212183. if (index > 1)
  212184. {
  212185. needToScan = true;
  212186. break;
  212187. }
  212188. pos += samplesPerFrame * framesPerIndexRead;
  212189. }
  212190. }
  212191. }
  212192. if (needToScan)
  212193. {
  212194. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212195. int pos = trackStart;
  212196. int last = -1;
  212197. while (pos < trackEnd - samplesPerFrame * 10)
  212198. {
  212199. const int frameNeeded = pos / samplesPerFrame;
  212200. device->overlapBuffer->dataLength = 0;
  212201. device->overlapBuffer->startFrame = 0;
  212202. device->overlapBuffer->numFrames = 0;
  212203. device->jitter = false;
  212204. firstFrameInBuffer = 0;
  212205. CDReadBuffer readBuffer (4);
  212206. readBuffer.wantsIndex = true;
  212207. int i;
  212208. for (i = 5; --i >= 0;)
  212209. {
  212210. readBuffer.startFrame = frameNeeded;
  212211. readBuffer.numFrames = framesPerIndexRead;
  212212. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212213. break;
  212214. }
  212215. if (i < 0)
  212216. break;
  212217. if (readBuffer.index > last && readBuffer.index > 1)
  212218. {
  212219. last = readBuffer.index;
  212220. indexes.add (pos);
  212221. }
  212222. pos += samplesPerFrame * framesPerIndexRead;
  212223. }
  212224. indexes.removeValue (trackStart);
  212225. }
  212226. return indexes;
  212227. }
  212228. void AudioCDReader::ejectDisk()
  212229. {
  212230. using namespace CDReaderHelpers;
  212231. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212232. }
  212233. #endif
  212234. #if JUCE_USE_CDBURNER
  212235. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212236. {
  212237. CoInitialize (0);
  212238. IDiscMaster* dm;
  212239. IDiscRecorder* result = 0;
  212240. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212241. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212242. IID_IDiscMaster,
  212243. (void**) &dm)))
  212244. {
  212245. if (SUCCEEDED (dm->Open()))
  212246. {
  212247. IEnumDiscRecorders* drEnum = 0;
  212248. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212249. {
  212250. IDiscRecorder* dr = 0;
  212251. DWORD dummy;
  212252. int index = 0;
  212253. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212254. {
  212255. if (indexToOpen == index)
  212256. {
  212257. result = dr;
  212258. break;
  212259. }
  212260. else if (list != 0)
  212261. {
  212262. BSTR path;
  212263. if (SUCCEEDED (dr->GetPath (&path)))
  212264. list->add ((const WCHAR*) path);
  212265. }
  212266. ++index;
  212267. dr->Release();
  212268. }
  212269. drEnum->Release();
  212270. }
  212271. if (master == 0)
  212272. dm->Close();
  212273. }
  212274. if (master != 0)
  212275. *master = dm;
  212276. else
  212277. dm->Release();
  212278. }
  212279. return result;
  212280. }
  212281. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212282. public Timer
  212283. {
  212284. public:
  212285. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212286. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212287. listener (0), progress (0), shouldCancel (false)
  212288. {
  212289. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212290. jassert (SUCCEEDED (hr));
  212291. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212292. //jassert (SUCCEEDED (hr));
  212293. lastState = getDiskState();
  212294. startTimer (2000);
  212295. }
  212296. ~Pimpl() {}
  212297. void releaseObjects()
  212298. {
  212299. discRecorder->Close();
  212300. if (redbook != 0)
  212301. redbook->Release();
  212302. discRecorder->Release();
  212303. discMaster->Release();
  212304. Release();
  212305. }
  212306. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212307. {
  212308. if (listener != 0 && ! shouldCancel)
  212309. shouldCancel = listener->audioCDBurnProgress (progress);
  212310. *pbCancel = shouldCancel;
  212311. return S_OK;
  212312. }
  212313. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212314. {
  212315. progress = nCompleted / (float) nTotal;
  212316. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212317. return E_NOTIMPL;
  212318. }
  212319. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212320. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212321. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212322. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212323. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212324. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212325. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212326. class ScopedDiscOpener
  212327. {
  212328. public:
  212329. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212330. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212331. private:
  212332. Pimpl& pimpl;
  212333. ScopedDiscOpener (const ScopedDiscOpener&);
  212334. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212335. };
  212336. DiskState getDiskState()
  212337. {
  212338. const ScopedDiscOpener opener (*this);
  212339. long type, flags;
  212340. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212341. if (FAILED (hr))
  212342. return unknown;
  212343. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212344. return writableDiskPresent;
  212345. if (type == 0)
  212346. return noDisc;
  212347. else
  212348. return readOnlyDiskPresent;
  212349. }
  212350. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212351. {
  212352. ComSmartPtr<IPropertyStorage> prop;
  212353. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212354. return defaultReturn;
  212355. PROPSPEC iPropSpec;
  212356. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212357. iPropSpec.lpwstr = name;
  212358. PROPVARIANT iPropVariant;
  212359. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212360. ? defaultReturn : (int) iPropVariant.lVal;
  212361. }
  212362. bool setIntProperty (const LPOLESTR name, const int value) const
  212363. {
  212364. ComSmartPtr<IPropertyStorage> prop;
  212365. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212366. return false;
  212367. PROPSPEC iPropSpec;
  212368. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212369. iPropSpec.lpwstr = name;
  212370. PROPVARIANT iPropVariant;
  212371. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212372. return false;
  212373. iPropVariant.lVal = (long) value;
  212374. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212375. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212376. }
  212377. void timerCallback()
  212378. {
  212379. const DiskState state = getDiskState();
  212380. if (state != lastState)
  212381. {
  212382. lastState = state;
  212383. owner.sendChangeMessage (&owner);
  212384. }
  212385. }
  212386. AudioCDBurner& owner;
  212387. DiskState lastState;
  212388. IDiscMaster* discMaster;
  212389. IDiscRecorder* discRecorder;
  212390. IRedbookDiscMaster* redbook;
  212391. AudioCDBurner::BurnProgressListener* listener;
  212392. float progress;
  212393. bool shouldCancel;
  212394. };
  212395. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212396. {
  212397. IDiscMaster* discMaster = 0;
  212398. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212399. if (discRecorder != 0)
  212400. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212401. }
  212402. AudioCDBurner::~AudioCDBurner()
  212403. {
  212404. if (pimpl != 0)
  212405. pimpl.release()->releaseObjects();
  212406. }
  212407. const StringArray AudioCDBurner::findAvailableDevices()
  212408. {
  212409. StringArray devs;
  212410. enumCDBurners (&devs, -1, 0);
  212411. return devs;
  212412. }
  212413. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212414. {
  212415. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212416. if (b->pimpl == 0)
  212417. b = 0;
  212418. return b.release();
  212419. }
  212420. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212421. {
  212422. return pimpl->getDiskState();
  212423. }
  212424. bool AudioCDBurner::isDiskPresent() const
  212425. {
  212426. return getDiskState() == writableDiskPresent;
  212427. }
  212428. bool AudioCDBurner::openTray()
  212429. {
  212430. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212431. return SUCCEEDED (pimpl->discRecorder->Eject());
  212432. }
  212433. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212434. {
  212435. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212436. DiskState oldState = getDiskState();
  212437. DiskState newState = oldState;
  212438. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212439. {
  212440. newState = getDiskState();
  212441. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212442. }
  212443. return newState;
  212444. }
  212445. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212446. {
  212447. Array<int> results;
  212448. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212449. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212450. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212451. if (speeds[i] <= maxSpeed)
  212452. results.add (speeds[i]);
  212453. results.addIfNotAlreadyThere (maxSpeed);
  212454. return results;
  212455. }
  212456. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212457. {
  212458. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212459. return false;
  212460. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212461. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212462. }
  212463. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212464. {
  212465. long blocksFree = 0;
  212466. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212467. return blocksFree;
  212468. }
  212469. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212470. bool performFakeBurnForTesting, int writeSpeed)
  212471. {
  212472. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212473. pimpl->listener = listener;
  212474. pimpl->progress = 0;
  212475. pimpl->shouldCancel = false;
  212476. UINT_PTR cookie;
  212477. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212478. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212479. ejectDiscAfterwards);
  212480. String error;
  212481. if (hr != S_OK)
  212482. {
  212483. const char* e = "Couldn't open or write to the CD device";
  212484. if (hr == IMAPI_E_USERABORT)
  212485. e = "User cancelled the write operation";
  212486. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212487. e = "No Disk present";
  212488. error = e;
  212489. }
  212490. pimpl->discMaster->ProgressUnadvise (cookie);
  212491. pimpl->listener = 0;
  212492. return error;
  212493. }
  212494. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212495. {
  212496. if (audioSource == 0)
  212497. return false;
  212498. ScopedPointer<AudioSource> source (audioSource);
  212499. long bytesPerBlock;
  212500. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212501. const int samplesPerBlock = bytesPerBlock / 4;
  212502. bool ok = true;
  212503. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212504. HeapBlock <byte> buffer (bytesPerBlock);
  212505. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212506. int samplesDone = 0;
  212507. source->prepareToPlay (samplesPerBlock, 44100.0);
  212508. while (ok)
  212509. {
  212510. {
  212511. AudioSourceChannelInfo info;
  212512. info.buffer = &sourceBuffer;
  212513. info.numSamples = samplesPerBlock;
  212514. info.startSample = 0;
  212515. sourceBuffer.clear();
  212516. source->getNextAudioBlock (info);
  212517. }
  212518. zeromem (buffer, bytesPerBlock);
  212519. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212520. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212521. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212522. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212523. CDSampleFormat left (buffer, 2);
  212524. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212525. CDSampleFormat right (buffer + 2, 2);
  212526. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212527. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212528. if (FAILED (hr))
  212529. ok = false;
  212530. samplesDone += samplesPerBlock;
  212531. if (samplesDone >= numSamples)
  212532. break;
  212533. }
  212534. hr = pimpl->redbook->CloseAudioTrack();
  212535. return ok && hr == S_OK;
  212536. }
  212537. #endif
  212538. #endif
  212539. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212540. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212541. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212542. // compiled on its own).
  212543. #if JUCE_INCLUDED_FILE
  212544. class MidiInCollector
  212545. {
  212546. public:
  212547. MidiInCollector (MidiInput* const input_,
  212548. MidiInputCallback& callback_)
  212549. : deviceHandle (0),
  212550. input (input_),
  212551. callback (callback_),
  212552. concatenator (4096),
  212553. isStarted (false),
  212554. startTime (0)
  212555. {
  212556. }
  212557. ~MidiInCollector()
  212558. {
  212559. stop();
  212560. if (deviceHandle != 0)
  212561. {
  212562. int count = 5;
  212563. while (--count >= 0)
  212564. {
  212565. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212566. break;
  212567. Sleep (20);
  212568. }
  212569. }
  212570. }
  212571. void handleMessage (const uint32 message, const uint32 timeStamp)
  212572. {
  212573. if ((message & 0xff) >= 0x80 && isStarted)
  212574. {
  212575. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212576. writeFinishedBlocks();
  212577. }
  212578. }
  212579. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212580. {
  212581. if (isStarted)
  212582. {
  212583. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212584. writeFinishedBlocks();
  212585. }
  212586. }
  212587. void start()
  212588. {
  212589. jassert (deviceHandle != 0);
  212590. if (deviceHandle != 0 && ! isStarted)
  212591. {
  212592. activeMidiCollectors.addIfNotAlreadyThere (this);
  212593. for (int i = 0; i < (int) numHeaders; ++i)
  212594. headers[i].write (deviceHandle);
  212595. startTime = Time::getMillisecondCounter();
  212596. MMRESULT res = midiInStart (deviceHandle);
  212597. if (res == MMSYSERR_NOERROR)
  212598. {
  212599. concatenator.reset();
  212600. isStarted = true;
  212601. }
  212602. else
  212603. {
  212604. unprepareAllHeaders();
  212605. }
  212606. }
  212607. }
  212608. void stop()
  212609. {
  212610. if (isStarted)
  212611. {
  212612. isStarted = false;
  212613. midiInReset (deviceHandle);
  212614. midiInStop (deviceHandle);
  212615. activeMidiCollectors.removeValue (this);
  212616. unprepareAllHeaders();
  212617. concatenator.reset();
  212618. }
  212619. }
  212620. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212621. {
  212622. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212623. if (activeMidiCollectors.contains (collector))
  212624. {
  212625. if (uMsg == MIM_DATA)
  212626. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212627. else if (uMsg == MIM_LONGDATA)
  212628. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212629. }
  212630. }
  212631. juce_UseDebuggingNewOperator
  212632. HMIDIIN deviceHandle;
  212633. private:
  212634. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212635. MidiInput* input;
  212636. MidiInputCallback& callback;
  212637. MidiDataConcatenator concatenator;
  212638. bool volatile isStarted;
  212639. uint32 startTime;
  212640. class MidiHeader
  212641. {
  212642. public:
  212643. MidiHeader()
  212644. {
  212645. zerostruct (hdr);
  212646. hdr.lpData = data;
  212647. hdr.dwBufferLength = numElementsInArray (data);
  212648. }
  212649. void write (HMIDIIN deviceHandle)
  212650. {
  212651. hdr.dwBytesRecorded = 0;
  212652. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212653. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212654. }
  212655. void writeIfFinished (HMIDIIN deviceHandle)
  212656. {
  212657. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212658. {
  212659. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212660. (void) res;
  212661. write (deviceHandle);
  212662. }
  212663. }
  212664. void unprepare (HMIDIIN deviceHandle)
  212665. {
  212666. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212667. {
  212668. int c = 10;
  212669. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212670. Thread::sleep (20);
  212671. jassert (c >= 0);
  212672. }
  212673. }
  212674. private:
  212675. MIDIHDR hdr;
  212676. char data [256];
  212677. MidiHeader (const MidiHeader&);
  212678. MidiHeader& operator= (const MidiHeader&);
  212679. };
  212680. enum { numHeaders = 32 };
  212681. MidiHeader headers [numHeaders];
  212682. void writeFinishedBlocks()
  212683. {
  212684. for (int i = 0; i < (int) numHeaders; ++i)
  212685. headers[i].writeIfFinished (deviceHandle);
  212686. }
  212687. void unprepareAllHeaders()
  212688. {
  212689. for (int i = 0; i < (int) numHeaders; ++i)
  212690. headers[i].unprepare (deviceHandle);
  212691. }
  212692. double convertTimeStamp (uint32 timeStamp)
  212693. {
  212694. timeStamp += startTime;
  212695. const uint32 now = Time::getMillisecondCounter();
  212696. if (timeStamp > now)
  212697. {
  212698. if (timeStamp > now + 2)
  212699. --startTime;
  212700. timeStamp = now;
  212701. }
  212702. return timeStamp * 0.001;
  212703. }
  212704. MidiInCollector (const MidiInCollector&);
  212705. MidiInCollector& operator= (const MidiInCollector&);
  212706. };
  212707. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212708. const StringArray MidiInput::getDevices()
  212709. {
  212710. StringArray s;
  212711. const int num = midiInGetNumDevs();
  212712. for (int i = 0; i < num; ++i)
  212713. {
  212714. MIDIINCAPS mc;
  212715. zerostruct (mc);
  212716. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212717. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212718. }
  212719. return s;
  212720. }
  212721. int MidiInput::getDefaultDeviceIndex()
  212722. {
  212723. return 0;
  212724. }
  212725. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212726. {
  212727. if (callback == 0)
  212728. return 0;
  212729. UINT deviceId = MIDI_MAPPER;
  212730. int n = 0;
  212731. String name;
  212732. const int num = midiInGetNumDevs();
  212733. for (int i = 0; i < num; ++i)
  212734. {
  212735. MIDIINCAPS mc;
  212736. zerostruct (mc);
  212737. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212738. {
  212739. if (index == n)
  212740. {
  212741. deviceId = i;
  212742. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212743. break;
  212744. }
  212745. ++n;
  212746. }
  212747. }
  212748. ScopedPointer <MidiInput> in (new MidiInput (name));
  212749. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212750. HMIDIIN h;
  212751. HRESULT err = midiInOpen (&h, deviceId,
  212752. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212753. (DWORD_PTR) (MidiInCollector*) collector,
  212754. CALLBACK_FUNCTION);
  212755. if (err == MMSYSERR_NOERROR)
  212756. {
  212757. collector->deviceHandle = h;
  212758. in->internal = collector.release();
  212759. return in.release();
  212760. }
  212761. return 0;
  212762. }
  212763. MidiInput::MidiInput (const String& name_)
  212764. : name (name_),
  212765. internal (0)
  212766. {
  212767. }
  212768. MidiInput::~MidiInput()
  212769. {
  212770. delete static_cast <MidiInCollector*> (internal);
  212771. }
  212772. void MidiInput::start()
  212773. {
  212774. static_cast <MidiInCollector*> (internal)->start();
  212775. }
  212776. void MidiInput::stop()
  212777. {
  212778. static_cast <MidiInCollector*> (internal)->stop();
  212779. }
  212780. struct MidiOutHandle
  212781. {
  212782. int refCount;
  212783. UINT deviceId;
  212784. HMIDIOUT handle;
  212785. static Array<MidiOutHandle*> activeHandles;
  212786. juce_UseDebuggingNewOperator
  212787. };
  212788. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212789. const StringArray MidiOutput::getDevices()
  212790. {
  212791. StringArray s;
  212792. const int num = midiOutGetNumDevs();
  212793. for (int i = 0; i < num; ++i)
  212794. {
  212795. MIDIOUTCAPS mc;
  212796. zerostruct (mc);
  212797. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212798. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212799. }
  212800. return s;
  212801. }
  212802. int MidiOutput::getDefaultDeviceIndex()
  212803. {
  212804. const int num = midiOutGetNumDevs();
  212805. int n = 0;
  212806. for (int i = 0; i < num; ++i)
  212807. {
  212808. MIDIOUTCAPS mc;
  212809. zerostruct (mc);
  212810. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212811. {
  212812. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212813. return n;
  212814. ++n;
  212815. }
  212816. }
  212817. return 0;
  212818. }
  212819. MidiOutput* MidiOutput::openDevice (int index)
  212820. {
  212821. UINT deviceId = MIDI_MAPPER;
  212822. const int num = midiOutGetNumDevs();
  212823. int i, n = 0;
  212824. for (i = 0; i < num; ++i)
  212825. {
  212826. MIDIOUTCAPS mc;
  212827. zerostruct (mc);
  212828. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212829. {
  212830. // use the microsoft sw synth as a default - best not to allow deviceId
  212831. // to be MIDI_MAPPER, or else device sharing breaks
  212832. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212833. deviceId = i;
  212834. if (index == n)
  212835. {
  212836. deviceId = i;
  212837. break;
  212838. }
  212839. ++n;
  212840. }
  212841. }
  212842. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212843. {
  212844. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212845. if (han != 0 && han->deviceId == deviceId)
  212846. {
  212847. han->refCount++;
  212848. MidiOutput* const out = new MidiOutput();
  212849. out->internal = han;
  212850. return out;
  212851. }
  212852. }
  212853. for (i = 4; --i >= 0;)
  212854. {
  212855. HMIDIOUT h = 0;
  212856. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212857. if (res == MMSYSERR_NOERROR)
  212858. {
  212859. MidiOutHandle* const han = new MidiOutHandle();
  212860. han->deviceId = deviceId;
  212861. han->refCount = 1;
  212862. han->handle = h;
  212863. MidiOutHandle::activeHandles.add (han);
  212864. MidiOutput* const out = new MidiOutput();
  212865. out->internal = han;
  212866. return out;
  212867. }
  212868. else if (res == MMSYSERR_ALLOCATED)
  212869. {
  212870. Sleep (100);
  212871. }
  212872. else
  212873. {
  212874. break;
  212875. }
  212876. }
  212877. return 0;
  212878. }
  212879. MidiOutput::~MidiOutput()
  212880. {
  212881. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212882. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212883. {
  212884. midiOutClose (h->handle);
  212885. MidiOutHandle::activeHandles.removeValue (h);
  212886. delete h;
  212887. }
  212888. }
  212889. void MidiOutput::reset()
  212890. {
  212891. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212892. midiOutReset (h->handle);
  212893. }
  212894. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212895. {
  212896. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212897. DWORD n;
  212898. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212899. {
  212900. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212901. rightVol = nn[0] / (float) 0xffff;
  212902. leftVol = nn[1] / (float) 0xffff;
  212903. return true;
  212904. }
  212905. else
  212906. {
  212907. rightVol = leftVol = 1.0f;
  212908. return false;
  212909. }
  212910. }
  212911. void MidiOutput::setVolume (float leftVol, float rightVol)
  212912. {
  212913. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212914. DWORD n;
  212915. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212916. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212917. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212918. midiOutSetVolume (handle->handle, n);
  212919. }
  212920. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212921. {
  212922. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212923. if (message.getRawDataSize() > 3
  212924. || message.isSysEx())
  212925. {
  212926. MIDIHDR h;
  212927. zerostruct (h);
  212928. h.lpData = (char*) message.getRawData();
  212929. h.dwBufferLength = message.getRawDataSize();
  212930. h.dwBytesRecorded = message.getRawDataSize();
  212931. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212932. {
  212933. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212934. if (res == MMSYSERR_NOERROR)
  212935. {
  212936. while ((h.dwFlags & MHDR_DONE) == 0)
  212937. Sleep (1);
  212938. int count = 500; // 1 sec timeout
  212939. while (--count >= 0)
  212940. {
  212941. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212942. if (res == MIDIERR_STILLPLAYING)
  212943. Sleep (2);
  212944. else
  212945. break;
  212946. }
  212947. }
  212948. }
  212949. }
  212950. else
  212951. {
  212952. midiOutShortMsg (handle->handle,
  212953. *(unsigned int*) message.getRawData());
  212954. }
  212955. }
  212956. #endif
  212957. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212958. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212959. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212960. // compiled on its own).
  212961. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212962. #undef WINDOWS
  212963. // #define ASIO_DEBUGGING 1
  212964. #if ASIO_DEBUGGING
  212965. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212966. #else
  212967. #define log(a) {}
  212968. #endif
  212969. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212970. to be pretty random about whether or not they do this. If you hit an error using these functions
  212971. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212972. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212973. */
  212974. #define JUCE_ASIOCALLBACK __cdecl
  212975. #if ASIO_DEBUGGING
  212976. static void logError (const String& context, long error)
  212977. {
  212978. String err ("unknown error");
  212979. if (error == ASE_NotPresent) err = "Not Present";
  212980. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212981. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212982. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212983. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212984. else if (error == ASE_NoClock) err = "No Clock";
  212985. else if (error == ASE_NoMemory) err = "Out of memory";
  212986. log ("!!error: " + context + " - " + err);
  212987. }
  212988. #else
  212989. #define logError(a, b) {}
  212990. #endif
  212991. class ASIOAudioIODevice;
  212992. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212993. static const int maxASIOChannels = 160;
  212994. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212995. private Timer
  212996. {
  212997. public:
  212998. Component ourWindow;
  212999. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  213000. const String& optionalDllForDirectLoading_)
  213001. : AudioIODevice (name_, "ASIO"),
  213002. asioObject (0),
  213003. classId (classId_),
  213004. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  213005. currentBitDepth (16),
  213006. currentSampleRate (0),
  213007. isOpen_ (false),
  213008. isStarted (false),
  213009. postOutput (true),
  213010. insideControlPanelModalLoop (false),
  213011. shouldUsePreferredSize (false)
  213012. {
  213013. name = name_;
  213014. ourWindow.addToDesktop (0);
  213015. windowHandle = ourWindow.getWindowHandle();
  213016. jassert (currentASIODev [slotNumber] == 0);
  213017. currentASIODev [slotNumber] = this;
  213018. openDevice();
  213019. }
  213020. ~ASIOAudioIODevice()
  213021. {
  213022. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213023. if (currentASIODev[i] == this)
  213024. currentASIODev[i] = 0;
  213025. close();
  213026. log ("ASIO - exiting");
  213027. removeCurrentDriver();
  213028. }
  213029. void updateSampleRates()
  213030. {
  213031. // find a list of sample rates..
  213032. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  213033. sampleRates.clear();
  213034. if (asioObject != 0)
  213035. {
  213036. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  213037. {
  213038. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  213039. if (err == 0)
  213040. {
  213041. sampleRates.add ((int) possibleSampleRates[index]);
  213042. log ("rate: " + String ((int) possibleSampleRates[index]));
  213043. }
  213044. else if (err != ASE_NoClock)
  213045. {
  213046. logError ("CanSampleRate", err);
  213047. }
  213048. }
  213049. if (sampleRates.size() == 0)
  213050. {
  213051. double cr = 0;
  213052. const long err = asioObject->getSampleRate (&cr);
  213053. log ("No sample rates supported - current rate: " + String ((int) cr));
  213054. if (err == 0)
  213055. sampleRates.add ((int) cr);
  213056. }
  213057. }
  213058. }
  213059. const StringArray getOutputChannelNames() { return outputChannelNames; }
  213060. const StringArray getInputChannelNames() { return inputChannelNames; }
  213061. int getNumSampleRates() { return sampleRates.size(); }
  213062. double getSampleRate (int index) { return sampleRates [index]; }
  213063. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  213064. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  213065. int getDefaultBufferSize() { return preferredSize; }
  213066. const String open (const BigInteger& inputChannels,
  213067. const BigInteger& outputChannels,
  213068. double sr,
  213069. int bufferSizeSamples)
  213070. {
  213071. close();
  213072. currentCallback = 0;
  213073. if (bufferSizeSamples <= 0)
  213074. shouldUsePreferredSize = true;
  213075. if (asioObject == 0 || ! isASIOOpen)
  213076. {
  213077. log ("Warning: device not open");
  213078. const String err (openDevice());
  213079. if (asioObject == 0 || ! isASIOOpen)
  213080. return err;
  213081. }
  213082. isStarted = false;
  213083. bufferIndex = -1;
  213084. long err = 0;
  213085. long newPreferredSize = 0;
  213086. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  213087. minSize = 0;
  213088. maxSize = 0;
  213089. newPreferredSize = 0;
  213090. granularity = 0;
  213091. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  213092. {
  213093. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  213094. shouldUsePreferredSize = true;
  213095. preferredSize = newPreferredSize;
  213096. }
  213097. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  213098. // dynamic changes to the buffer size...
  213099. shouldUsePreferredSize = shouldUsePreferredSize
  213100. || getName().containsIgnoreCase ("Digidesign");
  213101. if (shouldUsePreferredSize)
  213102. {
  213103. log ("Using preferred size for buffer..");
  213104. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213105. {
  213106. bufferSizeSamples = preferredSize;
  213107. }
  213108. else
  213109. {
  213110. bufferSizeSamples = 1024;
  213111. logError ("GetBufferSize1", err);
  213112. }
  213113. shouldUsePreferredSize = false;
  213114. }
  213115. int sampleRate = roundDoubleToInt (sr);
  213116. currentSampleRate = sampleRate;
  213117. currentBlockSizeSamples = bufferSizeSamples;
  213118. currentChansOut.clear();
  213119. currentChansIn.clear();
  213120. zeromem (inBuffers, sizeof (inBuffers));
  213121. zeromem (outBuffers, sizeof (outBuffers));
  213122. updateSampleRates();
  213123. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  213124. sampleRate = sampleRates[0];
  213125. jassert (sampleRate != 0);
  213126. if (sampleRate == 0)
  213127. sampleRate = 44100;
  213128. long numSources = 32;
  213129. ASIOClockSource clocks[32];
  213130. zeromem (clocks, sizeof (clocks));
  213131. asioObject->getClockSources (clocks, &numSources);
  213132. bool isSourceSet = false;
  213133. // careful not to remove this loop because it does more than just logging!
  213134. int i;
  213135. for (i = 0; i < numSources; ++i)
  213136. {
  213137. String s ("clock: ");
  213138. s += clocks[i].name;
  213139. if (clocks[i].isCurrentSource)
  213140. {
  213141. isSourceSet = true;
  213142. s << " (cur)";
  213143. }
  213144. log (s);
  213145. }
  213146. if (numSources > 1 && ! isSourceSet)
  213147. {
  213148. log ("setting clock source");
  213149. asioObject->setClockSource (clocks[0].index);
  213150. Thread::sleep (20);
  213151. }
  213152. else
  213153. {
  213154. if (numSources == 0)
  213155. {
  213156. log ("ASIO - no clock sources!");
  213157. }
  213158. }
  213159. double cr = 0;
  213160. err = asioObject->getSampleRate (&cr);
  213161. if (err == 0)
  213162. {
  213163. currentSampleRate = cr;
  213164. }
  213165. else
  213166. {
  213167. logError ("GetSampleRate", err);
  213168. currentSampleRate = 0;
  213169. }
  213170. error = String::empty;
  213171. needToReset = false;
  213172. isReSync = false;
  213173. err = 0;
  213174. bool buffersCreated = false;
  213175. if (currentSampleRate != sampleRate)
  213176. {
  213177. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  213178. err = asioObject->setSampleRate (sampleRate);
  213179. if (err == ASE_NoClock && numSources > 0)
  213180. {
  213181. log ("trying to set a clock source..");
  213182. Thread::sleep (10);
  213183. err = asioObject->setClockSource (clocks[0].index);
  213184. if (err != 0)
  213185. {
  213186. logError ("SetClock", err);
  213187. }
  213188. Thread::sleep (10);
  213189. err = asioObject->setSampleRate (sampleRate);
  213190. }
  213191. }
  213192. if (err == 0)
  213193. {
  213194. currentSampleRate = sampleRate;
  213195. if (needToReset)
  213196. {
  213197. if (isReSync)
  213198. {
  213199. log ("Resync request");
  213200. }
  213201. log ("! Resetting ASIO after sample rate change");
  213202. removeCurrentDriver();
  213203. loadDriver();
  213204. const String error (initDriver());
  213205. if (error.isNotEmpty())
  213206. {
  213207. log ("ASIOInit: " + error);
  213208. }
  213209. needToReset = false;
  213210. isReSync = false;
  213211. }
  213212. numActiveInputChans = 0;
  213213. numActiveOutputChans = 0;
  213214. ASIOBufferInfo* info = bufferInfos;
  213215. int i;
  213216. for (i = 0; i < totalNumInputChans; ++i)
  213217. {
  213218. if (inputChannels[i])
  213219. {
  213220. currentChansIn.setBit (i);
  213221. info->isInput = 1;
  213222. info->channelNum = i;
  213223. info->buffers[0] = info->buffers[1] = 0;
  213224. ++info;
  213225. ++numActiveInputChans;
  213226. }
  213227. }
  213228. for (i = 0; i < totalNumOutputChans; ++i)
  213229. {
  213230. if (outputChannels[i])
  213231. {
  213232. currentChansOut.setBit (i);
  213233. info->isInput = 0;
  213234. info->channelNum = i;
  213235. info->buffers[0] = info->buffers[1] = 0;
  213236. ++info;
  213237. ++numActiveOutputChans;
  213238. }
  213239. }
  213240. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213241. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213242. if (currentASIODev[0] == this)
  213243. {
  213244. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213245. callbacks.asioMessage = &asioMessagesCallback0;
  213246. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213247. }
  213248. else if (currentASIODev[1] == this)
  213249. {
  213250. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213251. callbacks.asioMessage = &asioMessagesCallback1;
  213252. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213253. }
  213254. else if (currentASIODev[2] == this)
  213255. {
  213256. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213257. callbacks.asioMessage = &asioMessagesCallback2;
  213258. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213259. }
  213260. else
  213261. {
  213262. jassertfalse;
  213263. }
  213264. log ("disposing buffers");
  213265. err = asioObject->disposeBuffers();
  213266. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213267. err = asioObject->createBuffers (bufferInfos,
  213268. totalBuffers,
  213269. currentBlockSizeSamples,
  213270. &callbacks);
  213271. if (err != 0)
  213272. {
  213273. currentBlockSizeSamples = preferredSize;
  213274. logError ("create buffers 2", err);
  213275. asioObject->disposeBuffers();
  213276. err = asioObject->createBuffers (bufferInfos,
  213277. totalBuffers,
  213278. currentBlockSizeSamples,
  213279. &callbacks);
  213280. }
  213281. if (err == 0)
  213282. {
  213283. buffersCreated = true;
  213284. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213285. int n = 0;
  213286. Array <int> types;
  213287. currentBitDepth = 16;
  213288. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213289. {
  213290. if (inputChannels[i])
  213291. {
  213292. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213293. ASIOChannelInfo channelInfo;
  213294. zerostruct (channelInfo);
  213295. channelInfo.channel = i;
  213296. channelInfo.isInput = 1;
  213297. asioObject->getChannelInfo (&channelInfo);
  213298. types.addIfNotAlreadyThere (channelInfo.type);
  213299. typeToFormatParameters (channelInfo.type,
  213300. inputChannelBitDepths[n],
  213301. inputChannelBytesPerSample[n],
  213302. inputChannelIsFloat[n],
  213303. inputChannelLittleEndian[n]);
  213304. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213305. ++n;
  213306. }
  213307. }
  213308. jassert (numActiveInputChans == n);
  213309. n = 0;
  213310. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213311. {
  213312. if (outputChannels[i])
  213313. {
  213314. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213315. ASIOChannelInfo channelInfo;
  213316. zerostruct (channelInfo);
  213317. channelInfo.channel = i;
  213318. channelInfo.isInput = 0;
  213319. asioObject->getChannelInfo (&channelInfo);
  213320. types.addIfNotAlreadyThere (channelInfo.type);
  213321. typeToFormatParameters (channelInfo.type,
  213322. outputChannelBitDepths[n],
  213323. outputChannelBytesPerSample[n],
  213324. outputChannelIsFloat[n],
  213325. outputChannelLittleEndian[n]);
  213326. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213327. ++n;
  213328. }
  213329. }
  213330. jassert (numActiveOutputChans == n);
  213331. for (i = types.size(); --i >= 0;)
  213332. {
  213333. log ("channel format: " + String (types[i]));
  213334. }
  213335. jassert (n <= totalBuffers);
  213336. for (i = 0; i < numActiveOutputChans; ++i)
  213337. {
  213338. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213339. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213340. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213341. {
  213342. log ("!! Null buffers");
  213343. }
  213344. else
  213345. {
  213346. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213347. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213348. }
  213349. }
  213350. inputLatency = outputLatency = 0;
  213351. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213352. {
  213353. log ("ASIO - no latencies");
  213354. }
  213355. else
  213356. {
  213357. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213358. }
  213359. isOpen_ = true;
  213360. log ("starting ASIO");
  213361. calledback = false;
  213362. err = asioObject->start();
  213363. if (err != 0)
  213364. {
  213365. isOpen_ = false;
  213366. log ("ASIO - stop on failure");
  213367. Thread::sleep (10);
  213368. asioObject->stop();
  213369. error = "Can't start device";
  213370. Thread::sleep (10);
  213371. }
  213372. else
  213373. {
  213374. int count = 300;
  213375. while (--count > 0 && ! calledback)
  213376. Thread::sleep (10);
  213377. isStarted = true;
  213378. if (! calledback)
  213379. {
  213380. error = "Device didn't start correctly";
  213381. log ("ASIO didn't callback - stopping..");
  213382. asioObject->stop();
  213383. }
  213384. }
  213385. }
  213386. else
  213387. {
  213388. error = "Can't create i/o buffers";
  213389. }
  213390. }
  213391. else
  213392. {
  213393. error = "Can't set sample rate: ";
  213394. error << sampleRate;
  213395. }
  213396. if (error.isNotEmpty())
  213397. {
  213398. logError (error, err);
  213399. if (asioObject != 0 && buffersCreated)
  213400. asioObject->disposeBuffers();
  213401. Thread::sleep (20);
  213402. isStarted = false;
  213403. isOpen_ = false;
  213404. const String errorCopy (error);
  213405. close(); // (this resets the error string)
  213406. error = errorCopy;
  213407. }
  213408. needToReset = false;
  213409. isReSync = false;
  213410. return error;
  213411. }
  213412. void close()
  213413. {
  213414. error = String::empty;
  213415. stopTimer();
  213416. stop();
  213417. if (isASIOOpen && isOpen_)
  213418. {
  213419. const ScopedLock sl (callbackLock);
  213420. isOpen_ = false;
  213421. isStarted = false;
  213422. needToReset = false;
  213423. isReSync = false;
  213424. log ("ASIO - stopping");
  213425. if (asioObject != 0)
  213426. {
  213427. Thread::sleep (20);
  213428. asioObject->stop();
  213429. Thread::sleep (10);
  213430. asioObject->disposeBuffers();
  213431. }
  213432. Thread::sleep (10);
  213433. }
  213434. }
  213435. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  213436. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  213437. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  213438. double getCurrentSampleRate() { return currentSampleRate; }
  213439. int getCurrentBitDepth() { return currentBitDepth; }
  213440. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  213441. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  213442. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  213443. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  213444. void start (AudioIODeviceCallback* callback)
  213445. {
  213446. if (callback != 0)
  213447. {
  213448. callback->audioDeviceAboutToStart (this);
  213449. const ScopedLock sl (callbackLock);
  213450. currentCallback = callback;
  213451. }
  213452. }
  213453. void stop()
  213454. {
  213455. AudioIODeviceCallback* const lastCallback = currentCallback;
  213456. {
  213457. const ScopedLock sl (callbackLock);
  213458. currentCallback = 0;
  213459. }
  213460. if (lastCallback != 0)
  213461. lastCallback->audioDeviceStopped();
  213462. }
  213463. const String getLastError() { return error; }
  213464. bool hasControlPanel() const { return true; }
  213465. bool showControlPanel()
  213466. {
  213467. log ("ASIO - showing control panel");
  213468. Component modalWindow (String::empty);
  213469. modalWindow.setOpaque (true);
  213470. modalWindow.addToDesktop (0);
  213471. modalWindow.enterModalState();
  213472. bool done = false;
  213473. JUCE_TRY
  213474. {
  213475. // are there are devices that need to be closed before showing their control panel?
  213476. // close();
  213477. insideControlPanelModalLoop = true;
  213478. const uint32 started = Time::getMillisecondCounter();
  213479. if (asioObject != 0)
  213480. {
  213481. asioObject->controlPanel();
  213482. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213483. log ("spent: " + String (spent));
  213484. if (spent > 300)
  213485. {
  213486. shouldUsePreferredSize = true;
  213487. done = true;
  213488. }
  213489. }
  213490. }
  213491. JUCE_CATCH_ALL
  213492. insideControlPanelModalLoop = false;
  213493. return done;
  213494. }
  213495. void resetRequest() throw()
  213496. {
  213497. needToReset = true;
  213498. }
  213499. void resyncRequest() throw()
  213500. {
  213501. needToReset = true;
  213502. isReSync = true;
  213503. }
  213504. void timerCallback()
  213505. {
  213506. if (! insideControlPanelModalLoop)
  213507. {
  213508. stopTimer();
  213509. // used to cause a reset
  213510. log ("! ASIO restart request!");
  213511. if (isOpen_)
  213512. {
  213513. AudioIODeviceCallback* const oldCallback = currentCallback;
  213514. close();
  213515. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213516. currentSampleRate, currentBlockSizeSamples);
  213517. if (oldCallback != 0)
  213518. start (oldCallback);
  213519. }
  213520. }
  213521. else
  213522. {
  213523. startTimer (100);
  213524. }
  213525. }
  213526. juce_UseDebuggingNewOperator
  213527. private:
  213528. IASIO* volatile asioObject;
  213529. ASIOCallbacks callbacks;
  213530. void* windowHandle;
  213531. CLSID classId;
  213532. const String optionalDllForDirectLoading;
  213533. String error;
  213534. long totalNumInputChans, totalNumOutputChans;
  213535. StringArray inputChannelNames, outputChannelNames;
  213536. Array<int> sampleRates, bufferSizes;
  213537. long inputLatency, outputLatency;
  213538. long minSize, maxSize, preferredSize, granularity;
  213539. int volatile currentBlockSizeSamples;
  213540. int volatile currentBitDepth;
  213541. double volatile currentSampleRate;
  213542. BigInteger currentChansOut, currentChansIn;
  213543. AudioIODeviceCallback* volatile currentCallback;
  213544. CriticalSection callbackLock;
  213545. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213546. float* inBuffers [maxASIOChannels];
  213547. float* outBuffers [maxASIOChannels];
  213548. int inputChannelBitDepths [maxASIOChannels];
  213549. int outputChannelBitDepths [maxASIOChannels];
  213550. int inputChannelBytesPerSample [maxASIOChannels];
  213551. int outputChannelBytesPerSample [maxASIOChannels];
  213552. bool inputChannelIsFloat [maxASIOChannels];
  213553. bool outputChannelIsFloat [maxASIOChannels];
  213554. bool inputChannelLittleEndian [maxASIOChannels];
  213555. bool outputChannelLittleEndian [maxASIOChannels];
  213556. WaitableEvent event1;
  213557. HeapBlock <float> tempBuffer;
  213558. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213559. bool isOpen_, isStarted;
  213560. bool volatile isASIOOpen;
  213561. bool volatile calledback;
  213562. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213563. bool volatile insideControlPanelModalLoop;
  213564. bool volatile shouldUsePreferredSize;
  213565. void removeCurrentDriver()
  213566. {
  213567. if (asioObject != 0)
  213568. {
  213569. asioObject->Release();
  213570. asioObject = 0;
  213571. }
  213572. }
  213573. bool loadDriver()
  213574. {
  213575. removeCurrentDriver();
  213576. JUCE_TRY
  213577. {
  213578. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213579. classId, (void**) &asioObject) == S_OK)
  213580. {
  213581. return true;
  213582. }
  213583. // If a class isn't registered but we have a path for it, we can fallback to
  213584. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213585. if (optionalDllForDirectLoading.isNotEmpty())
  213586. {
  213587. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213588. if (h != 0)
  213589. {
  213590. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213591. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213592. if (dllGetClassObject != 0)
  213593. {
  213594. IClassFactory* classFactory = 0;
  213595. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213596. if (classFactory != 0)
  213597. {
  213598. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213599. classFactory->Release();
  213600. }
  213601. return asioObject != 0;
  213602. }
  213603. }
  213604. }
  213605. }
  213606. JUCE_CATCH_ALL
  213607. asioObject = 0;
  213608. return false;
  213609. }
  213610. const String initDriver()
  213611. {
  213612. if (asioObject != 0)
  213613. {
  213614. char buffer [256];
  213615. zeromem (buffer, sizeof (buffer));
  213616. if (! asioObject->init (windowHandle))
  213617. {
  213618. asioObject->getErrorMessage (buffer);
  213619. return String (buffer, sizeof (buffer) - 1);
  213620. }
  213621. // just in case any daft drivers expect this to be called..
  213622. asioObject->getDriverName (buffer);
  213623. return String::empty;
  213624. }
  213625. return "No Driver";
  213626. }
  213627. const String openDevice()
  213628. {
  213629. // use this in case the driver starts opening dialog boxes..
  213630. Component modalWindow (String::empty);
  213631. modalWindow.setOpaque (true);
  213632. modalWindow.addToDesktop (0);
  213633. modalWindow.enterModalState();
  213634. // open the device and get its info..
  213635. log ("opening ASIO device: " + getName());
  213636. needToReset = false;
  213637. isReSync = false;
  213638. outputChannelNames.clear();
  213639. inputChannelNames.clear();
  213640. bufferSizes.clear();
  213641. sampleRates.clear();
  213642. isASIOOpen = false;
  213643. isOpen_ = false;
  213644. totalNumInputChans = 0;
  213645. totalNumOutputChans = 0;
  213646. numActiveInputChans = 0;
  213647. numActiveOutputChans = 0;
  213648. currentCallback = 0;
  213649. error = String::empty;
  213650. if (getName().isEmpty())
  213651. return error;
  213652. long err = 0;
  213653. if (loadDriver())
  213654. {
  213655. if ((error = initDriver()).isEmpty())
  213656. {
  213657. numActiveInputChans = 0;
  213658. numActiveOutputChans = 0;
  213659. totalNumInputChans = 0;
  213660. totalNumOutputChans = 0;
  213661. if (asioObject != 0
  213662. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213663. {
  213664. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213665. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213666. {
  213667. // find a list of buffer sizes..
  213668. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213669. if (granularity >= 0)
  213670. {
  213671. granularity = jmax (1, (int) granularity);
  213672. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213673. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213674. }
  213675. else if (granularity < 0)
  213676. {
  213677. for (int i = 0; i < 18; ++i)
  213678. {
  213679. const int s = (1 << i);
  213680. if (s >= minSize && s <= maxSize)
  213681. bufferSizes.add (s);
  213682. }
  213683. }
  213684. if (! bufferSizes.contains (preferredSize))
  213685. bufferSizes.insert (0, preferredSize);
  213686. double currentRate = 0;
  213687. asioObject->getSampleRate (&currentRate);
  213688. if (currentRate <= 0.0 || currentRate > 192001.0)
  213689. {
  213690. log ("setting sample rate");
  213691. err = asioObject->setSampleRate (44100.0);
  213692. if (err != 0)
  213693. {
  213694. logError ("setting sample rate", err);
  213695. }
  213696. asioObject->getSampleRate (&currentRate);
  213697. }
  213698. currentSampleRate = currentRate;
  213699. postOutput = (asioObject->outputReady() == 0);
  213700. if (postOutput)
  213701. {
  213702. log ("ASIO outputReady = ok");
  213703. }
  213704. updateSampleRates();
  213705. // ..because cubase does it at this point
  213706. inputLatency = outputLatency = 0;
  213707. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213708. {
  213709. log ("ASIO - no latencies");
  213710. }
  213711. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213712. // create some dummy buffers now.. because cubase does..
  213713. numActiveInputChans = 0;
  213714. numActiveOutputChans = 0;
  213715. ASIOBufferInfo* info = bufferInfos;
  213716. int i, numChans = 0;
  213717. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213718. {
  213719. info->isInput = 1;
  213720. info->channelNum = i;
  213721. info->buffers[0] = info->buffers[1] = 0;
  213722. ++info;
  213723. ++numChans;
  213724. }
  213725. const int outputBufferIndex = numChans;
  213726. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213727. {
  213728. info->isInput = 0;
  213729. info->channelNum = i;
  213730. info->buffers[0] = info->buffers[1] = 0;
  213731. ++info;
  213732. ++numChans;
  213733. }
  213734. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213735. if (currentASIODev[0] == this)
  213736. {
  213737. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213738. callbacks.asioMessage = &asioMessagesCallback0;
  213739. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213740. }
  213741. else if (currentASIODev[1] == this)
  213742. {
  213743. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213744. callbacks.asioMessage = &asioMessagesCallback1;
  213745. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213746. }
  213747. else if (currentASIODev[2] == this)
  213748. {
  213749. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213750. callbacks.asioMessage = &asioMessagesCallback2;
  213751. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213752. }
  213753. else
  213754. {
  213755. jassertfalse;
  213756. }
  213757. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213758. if (preferredSize > 0)
  213759. {
  213760. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213761. if (err != 0)
  213762. {
  213763. logError ("dummy buffers", err);
  213764. }
  213765. }
  213766. long newInps = 0, newOuts = 0;
  213767. asioObject->getChannels (&newInps, &newOuts);
  213768. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213769. {
  213770. totalNumInputChans = newInps;
  213771. totalNumOutputChans = newOuts;
  213772. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213773. }
  213774. updateSampleRates();
  213775. ASIOChannelInfo channelInfo;
  213776. channelInfo.type = 0;
  213777. for (i = 0; i < totalNumInputChans; ++i)
  213778. {
  213779. zerostruct (channelInfo);
  213780. channelInfo.channel = i;
  213781. channelInfo.isInput = 1;
  213782. asioObject->getChannelInfo (&channelInfo);
  213783. inputChannelNames.add (String (channelInfo.name));
  213784. }
  213785. for (i = 0; i < totalNumOutputChans; ++i)
  213786. {
  213787. zerostruct (channelInfo);
  213788. channelInfo.channel = i;
  213789. channelInfo.isInput = 0;
  213790. asioObject->getChannelInfo (&channelInfo);
  213791. outputChannelNames.add (String (channelInfo.name));
  213792. typeToFormatParameters (channelInfo.type,
  213793. outputChannelBitDepths[i],
  213794. outputChannelBytesPerSample[i],
  213795. outputChannelIsFloat[i],
  213796. outputChannelLittleEndian[i]);
  213797. if (i < 2)
  213798. {
  213799. // clear the channels that are used with the dummy stuff
  213800. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213801. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213802. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213803. }
  213804. }
  213805. outputChannelNames.trim();
  213806. inputChannelNames.trim();
  213807. outputChannelNames.appendNumbersToDuplicates (false, true);
  213808. inputChannelNames.appendNumbersToDuplicates (false, true);
  213809. // start and stop because cubase does it..
  213810. asioObject->getLatencies (&inputLatency, &outputLatency);
  213811. if ((err = asioObject->start()) != 0)
  213812. {
  213813. // ignore an error here, as it might start later after setting other stuff up
  213814. logError ("ASIO start", err);
  213815. }
  213816. Thread::sleep (100);
  213817. asioObject->stop();
  213818. }
  213819. else
  213820. {
  213821. error = "Can't detect buffer sizes";
  213822. }
  213823. }
  213824. else
  213825. {
  213826. error = "Can't detect asio channels";
  213827. }
  213828. }
  213829. }
  213830. else
  213831. {
  213832. error = "No such device";
  213833. }
  213834. if (error.isNotEmpty())
  213835. {
  213836. logError (error, err);
  213837. if (asioObject != 0)
  213838. asioObject->disposeBuffers();
  213839. removeCurrentDriver();
  213840. isASIOOpen = false;
  213841. }
  213842. else
  213843. {
  213844. isASIOOpen = true;
  213845. log ("ASIO device open");
  213846. }
  213847. isOpen_ = false;
  213848. needToReset = false;
  213849. isReSync = false;
  213850. return error;
  213851. }
  213852. void JUCE_ASIOCALLBACK callback (const long index)
  213853. {
  213854. if (isStarted)
  213855. {
  213856. bufferIndex = index;
  213857. processBuffer();
  213858. }
  213859. else
  213860. {
  213861. if (postOutput && (asioObject != 0))
  213862. asioObject->outputReady();
  213863. }
  213864. calledback = true;
  213865. }
  213866. void processBuffer()
  213867. {
  213868. const ASIOBufferInfo* const infos = bufferInfos;
  213869. const int bi = bufferIndex;
  213870. const ScopedLock sl (callbackLock);
  213871. if (needToReset)
  213872. {
  213873. needToReset = false;
  213874. if (isReSync)
  213875. {
  213876. log ("! ASIO resync");
  213877. isReSync = false;
  213878. }
  213879. else
  213880. {
  213881. startTimer (20);
  213882. }
  213883. }
  213884. if (bi >= 0)
  213885. {
  213886. const int samps = currentBlockSizeSamples;
  213887. if (currentCallback != 0)
  213888. {
  213889. int i;
  213890. for (i = 0; i < numActiveInputChans; ++i)
  213891. {
  213892. float* const dst = inBuffers[i];
  213893. jassert (dst != 0);
  213894. const char* const src = (const char*) (infos[i].buffers[bi]);
  213895. if (inputChannelIsFloat[i])
  213896. {
  213897. memcpy (dst, src, samps * sizeof (float));
  213898. }
  213899. else
  213900. {
  213901. jassert (dst == tempBuffer + (samps * i));
  213902. switch (inputChannelBitDepths[i])
  213903. {
  213904. case 16:
  213905. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213906. samps, inputChannelLittleEndian[i]);
  213907. break;
  213908. case 24:
  213909. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213910. samps, inputChannelLittleEndian[i]);
  213911. break;
  213912. case 32:
  213913. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213914. samps, inputChannelLittleEndian[i]);
  213915. break;
  213916. case 64:
  213917. jassertfalse;
  213918. break;
  213919. }
  213920. }
  213921. }
  213922. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213923. outBuffers, numActiveOutputChans, samps);
  213924. for (i = 0; i < numActiveOutputChans; ++i)
  213925. {
  213926. float* const src = outBuffers[i];
  213927. jassert (src != 0);
  213928. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213929. if (outputChannelIsFloat[i])
  213930. {
  213931. memcpy (dst, src, samps * sizeof (float));
  213932. }
  213933. else
  213934. {
  213935. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213936. switch (outputChannelBitDepths[i])
  213937. {
  213938. case 16:
  213939. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213940. samps, outputChannelLittleEndian[i]);
  213941. break;
  213942. case 24:
  213943. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213944. samps, outputChannelLittleEndian[i]);
  213945. break;
  213946. case 32:
  213947. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213948. samps, outputChannelLittleEndian[i]);
  213949. break;
  213950. case 64:
  213951. jassertfalse;
  213952. break;
  213953. }
  213954. }
  213955. }
  213956. }
  213957. else
  213958. {
  213959. for (int i = 0; i < numActiveOutputChans; ++i)
  213960. {
  213961. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213962. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213963. }
  213964. }
  213965. }
  213966. if (postOutput)
  213967. asioObject->outputReady();
  213968. }
  213969. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213970. {
  213971. if (currentASIODev[0] != 0)
  213972. currentASIODev[0]->callback (index);
  213973. return 0;
  213974. }
  213975. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213976. {
  213977. if (currentASIODev[1] != 0)
  213978. currentASIODev[1]->callback (index);
  213979. return 0;
  213980. }
  213981. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213982. {
  213983. if (currentASIODev[2] != 0)
  213984. currentASIODev[2]->callback (index);
  213985. return 0;
  213986. }
  213987. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213988. {
  213989. if (currentASIODev[0] != 0)
  213990. currentASIODev[0]->callback (index);
  213991. }
  213992. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213993. {
  213994. if (currentASIODev[1] != 0)
  213995. currentASIODev[1]->callback (index);
  213996. }
  213997. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213998. {
  213999. if (currentASIODev[2] != 0)
  214000. currentASIODev[2]->callback (index);
  214001. }
  214002. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  214003. {
  214004. return asioMessagesCallback (selector, value, 0);
  214005. }
  214006. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  214007. {
  214008. return asioMessagesCallback (selector, value, 1);
  214009. }
  214010. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  214011. {
  214012. return asioMessagesCallback (selector, value, 2);
  214013. }
  214014. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  214015. {
  214016. switch (selector)
  214017. {
  214018. case kAsioSelectorSupported:
  214019. if (value == kAsioResetRequest
  214020. || value == kAsioEngineVersion
  214021. || value == kAsioResyncRequest
  214022. || value == kAsioLatenciesChanged
  214023. || value == kAsioSupportsInputMonitor)
  214024. return 1;
  214025. break;
  214026. case kAsioBufferSizeChange:
  214027. break;
  214028. case kAsioResetRequest:
  214029. if (currentASIODev[deviceIndex] != 0)
  214030. currentASIODev[deviceIndex]->resetRequest();
  214031. return 1;
  214032. case kAsioResyncRequest:
  214033. if (currentASIODev[deviceIndex] != 0)
  214034. currentASIODev[deviceIndex]->resyncRequest();
  214035. return 1;
  214036. case kAsioLatenciesChanged:
  214037. return 1;
  214038. case kAsioEngineVersion:
  214039. return 2;
  214040. case kAsioSupportsTimeInfo:
  214041. case kAsioSupportsTimeCode:
  214042. return 0;
  214043. }
  214044. return 0;
  214045. }
  214046. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  214047. {
  214048. }
  214049. static void convertInt16ToFloat (const char* src,
  214050. float* dest,
  214051. const int srcStrideBytes,
  214052. int numSamples,
  214053. const bool littleEndian) throw()
  214054. {
  214055. const double g = 1.0 / 32768.0;
  214056. if (littleEndian)
  214057. {
  214058. while (--numSamples >= 0)
  214059. {
  214060. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  214061. src += srcStrideBytes;
  214062. }
  214063. }
  214064. else
  214065. {
  214066. while (--numSamples >= 0)
  214067. {
  214068. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  214069. src += srcStrideBytes;
  214070. }
  214071. }
  214072. }
  214073. static void convertFloatToInt16 (const float* src,
  214074. char* dest,
  214075. const int dstStrideBytes,
  214076. int numSamples,
  214077. const bool littleEndian) throw()
  214078. {
  214079. const double maxVal = (double) 0x7fff;
  214080. if (littleEndian)
  214081. {
  214082. while (--numSamples >= 0)
  214083. {
  214084. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214085. dest += dstStrideBytes;
  214086. }
  214087. }
  214088. else
  214089. {
  214090. while (--numSamples >= 0)
  214091. {
  214092. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214093. dest += dstStrideBytes;
  214094. }
  214095. }
  214096. }
  214097. static void convertInt24ToFloat (const char* src,
  214098. float* dest,
  214099. const int srcStrideBytes,
  214100. int numSamples,
  214101. const bool littleEndian) throw()
  214102. {
  214103. const double g = 1.0 / 0x7fffff;
  214104. if (littleEndian)
  214105. {
  214106. while (--numSamples >= 0)
  214107. {
  214108. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  214109. src += srcStrideBytes;
  214110. }
  214111. }
  214112. else
  214113. {
  214114. while (--numSamples >= 0)
  214115. {
  214116. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  214117. src += srcStrideBytes;
  214118. }
  214119. }
  214120. }
  214121. static void convertFloatToInt24 (const float* src,
  214122. char* dest,
  214123. const int dstStrideBytes,
  214124. int numSamples,
  214125. const bool littleEndian) throw()
  214126. {
  214127. const double maxVal = (double) 0x7fffff;
  214128. if (littleEndian)
  214129. {
  214130. while (--numSamples >= 0)
  214131. {
  214132. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214133. dest += dstStrideBytes;
  214134. }
  214135. }
  214136. else
  214137. {
  214138. while (--numSamples >= 0)
  214139. {
  214140. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214141. dest += dstStrideBytes;
  214142. }
  214143. }
  214144. }
  214145. static void convertInt32ToFloat (const char* src,
  214146. float* dest,
  214147. const int srcStrideBytes,
  214148. int numSamples,
  214149. const bool littleEndian) throw()
  214150. {
  214151. const double g = 1.0 / 0x7fffffff;
  214152. if (littleEndian)
  214153. {
  214154. while (--numSamples >= 0)
  214155. {
  214156. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  214157. src += srcStrideBytes;
  214158. }
  214159. }
  214160. else
  214161. {
  214162. while (--numSamples >= 0)
  214163. {
  214164. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  214165. src += srcStrideBytes;
  214166. }
  214167. }
  214168. }
  214169. static void convertFloatToInt32 (const float* src,
  214170. char* dest,
  214171. const int dstStrideBytes,
  214172. int numSamples,
  214173. const bool littleEndian) throw()
  214174. {
  214175. const double maxVal = (double) 0x7fffffff;
  214176. if (littleEndian)
  214177. {
  214178. while (--numSamples >= 0)
  214179. {
  214180. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214181. dest += dstStrideBytes;
  214182. }
  214183. }
  214184. else
  214185. {
  214186. while (--numSamples >= 0)
  214187. {
  214188. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214189. dest += dstStrideBytes;
  214190. }
  214191. }
  214192. }
  214193. static void typeToFormatParameters (const long type,
  214194. int& bitDepth,
  214195. int& byteStride,
  214196. bool& formatIsFloat,
  214197. bool& littleEndian) throw()
  214198. {
  214199. bitDepth = 0;
  214200. littleEndian = false;
  214201. formatIsFloat = false;
  214202. switch (type)
  214203. {
  214204. case ASIOSTInt16MSB:
  214205. case ASIOSTInt16LSB:
  214206. case ASIOSTInt32MSB16:
  214207. case ASIOSTInt32LSB16:
  214208. bitDepth = 16; break;
  214209. case ASIOSTFloat32MSB:
  214210. case ASIOSTFloat32LSB:
  214211. formatIsFloat = true;
  214212. bitDepth = 32; break;
  214213. case ASIOSTInt32MSB:
  214214. case ASIOSTInt32LSB:
  214215. bitDepth = 32; break;
  214216. case ASIOSTInt24MSB:
  214217. case ASIOSTInt24LSB:
  214218. case ASIOSTInt32MSB24:
  214219. case ASIOSTInt32LSB24:
  214220. case ASIOSTInt32MSB18:
  214221. case ASIOSTInt32MSB20:
  214222. case ASIOSTInt32LSB18:
  214223. case ASIOSTInt32LSB20:
  214224. bitDepth = 24; break;
  214225. case ASIOSTFloat64MSB:
  214226. case ASIOSTFloat64LSB:
  214227. default:
  214228. bitDepth = 64;
  214229. break;
  214230. }
  214231. switch (type)
  214232. {
  214233. case ASIOSTInt16MSB:
  214234. case ASIOSTInt32MSB16:
  214235. case ASIOSTFloat32MSB:
  214236. case ASIOSTFloat64MSB:
  214237. case ASIOSTInt32MSB:
  214238. case ASIOSTInt32MSB18:
  214239. case ASIOSTInt32MSB20:
  214240. case ASIOSTInt32MSB24:
  214241. case ASIOSTInt24MSB:
  214242. littleEndian = false; break;
  214243. case ASIOSTInt16LSB:
  214244. case ASIOSTInt32LSB16:
  214245. case ASIOSTFloat32LSB:
  214246. case ASIOSTFloat64LSB:
  214247. case ASIOSTInt32LSB:
  214248. case ASIOSTInt32LSB18:
  214249. case ASIOSTInt32LSB20:
  214250. case ASIOSTInt32LSB24:
  214251. case ASIOSTInt24LSB:
  214252. littleEndian = true; break;
  214253. default:
  214254. break;
  214255. }
  214256. switch (type)
  214257. {
  214258. case ASIOSTInt16LSB:
  214259. case ASIOSTInt16MSB:
  214260. byteStride = 2; break;
  214261. case ASIOSTInt24LSB:
  214262. case ASIOSTInt24MSB:
  214263. byteStride = 3; break;
  214264. case ASIOSTInt32MSB16:
  214265. case ASIOSTInt32LSB16:
  214266. case ASIOSTInt32MSB:
  214267. case ASIOSTInt32MSB18:
  214268. case ASIOSTInt32MSB20:
  214269. case ASIOSTInt32MSB24:
  214270. case ASIOSTInt32LSB:
  214271. case ASIOSTInt32LSB18:
  214272. case ASIOSTInt32LSB20:
  214273. case ASIOSTInt32LSB24:
  214274. case ASIOSTFloat32LSB:
  214275. case ASIOSTFloat32MSB:
  214276. byteStride = 4; break;
  214277. case ASIOSTFloat64MSB:
  214278. case ASIOSTFloat64LSB:
  214279. byteStride = 8; break;
  214280. default:
  214281. break;
  214282. }
  214283. }
  214284. };
  214285. class ASIOAudioIODeviceType : public AudioIODeviceType
  214286. {
  214287. public:
  214288. ASIOAudioIODeviceType()
  214289. : AudioIODeviceType ("ASIO"),
  214290. hasScanned (false)
  214291. {
  214292. CoInitialize (0);
  214293. }
  214294. ~ASIOAudioIODeviceType()
  214295. {
  214296. }
  214297. void scanForDevices()
  214298. {
  214299. hasScanned = true;
  214300. deviceNames.clear();
  214301. classIds.clear();
  214302. HKEY hk = 0;
  214303. int index = 0;
  214304. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214305. {
  214306. for (;;)
  214307. {
  214308. char name [256];
  214309. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214310. {
  214311. addDriverInfo (name, hk);
  214312. }
  214313. else
  214314. {
  214315. break;
  214316. }
  214317. }
  214318. RegCloseKey (hk);
  214319. }
  214320. }
  214321. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214322. {
  214323. jassert (hasScanned); // need to call scanForDevices() before doing this
  214324. return deviceNames;
  214325. }
  214326. int getDefaultDeviceIndex (bool) const
  214327. {
  214328. jassert (hasScanned); // need to call scanForDevices() before doing this
  214329. for (int i = deviceNames.size(); --i >= 0;)
  214330. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214331. return i; // asio4all is a safe choice for a default..
  214332. #if JUCE_DEBUG
  214333. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214334. return 1; // (the digi m-box driver crashes the app when you run
  214335. // it in the debugger, which can be a bit annoying)
  214336. #endif
  214337. return 0;
  214338. }
  214339. static int findFreeSlot()
  214340. {
  214341. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214342. if (currentASIODev[i] == 0)
  214343. return i;
  214344. jassertfalse; // unfortunately you can only have a finite number
  214345. // of ASIO devices open at the same time..
  214346. return -1;
  214347. }
  214348. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214349. {
  214350. jassert (hasScanned); // need to call scanForDevices() before doing this
  214351. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214352. }
  214353. bool hasSeparateInputsAndOutputs() const { return false; }
  214354. AudioIODevice* createDevice (const String& outputDeviceName,
  214355. const String& inputDeviceName)
  214356. {
  214357. // ASIO can't open two different devices for input and output - they must be the same one.
  214358. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214359. jassert (hasScanned); // need to call scanForDevices() before doing this
  214360. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214361. : inputDeviceName);
  214362. if (index >= 0)
  214363. {
  214364. const int freeSlot = findFreeSlot();
  214365. if (freeSlot >= 0)
  214366. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214367. }
  214368. return 0;
  214369. }
  214370. juce_UseDebuggingNewOperator
  214371. private:
  214372. StringArray deviceNames;
  214373. OwnedArray <CLSID> classIds;
  214374. bool hasScanned;
  214375. static bool checkClassIsOk (const String& classId)
  214376. {
  214377. HKEY hk = 0;
  214378. bool ok = false;
  214379. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214380. {
  214381. int index = 0;
  214382. for (;;)
  214383. {
  214384. WCHAR buf [512];
  214385. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214386. {
  214387. if (classId.equalsIgnoreCase (buf))
  214388. {
  214389. HKEY subKey, pathKey;
  214390. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214391. {
  214392. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214393. {
  214394. WCHAR pathName [1024];
  214395. DWORD dtype = REG_SZ;
  214396. DWORD dsize = sizeof (pathName);
  214397. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214398. ok = File (pathName).exists();
  214399. RegCloseKey (pathKey);
  214400. }
  214401. RegCloseKey (subKey);
  214402. }
  214403. break;
  214404. }
  214405. }
  214406. else
  214407. {
  214408. break;
  214409. }
  214410. }
  214411. RegCloseKey (hk);
  214412. }
  214413. return ok;
  214414. }
  214415. void addDriverInfo (const String& keyName, HKEY hk)
  214416. {
  214417. HKEY subKey;
  214418. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214419. {
  214420. WCHAR buf [256];
  214421. zerostruct (buf);
  214422. DWORD dtype = REG_SZ;
  214423. DWORD dsize = sizeof (buf);
  214424. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214425. {
  214426. if (dsize > 0 && checkClassIsOk (buf))
  214427. {
  214428. CLSID classId;
  214429. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214430. {
  214431. dtype = REG_SZ;
  214432. dsize = sizeof (buf);
  214433. String deviceName;
  214434. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214435. deviceName = buf;
  214436. else
  214437. deviceName = keyName;
  214438. log ("found " + deviceName);
  214439. deviceNames.add (deviceName);
  214440. classIds.add (new CLSID (classId));
  214441. }
  214442. }
  214443. RegCloseKey (subKey);
  214444. }
  214445. }
  214446. }
  214447. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214448. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214449. };
  214450. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214451. {
  214452. return new ASIOAudioIODeviceType();
  214453. }
  214454. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214455. void* guid,
  214456. const String& optionalDllForDirectLoading)
  214457. {
  214458. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214459. if (freeSlot < 0)
  214460. return 0;
  214461. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214462. }
  214463. #undef log
  214464. #endif
  214465. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214466. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214467. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214468. // compiled on its own).
  214469. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214470. END_JUCE_NAMESPACE
  214471. extern "C"
  214472. {
  214473. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214474. typedef struct typeDSBUFFERDESC
  214475. {
  214476. DWORD dwSize;
  214477. DWORD dwFlags;
  214478. DWORD dwBufferBytes;
  214479. DWORD dwReserved;
  214480. LPWAVEFORMATEX lpwfxFormat;
  214481. GUID guid3DAlgorithm;
  214482. } DSBUFFERDESC;
  214483. struct IDirectSoundBuffer;
  214484. #undef INTERFACE
  214485. #define INTERFACE IDirectSound
  214486. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214487. {
  214488. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214489. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214490. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214491. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214492. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214493. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214494. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214495. STDMETHOD(Compact) (THIS) PURE;
  214496. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214497. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214498. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214499. };
  214500. #undef INTERFACE
  214501. #define INTERFACE IDirectSoundBuffer
  214502. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214503. {
  214504. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214505. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214506. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214507. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214508. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214509. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214510. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214511. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214512. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214513. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214514. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214515. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214516. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214517. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214518. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214519. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214520. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214521. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214522. STDMETHOD(Stop) (THIS) PURE;
  214523. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214524. STDMETHOD(Restore) (THIS) PURE;
  214525. };
  214526. typedef struct typeDSCBUFFERDESC
  214527. {
  214528. DWORD dwSize;
  214529. DWORD dwFlags;
  214530. DWORD dwBufferBytes;
  214531. DWORD dwReserved;
  214532. LPWAVEFORMATEX lpwfxFormat;
  214533. } DSCBUFFERDESC;
  214534. struct IDirectSoundCaptureBuffer;
  214535. #undef INTERFACE
  214536. #define INTERFACE IDirectSoundCapture
  214537. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214538. {
  214539. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214540. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214541. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214542. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214543. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214544. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214545. };
  214546. #undef INTERFACE
  214547. #define INTERFACE IDirectSoundCaptureBuffer
  214548. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214549. {
  214550. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214551. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214552. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214553. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214554. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214555. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214556. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214557. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214558. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214559. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214560. STDMETHOD(Stop) (THIS) PURE;
  214561. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214562. };
  214563. };
  214564. BEGIN_JUCE_NAMESPACE
  214565. static const String getDSErrorMessage (HRESULT hr)
  214566. {
  214567. const char* result = 0;
  214568. switch (hr)
  214569. {
  214570. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214571. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214572. case E_INVALIDARG: result = "Invalid parameter"; break;
  214573. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214574. case E_FAIL: result = "Generic error"; break;
  214575. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214576. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214577. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214578. case E_NOTIMPL: result = "Unsupported function"; break;
  214579. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214580. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214581. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214582. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214583. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214584. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214585. case E_NOINTERFACE: result = "No interface"; break;
  214586. case S_OK: result = "No error"; break;
  214587. default: return "Unknown error: " + String ((int) hr);
  214588. }
  214589. return result;
  214590. }
  214591. #define DS_DEBUGGING 1
  214592. #ifdef DS_DEBUGGING
  214593. #define CATCH JUCE_CATCH_EXCEPTION
  214594. #undef log
  214595. #define log(a) Logger::writeToLog(a);
  214596. #undef logError
  214597. #define logError(a) logDSError(a, __LINE__);
  214598. static void logDSError (HRESULT hr, int lineNum)
  214599. {
  214600. if (hr != S_OK)
  214601. {
  214602. String error ("DS error at line ");
  214603. error << lineNum << " - " << getDSErrorMessage (hr);
  214604. log (error);
  214605. }
  214606. }
  214607. #else
  214608. #define CATCH JUCE_CATCH_ALL
  214609. #define log(a)
  214610. #define logError(a)
  214611. #endif
  214612. #define DSOUND_FUNCTION(functionName, params) \
  214613. typedef HRESULT (WINAPI *type##functionName) params; \
  214614. static type##functionName ds##functionName = 0;
  214615. #define DSOUND_FUNCTION_LOAD(functionName) \
  214616. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214617. jassert (ds##functionName != 0);
  214618. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214619. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214620. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214621. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214622. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214623. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214624. static void initialiseDSoundFunctions()
  214625. {
  214626. if (dsDirectSoundCreate == 0)
  214627. {
  214628. HMODULE h = LoadLibraryA ("dsound.dll");
  214629. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214630. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214631. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214632. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214633. }
  214634. }
  214635. class DSoundInternalOutChannel
  214636. {
  214637. String name;
  214638. LPGUID guid;
  214639. int sampleRate, bufferSizeSamples;
  214640. float* leftBuffer;
  214641. float* rightBuffer;
  214642. IDirectSound* pDirectSound;
  214643. IDirectSoundBuffer* pOutputBuffer;
  214644. DWORD writeOffset;
  214645. int totalBytesPerBuffer;
  214646. int bytesPerBuffer;
  214647. unsigned int lastPlayCursor;
  214648. public:
  214649. int bitDepth;
  214650. bool doneFlag;
  214651. DSoundInternalOutChannel (const String& name_,
  214652. LPGUID guid_,
  214653. int rate,
  214654. int bufferSize,
  214655. float* left,
  214656. float* right)
  214657. : name (name_),
  214658. guid (guid_),
  214659. sampleRate (rate),
  214660. bufferSizeSamples (bufferSize),
  214661. leftBuffer (left),
  214662. rightBuffer (right),
  214663. pDirectSound (0),
  214664. pOutputBuffer (0),
  214665. bitDepth (16)
  214666. {
  214667. }
  214668. ~DSoundInternalOutChannel()
  214669. {
  214670. close();
  214671. }
  214672. void close()
  214673. {
  214674. HRESULT hr;
  214675. if (pOutputBuffer != 0)
  214676. {
  214677. JUCE_TRY
  214678. {
  214679. log ("closing dsound out: " + name);
  214680. hr = pOutputBuffer->Stop();
  214681. logError (hr);
  214682. }
  214683. CATCH
  214684. JUCE_TRY
  214685. {
  214686. hr = pOutputBuffer->Release();
  214687. logError (hr);
  214688. }
  214689. CATCH
  214690. pOutputBuffer = 0;
  214691. }
  214692. if (pDirectSound != 0)
  214693. {
  214694. JUCE_TRY
  214695. {
  214696. hr = pDirectSound->Release();
  214697. logError (hr);
  214698. }
  214699. CATCH
  214700. pDirectSound = 0;
  214701. }
  214702. }
  214703. const String open()
  214704. {
  214705. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214706. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214707. pDirectSound = 0;
  214708. pOutputBuffer = 0;
  214709. writeOffset = 0;
  214710. String error;
  214711. HRESULT hr = E_NOINTERFACE;
  214712. if (dsDirectSoundCreate != 0)
  214713. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214714. if (hr == S_OK)
  214715. {
  214716. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214717. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214718. const int numChannels = 2;
  214719. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214720. logError (hr);
  214721. if (hr == S_OK)
  214722. {
  214723. IDirectSoundBuffer* pPrimaryBuffer;
  214724. DSBUFFERDESC primaryDesc;
  214725. zerostruct (primaryDesc);
  214726. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214727. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214728. primaryDesc.dwBufferBytes = 0;
  214729. primaryDesc.lpwfxFormat = 0;
  214730. log ("opening dsound out step 2");
  214731. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214732. logError (hr);
  214733. if (hr == S_OK)
  214734. {
  214735. WAVEFORMATEX wfFormat;
  214736. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214737. wfFormat.nChannels = (unsigned short) numChannels;
  214738. wfFormat.nSamplesPerSec = sampleRate;
  214739. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214740. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214741. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214742. wfFormat.cbSize = 0;
  214743. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214744. logError (hr);
  214745. if (hr == S_OK)
  214746. {
  214747. DSBUFFERDESC secondaryDesc;
  214748. zerostruct (secondaryDesc);
  214749. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214750. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214751. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214752. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214753. secondaryDesc.lpwfxFormat = &wfFormat;
  214754. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214755. logError (hr);
  214756. if (hr == S_OK)
  214757. {
  214758. log ("opening dsound out step 3");
  214759. DWORD dwDataLen;
  214760. unsigned char* pDSBuffData;
  214761. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214762. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214763. logError (hr);
  214764. if (hr == S_OK)
  214765. {
  214766. zeromem (pDSBuffData, dwDataLen);
  214767. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214768. if (hr == S_OK)
  214769. {
  214770. hr = pOutputBuffer->SetCurrentPosition (0);
  214771. if (hr == S_OK)
  214772. {
  214773. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214774. if (hr == S_OK)
  214775. return String::empty;
  214776. }
  214777. }
  214778. }
  214779. }
  214780. }
  214781. }
  214782. }
  214783. }
  214784. error = getDSErrorMessage (hr);
  214785. close();
  214786. return error;
  214787. }
  214788. void synchronisePosition()
  214789. {
  214790. if (pOutputBuffer != 0)
  214791. {
  214792. DWORD playCursor;
  214793. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214794. }
  214795. }
  214796. bool service()
  214797. {
  214798. if (pOutputBuffer == 0)
  214799. return true;
  214800. DWORD playCursor, writeCursor;
  214801. for (;;)
  214802. {
  214803. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214804. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214805. {
  214806. pOutputBuffer->Restore();
  214807. continue;
  214808. }
  214809. if (hr == S_OK)
  214810. break;
  214811. logError (hr);
  214812. jassertfalse;
  214813. return true;
  214814. }
  214815. int playWriteGap = writeCursor - playCursor;
  214816. if (playWriteGap < 0)
  214817. playWriteGap += totalBytesPerBuffer;
  214818. int bytesEmpty = playCursor - writeOffset;
  214819. if (bytesEmpty < 0)
  214820. bytesEmpty += totalBytesPerBuffer;
  214821. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214822. {
  214823. writeOffset = writeCursor;
  214824. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214825. }
  214826. if (bytesEmpty >= bytesPerBuffer)
  214827. {
  214828. void* lpbuf1 = 0;
  214829. void* lpbuf2 = 0;
  214830. DWORD dwSize1 = 0;
  214831. DWORD dwSize2 = 0;
  214832. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214833. bytesPerBuffer,
  214834. &lpbuf1, &dwSize1,
  214835. &lpbuf2, &dwSize2, 0);
  214836. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214837. {
  214838. pOutputBuffer->Restore();
  214839. hr = pOutputBuffer->Lock (writeOffset,
  214840. bytesPerBuffer,
  214841. &lpbuf1, &dwSize1,
  214842. &lpbuf2, &dwSize2, 0);
  214843. }
  214844. if (hr == S_OK)
  214845. {
  214846. if (bitDepth == 16)
  214847. {
  214848. const float gainL = 32767.0f;
  214849. const float gainR = 32767.0f;
  214850. int* dest = static_cast<int*> (lpbuf1);
  214851. const float* left = leftBuffer;
  214852. const float* right = rightBuffer;
  214853. int samples1 = dwSize1 >> 2;
  214854. int samples2 = dwSize2 >> 2;
  214855. if (left == 0)
  214856. {
  214857. while (--samples1 >= 0)
  214858. {
  214859. int r = roundToInt (gainR * *right++);
  214860. if (r < -32768)
  214861. r = -32768;
  214862. else if (r > 32767)
  214863. r = 32767;
  214864. *dest++ = (r << 16);
  214865. }
  214866. dest = static_cast<int*> (lpbuf2);
  214867. while (--samples2 >= 0)
  214868. {
  214869. int r = roundToInt (gainR * *right++);
  214870. if (r < -32768)
  214871. r = -32768;
  214872. else if (r > 32767)
  214873. r = 32767;
  214874. *dest++ = (r << 16);
  214875. }
  214876. }
  214877. else if (right == 0)
  214878. {
  214879. while (--samples1 >= 0)
  214880. {
  214881. int l = roundToInt (gainL * *left++);
  214882. if (l < -32768)
  214883. l = -32768;
  214884. else if (l > 32767)
  214885. l = 32767;
  214886. l &= 0xffff;
  214887. *dest++ = l;
  214888. }
  214889. dest = static_cast<int*> (lpbuf2);
  214890. while (--samples2 >= 0)
  214891. {
  214892. int l = roundToInt (gainL * *left++);
  214893. if (l < -32768)
  214894. l = -32768;
  214895. else if (l > 32767)
  214896. l = 32767;
  214897. l &= 0xffff;
  214898. *dest++ = l;
  214899. }
  214900. }
  214901. else
  214902. {
  214903. while (--samples1 >= 0)
  214904. {
  214905. int l = roundToInt (gainL * *left++);
  214906. if (l < -32768)
  214907. l = -32768;
  214908. else if (l > 32767)
  214909. l = 32767;
  214910. l &= 0xffff;
  214911. int r = roundToInt (gainR * *right++);
  214912. if (r < -32768)
  214913. r = -32768;
  214914. else if (r > 32767)
  214915. r = 32767;
  214916. *dest++ = (r << 16) | l;
  214917. }
  214918. dest = static_cast<int*> (lpbuf2);
  214919. while (--samples2 >= 0)
  214920. {
  214921. int l = roundToInt (gainL * *left++);
  214922. if (l < -32768)
  214923. l = -32768;
  214924. else if (l > 32767)
  214925. l = 32767;
  214926. l &= 0xffff;
  214927. int r = roundToInt (gainR * *right++);
  214928. if (r < -32768)
  214929. r = -32768;
  214930. else if (r > 32767)
  214931. r = 32767;
  214932. *dest++ = (r << 16) | l;
  214933. }
  214934. }
  214935. }
  214936. else
  214937. {
  214938. jassertfalse;
  214939. }
  214940. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214941. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214942. }
  214943. else
  214944. {
  214945. jassertfalse;
  214946. logError (hr);
  214947. }
  214948. bytesEmpty -= bytesPerBuffer;
  214949. return true;
  214950. }
  214951. else
  214952. {
  214953. return false;
  214954. }
  214955. }
  214956. };
  214957. struct DSoundInternalInChannel
  214958. {
  214959. String name;
  214960. LPGUID guid;
  214961. int sampleRate, bufferSizeSamples;
  214962. float* leftBuffer;
  214963. float* rightBuffer;
  214964. IDirectSound* pDirectSound;
  214965. IDirectSoundCapture* pDirectSoundCapture;
  214966. IDirectSoundCaptureBuffer* pInputBuffer;
  214967. public:
  214968. unsigned int readOffset;
  214969. int bytesPerBuffer, totalBytesPerBuffer;
  214970. int bitDepth;
  214971. bool doneFlag;
  214972. DSoundInternalInChannel (const String& name_,
  214973. LPGUID guid_,
  214974. int rate,
  214975. int bufferSize,
  214976. float* left,
  214977. float* right)
  214978. : name (name_),
  214979. guid (guid_),
  214980. sampleRate (rate),
  214981. bufferSizeSamples (bufferSize),
  214982. leftBuffer (left),
  214983. rightBuffer (right),
  214984. pDirectSound (0),
  214985. pDirectSoundCapture (0),
  214986. pInputBuffer (0),
  214987. bitDepth (16)
  214988. {
  214989. }
  214990. ~DSoundInternalInChannel()
  214991. {
  214992. close();
  214993. }
  214994. void close()
  214995. {
  214996. HRESULT hr;
  214997. if (pInputBuffer != 0)
  214998. {
  214999. JUCE_TRY
  215000. {
  215001. log ("closing dsound in: " + name);
  215002. hr = pInputBuffer->Stop();
  215003. logError (hr);
  215004. }
  215005. CATCH
  215006. JUCE_TRY
  215007. {
  215008. hr = pInputBuffer->Release();
  215009. logError (hr);
  215010. }
  215011. CATCH
  215012. pInputBuffer = 0;
  215013. }
  215014. if (pDirectSoundCapture != 0)
  215015. {
  215016. JUCE_TRY
  215017. {
  215018. hr = pDirectSoundCapture->Release();
  215019. logError (hr);
  215020. }
  215021. CATCH
  215022. pDirectSoundCapture = 0;
  215023. }
  215024. if (pDirectSound != 0)
  215025. {
  215026. JUCE_TRY
  215027. {
  215028. hr = pDirectSound->Release();
  215029. logError (hr);
  215030. }
  215031. CATCH
  215032. pDirectSound = 0;
  215033. }
  215034. }
  215035. const String open()
  215036. {
  215037. log ("opening dsound in device: " + name
  215038. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  215039. pDirectSound = 0;
  215040. pDirectSoundCapture = 0;
  215041. pInputBuffer = 0;
  215042. readOffset = 0;
  215043. totalBytesPerBuffer = 0;
  215044. String error;
  215045. HRESULT hr = E_NOINTERFACE;
  215046. if (dsDirectSoundCaptureCreate != 0)
  215047. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  215048. logError (hr);
  215049. if (hr == S_OK)
  215050. {
  215051. const int numChannels = 2;
  215052. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  215053. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  215054. WAVEFORMATEX wfFormat;
  215055. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  215056. wfFormat.nChannels = (unsigned short)numChannels;
  215057. wfFormat.nSamplesPerSec = sampleRate;
  215058. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  215059. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  215060. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  215061. wfFormat.cbSize = 0;
  215062. DSCBUFFERDESC captureDesc;
  215063. zerostruct (captureDesc);
  215064. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  215065. captureDesc.dwFlags = 0;
  215066. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  215067. captureDesc.lpwfxFormat = &wfFormat;
  215068. log ("opening dsound in step 2");
  215069. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  215070. logError (hr);
  215071. if (hr == S_OK)
  215072. {
  215073. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  215074. logError (hr);
  215075. if (hr == S_OK)
  215076. return String::empty;
  215077. }
  215078. }
  215079. error = getDSErrorMessage (hr);
  215080. close();
  215081. return error;
  215082. }
  215083. void synchronisePosition()
  215084. {
  215085. if (pInputBuffer != 0)
  215086. {
  215087. DWORD capturePos;
  215088. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  215089. }
  215090. }
  215091. bool service()
  215092. {
  215093. if (pInputBuffer == 0)
  215094. return true;
  215095. DWORD capturePos, readPos;
  215096. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  215097. logError (hr);
  215098. if (hr != S_OK)
  215099. return true;
  215100. int bytesFilled = readPos - readOffset;
  215101. if (bytesFilled < 0)
  215102. bytesFilled += totalBytesPerBuffer;
  215103. if (bytesFilled >= bytesPerBuffer)
  215104. {
  215105. LPBYTE lpbuf1 = 0;
  215106. LPBYTE lpbuf2 = 0;
  215107. DWORD dwsize1 = 0;
  215108. DWORD dwsize2 = 0;
  215109. HRESULT hr = pInputBuffer->Lock (readOffset,
  215110. bytesPerBuffer,
  215111. (void**) &lpbuf1, &dwsize1,
  215112. (void**) &lpbuf2, &dwsize2, 0);
  215113. if (hr == S_OK)
  215114. {
  215115. if (bitDepth == 16)
  215116. {
  215117. const float g = 1.0f / 32768.0f;
  215118. float* destL = leftBuffer;
  215119. float* destR = rightBuffer;
  215120. int samples1 = dwsize1 >> 2;
  215121. int samples2 = dwsize2 >> 2;
  215122. const short* src = (const short*)lpbuf1;
  215123. if (destL == 0)
  215124. {
  215125. while (--samples1 >= 0)
  215126. {
  215127. ++src;
  215128. *destR++ = *src++ * g;
  215129. }
  215130. src = (const short*)lpbuf2;
  215131. while (--samples2 >= 0)
  215132. {
  215133. ++src;
  215134. *destR++ = *src++ * g;
  215135. }
  215136. }
  215137. else if (destR == 0)
  215138. {
  215139. while (--samples1 >= 0)
  215140. {
  215141. *destL++ = *src++ * g;
  215142. ++src;
  215143. }
  215144. src = (const short*)lpbuf2;
  215145. while (--samples2 >= 0)
  215146. {
  215147. *destL++ = *src++ * g;
  215148. ++src;
  215149. }
  215150. }
  215151. else
  215152. {
  215153. while (--samples1 >= 0)
  215154. {
  215155. *destL++ = *src++ * g;
  215156. *destR++ = *src++ * g;
  215157. }
  215158. src = (const short*)lpbuf2;
  215159. while (--samples2 >= 0)
  215160. {
  215161. *destL++ = *src++ * g;
  215162. *destR++ = *src++ * g;
  215163. }
  215164. }
  215165. }
  215166. else
  215167. {
  215168. jassertfalse;
  215169. }
  215170. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  215171. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  215172. }
  215173. else
  215174. {
  215175. logError (hr);
  215176. jassertfalse;
  215177. }
  215178. bytesFilled -= bytesPerBuffer;
  215179. return true;
  215180. }
  215181. else
  215182. {
  215183. return false;
  215184. }
  215185. }
  215186. };
  215187. class DSoundAudioIODevice : public AudioIODevice,
  215188. public Thread
  215189. {
  215190. public:
  215191. DSoundAudioIODevice (const String& deviceName,
  215192. const int outputDeviceIndex_,
  215193. const int inputDeviceIndex_)
  215194. : AudioIODevice (deviceName, "DirectSound"),
  215195. Thread ("Juce DSound"),
  215196. isOpen_ (false),
  215197. isStarted (false),
  215198. outputDeviceIndex (outputDeviceIndex_),
  215199. inputDeviceIndex (inputDeviceIndex_),
  215200. totalSamplesOut (0),
  215201. sampleRate (0.0),
  215202. inputBuffers (1, 1),
  215203. outputBuffers (1, 1),
  215204. callback (0),
  215205. bufferSizeSamples (0)
  215206. {
  215207. if (outputDeviceIndex_ >= 0)
  215208. {
  215209. outChannels.add (TRANS("Left"));
  215210. outChannels.add (TRANS("Right"));
  215211. }
  215212. if (inputDeviceIndex_ >= 0)
  215213. {
  215214. inChannels.add (TRANS("Left"));
  215215. inChannels.add (TRANS("Right"));
  215216. }
  215217. }
  215218. ~DSoundAudioIODevice()
  215219. {
  215220. close();
  215221. }
  215222. const StringArray getOutputChannelNames()
  215223. {
  215224. return outChannels;
  215225. }
  215226. const StringArray getInputChannelNames()
  215227. {
  215228. return inChannels;
  215229. }
  215230. int getNumSampleRates()
  215231. {
  215232. return 4;
  215233. }
  215234. double getSampleRate (int index)
  215235. {
  215236. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215237. return samps [jlimit (0, 3, index)];
  215238. }
  215239. int getNumBufferSizesAvailable()
  215240. {
  215241. return 50;
  215242. }
  215243. int getBufferSizeSamples (int index)
  215244. {
  215245. int n = 64;
  215246. for (int i = 0; i < index; ++i)
  215247. n += (n < 512) ? 32
  215248. : ((n < 1024) ? 64
  215249. : ((n < 2048) ? 128 : 256));
  215250. return n;
  215251. }
  215252. int getDefaultBufferSize()
  215253. {
  215254. return 2560;
  215255. }
  215256. const String open (const BigInteger& inputChannels,
  215257. const BigInteger& outputChannels,
  215258. double sampleRate,
  215259. int bufferSizeSamples)
  215260. {
  215261. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215262. isOpen_ = lastError.isEmpty();
  215263. return lastError;
  215264. }
  215265. void close()
  215266. {
  215267. stop();
  215268. if (isOpen_)
  215269. {
  215270. closeDevice();
  215271. isOpen_ = false;
  215272. }
  215273. }
  215274. bool isOpen()
  215275. {
  215276. return isOpen_ && isThreadRunning();
  215277. }
  215278. int getCurrentBufferSizeSamples()
  215279. {
  215280. return bufferSizeSamples;
  215281. }
  215282. double getCurrentSampleRate()
  215283. {
  215284. return sampleRate;
  215285. }
  215286. int getCurrentBitDepth()
  215287. {
  215288. int i, bits = 256;
  215289. for (i = inChans.size(); --i >= 0;)
  215290. bits = jmin (bits, inChans[i]->bitDepth);
  215291. for (i = outChans.size(); --i >= 0;)
  215292. bits = jmin (bits, outChans[i]->bitDepth);
  215293. if (bits > 32)
  215294. bits = 16;
  215295. return bits;
  215296. }
  215297. const BigInteger getActiveOutputChannels() const
  215298. {
  215299. return enabledOutputs;
  215300. }
  215301. const BigInteger getActiveInputChannels() const
  215302. {
  215303. return enabledInputs;
  215304. }
  215305. int getOutputLatencyInSamples()
  215306. {
  215307. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215308. }
  215309. int getInputLatencyInSamples()
  215310. {
  215311. return getOutputLatencyInSamples();
  215312. }
  215313. void start (AudioIODeviceCallback* call)
  215314. {
  215315. if (isOpen_ && call != 0 && ! isStarted)
  215316. {
  215317. if (! isThreadRunning())
  215318. {
  215319. // something gone wrong and the thread's stopped..
  215320. isOpen_ = false;
  215321. return;
  215322. }
  215323. call->audioDeviceAboutToStart (this);
  215324. const ScopedLock sl (startStopLock);
  215325. callback = call;
  215326. isStarted = true;
  215327. }
  215328. }
  215329. void stop()
  215330. {
  215331. if (isStarted)
  215332. {
  215333. AudioIODeviceCallback* const callbackLocal = callback;
  215334. {
  215335. const ScopedLock sl (startStopLock);
  215336. isStarted = false;
  215337. }
  215338. if (callbackLocal != 0)
  215339. callbackLocal->audioDeviceStopped();
  215340. }
  215341. }
  215342. bool isPlaying()
  215343. {
  215344. return isStarted && isOpen_ && isThreadRunning();
  215345. }
  215346. const String getLastError()
  215347. {
  215348. return lastError;
  215349. }
  215350. juce_UseDebuggingNewOperator
  215351. StringArray inChannels, outChannels;
  215352. int outputDeviceIndex, inputDeviceIndex;
  215353. private:
  215354. bool isOpen_;
  215355. bool isStarted;
  215356. String lastError;
  215357. OwnedArray <DSoundInternalInChannel> inChans;
  215358. OwnedArray <DSoundInternalOutChannel> outChans;
  215359. WaitableEvent startEvent;
  215360. int bufferSizeSamples;
  215361. int volatile totalSamplesOut;
  215362. int64 volatile lastBlockTime;
  215363. double sampleRate;
  215364. BigInteger enabledInputs, enabledOutputs;
  215365. AudioSampleBuffer inputBuffers, outputBuffers;
  215366. AudioIODeviceCallback* callback;
  215367. CriticalSection startStopLock;
  215368. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215369. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215370. const String openDevice (const BigInteger& inputChannels,
  215371. const BigInteger& outputChannels,
  215372. double sampleRate_,
  215373. int bufferSizeSamples_);
  215374. void closeDevice()
  215375. {
  215376. isStarted = false;
  215377. stopThread (5000);
  215378. inChans.clear();
  215379. outChans.clear();
  215380. inputBuffers.setSize (1, 1);
  215381. outputBuffers.setSize (1, 1);
  215382. }
  215383. void resync()
  215384. {
  215385. if (! threadShouldExit())
  215386. {
  215387. sleep (5);
  215388. int i;
  215389. for (i = 0; i < outChans.size(); ++i)
  215390. outChans.getUnchecked(i)->synchronisePosition();
  215391. for (i = 0; i < inChans.size(); ++i)
  215392. inChans.getUnchecked(i)->synchronisePosition();
  215393. }
  215394. }
  215395. public:
  215396. void run()
  215397. {
  215398. while (! threadShouldExit())
  215399. {
  215400. if (wait (100))
  215401. break;
  215402. }
  215403. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215404. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215405. while (! threadShouldExit())
  215406. {
  215407. int numToDo = 0;
  215408. uint32 startTime = Time::getMillisecondCounter();
  215409. int i;
  215410. for (i = inChans.size(); --i >= 0;)
  215411. {
  215412. inChans.getUnchecked(i)->doneFlag = false;
  215413. ++numToDo;
  215414. }
  215415. for (i = outChans.size(); --i >= 0;)
  215416. {
  215417. outChans.getUnchecked(i)->doneFlag = false;
  215418. ++numToDo;
  215419. }
  215420. if (numToDo > 0)
  215421. {
  215422. const int maxCount = 3;
  215423. int count = maxCount;
  215424. for (;;)
  215425. {
  215426. for (i = inChans.size(); --i >= 0;)
  215427. {
  215428. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215429. if ((! in->doneFlag) && in->service())
  215430. {
  215431. in->doneFlag = true;
  215432. --numToDo;
  215433. }
  215434. }
  215435. for (i = outChans.size(); --i >= 0;)
  215436. {
  215437. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215438. if ((! out->doneFlag) && out->service())
  215439. {
  215440. out->doneFlag = true;
  215441. --numToDo;
  215442. }
  215443. }
  215444. if (numToDo <= 0)
  215445. break;
  215446. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215447. {
  215448. resync();
  215449. break;
  215450. }
  215451. if (--count <= 0)
  215452. {
  215453. Sleep (1);
  215454. count = maxCount;
  215455. }
  215456. if (threadShouldExit())
  215457. return;
  215458. }
  215459. }
  215460. else
  215461. {
  215462. sleep (1);
  215463. }
  215464. const ScopedLock sl (startStopLock);
  215465. if (isStarted)
  215466. {
  215467. JUCE_TRY
  215468. {
  215469. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215470. inputBuffers.getNumChannels(),
  215471. outputBuffers.getArrayOfChannels(),
  215472. outputBuffers.getNumChannels(),
  215473. bufferSizeSamples);
  215474. }
  215475. JUCE_CATCH_EXCEPTION
  215476. totalSamplesOut += bufferSizeSamples;
  215477. }
  215478. else
  215479. {
  215480. outputBuffers.clear();
  215481. totalSamplesOut = 0;
  215482. sleep (1);
  215483. }
  215484. }
  215485. }
  215486. };
  215487. class DSoundAudioIODeviceType : public AudioIODeviceType
  215488. {
  215489. public:
  215490. DSoundAudioIODeviceType()
  215491. : AudioIODeviceType ("DirectSound"),
  215492. hasScanned (false)
  215493. {
  215494. initialiseDSoundFunctions();
  215495. }
  215496. ~DSoundAudioIODeviceType()
  215497. {
  215498. }
  215499. void scanForDevices()
  215500. {
  215501. hasScanned = true;
  215502. outputDeviceNames.clear();
  215503. outputGuids.clear();
  215504. inputDeviceNames.clear();
  215505. inputGuids.clear();
  215506. if (dsDirectSoundEnumerateW != 0)
  215507. {
  215508. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215509. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215510. }
  215511. }
  215512. const StringArray getDeviceNames (bool wantInputNames) const
  215513. {
  215514. jassert (hasScanned); // need to call scanForDevices() before doing this
  215515. return wantInputNames ? inputDeviceNames
  215516. : outputDeviceNames;
  215517. }
  215518. int getDefaultDeviceIndex (bool /*forInput*/) const
  215519. {
  215520. jassert (hasScanned); // need to call scanForDevices() before doing this
  215521. return 0;
  215522. }
  215523. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215524. {
  215525. jassert (hasScanned); // need to call scanForDevices() before doing this
  215526. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215527. if (d == 0)
  215528. return -1;
  215529. return asInput ? d->inputDeviceIndex
  215530. : d->outputDeviceIndex;
  215531. }
  215532. bool hasSeparateInputsAndOutputs() const { return true; }
  215533. AudioIODevice* createDevice (const String& outputDeviceName,
  215534. const String& inputDeviceName)
  215535. {
  215536. jassert (hasScanned); // need to call scanForDevices() before doing this
  215537. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215538. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215539. if (outputIndex >= 0 || inputIndex >= 0)
  215540. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215541. : inputDeviceName,
  215542. outputIndex, inputIndex);
  215543. return 0;
  215544. }
  215545. juce_UseDebuggingNewOperator
  215546. StringArray outputDeviceNames;
  215547. OwnedArray <GUID> outputGuids;
  215548. StringArray inputDeviceNames;
  215549. OwnedArray <GUID> inputGuids;
  215550. private:
  215551. bool hasScanned;
  215552. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215553. {
  215554. desc = desc.trim();
  215555. if (desc.isNotEmpty())
  215556. {
  215557. const String origDesc (desc);
  215558. int n = 2;
  215559. while (outputDeviceNames.contains (desc))
  215560. desc = origDesc + " (" + String (n++) + ")";
  215561. outputDeviceNames.add (desc);
  215562. if (lpGUID != 0)
  215563. outputGuids.add (new GUID (*lpGUID));
  215564. else
  215565. outputGuids.add (0);
  215566. }
  215567. return TRUE;
  215568. }
  215569. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215570. {
  215571. return ((DSoundAudioIODeviceType*) object)
  215572. ->outputEnumProc (lpGUID, String (description));
  215573. }
  215574. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215575. {
  215576. return ((DSoundAudioIODeviceType*) object)
  215577. ->outputEnumProc (lpGUID, String (description));
  215578. }
  215579. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215580. {
  215581. desc = desc.trim();
  215582. if (desc.isNotEmpty())
  215583. {
  215584. const String origDesc (desc);
  215585. int n = 2;
  215586. while (inputDeviceNames.contains (desc))
  215587. desc = origDesc + " (" + String (n++) + ")";
  215588. inputDeviceNames.add (desc);
  215589. if (lpGUID != 0)
  215590. inputGuids.add (new GUID (*lpGUID));
  215591. else
  215592. inputGuids.add (0);
  215593. }
  215594. return TRUE;
  215595. }
  215596. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215597. {
  215598. return ((DSoundAudioIODeviceType*) object)
  215599. ->inputEnumProc (lpGUID, String (description));
  215600. }
  215601. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215602. {
  215603. return ((DSoundAudioIODeviceType*) object)
  215604. ->inputEnumProc (lpGUID, String (description));
  215605. }
  215606. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215607. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215608. };
  215609. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215610. const BigInteger& outputChannels,
  215611. double sampleRate_,
  215612. int bufferSizeSamples_)
  215613. {
  215614. closeDevice();
  215615. totalSamplesOut = 0;
  215616. sampleRate = sampleRate_;
  215617. if (bufferSizeSamples_ <= 0)
  215618. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215619. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215620. DSoundAudioIODeviceType dlh;
  215621. dlh.scanForDevices();
  215622. enabledInputs = inputChannels;
  215623. enabledInputs.setRange (inChannels.size(),
  215624. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215625. false);
  215626. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215627. inputBuffers.clear();
  215628. int i, numIns = 0;
  215629. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215630. {
  215631. float* left = 0;
  215632. if (enabledInputs[i])
  215633. left = inputBuffers.getSampleData (numIns++);
  215634. float* right = 0;
  215635. if (enabledInputs[i + 1])
  215636. right = inputBuffers.getSampleData (numIns++);
  215637. if (left != 0 || right != 0)
  215638. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215639. dlh.inputGuids [inputDeviceIndex],
  215640. (int) sampleRate, bufferSizeSamples,
  215641. left, right));
  215642. }
  215643. enabledOutputs = outputChannels;
  215644. enabledOutputs.setRange (outChannels.size(),
  215645. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215646. false);
  215647. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215648. outputBuffers.clear();
  215649. int numOuts = 0;
  215650. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215651. {
  215652. float* left = 0;
  215653. if (enabledOutputs[i])
  215654. left = outputBuffers.getSampleData (numOuts++);
  215655. float* right = 0;
  215656. if (enabledOutputs[i + 1])
  215657. right = outputBuffers.getSampleData (numOuts++);
  215658. if (left != 0 || right != 0)
  215659. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215660. dlh.outputGuids [outputDeviceIndex],
  215661. (int) sampleRate, bufferSizeSamples,
  215662. left, right));
  215663. }
  215664. String error;
  215665. // boost our priority while opening the devices to try to get better sync between them
  215666. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215667. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215668. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215669. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215670. for (i = 0; i < outChans.size(); ++i)
  215671. {
  215672. error = outChans[i]->open();
  215673. if (error.isNotEmpty())
  215674. {
  215675. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215676. break;
  215677. }
  215678. }
  215679. if (error.isEmpty())
  215680. {
  215681. for (i = 0; i < inChans.size(); ++i)
  215682. {
  215683. error = inChans[i]->open();
  215684. if (error.isNotEmpty())
  215685. {
  215686. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215687. break;
  215688. }
  215689. }
  215690. }
  215691. if (error.isEmpty())
  215692. {
  215693. totalSamplesOut = 0;
  215694. for (i = 0; i < outChans.size(); ++i)
  215695. outChans.getUnchecked(i)->synchronisePosition();
  215696. for (i = 0; i < inChans.size(); ++i)
  215697. inChans.getUnchecked(i)->synchronisePosition();
  215698. startThread (9);
  215699. sleep (10);
  215700. notify();
  215701. }
  215702. else
  215703. {
  215704. log (error);
  215705. }
  215706. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215707. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215708. return error;
  215709. }
  215710. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215711. {
  215712. return new DSoundAudioIODeviceType();
  215713. }
  215714. #undef log
  215715. #endif
  215716. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215717. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215718. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215719. // compiled on its own).
  215720. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215721. #ifndef WASAPI_ENABLE_LOGGING
  215722. #define WASAPI_ENABLE_LOGGING 1
  215723. #endif
  215724. namespace WasapiClasses
  215725. {
  215726. static void logFailure (HRESULT hr)
  215727. {
  215728. (void) hr;
  215729. #if WASAPI_ENABLE_LOGGING
  215730. if (FAILED (hr))
  215731. {
  215732. String e;
  215733. e << Time::getCurrentTime().toString (true, true, true, true)
  215734. << " -- WASAPI error: ";
  215735. switch (hr)
  215736. {
  215737. case E_POINTER: e << "E_POINTER"; break;
  215738. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215739. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215740. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215741. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215742. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215743. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215744. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215745. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215746. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215747. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215748. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215749. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215750. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215751. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215752. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215753. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215754. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215755. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215756. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215757. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215758. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215759. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215760. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215761. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215762. default: e << String::toHexString ((int) hr); break;
  215763. }
  215764. DBG (e);
  215765. jassertfalse;
  215766. }
  215767. #endif
  215768. }
  215769. #undef check
  215770. static bool check (HRESULT hr)
  215771. {
  215772. logFailure (hr);
  215773. return SUCCEEDED (hr);
  215774. }
  215775. static const String getDeviceID (IMMDevice* const device)
  215776. {
  215777. String s;
  215778. WCHAR* deviceId = 0;
  215779. if (check (device->GetId (&deviceId)))
  215780. {
  215781. s = String (deviceId);
  215782. CoTaskMemFree (deviceId);
  215783. }
  215784. return s;
  215785. }
  215786. static EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215787. {
  215788. EDataFlow flow = eRender;
  215789. ComSmartPtr <IMMEndpoint> endPoint;
  215790. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215791. (void) check (endPoint->GetDataFlow (&flow));
  215792. return flow;
  215793. }
  215794. static int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215795. {
  215796. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215797. }
  215798. static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215799. {
  215800. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215801. : sizeof (WAVEFORMATEX));
  215802. }
  215803. class WASAPIDeviceBase
  215804. {
  215805. public:
  215806. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215807. : device (device_),
  215808. sampleRate (0),
  215809. numChannels (0),
  215810. actualNumChannels (0),
  215811. defaultSampleRate (0),
  215812. minBufferSize (0),
  215813. defaultBufferSize (0),
  215814. latencySamples (0),
  215815. useExclusiveMode (useExclusiveMode_)
  215816. {
  215817. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215818. ComSmartPtr <IAudioClient> tempClient (createClient());
  215819. if (tempClient == 0)
  215820. return;
  215821. REFERENCE_TIME defaultPeriod, minPeriod;
  215822. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215823. return;
  215824. WAVEFORMATEX* mixFormat = 0;
  215825. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215826. return;
  215827. WAVEFORMATEXTENSIBLE format;
  215828. copyWavFormat (format, mixFormat);
  215829. CoTaskMemFree (mixFormat);
  215830. actualNumChannels = numChannels = format.Format.nChannels;
  215831. defaultSampleRate = format.Format.nSamplesPerSec;
  215832. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215833. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215834. rates.addUsingDefaultSort (defaultSampleRate);
  215835. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215836. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215837. {
  215838. if (ratesToTest[i] == defaultSampleRate)
  215839. continue;
  215840. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215841. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215842. (WAVEFORMATEX*) &format, 0)))
  215843. if (! rates.contains (ratesToTest[i]))
  215844. rates.addUsingDefaultSort (ratesToTest[i]);
  215845. }
  215846. }
  215847. ~WASAPIDeviceBase()
  215848. {
  215849. device = 0;
  215850. CloseHandle (clientEvent);
  215851. }
  215852. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215853. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215854. {
  215855. sampleRate = newSampleRate;
  215856. channels = newChannels;
  215857. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215858. numChannels = channels.getHighestBit() + 1;
  215859. if (numChannels == 0)
  215860. return true;
  215861. client = createClient();
  215862. if (client != 0
  215863. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215864. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215865. {
  215866. channelMaps.clear();
  215867. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215868. if (channels[i])
  215869. channelMaps.add (i);
  215870. REFERENCE_TIME latency;
  215871. if (check (client->GetStreamLatency (&latency)))
  215872. latencySamples = refTimeToSamples (latency, sampleRate);
  215873. (void) check (client->GetBufferSize (&actualBufferSize));
  215874. return check (client->SetEventHandle (clientEvent));
  215875. }
  215876. return false;
  215877. }
  215878. void closeClient()
  215879. {
  215880. if (client != 0)
  215881. client->Stop();
  215882. client = 0;
  215883. ResetEvent (clientEvent);
  215884. }
  215885. ComSmartPtr <IMMDevice> device;
  215886. ComSmartPtr <IAudioClient> client;
  215887. double sampleRate, defaultSampleRate;
  215888. int numChannels, actualNumChannels;
  215889. int minBufferSize, defaultBufferSize, latencySamples;
  215890. const bool useExclusiveMode;
  215891. Array <double> rates;
  215892. HANDLE clientEvent;
  215893. BigInteger channels;
  215894. Array <int> channelMaps;
  215895. UINT32 actualBufferSize;
  215896. int bytesPerSample;
  215897. virtual void updateFormat (bool isFloat) = 0;
  215898. private:
  215899. const ComSmartPtr <IAudioClient> createClient()
  215900. {
  215901. ComSmartPtr <IAudioClient> client;
  215902. if (device != 0)
  215903. {
  215904. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215905. logFailure (hr);
  215906. }
  215907. return client;
  215908. }
  215909. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215910. {
  215911. WAVEFORMATEXTENSIBLE format;
  215912. zerostruct (format);
  215913. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215914. {
  215915. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215916. }
  215917. else
  215918. {
  215919. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215920. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215921. }
  215922. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215923. format.Format.nChannels = (WORD) numChannels;
  215924. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215925. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215926. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215927. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215928. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215929. switch (numChannels)
  215930. {
  215931. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215932. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215933. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215934. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215935. 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;
  215936. default: break;
  215937. }
  215938. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215939. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215940. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215941. logFailure (hr);
  215942. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215943. {
  215944. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215945. hr = S_OK;
  215946. }
  215947. CoTaskMemFree (nearestFormat);
  215948. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215949. if (useExclusiveMode)
  215950. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215951. GUID session;
  215952. if (hr == S_OK
  215953. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215954. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215955. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215956. {
  215957. actualNumChannels = format.Format.nChannels;
  215958. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215959. bytesPerSample = format.Format.wBitsPerSample / 8;
  215960. updateFormat (isFloat);
  215961. return true;
  215962. }
  215963. return false;
  215964. }
  215965. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215966. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215967. };
  215968. class WASAPIInputDevice : public WASAPIDeviceBase
  215969. {
  215970. public:
  215971. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215972. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215973. reservoir (1, 1)
  215974. {
  215975. }
  215976. ~WASAPIInputDevice()
  215977. {
  215978. close();
  215979. }
  215980. bool open (const double newSampleRate, const BigInteger& newChannels)
  215981. {
  215982. reservoirSize = 0;
  215983. reservoirCapacity = 16384;
  215984. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215985. return openClient (newSampleRate, newChannels)
  215986. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  215987. }
  215988. void close()
  215989. {
  215990. closeClient();
  215991. captureClient = 0;
  215992. reservoir.setSize (0);
  215993. }
  215994. void updateFormat (bool isFloat)
  215995. {
  215996. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215997. if (isFloat)
  215998. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215999. else if (bytesPerSample == 4)
  216000. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  216001. else if (bytesPerSample == 3)
  216002. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  216003. else
  216004. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  216005. }
  216006. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  216007. {
  216008. if (numChannels <= 0)
  216009. return;
  216010. int offset = 0;
  216011. while (bufferSize > 0)
  216012. {
  216013. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  216014. {
  216015. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  216016. for (int i = 0; i < numDestBuffers; ++i)
  216017. converter->convertSamples (destBuffers[i], offset, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  216018. bufferSize -= samplesToDo;
  216019. offset += samplesToDo;
  216020. reservoirSize -= samplesToDo;
  216021. }
  216022. else
  216023. {
  216024. UINT32 packetLength = 0;
  216025. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  216026. break;
  216027. if (packetLength == 0)
  216028. {
  216029. if (thread.threadShouldExit())
  216030. break;
  216031. Thread::sleep (1);
  216032. continue;
  216033. }
  216034. uint8* inputData = 0;
  216035. UINT32 numSamplesAvailable;
  216036. DWORD flags;
  216037. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  216038. {
  216039. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  216040. for (int i = 0; i < numDestBuffers; ++i)
  216041. converter->convertSamples (destBuffers[i], offset, inputData, channelMaps.getUnchecked(i), samplesToDo);
  216042. bufferSize -= samplesToDo;
  216043. offset += samplesToDo;
  216044. if (samplesToDo < (int) numSamplesAvailable)
  216045. {
  216046. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  216047. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  216048. bytesPerSample * actualNumChannels * reservoirSize);
  216049. }
  216050. captureClient->ReleaseBuffer (numSamplesAvailable);
  216051. }
  216052. }
  216053. }
  216054. }
  216055. ComSmartPtr <IAudioCaptureClient> captureClient;
  216056. MemoryBlock reservoir;
  216057. int reservoirSize, reservoirCapacity;
  216058. ScopedPointer <AudioData::Converter> converter;
  216059. private:
  216060. WASAPIInputDevice (const WASAPIInputDevice&);
  216061. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  216062. };
  216063. class WASAPIOutputDevice : public WASAPIDeviceBase
  216064. {
  216065. public:
  216066. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  216067. : WASAPIDeviceBase (device_, useExclusiveMode_)
  216068. {
  216069. }
  216070. ~WASAPIOutputDevice()
  216071. {
  216072. close();
  216073. }
  216074. bool open (const double newSampleRate, const BigInteger& newChannels)
  216075. {
  216076. return openClient (newSampleRate, newChannels)
  216077. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  216078. }
  216079. void close()
  216080. {
  216081. closeClient();
  216082. renderClient = 0;
  216083. }
  216084. void updateFormat (bool isFloat)
  216085. {
  216086. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  216087. if (isFloat)
  216088. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216089. else if (bytesPerSample == 4)
  216090. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216091. else if (bytesPerSample == 3)
  216092. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216093. else
  216094. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216095. }
  216096. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  216097. {
  216098. if (numChannels <= 0)
  216099. return;
  216100. int offset = 0;
  216101. while (bufferSize > 0)
  216102. {
  216103. UINT32 padding = 0;
  216104. if (! check (client->GetCurrentPadding (&padding)))
  216105. return;
  216106. int samplesToDo = useExclusiveMode ? bufferSize
  216107. : jmin ((int) (actualBufferSize - padding), bufferSize);
  216108. if (samplesToDo <= 0)
  216109. {
  216110. if (thread.threadShouldExit())
  216111. break;
  216112. Thread::sleep (0);
  216113. continue;
  216114. }
  216115. uint8* outputData = 0;
  216116. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  216117. {
  216118. for (int i = 0; i < numSrcBuffers; ++i)
  216119. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i], offset, samplesToDo);
  216120. renderClient->ReleaseBuffer (samplesToDo, 0);
  216121. offset += samplesToDo;
  216122. bufferSize -= samplesToDo;
  216123. }
  216124. }
  216125. }
  216126. ComSmartPtr <IAudioRenderClient> renderClient;
  216127. ScopedPointer <AudioData::Converter> converter;
  216128. private:
  216129. WASAPIOutputDevice (const WASAPIOutputDevice&);
  216130. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  216131. };
  216132. class WASAPIAudioIODevice : public AudioIODevice,
  216133. public Thread
  216134. {
  216135. public:
  216136. WASAPIAudioIODevice (const String& deviceName,
  216137. const String& outputDeviceId_,
  216138. const String& inputDeviceId_,
  216139. const bool useExclusiveMode_)
  216140. : AudioIODevice (deviceName, "Windows Audio"),
  216141. Thread ("Juce WASAPI"),
  216142. isOpen_ (false),
  216143. isStarted (false),
  216144. outputDeviceId (outputDeviceId_),
  216145. inputDeviceId (inputDeviceId_),
  216146. useExclusiveMode (useExclusiveMode_),
  216147. currentBufferSizeSamples (0),
  216148. currentSampleRate (0),
  216149. callback (0)
  216150. {
  216151. }
  216152. ~WASAPIAudioIODevice()
  216153. {
  216154. close();
  216155. }
  216156. bool initialise()
  216157. {
  216158. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  216159. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  216160. latencyIn = latencyOut = 0;
  216161. Array <double> ratesIn, ratesOut;
  216162. if (createDevices())
  216163. {
  216164. jassert (inputDevice != 0 || outputDevice != 0);
  216165. if (inputDevice != 0 && outputDevice != 0)
  216166. {
  216167. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  216168. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  216169. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  216170. sampleRates = inputDevice->rates;
  216171. sampleRates.removeValuesNotIn (outputDevice->rates);
  216172. }
  216173. else
  216174. {
  216175. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  216176. : static_cast<WASAPIDeviceBase*> (outputDevice);
  216177. defaultSampleRate = d->defaultSampleRate;
  216178. minBufferSize = d->minBufferSize;
  216179. defaultBufferSize = d->defaultBufferSize;
  216180. sampleRates = d->rates;
  216181. }
  216182. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  216183. if (minBufferSize != defaultBufferSize)
  216184. bufferSizes.addUsingDefaultSort (minBufferSize);
  216185. int n = 64;
  216186. for (int i = 0; i < 40; ++i)
  216187. {
  216188. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216189. bufferSizes.addUsingDefaultSort (n);
  216190. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216191. }
  216192. return true;
  216193. }
  216194. return false;
  216195. }
  216196. const StringArray getOutputChannelNames()
  216197. {
  216198. StringArray outChannels;
  216199. if (outputDevice != 0)
  216200. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216201. outChannels.add ("Output channel " + String (i));
  216202. return outChannels;
  216203. }
  216204. const StringArray getInputChannelNames()
  216205. {
  216206. StringArray inChannels;
  216207. if (inputDevice != 0)
  216208. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216209. inChannels.add ("Input channel " + String (i));
  216210. return inChannels;
  216211. }
  216212. int getNumSampleRates() { return sampleRates.size(); }
  216213. double getSampleRate (int index) { return sampleRates [index]; }
  216214. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216215. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216216. int getDefaultBufferSize() { return defaultBufferSize; }
  216217. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216218. double getCurrentSampleRate() { return currentSampleRate; }
  216219. int getCurrentBitDepth() { return 32; }
  216220. int getOutputLatencyInSamples() { return latencyOut; }
  216221. int getInputLatencyInSamples() { return latencyIn; }
  216222. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216223. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216224. const String getLastError() { return lastError; }
  216225. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216226. double sampleRate, int bufferSizeSamples)
  216227. {
  216228. close();
  216229. lastError = String::empty;
  216230. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216231. {
  216232. lastError = "The input and output devices don't share a common sample rate!";
  216233. return lastError;
  216234. }
  216235. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216236. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216237. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216238. {
  216239. lastError = "Couldn't open the input device!";
  216240. return lastError;
  216241. }
  216242. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216243. {
  216244. close();
  216245. lastError = "Couldn't open the output device!";
  216246. return lastError;
  216247. }
  216248. if (inputDevice != 0)
  216249. ResetEvent (inputDevice->clientEvent);
  216250. if (outputDevice != 0)
  216251. ResetEvent (outputDevice->clientEvent);
  216252. startThread (8);
  216253. Thread::sleep (5);
  216254. if (inputDevice != 0 && inputDevice->client != 0)
  216255. {
  216256. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216257. HRESULT hr = inputDevice->client->Start();
  216258. logFailure (hr); //xxx handle this
  216259. }
  216260. if (outputDevice != 0 && outputDevice->client != 0)
  216261. {
  216262. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216263. HRESULT hr = outputDevice->client->Start();
  216264. logFailure (hr); //xxx handle this
  216265. }
  216266. isOpen_ = true;
  216267. return lastError;
  216268. }
  216269. void close()
  216270. {
  216271. stop();
  216272. if (inputDevice != 0)
  216273. SetEvent (inputDevice->clientEvent);
  216274. if (outputDevice != 0)
  216275. SetEvent (outputDevice->clientEvent);
  216276. stopThread (5000);
  216277. if (inputDevice != 0)
  216278. inputDevice->close();
  216279. if (outputDevice != 0)
  216280. outputDevice->close();
  216281. isOpen_ = false;
  216282. }
  216283. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216284. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216285. void start (AudioIODeviceCallback* call)
  216286. {
  216287. if (isOpen_ && call != 0 && ! isStarted)
  216288. {
  216289. if (! isThreadRunning())
  216290. {
  216291. // something's gone wrong and the thread's stopped..
  216292. isOpen_ = false;
  216293. return;
  216294. }
  216295. call->audioDeviceAboutToStart (this);
  216296. const ScopedLock sl (startStopLock);
  216297. callback = call;
  216298. isStarted = true;
  216299. }
  216300. }
  216301. void stop()
  216302. {
  216303. if (isStarted)
  216304. {
  216305. AudioIODeviceCallback* const callbackLocal = callback;
  216306. {
  216307. const ScopedLock sl (startStopLock);
  216308. isStarted = false;
  216309. }
  216310. if (callbackLocal != 0)
  216311. callbackLocal->audioDeviceStopped();
  216312. }
  216313. }
  216314. void setMMThreadPriority()
  216315. {
  216316. DynamicLibraryLoader dll ("avrt.dll");
  216317. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216318. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216319. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216320. {
  216321. DWORD dummy = 0;
  216322. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216323. if (h != 0)
  216324. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216325. }
  216326. }
  216327. void run()
  216328. {
  216329. setMMThreadPriority();
  216330. const int bufferSize = currentBufferSizeSamples;
  216331. HANDLE events[2];
  216332. int numEvents = 0;
  216333. if (inputDevice != 0)
  216334. events [numEvents++] = inputDevice->clientEvent;
  216335. if (outputDevice != 0)
  216336. events [numEvents++] = outputDevice->clientEvent;
  216337. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216338. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216339. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216340. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216341. float** const inputBuffers = ins.getArrayOfChannels();
  216342. float** const outputBuffers = outs.getArrayOfChannels();
  216343. ins.clear();
  216344. while (! threadShouldExit())
  216345. {
  216346. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216347. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216348. if (result == WAIT_TIMEOUT)
  216349. continue;
  216350. if (threadShouldExit())
  216351. break;
  216352. if (inputDevice != 0)
  216353. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216354. // Make the callback..
  216355. {
  216356. const ScopedLock sl (startStopLock);
  216357. if (isStarted)
  216358. {
  216359. JUCE_TRY
  216360. {
  216361. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216362. numInputBuffers,
  216363. outputBuffers,
  216364. numOutputBuffers,
  216365. bufferSize);
  216366. }
  216367. JUCE_CATCH_EXCEPTION
  216368. }
  216369. else
  216370. {
  216371. outs.clear();
  216372. }
  216373. }
  216374. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216375. continue;
  216376. if (outputDevice != 0)
  216377. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216378. }
  216379. }
  216380. juce_UseDebuggingNewOperator
  216381. String outputDeviceId, inputDeviceId;
  216382. String lastError;
  216383. private:
  216384. // Device stats...
  216385. ScopedPointer<WASAPIInputDevice> inputDevice;
  216386. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216387. const bool useExclusiveMode;
  216388. double defaultSampleRate;
  216389. int minBufferSize, defaultBufferSize;
  216390. int latencyIn, latencyOut;
  216391. Array <double> sampleRates;
  216392. Array <int> bufferSizes;
  216393. // Active state...
  216394. bool isOpen_, isStarted;
  216395. int currentBufferSizeSamples;
  216396. double currentSampleRate;
  216397. AudioIODeviceCallback* callback;
  216398. CriticalSection startStopLock;
  216399. bool createDevices()
  216400. {
  216401. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216402. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216403. return false;
  216404. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216405. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216406. return false;
  216407. UINT32 numDevices = 0;
  216408. if (! check (deviceCollection->GetCount (&numDevices)))
  216409. return false;
  216410. for (UINT32 i = 0; i < numDevices; ++i)
  216411. {
  216412. ComSmartPtr <IMMDevice> device;
  216413. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216414. continue;
  216415. const String deviceId (getDeviceID (device));
  216416. if (deviceId.isEmpty())
  216417. continue;
  216418. const EDataFlow flow = getDataFlow (device);
  216419. if (deviceId == inputDeviceId && flow == eCapture)
  216420. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216421. else if (deviceId == outputDeviceId && flow == eRender)
  216422. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216423. }
  216424. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216425. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216426. }
  216427. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216428. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216429. };
  216430. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216431. {
  216432. public:
  216433. WASAPIAudioIODeviceType()
  216434. : AudioIODeviceType ("Windows Audio"),
  216435. hasScanned (false)
  216436. {
  216437. }
  216438. ~WASAPIAudioIODeviceType()
  216439. {
  216440. }
  216441. void scanForDevices()
  216442. {
  216443. hasScanned = true;
  216444. outputDeviceNames.clear();
  216445. inputDeviceNames.clear();
  216446. outputDeviceIds.clear();
  216447. inputDeviceIds.clear();
  216448. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216449. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216450. return;
  216451. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216452. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216453. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216454. UINT32 numDevices = 0;
  216455. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216456. && check (deviceCollection->GetCount (&numDevices))))
  216457. return;
  216458. for (UINT32 i = 0; i < numDevices; ++i)
  216459. {
  216460. ComSmartPtr <IMMDevice> device;
  216461. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216462. continue;
  216463. const String deviceId (getDeviceID (device));
  216464. DWORD state = 0;
  216465. if (! check (device->GetState (&state)))
  216466. continue;
  216467. if (state != DEVICE_STATE_ACTIVE)
  216468. continue;
  216469. String name;
  216470. {
  216471. ComSmartPtr <IPropertyStore> properties;
  216472. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216473. continue;
  216474. PROPVARIANT value;
  216475. PropVariantInit (&value);
  216476. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216477. name = value.pwszVal;
  216478. PropVariantClear (&value);
  216479. }
  216480. const EDataFlow flow = getDataFlow (device);
  216481. if (flow == eRender)
  216482. {
  216483. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216484. outputDeviceIds.insert (index, deviceId);
  216485. outputDeviceNames.insert (index, name);
  216486. }
  216487. else if (flow == eCapture)
  216488. {
  216489. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216490. inputDeviceIds.insert (index, deviceId);
  216491. inputDeviceNames.insert (index, name);
  216492. }
  216493. }
  216494. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216495. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216496. }
  216497. const StringArray getDeviceNames (bool wantInputNames) const
  216498. {
  216499. jassert (hasScanned); // need to call scanForDevices() before doing this
  216500. return wantInputNames ? inputDeviceNames
  216501. : outputDeviceNames;
  216502. }
  216503. int getDefaultDeviceIndex (bool /*forInput*/) const
  216504. {
  216505. jassert (hasScanned); // need to call scanForDevices() before doing this
  216506. return 0;
  216507. }
  216508. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216509. {
  216510. jassert (hasScanned); // need to call scanForDevices() before doing this
  216511. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216512. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216513. : outputDeviceIds.indexOf (d->outputDeviceId));
  216514. }
  216515. bool hasSeparateInputsAndOutputs() const { return true; }
  216516. AudioIODevice* createDevice (const String& outputDeviceName,
  216517. const String& inputDeviceName)
  216518. {
  216519. jassert (hasScanned); // need to call scanForDevices() before doing this
  216520. const bool useExclusiveMode = false;
  216521. ScopedPointer<WASAPIAudioIODevice> device;
  216522. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216523. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216524. if (outputIndex >= 0 || inputIndex >= 0)
  216525. {
  216526. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216527. : inputDeviceName,
  216528. outputDeviceIds [outputIndex],
  216529. inputDeviceIds [inputIndex],
  216530. useExclusiveMode);
  216531. if (! device->initialise())
  216532. device = 0;
  216533. }
  216534. return device.release();
  216535. }
  216536. juce_UseDebuggingNewOperator
  216537. StringArray outputDeviceNames, outputDeviceIds;
  216538. StringArray inputDeviceNames, inputDeviceIds;
  216539. private:
  216540. bool hasScanned;
  216541. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216542. {
  216543. String s;
  216544. IMMDevice* dev = 0;
  216545. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216546. eMultimedia, &dev)))
  216547. {
  216548. WCHAR* deviceId = 0;
  216549. if (check (dev->GetId (&deviceId)))
  216550. {
  216551. s = String (deviceId);
  216552. CoTaskMemFree (deviceId);
  216553. }
  216554. dev->Release();
  216555. }
  216556. return s;
  216557. }
  216558. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216559. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216560. };
  216561. }
  216562. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216563. {
  216564. return new WasapiClasses::WASAPIAudioIODeviceType();
  216565. }
  216566. #endif
  216567. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216568. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216569. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216570. // compiled on its own).
  216571. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216572. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216573. {
  216574. public:
  216575. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216576. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216577. const ComSmartPtr <IBaseFilter>& filter_,
  216578. int minWidth, int minHeight,
  216579. int maxWidth, int maxHeight)
  216580. : owner (owner_),
  216581. captureGraphBuilder (captureGraphBuilder_),
  216582. filter (filter_),
  216583. ok (false),
  216584. imageNeedsFlipping (false),
  216585. width (0),
  216586. height (0),
  216587. activeUsers (0),
  216588. recordNextFrameTime (false),
  216589. previewMaxFPS (60)
  216590. {
  216591. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216592. if (FAILED (hr))
  216593. return;
  216594. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216595. if (FAILED (hr))
  216596. return;
  216597. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216598. if (FAILED (hr))
  216599. return;
  216600. {
  216601. ComSmartPtr <IAMStreamConfig> streamConfig;
  216602. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216603. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216604. if (streamConfig != 0)
  216605. {
  216606. getVideoSizes (streamConfig);
  216607. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216608. return;
  216609. }
  216610. }
  216611. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216612. if (FAILED (hr))
  216613. return;
  216614. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216615. if (FAILED (hr))
  216616. return;
  216617. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216618. if (FAILED (hr))
  216619. return;
  216620. if (! connectFilters (filter, smartTee))
  216621. return;
  216622. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216623. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216624. if (FAILED (hr))
  216625. return;
  216626. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216627. if (FAILED (hr))
  216628. return;
  216629. AM_MEDIA_TYPE mt;
  216630. zerostruct (mt);
  216631. mt.majortype = MEDIATYPE_Video;
  216632. mt.subtype = MEDIASUBTYPE_RGB24;
  216633. mt.formattype = FORMAT_VideoInfo;
  216634. sampleGrabber->SetMediaType (&mt);
  216635. callback = new GrabberCallback (*this);
  216636. hr = sampleGrabber->SetCallback (callback, 1);
  216637. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216638. if (FAILED (hr))
  216639. return;
  216640. ComSmartPtr <IPin> grabberInputPin;
  216641. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216642. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216643. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216644. return;
  216645. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216646. if (FAILED (hr))
  216647. return;
  216648. zerostruct (mt);
  216649. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216650. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216651. width = pVih->bmiHeader.biWidth;
  216652. height = pVih->bmiHeader.biHeight;
  216653. ComSmartPtr <IBaseFilter> nullFilter;
  216654. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216655. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216656. if (connectFilters (sampleGrabberBase, nullFilter)
  216657. && addGraphToRot())
  216658. {
  216659. activeImage = Image (Image::RGB, width, height, true);
  216660. loadingImage = Image (Image::RGB, width, height, true);
  216661. ok = true;
  216662. }
  216663. }
  216664. ~DShowCameraDeviceInteral()
  216665. {
  216666. if (mediaControl != 0)
  216667. mediaControl->Stop();
  216668. removeGraphFromRot();
  216669. for (int i = viewerComps.size(); --i >= 0;)
  216670. viewerComps.getUnchecked(i)->ownerDeleted();
  216671. callback = 0;
  216672. graphBuilder = 0;
  216673. sampleGrabber = 0;
  216674. mediaControl = 0;
  216675. filter = 0;
  216676. captureGraphBuilder = 0;
  216677. smartTee = 0;
  216678. smartTeePreviewOutputPin = 0;
  216679. smartTeeCaptureOutputPin = 0;
  216680. asfWriter = 0;
  216681. }
  216682. void addUser()
  216683. {
  216684. if (ok && activeUsers++ == 0)
  216685. mediaControl->Run();
  216686. }
  216687. void removeUser()
  216688. {
  216689. if (ok && --activeUsers == 0)
  216690. mediaControl->Stop();
  216691. }
  216692. int getPreviewMaxFPS() const
  216693. {
  216694. return previewMaxFPS;
  216695. }
  216696. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216697. {
  216698. if (recordNextFrameTime)
  216699. {
  216700. const double defaultCameraLatency = 0.1;
  216701. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216702. recordNextFrameTime = false;
  216703. ComSmartPtr <IPin> pin;
  216704. if (getPin (filter, PINDIR_OUTPUT, pin))
  216705. {
  216706. ComSmartPtr <IAMPushSource> pushSource;
  216707. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216708. if (pushSource != 0)
  216709. {
  216710. REFERENCE_TIME latency = 0;
  216711. hr = pushSource->GetLatency (&latency);
  216712. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216713. }
  216714. }
  216715. }
  216716. {
  216717. const int lineStride = width * 3;
  216718. const ScopedLock sl (imageSwapLock);
  216719. {
  216720. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216721. for (int i = 0; i < height; ++i)
  216722. memcpy (destData.getLinePointer ((height - 1) - i),
  216723. buffer + lineStride * i,
  216724. lineStride);
  216725. }
  216726. imageNeedsFlipping = true;
  216727. }
  216728. if (listeners.size() > 0)
  216729. callListeners (loadingImage);
  216730. sendChangeMessage (this);
  216731. }
  216732. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216733. {
  216734. if (imageNeedsFlipping)
  216735. {
  216736. const ScopedLock sl (imageSwapLock);
  216737. swapVariables (loadingImage, activeImage);
  216738. imageNeedsFlipping = false;
  216739. }
  216740. RectanglePlacement rp (RectanglePlacement::centred);
  216741. double dx = 0, dy = 0, dw = width, dh = height;
  216742. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216743. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216744. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216745. g.saveState();
  216746. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216747. g.fillAll (Colours::black);
  216748. g.restoreState();
  216749. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216750. }
  216751. bool createFileCaptureFilter (const File& file, int quality)
  216752. {
  216753. removeFileCaptureFilter();
  216754. file.deleteFile();
  216755. mediaControl->Stop();
  216756. firstRecordedTime = Time();
  216757. recordNextFrameTime = true;
  216758. previewMaxFPS = 60;
  216759. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216760. if (SUCCEEDED (hr))
  216761. {
  216762. ComSmartPtr <IFileSinkFilter> fileSink;
  216763. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216764. if (SUCCEEDED (hr))
  216765. {
  216766. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216767. if (SUCCEEDED (hr))
  216768. {
  216769. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216770. if (SUCCEEDED (hr))
  216771. {
  216772. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216773. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216774. asfConfig->SetIndexMode (true);
  216775. ComSmartPtr <IWMProfileManager> profileManager;
  216776. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216777. // This gibberish is the DirectShow profile for a video-only wmv file.
  216778. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216779. " <streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\""
  216780. " streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\""
  216781. " bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216782. " <videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216783. " <wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\""
  216784. " btemporalcompression=\"1\" lsamplesize=\"0\">"
  216785. " <videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216786. " <rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216787. " <rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216788. " <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\""
  216789. " bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\""
  216790. " biclrused=\"0\" biclrimportant=\"0\"/>"
  216791. " </videoinfoheader>"
  216792. " </wmmediatype>"
  216793. " </streamconfig>"
  216794. "</profile>");
  216795. const int fps[] = { 10, 15, 30 };
  216796. const int maxFramesPerSecond = fps [quality % numElementsInArray (fps)];
  216797. prof = prof.replace ("$WIDTH", String (width))
  216798. .replace ("$HEIGHT", String (height))
  216799. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216800. ComSmartPtr <IWMProfile> currentProfile;
  216801. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216802. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216803. if (SUCCEEDED (hr))
  216804. {
  216805. ComSmartPtr <IPin> asfWriterInputPin;
  216806. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216807. {
  216808. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216809. if (SUCCEEDED (hr)
  216810. && ok && activeUsers > 0
  216811. && SUCCEEDED (mediaControl->Run()))
  216812. {
  216813. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216814. return true;
  216815. }
  216816. }
  216817. }
  216818. }
  216819. }
  216820. }
  216821. }
  216822. removeFileCaptureFilter();
  216823. if (ok && activeUsers > 0)
  216824. mediaControl->Run();
  216825. return false;
  216826. }
  216827. void removeFileCaptureFilter()
  216828. {
  216829. mediaControl->Stop();
  216830. if (asfWriter != 0)
  216831. {
  216832. graphBuilder->RemoveFilter (asfWriter);
  216833. asfWriter = 0;
  216834. }
  216835. if (ok && activeUsers > 0)
  216836. mediaControl->Run();
  216837. previewMaxFPS = 60;
  216838. }
  216839. void addListener (CameraDevice::Listener* listenerToAdd)
  216840. {
  216841. const ScopedLock sl (listenerLock);
  216842. if (listeners.size() == 0)
  216843. addUser();
  216844. listeners.addIfNotAlreadyThere (listenerToAdd);
  216845. }
  216846. void removeListener (CameraDevice::Listener* listenerToRemove)
  216847. {
  216848. const ScopedLock sl (listenerLock);
  216849. listeners.removeValue (listenerToRemove);
  216850. if (listeners.size() == 0)
  216851. removeUser();
  216852. }
  216853. void callListeners (const Image& image)
  216854. {
  216855. const ScopedLock sl (listenerLock);
  216856. for (int i = listeners.size(); --i >= 0;)
  216857. {
  216858. CameraDevice::Listener* const l = listeners[i];
  216859. if (l != 0)
  216860. l->imageReceived (image);
  216861. }
  216862. }
  216863. class DShowCaptureViewerComp : public Component,
  216864. public ChangeListener
  216865. {
  216866. public:
  216867. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216868. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216869. {
  216870. setOpaque (true);
  216871. owner->addChangeListener (this);
  216872. owner->addUser();
  216873. owner->viewerComps.add (this);
  216874. setSize (owner->width, owner->height);
  216875. }
  216876. ~DShowCaptureViewerComp()
  216877. {
  216878. if (owner != 0)
  216879. {
  216880. owner->viewerComps.removeValue (this);
  216881. owner->removeUser();
  216882. owner->removeChangeListener (this);
  216883. }
  216884. }
  216885. void ownerDeleted()
  216886. {
  216887. owner = 0;
  216888. }
  216889. void paint (Graphics& g)
  216890. {
  216891. g.setColour (Colours::black);
  216892. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216893. if (owner != 0)
  216894. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216895. else
  216896. g.fillAll (Colours::black);
  216897. }
  216898. void changeListenerCallback (void*)
  216899. {
  216900. const int64 now = Time::currentTimeMillis();
  216901. if (now >= lastRepaintTime + (1000 / maxFPS))
  216902. {
  216903. lastRepaintTime = now;
  216904. repaint();
  216905. if (owner != 0)
  216906. maxFPS = owner->getPreviewMaxFPS();
  216907. }
  216908. }
  216909. private:
  216910. DShowCameraDeviceInteral* owner;
  216911. int maxFPS;
  216912. int64 lastRepaintTime;
  216913. };
  216914. bool ok;
  216915. int width, height;
  216916. Time firstRecordedTime;
  216917. Array <DShowCaptureViewerComp*> viewerComps;
  216918. private:
  216919. CameraDevice* const owner;
  216920. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216921. ComSmartPtr <IBaseFilter> filter;
  216922. ComSmartPtr <IBaseFilter> smartTee;
  216923. ComSmartPtr <IGraphBuilder> graphBuilder;
  216924. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216925. ComSmartPtr <IMediaControl> mediaControl;
  216926. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216927. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216928. ComSmartPtr <IBaseFilter> asfWriter;
  216929. int activeUsers;
  216930. Array <int> widths, heights;
  216931. DWORD graphRegistrationID;
  216932. CriticalSection imageSwapLock;
  216933. bool imageNeedsFlipping;
  216934. Image loadingImage;
  216935. Image activeImage;
  216936. bool recordNextFrameTime;
  216937. int previewMaxFPS;
  216938. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216939. {
  216940. widths.clear();
  216941. heights.clear();
  216942. int count = 0, size = 0;
  216943. streamConfig->GetNumberOfCapabilities (&count, &size);
  216944. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216945. {
  216946. for (int i = 0; i < count; ++i)
  216947. {
  216948. VIDEO_STREAM_CONFIG_CAPS scc;
  216949. AM_MEDIA_TYPE* config;
  216950. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216951. if (SUCCEEDED (hr))
  216952. {
  216953. const int w = scc.InputSize.cx;
  216954. const int h = scc.InputSize.cy;
  216955. bool duplicate = false;
  216956. for (int j = widths.size(); --j >= 0;)
  216957. {
  216958. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216959. {
  216960. duplicate = true;
  216961. break;
  216962. }
  216963. }
  216964. if (! duplicate)
  216965. {
  216966. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216967. widths.add (w);
  216968. heights.add (h);
  216969. }
  216970. deleteMediaType (config);
  216971. }
  216972. }
  216973. }
  216974. }
  216975. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216976. const int minWidth, const int minHeight,
  216977. const int maxWidth, const int maxHeight)
  216978. {
  216979. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216980. streamConfig->GetNumberOfCapabilities (&count, &size);
  216981. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216982. {
  216983. AM_MEDIA_TYPE* config;
  216984. VIDEO_STREAM_CONFIG_CAPS scc;
  216985. for (int i = 0; i < count; ++i)
  216986. {
  216987. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216988. if (SUCCEEDED (hr))
  216989. {
  216990. if (scc.InputSize.cx >= minWidth
  216991. && scc.InputSize.cy >= minHeight
  216992. && scc.InputSize.cx <= maxWidth
  216993. && scc.InputSize.cy <= maxHeight)
  216994. {
  216995. int area = scc.InputSize.cx * scc.InputSize.cy;
  216996. if (area > bestArea)
  216997. {
  216998. bestIndex = i;
  216999. bestArea = area;
  217000. }
  217001. }
  217002. deleteMediaType (config);
  217003. }
  217004. }
  217005. if (bestIndex >= 0)
  217006. {
  217007. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  217008. hr = streamConfig->SetFormat (config);
  217009. deleteMediaType (config);
  217010. return SUCCEEDED (hr);
  217011. }
  217012. }
  217013. return false;
  217014. }
  217015. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  217016. {
  217017. ComSmartPtr <IEnumPins> enumerator;
  217018. ComSmartPtr <IPin> pin;
  217019. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  217020. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  217021. {
  217022. PIN_DIRECTION dir;
  217023. pin->QueryDirection (&dir);
  217024. if (wantedDirection == dir)
  217025. {
  217026. PIN_INFO info;
  217027. zerostruct (info);
  217028. pin->QueryPinInfo (&info);
  217029. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  217030. {
  217031. result = pin;
  217032. return true;
  217033. }
  217034. }
  217035. }
  217036. return false;
  217037. }
  217038. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  217039. {
  217040. ComSmartPtr <IPin> in, out;
  217041. return getPin (first, PINDIR_OUTPUT, out)
  217042. && getPin (second, PINDIR_INPUT, in)
  217043. && SUCCEEDED (graphBuilder->Connect (out, in));
  217044. }
  217045. bool addGraphToRot()
  217046. {
  217047. ComSmartPtr <IRunningObjectTable> rot;
  217048. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  217049. return false;
  217050. ComSmartPtr <IMoniker> moniker;
  217051. WCHAR buffer[128];
  217052. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  217053. if (FAILED (hr))
  217054. return false;
  217055. graphRegistrationID = 0;
  217056. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  217057. }
  217058. void removeGraphFromRot()
  217059. {
  217060. ComSmartPtr <IRunningObjectTable> rot;
  217061. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  217062. rot->Revoke (graphRegistrationID);
  217063. }
  217064. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  217065. {
  217066. if (pmt->cbFormat != 0)
  217067. CoTaskMemFree ((PVOID) pmt->pbFormat);
  217068. if (pmt->pUnk != 0)
  217069. pmt->pUnk->Release();
  217070. CoTaskMemFree (pmt);
  217071. }
  217072. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  217073. {
  217074. public:
  217075. GrabberCallback (DShowCameraDeviceInteral& owner_)
  217076. : owner (owner_)
  217077. {
  217078. }
  217079. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  217080. {
  217081. return E_FAIL;
  217082. }
  217083. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  217084. {
  217085. owner.handleFrame (time, buffer, bufferSize);
  217086. return S_OK;
  217087. }
  217088. private:
  217089. DShowCameraDeviceInteral& owner;
  217090. GrabberCallback (const GrabberCallback&);
  217091. GrabberCallback& operator= (const GrabberCallback&);
  217092. };
  217093. ComSmartPtr <GrabberCallback> callback;
  217094. Array <CameraDevice::Listener*> listeners;
  217095. CriticalSection listenerLock;
  217096. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  217097. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  217098. };
  217099. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  217100. : name (name_)
  217101. {
  217102. isRecording = false;
  217103. }
  217104. CameraDevice::~CameraDevice()
  217105. {
  217106. stopRecording();
  217107. delete static_cast <DShowCameraDeviceInteral*> (internal);
  217108. internal = 0;
  217109. }
  217110. Component* CameraDevice::createViewerComponent()
  217111. {
  217112. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  217113. }
  217114. const String CameraDevice::getFileExtension()
  217115. {
  217116. return ".wmv";
  217117. }
  217118. void CameraDevice::startRecordingToFile (const File& file, int quality)
  217119. {
  217120. jassert (quality >= 0 && quality <= 2);
  217121. stopRecording();
  217122. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217123. d->addUser();
  217124. isRecording = d->createFileCaptureFilter (file, quality);
  217125. }
  217126. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  217127. {
  217128. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217129. return d->firstRecordedTime;
  217130. }
  217131. void CameraDevice::stopRecording()
  217132. {
  217133. if (isRecording)
  217134. {
  217135. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217136. d->removeFileCaptureFilter();
  217137. d->removeUser();
  217138. isRecording = false;
  217139. }
  217140. }
  217141. void CameraDevice::addListener (Listener* listenerToAdd)
  217142. {
  217143. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217144. if (listenerToAdd != 0)
  217145. d->addListener (listenerToAdd);
  217146. }
  217147. void CameraDevice::removeListener (Listener* listenerToRemove)
  217148. {
  217149. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217150. if (listenerToRemove != 0)
  217151. d->removeListener (listenerToRemove);
  217152. }
  217153. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  217154. const int deviceIndexToOpen,
  217155. String& name)
  217156. {
  217157. int index = 0;
  217158. ComSmartPtr <IBaseFilter> result;
  217159. ComSmartPtr <ICreateDevEnum> pDevEnum;
  217160. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  217161. if (SUCCEEDED (hr))
  217162. {
  217163. ComSmartPtr <IEnumMoniker> enumerator;
  217164. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  217165. if (SUCCEEDED (hr) && enumerator != 0)
  217166. {
  217167. ComSmartPtr <IMoniker> moniker;
  217168. ULONG fetched;
  217169. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  217170. {
  217171. ComSmartPtr <IBaseFilter> captureFilter;
  217172. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  217173. if (SUCCEEDED (hr))
  217174. {
  217175. ComSmartPtr <IPropertyBag> propertyBag;
  217176. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  217177. if (SUCCEEDED (hr))
  217178. {
  217179. VARIANT var;
  217180. var.vt = VT_BSTR;
  217181. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  217182. propertyBag = 0;
  217183. if (SUCCEEDED (hr))
  217184. {
  217185. if (names != 0)
  217186. names->add (var.bstrVal);
  217187. if (index == deviceIndexToOpen)
  217188. {
  217189. name = var.bstrVal;
  217190. result = captureFilter;
  217191. break;
  217192. }
  217193. ++index;
  217194. }
  217195. }
  217196. }
  217197. }
  217198. }
  217199. }
  217200. return result;
  217201. }
  217202. const StringArray CameraDevice::getAvailableDevices()
  217203. {
  217204. StringArray devs;
  217205. String dummy;
  217206. enumerateCameras (&devs, -1, dummy);
  217207. return devs;
  217208. }
  217209. CameraDevice* CameraDevice::openDevice (int index,
  217210. int minWidth, int minHeight,
  217211. int maxWidth, int maxHeight)
  217212. {
  217213. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  217214. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217215. if (SUCCEEDED (hr))
  217216. {
  217217. String name;
  217218. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217219. if (filter != 0)
  217220. {
  217221. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217222. DShowCameraDeviceInteral* const intern
  217223. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217224. minWidth, minHeight, maxWidth, maxHeight);
  217225. cam->internal = intern;
  217226. if (intern->ok)
  217227. return cam.release();
  217228. }
  217229. }
  217230. return 0;
  217231. }
  217232. #endif
  217233. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217234. #endif
  217235. // Auto-link the other win32 libs that are needed by library calls..
  217236. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217237. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217238. // Auto-links to various win32 libs that are needed by library calls..
  217239. #pragma comment(lib, "kernel32.lib")
  217240. #pragma comment(lib, "user32.lib")
  217241. #pragma comment(lib, "shell32.lib")
  217242. #pragma comment(lib, "gdi32.lib")
  217243. #pragma comment(lib, "vfw32.lib")
  217244. #pragma comment(lib, "comdlg32.lib")
  217245. #pragma comment(lib, "winmm.lib")
  217246. #pragma comment(lib, "wininet.lib")
  217247. #pragma comment(lib, "ole32.lib")
  217248. #pragma comment(lib, "oleaut32.lib")
  217249. #pragma comment(lib, "advapi32.lib")
  217250. #pragma comment(lib, "ws2_32.lib")
  217251. #pragma comment(lib, "version.lib")
  217252. #ifdef _NATIVE_WCHAR_T_DEFINED
  217253. #ifdef _DEBUG
  217254. #pragma comment(lib, "comsuppwd.lib")
  217255. #else
  217256. #pragma comment(lib, "comsuppw.lib")
  217257. #endif
  217258. #else
  217259. #ifdef _DEBUG
  217260. #pragma comment(lib, "comsuppd.lib")
  217261. #else
  217262. #pragma comment(lib, "comsupp.lib")
  217263. #endif
  217264. #endif
  217265. #if JUCE_OPENGL
  217266. #pragma comment(lib, "OpenGL32.Lib")
  217267. #pragma comment(lib, "GlU32.Lib")
  217268. #endif
  217269. #if JUCE_QUICKTIME
  217270. #pragma comment (lib, "QTMLClient.lib")
  217271. #endif
  217272. #if JUCE_USE_CAMERA
  217273. #pragma comment (lib, "Strmiids.lib")
  217274. #pragma comment (lib, "wmvcore.lib")
  217275. #endif
  217276. #if JUCE_DIRECT2D
  217277. #pragma comment (lib, "Dwrite.lib")
  217278. #pragma comment (lib, "D2d1.lib")
  217279. #endif
  217280. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217281. #endif
  217282. END_JUCE_NAMESPACE
  217283. #endif
  217284. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217285. #endif
  217286. #if JUCE_LINUX
  217287. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217288. /*
  217289. This file wraps together all the mac-specific code, so that
  217290. we can include all the native headers just once, and compile all our
  217291. platform-specific stuff in one big lump, keeping it out of the way of
  217292. the rest of the codebase.
  217293. */
  217294. #if JUCE_LINUX
  217295. BEGIN_JUCE_NAMESPACE
  217296. #define JUCE_INCLUDED_FILE 1
  217297. // Now include the actual code files..
  217298. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217299. /*
  217300. This file contains posix routines that are common to both the Linux and Mac builds.
  217301. It gets included directly in the cpp files for these platforms.
  217302. */
  217303. CriticalSection::CriticalSection() throw()
  217304. {
  217305. pthread_mutexattr_t atts;
  217306. pthread_mutexattr_init (&atts);
  217307. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217308. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217309. pthread_mutex_init (&internal, &atts);
  217310. }
  217311. CriticalSection::~CriticalSection() throw()
  217312. {
  217313. pthread_mutex_destroy (&internal);
  217314. }
  217315. void CriticalSection::enter() const throw()
  217316. {
  217317. pthread_mutex_lock (&internal);
  217318. }
  217319. bool CriticalSection::tryEnter() const throw()
  217320. {
  217321. return pthread_mutex_trylock (&internal) == 0;
  217322. }
  217323. void CriticalSection::exit() const throw()
  217324. {
  217325. pthread_mutex_unlock (&internal);
  217326. }
  217327. class WaitableEventImpl
  217328. {
  217329. public:
  217330. WaitableEventImpl (const bool manualReset_)
  217331. : triggered (false),
  217332. manualReset (manualReset_)
  217333. {
  217334. pthread_cond_init (&condition, 0);
  217335. pthread_mutexattr_t atts;
  217336. pthread_mutexattr_init (&atts);
  217337. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217338. pthread_mutex_init (&mutex, &atts);
  217339. }
  217340. ~WaitableEventImpl()
  217341. {
  217342. pthread_cond_destroy (&condition);
  217343. pthread_mutex_destroy (&mutex);
  217344. }
  217345. bool wait (const int timeOutMillisecs) throw()
  217346. {
  217347. pthread_mutex_lock (&mutex);
  217348. if (! triggered)
  217349. {
  217350. if (timeOutMillisecs < 0)
  217351. {
  217352. do
  217353. {
  217354. pthread_cond_wait (&condition, &mutex);
  217355. }
  217356. while (! triggered);
  217357. }
  217358. else
  217359. {
  217360. struct timeval now;
  217361. gettimeofday (&now, 0);
  217362. struct timespec time;
  217363. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217364. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217365. if (time.tv_nsec >= 1000000000)
  217366. {
  217367. time.tv_nsec -= 1000000000;
  217368. time.tv_sec++;
  217369. }
  217370. do
  217371. {
  217372. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217373. {
  217374. pthread_mutex_unlock (&mutex);
  217375. return false;
  217376. }
  217377. }
  217378. while (! triggered);
  217379. }
  217380. }
  217381. if (! manualReset)
  217382. triggered = false;
  217383. pthread_mutex_unlock (&mutex);
  217384. return true;
  217385. }
  217386. void signal() throw()
  217387. {
  217388. pthread_mutex_lock (&mutex);
  217389. triggered = true;
  217390. pthread_cond_broadcast (&condition);
  217391. pthread_mutex_unlock (&mutex);
  217392. }
  217393. void reset() throw()
  217394. {
  217395. pthread_mutex_lock (&mutex);
  217396. triggered = false;
  217397. pthread_mutex_unlock (&mutex);
  217398. }
  217399. private:
  217400. pthread_cond_t condition;
  217401. pthread_mutex_t mutex;
  217402. bool triggered;
  217403. const bool manualReset;
  217404. WaitableEventImpl (const WaitableEventImpl&);
  217405. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217406. };
  217407. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217408. : internal (new WaitableEventImpl (manualReset))
  217409. {
  217410. }
  217411. WaitableEvent::~WaitableEvent() throw()
  217412. {
  217413. delete static_cast <WaitableEventImpl*> (internal);
  217414. }
  217415. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217416. {
  217417. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217418. }
  217419. void WaitableEvent::signal() const throw()
  217420. {
  217421. static_cast <WaitableEventImpl*> (internal)->signal();
  217422. }
  217423. void WaitableEvent::reset() const throw()
  217424. {
  217425. static_cast <WaitableEventImpl*> (internal)->reset();
  217426. }
  217427. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217428. {
  217429. struct timespec time;
  217430. time.tv_sec = millisecs / 1000;
  217431. time.tv_nsec = (millisecs % 1000) * 1000000;
  217432. nanosleep (&time, 0);
  217433. }
  217434. const juce_wchar File::separator = '/';
  217435. const String File::separatorString ("/");
  217436. const File File::getCurrentWorkingDirectory()
  217437. {
  217438. HeapBlock<char> heapBuffer;
  217439. char localBuffer [1024];
  217440. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217441. int bufferSize = 4096;
  217442. while (cwd == 0 && errno == ERANGE)
  217443. {
  217444. heapBuffer.malloc (bufferSize);
  217445. cwd = getcwd (heapBuffer, bufferSize - 1);
  217446. bufferSize += 1024;
  217447. }
  217448. return File (String::fromUTF8 (cwd));
  217449. }
  217450. bool File::setAsCurrentWorkingDirectory() const
  217451. {
  217452. return chdir (getFullPathName().toUTF8()) == 0;
  217453. }
  217454. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217455. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217456. #else
  217457. typedef struct stat juce_statStruct;
  217458. #endif
  217459. static bool juce_stat (const String& fileName, juce_statStruct& info)
  217460. {
  217461. return fileName.isNotEmpty()
  217462. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217463. && (stat64 (fileName.toUTF8(), &info) == 0);
  217464. #else
  217465. && (stat (fileName.toUTF8(), &info) == 0);
  217466. #endif
  217467. }
  217468. bool File::isDirectory() const
  217469. {
  217470. juce_statStruct info;
  217471. return fullPath.isEmpty()
  217472. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217473. }
  217474. bool File::exists() const
  217475. {
  217476. juce_statStruct info;
  217477. return fullPath.isNotEmpty()
  217478. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217479. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217480. #else
  217481. && (lstat (fullPath.toUTF8(), &info) == 0);
  217482. #endif
  217483. }
  217484. bool File::existsAsFile() const
  217485. {
  217486. return exists() && ! isDirectory();
  217487. }
  217488. int64 File::getSize() const
  217489. {
  217490. juce_statStruct info;
  217491. return juce_stat (fullPath, info) ? info.st_size : 0;
  217492. }
  217493. bool File::hasWriteAccess() const
  217494. {
  217495. if (exists())
  217496. return access (fullPath.toUTF8(), W_OK) == 0;
  217497. if ((! isDirectory()) && fullPath.containsChar (separator))
  217498. return getParentDirectory().hasWriteAccess();
  217499. return false;
  217500. }
  217501. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217502. {
  217503. juce_statStruct info;
  217504. if (! juce_stat (fullPath, info))
  217505. return false;
  217506. info.st_mode &= 0777; // Just permissions
  217507. if (shouldBeReadOnly)
  217508. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217509. else
  217510. // Give everybody write permission?
  217511. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217512. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217513. }
  217514. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217515. {
  217516. modificationTime = 0;
  217517. accessTime = 0;
  217518. creationTime = 0;
  217519. juce_statStruct info;
  217520. if (juce_stat (fullPath, info))
  217521. {
  217522. modificationTime = (int64) info.st_mtime * 1000;
  217523. accessTime = (int64) info.st_atime * 1000;
  217524. creationTime = (int64) info.st_ctime * 1000;
  217525. }
  217526. }
  217527. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217528. {
  217529. struct utimbuf times;
  217530. times.actime = (time_t) (accessTime / 1000);
  217531. times.modtime = (time_t) (modificationTime / 1000);
  217532. return utime (fullPath.toUTF8(), &times) == 0;
  217533. }
  217534. bool File::deleteFile() const
  217535. {
  217536. if (! exists())
  217537. return true;
  217538. else if (isDirectory())
  217539. return rmdir (fullPath.toUTF8()) == 0;
  217540. else
  217541. return remove (fullPath.toUTF8()) == 0;
  217542. }
  217543. bool File::moveInternal (const File& dest) const
  217544. {
  217545. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217546. return true;
  217547. if (hasWriteAccess() && copyInternal (dest))
  217548. {
  217549. if (deleteFile())
  217550. return true;
  217551. dest.deleteFile();
  217552. }
  217553. return false;
  217554. }
  217555. void File::createDirectoryInternal (const String& fileName) const
  217556. {
  217557. mkdir (fileName.toUTF8(), 0777);
  217558. }
  217559. int64 juce_fileSetPosition (void* handle, int64 pos)
  217560. {
  217561. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217562. return pos;
  217563. return -1;
  217564. }
  217565. void FileInputStream::openHandle()
  217566. {
  217567. totalSize = file.getSize();
  217568. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217569. if (f != -1)
  217570. fileHandle = (void*) f;
  217571. }
  217572. void FileInputStream::closeHandle()
  217573. {
  217574. if (fileHandle != 0)
  217575. {
  217576. close ((int) (pointer_sized_int) fileHandle);
  217577. fileHandle = 0;
  217578. }
  217579. }
  217580. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217581. {
  217582. if (fileHandle != 0)
  217583. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217584. return 0;
  217585. }
  217586. void FileOutputStream::openHandle()
  217587. {
  217588. if (file.exists())
  217589. {
  217590. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217591. if (f != -1)
  217592. {
  217593. currentPosition = lseek (f, 0, SEEK_END);
  217594. if (currentPosition >= 0)
  217595. fileHandle = (void*) f;
  217596. else
  217597. close (f);
  217598. }
  217599. }
  217600. else
  217601. {
  217602. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217603. if (f != -1)
  217604. fileHandle = (void*) f;
  217605. }
  217606. }
  217607. void FileOutputStream::closeHandle()
  217608. {
  217609. if (fileHandle != 0)
  217610. {
  217611. close ((int) (pointer_sized_int) fileHandle);
  217612. fileHandle = 0;
  217613. }
  217614. }
  217615. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217616. {
  217617. if (fileHandle != 0)
  217618. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217619. return 0;
  217620. }
  217621. void FileOutputStream::flushInternal()
  217622. {
  217623. if (fileHandle != 0)
  217624. fsync ((int) (pointer_sized_int) fileHandle);
  217625. }
  217626. const File juce_getExecutableFile()
  217627. {
  217628. Dl_info exeInfo;
  217629. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217630. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217631. }
  217632. // if this file doesn't exist, find a parent of it that does..
  217633. static bool juce_doStatFS (File f, struct statfs& result)
  217634. {
  217635. for (int i = 5; --i >= 0;)
  217636. {
  217637. if (f.exists())
  217638. break;
  217639. f = f.getParentDirectory();
  217640. }
  217641. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217642. }
  217643. int64 File::getBytesFreeOnVolume() const
  217644. {
  217645. struct statfs buf;
  217646. if (juce_doStatFS (*this, buf))
  217647. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217648. return 0;
  217649. }
  217650. int64 File::getVolumeTotalSize() const
  217651. {
  217652. struct statfs buf;
  217653. if (juce_doStatFS (*this, buf))
  217654. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217655. return 0;
  217656. }
  217657. const String File::getVolumeLabel() const
  217658. {
  217659. #if JUCE_MAC
  217660. struct VolAttrBuf
  217661. {
  217662. u_int32_t length;
  217663. attrreference_t mountPointRef;
  217664. char mountPointSpace [MAXPATHLEN];
  217665. } attrBuf;
  217666. struct attrlist attrList;
  217667. zerostruct (attrList);
  217668. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217669. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217670. File f (*this);
  217671. for (;;)
  217672. {
  217673. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217674. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217675. (int) attrBuf.mountPointRef.attr_length);
  217676. const File parent (f.getParentDirectory());
  217677. if (f == parent)
  217678. break;
  217679. f = parent;
  217680. }
  217681. #endif
  217682. return String::empty;
  217683. }
  217684. int File::getVolumeSerialNumber() const
  217685. {
  217686. return 0; // xxx
  217687. }
  217688. void juce_runSystemCommand (const String& command)
  217689. {
  217690. int result = system (command.toUTF8());
  217691. (void) result;
  217692. }
  217693. const String juce_getOutputFromCommand (const String& command)
  217694. {
  217695. // slight bodge here, as we just pipe the output into a temp file and read it...
  217696. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217697. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217698. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217699. String result (tempFile.loadFileAsString());
  217700. tempFile.deleteFile();
  217701. return result;
  217702. }
  217703. class InterProcessLock::Pimpl
  217704. {
  217705. public:
  217706. Pimpl (const String& name, const int timeOutMillisecs)
  217707. : handle (0), refCount (1)
  217708. {
  217709. #if JUCE_MAC
  217710. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217711. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217712. #else
  217713. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217714. #endif
  217715. temp.create();
  217716. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217717. if (handle != 0)
  217718. {
  217719. struct flock fl;
  217720. zerostruct (fl);
  217721. fl.l_whence = SEEK_SET;
  217722. fl.l_type = F_WRLCK;
  217723. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217724. for (;;)
  217725. {
  217726. const int result = fcntl (handle, F_SETLK, &fl);
  217727. if (result >= 0)
  217728. return;
  217729. if (errno != EINTR)
  217730. {
  217731. if (timeOutMillisecs == 0
  217732. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217733. break;
  217734. Thread::sleep (10);
  217735. }
  217736. }
  217737. }
  217738. closeFile();
  217739. }
  217740. ~Pimpl()
  217741. {
  217742. closeFile();
  217743. }
  217744. void closeFile()
  217745. {
  217746. if (handle != 0)
  217747. {
  217748. struct flock fl;
  217749. zerostruct (fl);
  217750. fl.l_whence = SEEK_SET;
  217751. fl.l_type = F_UNLCK;
  217752. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217753. {}
  217754. close (handle);
  217755. handle = 0;
  217756. }
  217757. }
  217758. int handle, refCount;
  217759. };
  217760. InterProcessLock::InterProcessLock (const String& name_)
  217761. : name (name_)
  217762. {
  217763. }
  217764. InterProcessLock::~InterProcessLock()
  217765. {
  217766. }
  217767. bool InterProcessLock::enter (const int timeOutMillisecs)
  217768. {
  217769. const ScopedLock sl (lock);
  217770. if (pimpl == 0)
  217771. {
  217772. pimpl = new Pimpl (name, timeOutMillisecs);
  217773. if (pimpl->handle == 0)
  217774. pimpl = 0;
  217775. }
  217776. else
  217777. {
  217778. pimpl->refCount++;
  217779. }
  217780. return pimpl != 0;
  217781. }
  217782. void InterProcessLock::exit()
  217783. {
  217784. const ScopedLock sl (lock);
  217785. // Trying to release the lock too many times!
  217786. jassert (pimpl != 0);
  217787. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217788. pimpl = 0;
  217789. }
  217790. void JUCE_API juce_threadEntryPoint (void*);
  217791. void* threadEntryProc (void* userData)
  217792. {
  217793. JUCE_AUTORELEASEPOOL
  217794. juce_threadEntryPoint (userData);
  217795. return 0;
  217796. }
  217797. void* juce_createThread (void* userData)
  217798. {
  217799. pthread_t handle = 0;
  217800. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217801. {
  217802. pthread_detach (handle);
  217803. return (void*) handle;
  217804. }
  217805. return 0;
  217806. }
  217807. void juce_killThread (void* handle)
  217808. {
  217809. if (handle != 0)
  217810. pthread_cancel ((pthread_t) handle);
  217811. }
  217812. void juce_setCurrentThreadName (const String& /*name*/)
  217813. {
  217814. }
  217815. bool juce_setThreadPriority (void* handle, int priority)
  217816. {
  217817. struct sched_param param;
  217818. int policy;
  217819. priority = jlimit (0, 10, priority);
  217820. if (handle == 0)
  217821. handle = (void*) pthread_self();
  217822. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217823. return false;
  217824. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217825. const int minPriority = sched_get_priority_min (policy);
  217826. const int maxPriority = sched_get_priority_max (policy);
  217827. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217828. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217829. }
  217830. Thread::ThreadID Thread::getCurrentThreadId()
  217831. {
  217832. return (ThreadID) pthread_self();
  217833. }
  217834. void Thread::yield()
  217835. {
  217836. sched_yield();
  217837. }
  217838. /* Remove this macro if you're having problems compiling the cpu affinity
  217839. calls (the API for these has changed about quite a bit in various Linux
  217840. versions, and a lot of distros seem to ship with obsolete versions)
  217841. */
  217842. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217843. #define SUPPORT_AFFINITIES 1
  217844. #endif
  217845. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217846. {
  217847. #if SUPPORT_AFFINITIES
  217848. cpu_set_t affinity;
  217849. CPU_ZERO (&affinity);
  217850. for (int i = 0; i < 32; ++i)
  217851. if ((affinityMask & (1 << i)) != 0)
  217852. CPU_SET (i, &affinity);
  217853. /*
  217854. N.B. If this line causes a compile error, then you've probably not got the latest
  217855. version of glibc installed.
  217856. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217857. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217858. */
  217859. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217860. sched_yield();
  217861. #else
  217862. /* affinities aren't supported because either the appropriate header files weren't found,
  217863. or the SUPPORT_AFFINITIES macro was turned off
  217864. */
  217865. jassertfalse;
  217866. #endif
  217867. }
  217868. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217869. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217870. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217871. // compiled on its own).
  217872. #if JUCE_INCLUDED_FILE
  217873. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217874. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217875. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217876. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217877. bool File::copyInternal (const File& dest) const
  217878. {
  217879. FileInputStream in (*this);
  217880. if (dest.deleteFile())
  217881. {
  217882. {
  217883. FileOutputStream out (dest);
  217884. if (out.failedToOpen())
  217885. return false;
  217886. if (out.writeFromInputStream (in, -1) == getSize())
  217887. return true;
  217888. }
  217889. dest.deleteFile();
  217890. }
  217891. return false;
  217892. }
  217893. void File::findFileSystemRoots (Array<File>& destArray)
  217894. {
  217895. destArray.add (File ("/"));
  217896. }
  217897. bool File::isOnCDRomDrive() const
  217898. {
  217899. struct statfs buf;
  217900. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217901. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217902. }
  217903. bool File::isOnHardDisk() const
  217904. {
  217905. struct statfs buf;
  217906. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217907. {
  217908. switch (buf.f_type)
  217909. {
  217910. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217911. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217912. case U_NFS_SUPER_MAGIC: // Network NFS
  217913. case U_SMB_SUPER_MAGIC: // Network Samba
  217914. return false;
  217915. default:
  217916. // Assume anything else is a hard-disk (but note it could
  217917. // be a RAM disk. There isn't a good way of determining
  217918. // this for sure)
  217919. return true;
  217920. }
  217921. }
  217922. // Assume so if this fails for some reason
  217923. return true;
  217924. }
  217925. bool File::isOnRemovableDrive() const
  217926. {
  217927. jassertfalse; // xxx not implemented for linux!
  217928. return false;
  217929. }
  217930. bool File::isHidden() const
  217931. {
  217932. return getFileName().startsWithChar ('.');
  217933. }
  217934. static const File juce_readlink (const String& file, const File& defaultFile)
  217935. {
  217936. const int size = 8192;
  217937. HeapBlock<char> buffer;
  217938. buffer.malloc (size + 4);
  217939. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217940. if (numBytes > 0 && numBytes <= size)
  217941. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217942. return defaultFile;
  217943. }
  217944. const File File::getLinkedTarget() const
  217945. {
  217946. return juce_readlink (getFullPathName().toUTF8(), *this);
  217947. }
  217948. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217949. const File File::getSpecialLocation (const SpecialLocationType type)
  217950. {
  217951. switch (type)
  217952. {
  217953. case userHomeDirectory:
  217954. {
  217955. const char* homeDir = getenv ("HOME");
  217956. if (homeDir == 0)
  217957. {
  217958. struct passwd* const pw = getpwuid (getuid());
  217959. if (pw != 0)
  217960. homeDir = pw->pw_dir;
  217961. }
  217962. return File (String::fromUTF8 (homeDir));
  217963. }
  217964. case userDocumentsDirectory:
  217965. case userMusicDirectory:
  217966. case userMoviesDirectory:
  217967. case userApplicationDataDirectory:
  217968. return File ("~");
  217969. case userDesktopDirectory:
  217970. return File ("~/Desktop");
  217971. case commonApplicationDataDirectory:
  217972. return File ("/var");
  217973. case globalApplicationsDirectory:
  217974. return File ("/usr");
  217975. case tempDirectory:
  217976. {
  217977. File tmp ("/var/tmp");
  217978. if (! tmp.isDirectory())
  217979. {
  217980. tmp = "/tmp";
  217981. if (! tmp.isDirectory())
  217982. tmp = File::getCurrentWorkingDirectory();
  217983. }
  217984. return tmp;
  217985. }
  217986. case invokedExecutableFile:
  217987. if (juce_Argv0 != 0)
  217988. return File (String::fromUTF8 (juce_Argv0));
  217989. // deliberate fall-through...
  217990. case currentExecutableFile:
  217991. case currentApplicationFile:
  217992. return juce_getExecutableFile();
  217993. case hostApplicationPath:
  217994. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217995. default:
  217996. jassertfalse; // unknown type?
  217997. break;
  217998. }
  217999. return File::nonexistent;
  218000. }
  218001. const String File::getVersion() const
  218002. {
  218003. return String::empty; // xxx not yet implemented
  218004. }
  218005. bool File::moveToTrash() const
  218006. {
  218007. if (! exists())
  218008. return true;
  218009. File trashCan ("~/.Trash");
  218010. if (! trashCan.isDirectory())
  218011. trashCan = "~/.local/share/Trash/files";
  218012. if (! trashCan.isDirectory())
  218013. return false;
  218014. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  218015. getFileExtension()));
  218016. }
  218017. class DirectoryIterator::NativeIterator::Pimpl
  218018. {
  218019. public:
  218020. Pimpl (const File& directory, const String& wildCard_)
  218021. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  218022. wildCard (wildCard_),
  218023. dir (opendir (directory.getFullPathName().toUTF8()))
  218024. {
  218025. if (wildCard == "*.*")
  218026. wildCard = "*";
  218027. wildcardUTF8 = wildCard.toUTF8();
  218028. }
  218029. ~Pimpl()
  218030. {
  218031. if (dir != 0)
  218032. closedir (dir);
  218033. }
  218034. bool next (String& filenameFound,
  218035. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218036. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218037. {
  218038. if (dir == 0)
  218039. return false;
  218040. for (;;)
  218041. {
  218042. struct dirent* const de = readdir (dir);
  218043. if (de == 0)
  218044. return false;
  218045. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  218046. {
  218047. filenameFound = String::fromUTF8 (de->d_name);
  218048. const String path (parentDir + filenameFound);
  218049. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  218050. {
  218051. struct stat info;
  218052. const bool statOk = juce_stat (path, info);
  218053. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  218054. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  218055. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  218056. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  218057. }
  218058. if (isHidden != 0)
  218059. *isHidden = filenameFound.startsWithChar ('.');
  218060. if (isReadOnly != 0)
  218061. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  218062. return true;
  218063. }
  218064. }
  218065. }
  218066. private:
  218067. String parentDir, wildCard;
  218068. const char* wildcardUTF8;
  218069. DIR* dir;
  218070. Pimpl (const Pimpl&);
  218071. Pimpl& operator= (const Pimpl&);
  218072. };
  218073. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  218074. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  218075. {
  218076. }
  218077. DirectoryIterator::NativeIterator::~NativeIterator()
  218078. {
  218079. }
  218080. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  218081. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218082. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218083. {
  218084. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  218085. }
  218086. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  218087. {
  218088. String cmdString (fileName.replace (" ", "\\ ",false));
  218089. cmdString << " " << parameters;
  218090. if (URL::isProbablyAWebsiteURL (fileName)
  218091. || cmdString.startsWithIgnoreCase ("file:")
  218092. || URL::isProbablyAnEmailAddress (fileName))
  218093. {
  218094. // create a command that tries to launch a bunch of likely browsers
  218095. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  218096. StringArray cmdLines;
  218097. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  218098. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  218099. cmdString = cmdLines.joinIntoString (" || ");
  218100. }
  218101. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  218102. const int cpid = fork();
  218103. if (cpid == 0)
  218104. {
  218105. setsid();
  218106. // Child process
  218107. execve (argv[0], (char**) argv, environ);
  218108. exit (0);
  218109. }
  218110. return cpid >= 0;
  218111. }
  218112. void File::revealToUser() const
  218113. {
  218114. if (isDirectory())
  218115. startAsProcess();
  218116. else if (getParentDirectory().exists())
  218117. getParentDirectory().startAsProcess();
  218118. }
  218119. #endif
  218120. /*** End of inlined file: juce_linux_Files.cpp ***/
  218121. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  218122. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218123. // compiled on its own).
  218124. #if JUCE_INCLUDED_FILE
  218125. struct NamedPipeInternal
  218126. {
  218127. String pipeInName, pipeOutName;
  218128. int pipeIn, pipeOut;
  218129. bool volatile createdPipe, blocked, stopReadOperation;
  218130. static void signalHandler (int) {}
  218131. };
  218132. void NamedPipe::cancelPendingReads()
  218133. {
  218134. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  218135. {
  218136. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218137. intern->stopReadOperation = true;
  218138. char buffer [1] = { 0 };
  218139. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  218140. (void) bytesWritten;
  218141. int timeout = 2000;
  218142. while (intern->blocked && --timeout >= 0)
  218143. Thread::sleep (2);
  218144. intern->stopReadOperation = false;
  218145. }
  218146. }
  218147. void NamedPipe::close()
  218148. {
  218149. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218150. if (intern != 0)
  218151. {
  218152. internal = 0;
  218153. if (intern->pipeIn != -1)
  218154. ::close (intern->pipeIn);
  218155. if (intern->pipeOut != -1)
  218156. ::close (intern->pipeOut);
  218157. if (intern->createdPipe)
  218158. {
  218159. unlink (intern->pipeInName.toUTF8());
  218160. unlink (intern->pipeOutName.toUTF8());
  218161. }
  218162. delete intern;
  218163. }
  218164. }
  218165. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  218166. {
  218167. close();
  218168. NamedPipeInternal* const intern = new NamedPipeInternal();
  218169. internal = intern;
  218170. intern->createdPipe = createPipe;
  218171. intern->blocked = false;
  218172. intern->stopReadOperation = false;
  218173. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  218174. siginterrupt (SIGPIPE, 1);
  218175. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  218176. intern->pipeInName = pipePath + "_in";
  218177. intern->pipeOutName = pipePath + "_out";
  218178. intern->pipeIn = -1;
  218179. intern->pipeOut = -1;
  218180. if (createPipe)
  218181. {
  218182. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  218183. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  218184. {
  218185. delete intern;
  218186. internal = 0;
  218187. return false;
  218188. }
  218189. }
  218190. return true;
  218191. }
  218192. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218193. {
  218194. int bytesRead = -1;
  218195. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218196. if (intern != 0)
  218197. {
  218198. intern->blocked = true;
  218199. if (intern->pipeIn == -1)
  218200. {
  218201. if (intern->createdPipe)
  218202. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  218203. else
  218204. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  218205. if (intern->pipeIn == -1)
  218206. {
  218207. intern->blocked = false;
  218208. return -1;
  218209. }
  218210. }
  218211. bytesRead = 0;
  218212. char* p = static_cast<char*> (destBuffer);
  218213. while (bytesRead < maxBytesToRead)
  218214. {
  218215. const int bytesThisTime = maxBytesToRead - bytesRead;
  218216. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218217. if (numRead <= 0 || intern->stopReadOperation)
  218218. {
  218219. bytesRead = -1;
  218220. break;
  218221. }
  218222. bytesRead += numRead;
  218223. p += bytesRead;
  218224. }
  218225. intern->blocked = false;
  218226. }
  218227. return bytesRead;
  218228. }
  218229. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218230. {
  218231. int bytesWritten = -1;
  218232. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218233. if (intern != 0)
  218234. {
  218235. if (intern->pipeOut == -1)
  218236. {
  218237. if (intern->createdPipe)
  218238. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218239. else
  218240. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218241. if (intern->pipeOut == -1)
  218242. {
  218243. return -1;
  218244. }
  218245. }
  218246. const char* p = static_cast<const char*> (sourceBuffer);
  218247. bytesWritten = 0;
  218248. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218249. while (bytesWritten < numBytesToWrite
  218250. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218251. {
  218252. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218253. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218254. if (numWritten <= 0)
  218255. {
  218256. bytesWritten = -1;
  218257. break;
  218258. }
  218259. bytesWritten += numWritten;
  218260. p += bytesWritten;
  218261. }
  218262. }
  218263. return bytesWritten;
  218264. }
  218265. #endif
  218266. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218267. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218268. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218269. // compiled on its own).
  218270. #if JUCE_INCLUDED_FILE
  218271. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218272. {
  218273. int numResults = 0;
  218274. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218275. if (s != -1)
  218276. {
  218277. char buf [1024];
  218278. struct ifconf ifc;
  218279. ifc.ifc_len = sizeof (buf);
  218280. ifc.ifc_buf = buf;
  218281. ioctl (s, SIOCGIFCONF, &ifc);
  218282. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218283. {
  218284. struct ifreq ifr;
  218285. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218286. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218287. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218288. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218289. && numResults < maxNum)
  218290. {
  218291. int64 a = 0;
  218292. for (int j = 6; --j >= 0;)
  218293. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218294. *addresses++ = a;
  218295. ++numResults;
  218296. }
  218297. }
  218298. close (s);
  218299. }
  218300. return numResults;
  218301. }
  218302. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218303. const String& emailSubject,
  218304. const String& bodyText,
  218305. const StringArray& filesToAttach)
  218306. {
  218307. jassertfalse; // xxx todo
  218308. return false;
  218309. }
  218310. /** A HTTP input stream that uses sockets.
  218311. */
  218312. class JUCE_HTTPSocketStream
  218313. {
  218314. public:
  218315. JUCE_HTTPSocketStream()
  218316. : readPosition (0),
  218317. socketHandle (-1),
  218318. levelsOfRedirection (0),
  218319. timeoutSeconds (15)
  218320. {
  218321. }
  218322. ~JUCE_HTTPSocketStream()
  218323. {
  218324. closeSocket();
  218325. }
  218326. bool open (const String& url,
  218327. const String& headers,
  218328. const MemoryBlock& postData,
  218329. const bool isPost,
  218330. URL::OpenStreamProgressCallback* callback,
  218331. void* callbackContext,
  218332. int timeOutMs)
  218333. {
  218334. closeSocket();
  218335. uint32 timeOutTime = Time::getMillisecondCounter();
  218336. if (timeOutMs == 0)
  218337. timeOutTime += 60000;
  218338. else if (timeOutMs < 0)
  218339. timeOutTime = 0xffffffff;
  218340. else
  218341. timeOutTime += timeOutMs;
  218342. String hostName, hostPath;
  218343. int hostPort;
  218344. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218345. return false;
  218346. const struct hostent* host = 0;
  218347. int port = 0;
  218348. String proxyName, proxyPath;
  218349. int proxyPort = 0;
  218350. String proxyURL (getenv ("http_proxy"));
  218351. if (proxyURL.startsWithIgnoreCase ("http://"))
  218352. {
  218353. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218354. return false;
  218355. host = gethostbyname (proxyName.toUTF8());
  218356. port = proxyPort;
  218357. }
  218358. else
  218359. {
  218360. host = gethostbyname (hostName.toUTF8());
  218361. port = hostPort;
  218362. }
  218363. if (host == 0)
  218364. return false;
  218365. struct sockaddr_in address;
  218366. zerostruct (address);
  218367. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218368. address.sin_family = host->h_addrtype;
  218369. address.sin_port = htons (port);
  218370. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218371. if (socketHandle == -1)
  218372. return false;
  218373. int receiveBufferSize = 16384;
  218374. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218375. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218376. #if JUCE_MAC
  218377. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218378. #endif
  218379. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218380. {
  218381. closeSocket();
  218382. return false;
  218383. }
  218384. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218385. proxyName, proxyPort,
  218386. hostPath, url,
  218387. headers, postData,
  218388. isPost));
  218389. size_t totalHeaderSent = 0;
  218390. while (totalHeaderSent < requestHeader.getSize())
  218391. {
  218392. if (Time::getMillisecondCounter() > timeOutTime)
  218393. {
  218394. closeSocket();
  218395. return false;
  218396. }
  218397. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218398. if (send (socketHandle,
  218399. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218400. numToSend, 0)
  218401. != numToSend)
  218402. {
  218403. closeSocket();
  218404. return false;
  218405. }
  218406. totalHeaderSent += numToSend;
  218407. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218408. {
  218409. closeSocket();
  218410. return false;
  218411. }
  218412. }
  218413. const String responseHeader (readResponse (timeOutTime));
  218414. if (responseHeader.isNotEmpty())
  218415. {
  218416. //DBG (responseHeader);
  218417. headerLines.clear();
  218418. headerLines.addLines (responseHeader);
  218419. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218420. .substring (0, 3).getIntValue();
  218421. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218422. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218423. String location (findHeaderItem (headerLines, "Location:"));
  218424. if (statusCode >= 300 && statusCode < 400
  218425. && location.isNotEmpty())
  218426. {
  218427. if (! location.startsWithIgnoreCase ("http://"))
  218428. location = "http://" + location;
  218429. if (levelsOfRedirection++ < 3)
  218430. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218431. }
  218432. else
  218433. {
  218434. levelsOfRedirection = 0;
  218435. return true;
  218436. }
  218437. }
  218438. closeSocket();
  218439. return false;
  218440. }
  218441. int read (void* buffer, int bytesToRead)
  218442. {
  218443. fd_set readbits;
  218444. FD_ZERO (&readbits);
  218445. FD_SET (socketHandle, &readbits);
  218446. struct timeval tv;
  218447. tv.tv_sec = timeoutSeconds;
  218448. tv.tv_usec = 0;
  218449. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218450. return 0; // (timeout)
  218451. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218452. readPosition += bytesRead;
  218453. return bytesRead;
  218454. }
  218455. int readPosition;
  218456. StringArray headerLines;
  218457. juce_UseDebuggingNewOperator
  218458. private:
  218459. int socketHandle, levelsOfRedirection;
  218460. const int timeoutSeconds;
  218461. void closeSocket()
  218462. {
  218463. if (socketHandle >= 0)
  218464. close (socketHandle);
  218465. socketHandle = -1;
  218466. }
  218467. const MemoryBlock createRequestHeader (const String& hostName,
  218468. const int hostPort,
  218469. const String& proxyName,
  218470. const int proxyPort,
  218471. const String& hostPath,
  218472. const String& originalURL,
  218473. const String& headers,
  218474. const MemoryBlock& postData,
  218475. const bool isPost)
  218476. {
  218477. String header (isPost ? "POST " : "GET ");
  218478. if (proxyName.isEmpty())
  218479. {
  218480. header << hostPath << " HTTP/1.0\r\nHost: "
  218481. << hostName << ':' << hostPort;
  218482. }
  218483. else
  218484. {
  218485. header << originalURL << " HTTP/1.0\r\nHost: "
  218486. << proxyName << ':' << proxyPort;
  218487. }
  218488. header << "\r\nUser-Agent: JUCE/"
  218489. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218490. << "\r\nConnection: Close\r\nContent-Length: "
  218491. << postData.getSize() << "\r\n"
  218492. << headers << "\r\n";
  218493. MemoryBlock mb;
  218494. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218495. mb.append (postData.getData(), postData.getSize());
  218496. return mb;
  218497. }
  218498. const String readResponse (const uint32 timeOutTime)
  218499. {
  218500. int bytesRead = 0, numConsecutiveLFs = 0;
  218501. MemoryBlock buffer (1024, true);
  218502. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218503. && Time::getMillisecondCounter() <= timeOutTime)
  218504. {
  218505. fd_set readbits;
  218506. FD_ZERO (&readbits);
  218507. FD_SET (socketHandle, &readbits);
  218508. struct timeval tv;
  218509. tv.tv_sec = timeoutSeconds;
  218510. tv.tv_usec = 0;
  218511. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218512. return String::empty; // (timeout)
  218513. buffer.ensureSize (bytesRead + 8, true);
  218514. char* const dest = (char*) buffer.getData() + bytesRead;
  218515. if (recv (socketHandle, dest, 1, 0) == -1)
  218516. return String::empty;
  218517. const char lastByte = *dest;
  218518. ++bytesRead;
  218519. if (lastByte == '\n')
  218520. ++numConsecutiveLFs;
  218521. else if (lastByte != '\r')
  218522. numConsecutiveLFs = 0;
  218523. }
  218524. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218525. if (header.startsWithIgnoreCase ("HTTP/"))
  218526. return header.trimEnd();
  218527. return String::empty;
  218528. }
  218529. static bool decomposeURL (const String& url,
  218530. String& host, String& path, int& port)
  218531. {
  218532. if (! url.startsWithIgnoreCase ("http://"))
  218533. return false;
  218534. const int nextSlash = url.indexOfChar (7, '/');
  218535. int nextColon = url.indexOfChar (7, ':');
  218536. if (nextColon > nextSlash && nextSlash > 0)
  218537. nextColon = -1;
  218538. if (nextColon >= 0)
  218539. {
  218540. host = url.substring (7, nextColon);
  218541. if (nextSlash >= 0)
  218542. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218543. else
  218544. port = url.substring (nextColon + 1).getIntValue();
  218545. }
  218546. else
  218547. {
  218548. port = 80;
  218549. if (nextSlash >= 0)
  218550. host = url.substring (7, nextSlash);
  218551. else
  218552. host = url.substring (7);
  218553. }
  218554. if (nextSlash >= 0)
  218555. path = url.substring (nextSlash);
  218556. else
  218557. path = "/";
  218558. return true;
  218559. }
  218560. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218561. {
  218562. for (int i = 0; i < lines.size(); ++i)
  218563. if (lines[i].startsWithIgnoreCase (itemName))
  218564. return lines[i].substring (itemName.length()).trim();
  218565. return String::empty;
  218566. }
  218567. };
  218568. void* juce_openInternetFile (const String& url,
  218569. const String& headers,
  218570. const MemoryBlock& postData,
  218571. const bool isPost,
  218572. URL::OpenStreamProgressCallback* callback,
  218573. void* callbackContext,
  218574. int timeOutMs)
  218575. {
  218576. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218577. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218578. return s.release();
  218579. return 0;
  218580. }
  218581. void juce_closeInternetFile (void* handle)
  218582. {
  218583. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218584. }
  218585. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218586. {
  218587. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218588. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218589. }
  218590. int64 juce_getInternetFileContentLength (void* handle)
  218591. {
  218592. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218593. if (s != 0)
  218594. {
  218595. //xxx todo
  218596. jassertfalse
  218597. }
  218598. return -1;
  218599. }
  218600. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218601. {
  218602. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218603. if (s != 0)
  218604. {
  218605. for (int i = 0; i < s->headerLines.size(); ++i)
  218606. {
  218607. const String& headersEntry = s->headerLines[i];
  218608. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218609. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218610. const String previousValue (headers [key]);
  218611. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218612. }
  218613. }
  218614. }
  218615. int juce_seekInInternetFile (void* handle, int newPosition)
  218616. {
  218617. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218618. return s != 0 ? s->readPosition : 0;
  218619. }
  218620. #endif
  218621. /*** End of inlined file: juce_linux_Network.cpp ***/
  218622. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218623. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218624. // compiled on its own).
  218625. #if JUCE_INCLUDED_FILE
  218626. void Logger::outputDebugString (const String& text)
  218627. {
  218628. std::cerr << text << std::endl;
  218629. }
  218630. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218631. {
  218632. return Linux;
  218633. }
  218634. const String SystemStats::getOperatingSystemName()
  218635. {
  218636. return "Linux";
  218637. }
  218638. bool SystemStats::isOperatingSystem64Bit()
  218639. {
  218640. #if JUCE_64BIT
  218641. return true;
  218642. #else
  218643. //xxx not sure how to find this out?..
  218644. return false;
  218645. #endif
  218646. }
  218647. static const String juce_getCpuInfo (const char* const key)
  218648. {
  218649. StringArray lines;
  218650. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218651. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218652. if (lines[i].startsWithIgnoreCase (key))
  218653. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218654. return String::empty;
  218655. }
  218656. const String SystemStats::getCpuVendor()
  218657. {
  218658. return juce_getCpuInfo ("vendor_id");
  218659. }
  218660. int SystemStats::getCpuSpeedInMegaherz()
  218661. {
  218662. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218663. }
  218664. int SystemStats::getMemorySizeInMegabytes()
  218665. {
  218666. struct sysinfo sysi;
  218667. if (sysinfo (&sysi) == 0)
  218668. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218669. return 0;
  218670. }
  218671. int SystemStats::getPageSize()
  218672. {
  218673. return sysconf (_SC_PAGESIZE);
  218674. }
  218675. const String SystemStats::getLogonName()
  218676. {
  218677. const char* user = getenv ("USER");
  218678. if (user == 0)
  218679. {
  218680. struct passwd* const pw = getpwuid (getuid());
  218681. if (pw != 0)
  218682. user = pw->pw_name;
  218683. }
  218684. return String::fromUTF8 (user);
  218685. }
  218686. const String SystemStats::getFullUserName()
  218687. {
  218688. return getLogonName();
  218689. }
  218690. void SystemStats::initialiseStats()
  218691. {
  218692. const String flags (juce_getCpuInfo ("flags"));
  218693. cpuFlags.hasMMX = flags.contains ("mmx");
  218694. cpuFlags.hasSSE = flags.contains ("sse");
  218695. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218696. cpuFlags.has3DNow = flags.contains ("3dnow");
  218697. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218698. }
  218699. void PlatformUtilities::fpuReset()
  218700. {
  218701. }
  218702. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218703. {
  218704. if (gettimeofday (t, 0) != 0)
  218705. return false;
  218706. static unsigned int calibrate = 0;
  218707. static bool calibrated = false;
  218708. if (! calibrated)
  218709. {
  218710. calibrated = true;
  218711. struct sysinfo sysi;
  218712. if (sysinfo (&sysi) == 0)
  218713. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218714. }
  218715. t->tv_sec -= calibrate;
  218716. return true;
  218717. }
  218718. uint32 juce_millisecondsSinceStartup() throw()
  218719. {
  218720. timeval t;
  218721. if (juce_getTimeSinceStartup (&t))
  218722. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218723. return 0;
  218724. }
  218725. int64 Time::getHighResolutionTicks() throw()
  218726. {
  218727. timeval t;
  218728. if (juce_getTimeSinceStartup (&t))
  218729. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218730. return 0;
  218731. }
  218732. int64 Time::getHighResolutionTicksPerSecond() throw()
  218733. {
  218734. return 1000000; // (microseconds)
  218735. }
  218736. double Time::getMillisecondCounterHiRes() throw()
  218737. {
  218738. return getHighResolutionTicks() * 0.001;
  218739. }
  218740. bool Time::setSystemTimeToThisTime() const
  218741. {
  218742. timeval t;
  218743. t.tv_sec = millisSinceEpoch % 1000000;
  218744. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218745. return settimeofday (&t, 0) ? false : true;
  218746. }
  218747. #endif
  218748. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218749. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218750. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218751. // compiled on its own).
  218752. #if JUCE_INCLUDED_FILE
  218753. /*
  218754. Note that a lot of methods that you'd expect to find in this file actually
  218755. live in juce_posix_SharedCode.h!
  218756. */
  218757. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218758. void Process::setPriority (ProcessPriority prior)
  218759. {
  218760. struct sched_param param;
  218761. int policy, maxp, minp;
  218762. const int p = (int) prior;
  218763. if (p <= 1)
  218764. policy = SCHED_OTHER;
  218765. else
  218766. policy = SCHED_RR;
  218767. minp = sched_get_priority_min (policy);
  218768. maxp = sched_get_priority_max (policy);
  218769. if (p < 2)
  218770. param.sched_priority = 0;
  218771. else if (p == 2 )
  218772. // Set to middle of lower realtime priority range
  218773. param.sched_priority = minp + (maxp - minp) / 4;
  218774. else
  218775. // Set to middle of higher realtime priority range
  218776. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218777. pthread_setschedparam (pthread_self(), policy, &param);
  218778. }
  218779. void Process::terminate()
  218780. {
  218781. exit (0);
  218782. }
  218783. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218784. {
  218785. static char testResult = 0;
  218786. if (testResult == 0)
  218787. {
  218788. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218789. if (testResult >= 0)
  218790. {
  218791. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218792. testResult = 1;
  218793. }
  218794. }
  218795. return testResult < 0;
  218796. }
  218797. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218798. {
  218799. return juce_isRunningUnderDebugger();
  218800. }
  218801. void Process::raisePrivilege()
  218802. {
  218803. // If running suid root, change effective user
  218804. // to root
  218805. if (geteuid() != 0 && getuid() == 0)
  218806. {
  218807. setreuid (geteuid(), getuid());
  218808. setregid (getegid(), getgid());
  218809. }
  218810. }
  218811. void Process::lowerPrivilege()
  218812. {
  218813. // If runing suid root, change effective user
  218814. // back to real user
  218815. if (geteuid() == 0 && getuid() != 0)
  218816. {
  218817. setreuid (geteuid(), getuid());
  218818. setregid (getegid(), getgid());
  218819. }
  218820. }
  218821. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218822. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218823. {
  218824. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218825. }
  218826. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218827. {
  218828. dlclose(handle);
  218829. }
  218830. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218831. {
  218832. return dlsym (libraryHandle, procedureName.toCString());
  218833. }
  218834. #endif
  218835. #endif
  218836. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218837. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218838. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218839. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218840. // compiled on its own).
  218841. #if JUCE_INCLUDED_FILE
  218842. extern Display* display;
  218843. extern Window juce_messageWindowHandle;
  218844. namespace ClipboardHelpers
  218845. {
  218846. static String localClipboardContent;
  218847. static Atom atom_UTF8_STRING;
  218848. static Atom atom_CLIPBOARD;
  218849. static Atom atom_TARGETS;
  218850. static void initSelectionAtoms()
  218851. {
  218852. static bool isInitialised = false;
  218853. if (! isInitialised)
  218854. {
  218855. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218856. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218857. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218858. }
  218859. }
  218860. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218861. // works only for strings shorter than 1000000 bytes
  218862. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218863. {
  218864. String returnData;
  218865. char* clipData;
  218866. Atom actualType;
  218867. int actualFormat;
  218868. unsigned long numItems, bytesLeft;
  218869. if (XGetWindowProperty (display, window, prop,
  218870. 0L /* offset */, 1000000 /* length (max) */, False,
  218871. AnyPropertyType /* format */,
  218872. &actualType, &actualFormat, &numItems, &bytesLeft,
  218873. (unsigned char**) &clipData) == Success)
  218874. {
  218875. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218876. returnData = String::fromUTF8 (clipData, numItems);
  218877. else if (actualType == XA_STRING && actualFormat == 8)
  218878. returnData = String (clipData, numItems);
  218879. if (clipData != 0)
  218880. XFree (clipData);
  218881. jassert (bytesLeft == 0 || numItems == 1000000);
  218882. }
  218883. XDeleteProperty (display, window, prop);
  218884. return returnData;
  218885. }
  218886. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218887. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218888. {
  218889. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218890. // The selection owner will be asked to set the JUCE_SEL property on the
  218891. // juce_messageWindowHandle with the selection content
  218892. XConvertSelection (display, selection, requestedFormat, property_name,
  218893. juce_messageWindowHandle, CurrentTime);
  218894. int count = 50; // will wait at most for 200 ms
  218895. while (--count >= 0)
  218896. {
  218897. XEvent event;
  218898. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218899. {
  218900. if (event.xselection.property == property_name)
  218901. {
  218902. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218903. selectionContent = readWindowProperty (event.xselection.requestor,
  218904. event.xselection.property,
  218905. requestedFormat);
  218906. return true;
  218907. }
  218908. else
  218909. {
  218910. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218911. }
  218912. }
  218913. // not very elegant.. we could do a select() or something like that...
  218914. // however clipboard content requesting is inherently slow on x11, it
  218915. // often takes 50ms or more so...
  218916. Thread::sleep (4);
  218917. }
  218918. return false;
  218919. }
  218920. }
  218921. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218922. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218923. {
  218924. ClipboardHelpers::initSelectionAtoms();
  218925. // the selection content is sent to the target window as a window property
  218926. XSelectionEvent reply;
  218927. reply.type = SelectionNotify;
  218928. reply.display = evt.display;
  218929. reply.requestor = evt.requestor;
  218930. reply.selection = evt.selection;
  218931. reply.target = evt.target;
  218932. reply.property = None; // == "fail"
  218933. reply.time = evt.time;
  218934. HeapBlock <char> data;
  218935. int propertyFormat = 0, numDataItems = 0;
  218936. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218937. {
  218938. if (evt.target == XA_STRING)
  218939. {
  218940. // format data according to system locale
  218941. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218942. data.calloc (numDataItems + 1);
  218943. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218944. propertyFormat = 8; // bits/item
  218945. }
  218946. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218947. {
  218948. // translate to utf8
  218949. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218950. data.calloc (numDataItems + 1);
  218951. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218952. propertyFormat = 8; // bits/item
  218953. }
  218954. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218955. {
  218956. // another application wants to know what we are able to send
  218957. numDataItems = 2;
  218958. propertyFormat = 32; // atoms are 32-bit
  218959. data.calloc (numDataItems * 4);
  218960. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218961. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218962. atoms[1] = XA_STRING;
  218963. }
  218964. }
  218965. else
  218966. {
  218967. DBG ("requested unsupported clipboard");
  218968. }
  218969. if (data != 0)
  218970. {
  218971. const int maxReasonableSelectionSize = 1000000;
  218972. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218973. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218974. {
  218975. XChangeProperty (evt.display, evt.requestor,
  218976. evt.property, evt.target,
  218977. propertyFormat /* 8 or 32 */, PropModeReplace,
  218978. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218979. reply.property = evt.property; // " == success"
  218980. }
  218981. }
  218982. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218983. }
  218984. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218985. {
  218986. ClipboardHelpers::initSelectionAtoms();
  218987. ClipboardHelpers::localClipboardContent = clipText;
  218988. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218989. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218990. }
  218991. const String SystemClipboard::getTextFromClipboard()
  218992. {
  218993. ClipboardHelpers::initSelectionAtoms();
  218994. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218995. level" clipboard that is supposed to be filled by ctrl-C
  218996. etc). When a clipboard manager is running, the content of this
  218997. selection is preserved even when the original selection owner
  218998. exits.
  218999. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  219000. filled by good old x11 apps such as xterm)
  219001. */
  219002. String content;
  219003. Atom selection = XA_PRIMARY;
  219004. Window selectionOwner = None;
  219005. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  219006. {
  219007. selection = ClipboardHelpers::atom_CLIPBOARD;
  219008. selectionOwner = XGetSelectionOwner (display, selection);
  219009. }
  219010. if (selectionOwner != None)
  219011. {
  219012. if (selectionOwner == juce_messageWindowHandle)
  219013. {
  219014. content = ClipboardHelpers::localClipboardContent;
  219015. }
  219016. else
  219017. {
  219018. // first try: we want an utf8 string
  219019. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  219020. if (! ok)
  219021. {
  219022. // second chance, ask for a good old locale-dependent string ..
  219023. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  219024. }
  219025. }
  219026. }
  219027. return content;
  219028. }
  219029. #endif
  219030. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  219031. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  219032. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219033. // compiled on its own).
  219034. #if JUCE_INCLUDED_FILE
  219035. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  219036. #define JUCE_DEBUG_XERRORS 1
  219037. #endif
  219038. Display* display = 0;
  219039. Window juce_messageWindowHandle = None;
  219040. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  219041. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  219042. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  219043. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  219044. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  219045. class InternalMessageQueue
  219046. {
  219047. public:
  219048. InternalMessageQueue()
  219049. : bytesInSocket (0),
  219050. totalEventCount (0)
  219051. {
  219052. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  219053. (void) ret; jassert (ret == 0);
  219054. //setNonBlocking (fd[0]);
  219055. //setNonBlocking (fd[1]);
  219056. }
  219057. ~InternalMessageQueue()
  219058. {
  219059. close (fd[0]);
  219060. close (fd[1]);
  219061. clearSingletonInstance();
  219062. }
  219063. void postMessage (Message* msg)
  219064. {
  219065. const int maxBytesInSocketQueue = 128;
  219066. ScopedLock sl (lock);
  219067. queue.add (msg);
  219068. if (bytesInSocket < maxBytesInSocketQueue)
  219069. {
  219070. ++bytesInSocket;
  219071. ScopedUnlock ul (lock);
  219072. const unsigned char x = 0xff;
  219073. size_t bytesWritten = write (fd[0], &x, 1);
  219074. (void) bytesWritten;
  219075. }
  219076. }
  219077. bool isEmpty() const
  219078. {
  219079. ScopedLock sl (lock);
  219080. return queue.size() == 0;
  219081. }
  219082. bool dispatchNextEvent()
  219083. {
  219084. // This alternates between giving priority to XEvents or internal messages,
  219085. // to keep everything running smoothly..
  219086. if ((++totalEventCount & 1) != 0)
  219087. return dispatchNextXEvent() || dispatchNextInternalMessage();
  219088. else
  219089. return dispatchNextInternalMessage() || dispatchNextXEvent();
  219090. }
  219091. // Wait for an event (either XEvent, or an internal Message)
  219092. bool sleepUntilEvent (const int timeoutMs)
  219093. {
  219094. if (! isEmpty())
  219095. return true;
  219096. if (display != 0)
  219097. {
  219098. ScopedXLock xlock;
  219099. if (XPending (display))
  219100. return true;
  219101. }
  219102. struct timeval tv;
  219103. tv.tv_sec = 0;
  219104. tv.tv_usec = timeoutMs * 1000;
  219105. int fd0 = getWaitHandle();
  219106. int fdmax = fd0;
  219107. fd_set readset;
  219108. FD_ZERO (&readset);
  219109. FD_SET (fd0, &readset);
  219110. if (display != 0)
  219111. {
  219112. ScopedXLock xlock;
  219113. int fd1 = XConnectionNumber (display);
  219114. FD_SET (fd1, &readset);
  219115. fdmax = jmax (fd0, fd1);
  219116. }
  219117. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  219118. return (ret > 0); // ret <= 0 if error or timeout
  219119. }
  219120. struct MessageThreadFuncCall
  219121. {
  219122. enum { uniqueID = 0x73774623 };
  219123. MessageCallbackFunction* func;
  219124. void* parameter;
  219125. void* result;
  219126. CriticalSection lock;
  219127. WaitableEvent event;
  219128. };
  219129. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  219130. private:
  219131. CriticalSection lock;
  219132. OwnedArray <Message> queue;
  219133. int fd[2];
  219134. int bytesInSocket;
  219135. int totalEventCount;
  219136. int getWaitHandle() const throw() { return fd[1]; }
  219137. static bool setNonBlocking (int handle)
  219138. {
  219139. int socketFlags = fcntl (handle, F_GETFL, 0);
  219140. if (socketFlags == -1)
  219141. return false;
  219142. socketFlags |= O_NONBLOCK;
  219143. return fcntl (handle, F_SETFL, socketFlags) == 0;
  219144. }
  219145. static bool dispatchNextXEvent()
  219146. {
  219147. if (display == 0)
  219148. return false;
  219149. XEvent evt;
  219150. {
  219151. ScopedXLock xlock;
  219152. if (! XPending (display))
  219153. return false;
  219154. XNextEvent (display, &evt);
  219155. }
  219156. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  219157. juce_handleSelectionRequest (evt.xselectionrequest);
  219158. else if (evt.xany.window != juce_messageWindowHandle)
  219159. juce_windowMessageReceive (&evt);
  219160. return true;
  219161. }
  219162. Message* popNextMessage()
  219163. {
  219164. ScopedLock sl (lock);
  219165. if (bytesInSocket > 0)
  219166. {
  219167. --bytesInSocket;
  219168. ScopedUnlock ul (lock);
  219169. unsigned char x;
  219170. size_t numBytes = read (fd[1], &x, 1);
  219171. (void) numBytes;
  219172. }
  219173. return queue.removeAndReturn (0);
  219174. }
  219175. bool dispatchNextInternalMessage()
  219176. {
  219177. ScopedPointer <Message> msg (popNextMessage());
  219178. if (msg == 0)
  219179. return false;
  219180. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  219181. {
  219182. // Handle callback message
  219183. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  219184. call->result = (*(call->func)) (call->parameter);
  219185. call->event.signal();
  219186. }
  219187. else
  219188. {
  219189. // Handle "normal" messages
  219190. MessageManager::getInstance()->deliverMessage (msg.release());
  219191. }
  219192. return true;
  219193. }
  219194. };
  219195. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  219196. namespace LinuxErrorHandling
  219197. {
  219198. static bool errorOccurred = false;
  219199. static bool keyboardBreakOccurred = false;
  219200. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219201. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219202. // Usually happens when client-server connection is broken
  219203. static int ioErrorHandler (Display* display)
  219204. {
  219205. DBG ("ERROR: connection to X server broken.. terminating.");
  219206. if (JUCEApplication::isStandaloneApp())
  219207. MessageManager::getInstance()->stopDispatchLoop();
  219208. errorOccurred = true;
  219209. return 0;
  219210. }
  219211. // A protocol error has occurred
  219212. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  219213. {
  219214. #if JUCE_DEBUG_XERRORS
  219215. char errorStr[64] = { 0 };
  219216. char requestStr[64] = { 0 };
  219217. XGetErrorText (display, event->error_code, errorStr, 64);
  219218. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219219. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219220. #endif
  219221. return 0;
  219222. }
  219223. static void installXErrorHandlers()
  219224. {
  219225. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219226. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219227. }
  219228. static void removeXErrorHandlers()
  219229. {
  219230. XSetIOErrorHandler (oldIOErrorHandler);
  219231. oldIOErrorHandler = 0;
  219232. XSetErrorHandler (oldErrorHandler);
  219233. oldErrorHandler = 0;
  219234. }
  219235. static void keyboardBreakSignalHandler (int sig)
  219236. {
  219237. if (sig == SIGINT)
  219238. keyboardBreakOccurred = true;
  219239. }
  219240. static void installKeyboardBreakHandler()
  219241. {
  219242. struct sigaction saction;
  219243. sigset_t maskSet;
  219244. sigemptyset (&maskSet);
  219245. saction.sa_handler = keyboardBreakSignalHandler;
  219246. saction.sa_mask = maskSet;
  219247. saction.sa_flags = 0;
  219248. sigaction (SIGINT, &saction, 0);
  219249. }
  219250. }
  219251. void MessageManager::doPlatformSpecificInitialisation()
  219252. {
  219253. // Initialise xlib for multiple thread support
  219254. static bool initThreadCalled = false;
  219255. if (! initThreadCalled)
  219256. {
  219257. if (! XInitThreads())
  219258. {
  219259. // This is fatal! Print error and closedown
  219260. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219261. if (JUCEApplication::isStandaloneApp())
  219262. Process::terminate();
  219263. return;
  219264. }
  219265. initThreadCalled = true;
  219266. }
  219267. LinuxErrorHandling::installXErrorHandlers();
  219268. LinuxErrorHandling::installKeyboardBreakHandler();
  219269. // Create the internal message queue
  219270. InternalMessageQueue::getInstance();
  219271. // Try to connect to a display
  219272. String displayName (getenv ("DISPLAY"));
  219273. if (displayName.isEmpty())
  219274. displayName = ":0.0";
  219275. display = XOpenDisplay (displayName.toCString());
  219276. if (display != 0) // This is not fatal! we can run headless.
  219277. {
  219278. // Create a context to store user data associated with Windows we create in WindowDriver
  219279. windowHandleXContext = XUniqueContext();
  219280. // We're only interested in client messages for this window, which are always sent
  219281. XSetWindowAttributes swa;
  219282. swa.event_mask = NoEventMask;
  219283. // Create our message window (this will never be mapped)
  219284. const int screen = DefaultScreen (display);
  219285. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219286. 0, 0, 1, 1, 0, 0, InputOnly,
  219287. DefaultVisual (display, screen),
  219288. CWEventMask, &swa);
  219289. }
  219290. }
  219291. void MessageManager::doPlatformSpecificShutdown()
  219292. {
  219293. InternalMessageQueue::deleteInstance();
  219294. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219295. {
  219296. XDestroyWindow (display, juce_messageWindowHandle);
  219297. XCloseDisplay (display);
  219298. juce_messageWindowHandle = 0;
  219299. display = 0;
  219300. LinuxErrorHandling::removeXErrorHandlers();
  219301. }
  219302. }
  219303. bool juce_postMessageToSystemQueue (Message* message)
  219304. {
  219305. if (LinuxErrorHandling::errorOccurred)
  219306. return false;
  219307. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219308. return true;
  219309. }
  219310. void MessageManager::broadcastMessage (const String& value)
  219311. {
  219312. /* TODO */
  219313. }
  219314. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219315. {
  219316. if (LinuxErrorHandling::errorOccurred)
  219317. return 0;
  219318. if (isThisTheMessageThread())
  219319. return func (parameter);
  219320. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219321. messageCallContext.func = func;
  219322. messageCallContext.parameter = parameter;
  219323. InternalMessageQueue::getInstanceWithoutCreating()
  219324. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219325. 0, 0, &messageCallContext));
  219326. // Wait for it to complete before continuing
  219327. messageCallContext.event.wait();
  219328. return messageCallContext.result;
  219329. }
  219330. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219331. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219332. {
  219333. while (! LinuxErrorHandling::errorOccurred)
  219334. {
  219335. if (LinuxErrorHandling::keyboardBreakOccurred)
  219336. {
  219337. LinuxErrorHandling::errorOccurred = true;
  219338. if (JUCEApplication::isStandaloneApp())
  219339. Process::terminate();
  219340. break;
  219341. }
  219342. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219343. return true;
  219344. if (returnIfNoPendingMessages)
  219345. break;
  219346. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219347. }
  219348. return false;
  219349. }
  219350. #endif
  219351. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219352. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219353. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219354. // compiled on its own).
  219355. #if JUCE_INCLUDED_FILE
  219356. class FreeTypeFontFace
  219357. {
  219358. public:
  219359. enum FontStyle
  219360. {
  219361. Plain = 0,
  219362. Bold = 1,
  219363. Italic = 2
  219364. };
  219365. FreeTypeFontFace (const String& familyName)
  219366. : hasSerif (false),
  219367. monospaced (false)
  219368. {
  219369. family = familyName;
  219370. }
  219371. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219372. {
  219373. if (names [(int) style].fileName.isEmpty())
  219374. {
  219375. names [(int) style].fileName = name;
  219376. names [(int) style].faceIndex = faceIndex;
  219377. }
  219378. }
  219379. const String& getFamilyName() const throw() { return family; }
  219380. const String& getFileName (const int style, int& faceIndex) const throw()
  219381. {
  219382. faceIndex = names[style].faceIndex;
  219383. return names[style].fileName;
  219384. }
  219385. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219386. bool getMonospaced() const throw() { return monospaced; }
  219387. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219388. bool getSerif() const throw() { return hasSerif; }
  219389. private:
  219390. String family;
  219391. struct FontNameIndex
  219392. {
  219393. String fileName;
  219394. int faceIndex;
  219395. };
  219396. FontNameIndex names[4];
  219397. bool hasSerif, monospaced;
  219398. };
  219399. class FreeTypeInterface : public DeletedAtShutdown
  219400. {
  219401. public:
  219402. FreeTypeInterface()
  219403. : ftLib (0),
  219404. lastFace (0),
  219405. lastBold (false),
  219406. lastItalic (false)
  219407. {
  219408. if (FT_Init_FreeType (&ftLib) != 0)
  219409. {
  219410. ftLib = 0;
  219411. DBG ("Failed to initialize FreeType");
  219412. }
  219413. StringArray fontDirs;
  219414. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219415. fontDirs.removeEmptyStrings (true);
  219416. if (fontDirs.size() == 0)
  219417. {
  219418. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219419. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219420. if (fontsInfo != 0)
  219421. {
  219422. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219423. {
  219424. fontDirs.add (e->getAllSubText().trim());
  219425. }
  219426. }
  219427. }
  219428. if (fontDirs.size() == 0)
  219429. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219430. for (int i = 0; i < fontDirs.size(); ++i)
  219431. enumerateFaces (fontDirs[i]);
  219432. }
  219433. ~FreeTypeInterface()
  219434. {
  219435. if (lastFace != 0)
  219436. FT_Done_Face (lastFace);
  219437. if (ftLib != 0)
  219438. FT_Done_FreeType (ftLib);
  219439. clearSingletonInstance();
  219440. }
  219441. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219442. {
  219443. for (int i = 0; i < faces.size(); i++)
  219444. if (faces[i]->getFamilyName() == familyName)
  219445. return faces[i];
  219446. if (! create)
  219447. return 0;
  219448. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219449. faces.add (newFace);
  219450. return newFace;
  219451. }
  219452. // Enumerate all font faces available in a given directory
  219453. void enumerateFaces (const String& path)
  219454. {
  219455. File dirPath (path);
  219456. if (path.isEmpty() || ! dirPath.isDirectory())
  219457. return;
  219458. DirectoryIterator di (dirPath, true);
  219459. while (di.next())
  219460. {
  219461. File possible (di.getFile());
  219462. if (possible.hasFileExtension ("ttf")
  219463. || possible.hasFileExtension ("pfb")
  219464. || possible.hasFileExtension ("pcf"))
  219465. {
  219466. FT_Face face;
  219467. int faceIndex = 0;
  219468. int numFaces = 0;
  219469. do
  219470. {
  219471. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219472. faceIndex, &face) == 0)
  219473. {
  219474. if (faceIndex == 0)
  219475. numFaces = face->num_faces;
  219476. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219477. {
  219478. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219479. int style = (int) FreeTypeFontFace::Plain;
  219480. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219481. style |= (int) FreeTypeFontFace::Bold;
  219482. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219483. style |= (int) FreeTypeFontFace::Italic;
  219484. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219485. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219486. // Surely there must be a better way to do this?
  219487. const String name (face->family_name);
  219488. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219489. || name.containsIgnoreCase ("Verdana")
  219490. || name.containsIgnoreCase ("Arial")));
  219491. }
  219492. FT_Done_Face (face);
  219493. }
  219494. ++faceIndex;
  219495. }
  219496. while (faceIndex < numFaces);
  219497. }
  219498. }
  219499. }
  219500. // Create a FreeType face object for a given font
  219501. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219502. {
  219503. FT_Face face = 0;
  219504. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219505. {
  219506. face = lastFace;
  219507. }
  219508. else
  219509. {
  219510. if (lastFace != 0)
  219511. {
  219512. FT_Done_Face (lastFace);
  219513. lastFace = 0;
  219514. }
  219515. lastFontName = fontName;
  219516. lastBold = bold;
  219517. lastItalic = italic;
  219518. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219519. if (ftFace != 0)
  219520. {
  219521. int style = (int) FreeTypeFontFace::Plain;
  219522. if (bold)
  219523. style |= (int) FreeTypeFontFace::Bold;
  219524. if (italic)
  219525. style |= (int) FreeTypeFontFace::Italic;
  219526. int faceIndex;
  219527. String fileName (ftFace->getFileName (style, faceIndex));
  219528. if (fileName.isEmpty())
  219529. {
  219530. style ^= (int) FreeTypeFontFace::Bold;
  219531. fileName = ftFace->getFileName (style, faceIndex);
  219532. if (fileName.isEmpty())
  219533. {
  219534. style ^= (int) FreeTypeFontFace::Bold;
  219535. style ^= (int) FreeTypeFontFace::Italic;
  219536. fileName = ftFace->getFileName (style, faceIndex);
  219537. if (! fileName.length())
  219538. {
  219539. style ^= (int) FreeTypeFontFace::Bold;
  219540. fileName = ftFace->getFileName (style, faceIndex);
  219541. }
  219542. }
  219543. }
  219544. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219545. {
  219546. face = lastFace;
  219547. // If there isn't a unicode charmap then select the first one.
  219548. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219549. FT_Set_Charmap (face, face->charmaps[0]);
  219550. }
  219551. }
  219552. }
  219553. return face;
  219554. }
  219555. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219556. {
  219557. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219558. const float height = (float) (face->ascender - face->descender);
  219559. const float scaleX = 1.0f / height;
  219560. const float scaleY = -1.0f / height;
  219561. Path destShape;
  219562. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219563. || face->glyph->format != ft_glyph_format_outline)
  219564. {
  219565. return false;
  219566. }
  219567. const FT_Outline* const outline = &face->glyph->outline;
  219568. const short* const contours = outline->contours;
  219569. const char* const tags = outline->tags;
  219570. FT_Vector* const points = outline->points;
  219571. for (int c = 0; c < outline->n_contours; c++)
  219572. {
  219573. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219574. const int endPoint = contours[c];
  219575. for (int p = startPoint; p <= endPoint; p++)
  219576. {
  219577. const float x = scaleX * points[p].x;
  219578. const float y = scaleY * points[p].y;
  219579. if (p == startPoint)
  219580. {
  219581. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219582. {
  219583. float x2 = scaleX * points [endPoint].x;
  219584. float y2 = scaleY * points [endPoint].y;
  219585. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219586. {
  219587. x2 = (x + x2) * 0.5f;
  219588. y2 = (y + y2) * 0.5f;
  219589. }
  219590. destShape.startNewSubPath (x2, y2);
  219591. }
  219592. else
  219593. {
  219594. destShape.startNewSubPath (x, y);
  219595. }
  219596. }
  219597. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219598. {
  219599. if (p != startPoint)
  219600. destShape.lineTo (x, y);
  219601. }
  219602. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219603. {
  219604. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219605. float x2 = scaleX * points [nextIndex].x;
  219606. float y2 = scaleY * points [nextIndex].y;
  219607. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219608. {
  219609. x2 = (x + x2) * 0.5f;
  219610. y2 = (y + y2) * 0.5f;
  219611. }
  219612. else
  219613. {
  219614. ++p;
  219615. }
  219616. destShape.quadraticTo (x, y, x2, y2);
  219617. }
  219618. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219619. {
  219620. if (p >= endPoint)
  219621. return false;
  219622. const int next1 = p + 1;
  219623. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219624. const float x2 = scaleX * points [next1].x;
  219625. const float y2 = scaleY * points [next1].y;
  219626. const float x3 = scaleX * points [next2].x;
  219627. const float y3 = scaleY * points [next2].y;
  219628. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219629. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219630. return false;
  219631. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219632. p += 2;
  219633. }
  219634. }
  219635. destShape.closeSubPath();
  219636. }
  219637. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219638. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219639. addKerning (face, dest, character, glyphIndex);
  219640. return true;
  219641. }
  219642. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219643. {
  219644. const float height = (float) (face->ascender - face->descender);
  219645. uint32 rightGlyphIndex;
  219646. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219647. while (rightGlyphIndex != 0)
  219648. {
  219649. FT_Vector kerning;
  219650. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219651. {
  219652. if (kerning.x != 0)
  219653. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219654. }
  219655. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219656. }
  219657. }
  219658. // Add a glyph to a font
  219659. bool addGlyphToFont (const uint32 character, const String& fontName,
  219660. bool bold, bool italic, CustomTypeface& dest)
  219661. {
  219662. FT_Face face = createFT_Face (fontName, bold, italic);
  219663. return face != 0 && addGlyph (face, dest, character);
  219664. }
  219665. void getFamilyNames (StringArray& familyNames) const
  219666. {
  219667. for (int i = 0; i < faces.size(); i++)
  219668. familyNames.add (faces[i]->getFamilyName());
  219669. }
  219670. void getMonospacedNames (StringArray& monoSpaced) const
  219671. {
  219672. for (int i = 0; i < faces.size(); i++)
  219673. if (faces[i]->getMonospaced())
  219674. monoSpaced.add (faces[i]->getFamilyName());
  219675. }
  219676. void getSerifNames (StringArray& serif) const
  219677. {
  219678. for (int i = 0; i < faces.size(); i++)
  219679. if (faces[i]->getSerif())
  219680. serif.add (faces[i]->getFamilyName());
  219681. }
  219682. void getSansSerifNames (StringArray& sansSerif) const
  219683. {
  219684. for (int i = 0; i < faces.size(); i++)
  219685. if (! faces[i]->getSerif())
  219686. sansSerif.add (faces[i]->getFamilyName());
  219687. }
  219688. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219689. private:
  219690. FT_Library ftLib;
  219691. FT_Face lastFace;
  219692. String lastFontName;
  219693. bool lastBold, lastItalic;
  219694. OwnedArray<FreeTypeFontFace> faces;
  219695. };
  219696. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219697. class FreetypeTypeface : public CustomTypeface
  219698. {
  219699. public:
  219700. FreetypeTypeface (const Font& font)
  219701. {
  219702. FT_Face face = FreeTypeInterface::getInstance()
  219703. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219704. if (face == 0)
  219705. {
  219706. #if JUCE_DEBUG
  219707. String msg ("Failed to create typeface: ");
  219708. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219709. DBG (msg);
  219710. #endif
  219711. }
  219712. else
  219713. {
  219714. setCharacteristics (font.getTypefaceName(),
  219715. face->ascender / (float) (face->ascender - face->descender),
  219716. font.isBold(), font.isItalic(),
  219717. L' ');
  219718. }
  219719. }
  219720. bool loadGlyphIfPossible (juce_wchar character)
  219721. {
  219722. return FreeTypeInterface::getInstance()
  219723. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219724. }
  219725. };
  219726. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219727. {
  219728. return new FreetypeTypeface (font);
  219729. }
  219730. const StringArray Font::findAllTypefaceNames()
  219731. {
  219732. StringArray s;
  219733. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219734. s.sort (true);
  219735. return s;
  219736. }
  219737. static const String pickBestFont (const StringArray& names,
  219738. const char* const choicesString)
  219739. {
  219740. StringArray choices;
  219741. choices.addTokens (String (choicesString), ",", String::empty);
  219742. choices.trim();
  219743. choices.removeEmptyStrings();
  219744. int i, j;
  219745. for (j = 0; j < choices.size(); ++j)
  219746. if (names.contains (choices[j], true))
  219747. return choices[j];
  219748. for (j = 0; j < choices.size(); ++j)
  219749. for (i = 0; i < names.size(); i++)
  219750. if (names[i].startsWithIgnoreCase (choices[j]))
  219751. return names[i];
  219752. for (j = 0; j < choices.size(); ++j)
  219753. for (i = 0; i < names.size(); i++)
  219754. if (names[i].containsIgnoreCase (choices[j]))
  219755. return names[i];
  219756. return names[0];
  219757. }
  219758. static const String linux_getDefaultSansSerifFontName()
  219759. {
  219760. StringArray allFonts;
  219761. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219762. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219763. }
  219764. static const String linux_getDefaultSerifFontName()
  219765. {
  219766. StringArray allFonts;
  219767. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219768. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219769. }
  219770. static const String linux_getDefaultMonospacedFontName()
  219771. {
  219772. StringArray allFonts;
  219773. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219774. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219775. }
  219776. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219777. {
  219778. defaultSans = linux_getDefaultSansSerifFontName();
  219779. defaultSerif = linux_getDefaultSerifFontName();
  219780. defaultFixed = linux_getDefaultMonospacedFontName();
  219781. }
  219782. #endif
  219783. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219784. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219785. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219786. // compiled on its own).
  219787. #if JUCE_INCLUDED_FILE
  219788. // These are defined in juce_linux_Messaging.cpp
  219789. extern Display* display;
  219790. extern XContext windowHandleXContext;
  219791. namespace Atoms
  219792. {
  219793. enum ProtocolItems
  219794. {
  219795. TAKE_FOCUS = 0,
  219796. DELETE_WINDOW = 1,
  219797. PING = 2
  219798. };
  219799. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219800. ActiveWin, Pid, WindowType, WindowState,
  219801. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219802. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219803. XdndActionDescription, XdndActionCopy,
  219804. allowedActions[5],
  219805. allowedMimeTypes[2];
  219806. const unsigned long DndVersion = 3;
  219807. static void initialiseAtoms()
  219808. {
  219809. static bool atomsInitialised = false;
  219810. if (! atomsInitialised)
  219811. {
  219812. atomsInitialised = true;
  219813. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219814. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219815. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219816. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219817. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219818. State = XInternAtom (display, "WM_STATE", True);
  219819. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219820. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219821. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219822. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219823. XdndAware = XInternAtom (display, "XdndAware", False);
  219824. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219825. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219826. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219827. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219828. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219829. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219830. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219831. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219832. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219833. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219834. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219835. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219836. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219837. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219838. allowedActions[1] = XdndActionCopy;
  219839. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219840. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219841. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219842. }
  219843. }
  219844. }
  219845. namespace Keys
  219846. {
  219847. enum MouseButtons
  219848. {
  219849. NoButton = 0,
  219850. LeftButton = 1,
  219851. MiddleButton = 2,
  219852. RightButton = 3,
  219853. WheelUp = 4,
  219854. WheelDown = 5
  219855. };
  219856. static int AltMask = 0;
  219857. static int NumLockMask = 0;
  219858. static bool numLock = false;
  219859. static bool capsLock = false;
  219860. static char keyStates [32];
  219861. static const int extendedKeyModifier = 0x10000000;
  219862. }
  219863. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219864. {
  219865. int keysym;
  219866. if (keyCode & Keys::extendedKeyModifier)
  219867. {
  219868. keysym = 0xff00 | (keyCode & 0xff);
  219869. }
  219870. else
  219871. {
  219872. keysym = keyCode;
  219873. if (keysym == (XK_Tab & 0xff)
  219874. || keysym == (XK_Return & 0xff)
  219875. || keysym == (XK_Escape & 0xff)
  219876. || keysym == (XK_BackSpace & 0xff))
  219877. {
  219878. keysym |= 0xff00;
  219879. }
  219880. }
  219881. ScopedXLock xlock;
  219882. const int keycode = XKeysymToKeycode (display, keysym);
  219883. const int keybyte = keycode >> 3;
  219884. const int keybit = (1 << (keycode & 7));
  219885. return (Keys::keyStates [keybyte] & keybit) != 0;
  219886. }
  219887. #if JUCE_USE_XSHM
  219888. namespace XSHMHelpers
  219889. {
  219890. static int trappedErrorCode = 0;
  219891. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219892. {
  219893. trappedErrorCode = err->error_code;
  219894. return 0;
  219895. }
  219896. static bool isShmAvailable() throw()
  219897. {
  219898. static bool isChecked = false;
  219899. static bool isAvailable = false;
  219900. if (! isChecked)
  219901. {
  219902. isChecked = true;
  219903. int major, minor;
  219904. Bool pixmaps;
  219905. ScopedXLock xlock;
  219906. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219907. {
  219908. trappedErrorCode = 0;
  219909. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219910. XShmSegmentInfo segmentInfo;
  219911. zerostruct (segmentInfo);
  219912. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219913. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219914. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219915. xImage->bytes_per_line * xImage->height,
  219916. IPC_CREAT | 0777)) >= 0)
  219917. {
  219918. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219919. if (segmentInfo.shmaddr != (void*) -1)
  219920. {
  219921. segmentInfo.readOnly = False;
  219922. xImage->data = segmentInfo.shmaddr;
  219923. XSync (display, False);
  219924. if (XShmAttach (display, &segmentInfo) != 0)
  219925. {
  219926. XSync (display, False);
  219927. XShmDetach (display, &segmentInfo);
  219928. isAvailable = true;
  219929. }
  219930. }
  219931. XFlush (display);
  219932. XDestroyImage (xImage);
  219933. shmdt (segmentInfo.shmaddr);
  219934. }
  219935. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219936. XSetErrorHandler (oldHandler);
  219937. if (trappedErrorCode != 0)
  219938. isAvailable = false;
  219939. }
  219940. }
  219941. return isAvailable;
  219942. }
  219943. }
  219944. #endif
  219945. #if JUCE_USE_XRENDER
  219946. namespace XRender
  219947. {
  219948. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219949. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219950. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219951. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219952. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219953. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219954. static tXRenderFindFormat xRenderFindFormat = 0;
  219955. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219956. static bool isAvailable()
  219957. {
  219958. static bool hasLoaded = false;
  219959. if (! hasLoaded)
  219960. {
  219961. ScopedXLock xlock;
  219962. hasLoaded = true;
  219963. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219964. if (h != 0)
  219965. {
  219966. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219967. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219968. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219969. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219970. }
  219971. if (xRenderQueryVersion != 0
  219972. && xRenderFindStandardFormat != 0
  219973. && xRenderFindFormat != 0
  219974. && xRenderFindVisualFormat != 0)
  219975. {
  219976. int major, minor;
  219977. if (xRenderQueryVersion (display, &major, &minor))
  219978. return true;
  219979. }
  219980. xRenderQueryVersion = 0;
  219981. }
  219982. return xRenderQueryVersion != 0;
  219983. }
  219984. static XRenderPictFormat* findPictureFormat()
  219985. {
  219986. ScopedXLock xlock;
  219987. XRenderPictFormat* pictFormat = 0;
  219988. if (isAvailable())
  219989. {
  219990. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219991. if (pictFormat == 0)
  219992. {
  219993. XRenderPictFormat desiredFormat;
  219994. desiredFormat.type = PictTypeDirect;
  219995. desiredFormat.depth = 32;
  219996. desiredFormat.direct.alphaMask = 0xff;
  219997. desiredFormat.direct.redMask = 0xff;
  219998. desiredFormat.direct.greenMask = 0xff;
  219999. desiredFormat.direct.blueMask = 0xff;
  220000. desiredFormat.direct.alpha = 24;
  220001. desiredFormat.direct.red = 16;
  220002. desiredFormat.direct.green = 8;
  220003. desiredFormat.direct.blue = 0;
  220004. pictFormat = xRenderFindFormat (display,
  220005. PictFormatType | PictFormatDepth
  220006. | PictFormatRedMask | PictFormatRed
  220007. | PictFormatGreenMask | PictFormatGreen
  220008. | PictFormatBlueMask | PictFormatBlue
  220009. | PictFormatAlphaMask | PictFormatAlpha,
  220010. &desiredFormat,
  220011. 0);
  220012. }
  220013. }
  220014. return pictFormat;
  220015. }
  220016. }
  220017. #endif
  220018. namespace Visuals
  220019. {
  220020. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  220021. {
  220022. ScopedXLock xlock;
  220023. Visual* visual = 0;
  220024. int numVisuals = 0;
  220025. long desiredMask = VisualNoMask;
  220026. XVisualInfo desiredVisual;
  220027. desiredVisual.screen = DefaultScreen (display);
  220028. desiredVisual.depth = desiredDepth;
  220029. desiredMask = VisualScreenMask | VisualDepthMask;
  220030. if (desiredDepth == 32)
  220031. {
  220032. desiredVisual.c_class = TrueColor;
  220033. desiredVisual.red_mask = 0x00FF0000;
  220034. desiredVisual.green_mask = 0x0000FF00;
  220035. desiredVisual.blue_mask = 0x000000FF;
  220036. desiredVisual.bits_per_rgb = 8;
  220037. desiredMask |= VisualClassMask;
  220038. desiredMask |= VisualRedMaskMask;
  220039. desiredMask |= VisualGreenMaskMask;
  220040. desiredMask |= VisualBlueMaskMask;
  220041. desiredMask |= VisualBitsPerRGBMask;
  220042. }
  220043. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220044. desiredMask,
  220045. &desiredVisual,
  220046. &numVisuals);
  220047. if (xvinfos != 0)
  220048. {
  220049. for (int i = 0; i < numVisuals; i++)
  220050. {
  220051. if (xvinfos[i].depth == desiredDepth)
  220052. {
  220053. visual = xvinfos[i].visual;
  220054. break;
  220055. }
  220056. }
  220057. XFree (xvinfos);
  220058. }
  220059. return visual;
  220060. }
  220061. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  220062. {
  220063. Visual* visual = 0;
  220064. if (desiredDepth == 32)
  220065. {
  220066. #if JUCE_USE_XSHM
  220067. if (XSHMHelpers::isShmAvailable())
  220068. {
  220069. #if JUCE_USE_XRENDER
  220070. if (XRender::isAvailable())
  220071. {
  220072. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  220073. if (pictFormat != 0)
  220074. {
  220075. int numVisuals = 0;
  220076. XVisualInfo desiredVisual;
  220077. desiredVisual.screen = DefaultScreen (display);
  220078. desiredVisual.depth = 32;
  220079. desiredVisual.bits_per_rgb = 8;
  220080. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220081. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  220082. &desiredVisual, &numVisuals);
  220083. if (xvinfos != 0)
  220084. {
  220085. for (int i = 0; i < numVisuals; ++i)
  220086. {
  220087. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  220088. if (pictVisualFormat != 0
  220089. && pictVisualFormat->type == PictTypeDirect
  220090. && pictVisualFormat->direct.alphaMask)
  220091. {
  220092. visual = xvinfos[i].visual;
  220093. matchedDepth = 32;
  220094. break;
  220095. }
  220096. }
  220097. XFree (xvinfos);
  220098. }
  220099. }
  220100. }
  220101. #endif
  220102. if (visual == 0)
  220103. {
  220104. visual = findVisualWithDepth (32);
  220105. if (visual != 0)
  220106. matchedDepth = 32;
  220107. }
  220108. }
  220109. #endif
  220110. }
  220111. if (visual == 0 && desiredDepth >= 24)
  220112. {
  220113. visual = findVisualWithDepth (24);
  220114. if (visual != 0)
  220115. matchedDepth = 24;
  220116. }
  220117. if (visual == 0 && desiredDepth >= 16)
  220118. {
  220119. visual = findVisualWithDepth (16);
  220120. if (visual != 0)
  220121. matchedDepth = 16;
  220122. }
  220123. return visual;
  220124. }
  220125. }
  220126. class XBitmapImage : public Image::SharedImage
  220127. {
  220128. public:
  220129. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  220130. const bool clearImage, const int imageDepth_, Visual* visual)
  220131. : Image::SharedImage (format_, w, h),
  220132. imageDepth (imageDepth_),
  220133. gc (None)
  220134. {
  220135. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  220136. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  220137. lineStride = ((w * pixelStride + 3) & ~3);
  220138. ScopedXLock xlock;
  220139. #if JUCE_USE_XSHM
  220140. usingXShm = false;
  220141. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  220142. {
  220143. zerostruct (segmentInfo);
  220144. segmentInfo.shmid = -1;
  220145. segmentInfo.shmaddr = (char *) -1;
  220146. segmentInfo.readOnly = False;
  220147. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  220148. if (xImage != 0)
  220149. {
  220150. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220151. xImage->bytes_per_line * xImage->height,
  220152. IPC_CREAT | 0777)) >= 0)
  220153. {
  220154. if (segmentInfo.shmid != -1)
  220155. {
  220156. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220157. if (segmentInfo.shmaddr != (void*) -1)
  220158. {
  220159. segmentInfo.readOnly = False;
  220160. xImage->data = segmentInfo.shmaddr;
  220161. imageData = (uint8*) segmentInfo.shmaddr;
  220162. if (XShmAttach (display, &segmentInfo) != 0)
  220163. usingXShm = true;
  220164. else
  220165. jassertfalse;
  220166. }
  220167. else
  220168. {
  220169. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220170. }
  220171. }
  220172. }
  220173. }
  220174. }
  220175. if (! usingXShm)
  220176. #endif
  220177. {
  220178. imageDataAllocated.malloc (lineStride * h);
  220179. imageData = imageDataAllocated;
  220180. if (format_ == Image::ARGB && clearImage)
  220181. zeromem (imageData, h * lineStride);
  220182. xImage = (XImage*) juce_calloc (sizeof (XImage));
  220183. xImage->width = w;
  220184. xImage->height = h;
  220185. xImage->xoffset = 0;
  220186. xImage->format = ZPixmap;
  220187. xImage->data = (char*) imageData;
  220188. xImage->byte_order = ImageByteOrder (display);
  220189. xImage->bitmap_unit = BitmapUnit (display);
  220190. xImage->bitmap_bit_order = BitmapBitOrder (display);
  220191. xImage->bitmap_pad = 32;
  220192. xImage->depth = pixelStride * 8;
  220193. xImage->bytes_per_line = lineStride;
  220194. xImage->bits_per_pixel = pixelStride * 8;
  220195. xImage->red_mask = 0x00FF0000;
  220196. xImage->green_mask = 0x0000FF00;
  220197. xImage->blue_mask = 0x000000FF;
  220198. if (imageDepth == 16)
  220199. {
  220200. const int pixelStride = 2;
  220201. const int lineStride = ((w * pixelStride + 3) & ~3);
  220202. imageData16Bit.malloc (lineStride * h);
  220203. xImage->data = imageData16Bit;
  220204. xImage->bitmap_pad = 16;
  220205. xImage->depth = pixelStride * 8;
  220206. xImage->bytes_per_line = lineStride;
  220207. xImage->bits_per_pixel = pixelStride * 8;
  220208. xImage->red_mask = visual->red_mask;
  220209. xImage->green_mask = visual->green_mask;
  220210. xImage->blue_mask = visual->blue_mask;
  220211. }
  220212. if (! XInitImage (xImage))
  220213. jassertfalse;
  220214. }
  220215. }
  220216. ~XBitmapImage()
  220217. {
  220218. ScopedXLock xlock;
  220219. if (gc != None)
  220220. XFreeGC (display, gc);
  220221. #if JUCE_USE_XSHM
  220222. if (usingXShm)
  220223. {
  220224. XShmDetach (display, &segmentInfo);
  220225. XFlush (display);
  220226. XDestroyImage (xImage);
  220227. shmdt (segmentInfo.shmaddr);
  220228. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220229. }
  220230. else
  220231. #endif
  220232. {
  220233. xImage->data = 0;
  220234. XDestroyImage (xImage);
  220235. }
  220236. }
  220237. Image::ImageType getType() const { return Image::NativeImage; }
  220238. LowLevelGraphicsContext* createLowLevelContext()
  220239. {
  220240. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220241. }
  220242. SharedImage* clone()
  220243. {
  220244. jassertfalse;
  220245. return 0;
  220246. }
  220247. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220248. {
  220249. ScopedXLock xlock;
  220250. if (gc == None)
  220251. {
  220252. XGCValues gcvalues;
  220253. gcvalues.foreground = None;
  220254. gcvalues.background = None;
  220255. gcvalues.function = GXcopy;
  220256. gcvalues.plane_mask = AllPlanes;
  220257. gcvalues.clip_mask = None;
  220258. gcvalues.graphics_exposures = False;
  220259. gc = XCreateGC (display, window,
  220260. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220261. &gcvalues);
  220262. }
  220263. if (imageDepth == 16)
  220264. {
  220265. const uint32 rMask = xImage->red_mask;
  220266. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220267. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220268. const uint32 gMask = xImage->green_mask;
  220269. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220270. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220271. const uint32 bMask = xImage->blue_mask;
  220272. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220273. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220274. const Image::BitmapData srcData (Image (this), false);
  220275. for (int y = sy; y < sy + dh; ++y)
  220276. {
  220277. const uint8* p = srcData.getPixelPointer (sx, y);
  220278. for (int x = sx; x < sx + dw; ++x)
  220279. {
  220280. const PixelRGB* const pixel = (const PixelRGB*) p;
  220281. p += srcData.pixelStride;
  220282. XPutPixel (xImage, x, y,
  220283. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220284. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220285. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220286. }
  220287. }
  220288. }
  220289. // blit results to screen.
  220290. #if JUCE_USE_XSHM
  220291. if (usingXShm)
  220292. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220293. else
  220294. #endif
  220295. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220296. }
  220297. juce_UseDebuggingNewOperator
  220298. private:
  220299. XImage* xImage;
  220300. const int imageDepth;
  220301. HeapBlock <uint8> imageDataAllocated;
  220302. HeapBlock <char> imageData16Bit;
  220303. GC gc;
  220304. #if JUCE_USE_XSHM
  220305. XShmSegmentInfo segmentInfo;
  220306. bool usingXShm;
  220307. #endif
  220308. static int getShiftNeeded (const uint32 mask) throw()
  220309. {
  220310. for (int i = 32; --i >= 0;)
  220311. if (((mask >> i) & 1) != 0)
  220312. return i - 7;
  220313. jassertfalse;
  220314. return 0;
  220315. }
  220316. };
  220317. class LinuxComponentPeer : public ComponentPeer
  220318. {
  220319. public:
  220320. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220321. : ComponentPeer (component, windowStyleFlags),
  220322. windowH (0),
  220323. parentWindow (0),
  220324. wx (0),
  220325. wy (0),
  220326. ww (0),
  220327. wh (0),
  220328. fullScreen (false),
  220329. mapped (false),
  220330. visual (0),
  220331. depth (0)
  220332. {
  220333. // it's dangerous to create a window on a thread other than the message thread..
  220334. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220335. repainter = new LinuxRepaintManager (this);
  220336. createWindow();
  220337. setTitle (component->getName());
  220338. }
  220339. ~LinuxComponentPeer()
  220340. {
  220341. // it's dangerous to delete a window on a thread other than the message thread..
  220342. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220343. deleteIconPixmaps();
  220344. destroyWindow();
  220345. windowH = 0;
  220346. }
  220347. void* getNativeHandle() const
  220348. {
  220349. return (void*) windowH;
  220350. }
  220351. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220352. {
  220353. XPointer peer = 0;
  220354. ScopedXLock xlock;
  220355. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220356. {
  220357. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220358. peer = 0;
  220359. }
  220360. return (LinuxComponentPeer*) peer;
  220361. }
  220362. void setVisible (bool shouldBeVisible)
  220363. {
  220364. ScopedXLock xlock;
  220365. if (shouldBeVisible)
  220366. XMapWindow (display, windowH);
  220367. else
  220368. XUnmapWindow (display, windowH);
  220369. }
  220370. void setTitle (const String& title)
  220371. {
  220372. setWindowTitle (windowH, title);
  220373. }
  220374. void setPosition (int x, int y)
  220375. {
  220376. setBounds (x, y, ww, wh, false);
  220377. }
  220378. void setSize (int w, int h)
  220379. {
  220380. setBounds (wx, wy, w, h, false);
  220381. }
  220382. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220383. {
  220384. fullScreen = isNowFullScreen;
  220385. if (windowH != 0)
  220386. {
  220387. Component::SafePointer<Component> deletionChecker (component);
  220388. wx = x;
  220389. wy = y;
  220390. ww = jmax (1, w);
  220391. wh = jmax (1, h);
  220392. ScopedXLock xlock;
  220393. // Make sure the Window manager does what we want
  220394. XSizeHints* hints = XAllocSizeHints();
  220395. hints->flags = USSize | USPosition;
  220396. hints->width = ww;
  220397. hints->height = wh;
  220398. hints->x = wx;
  220399. hints->y = wy;
  220400. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220401. {
  220402. hints->min_width = hints->max_width = hints->width;
  220403. hints->min_height = hints->max_height = hints->height;
  220404. hints->flags |= PMinSize | PMaxSize;
  220405. }
  220406. XSetWMNormalHints (display, windowH, hints);
  220407. XFree (hints);
  220408. XMoveResizeWindow (display, windowH,
  220409. wx - windowBorder.getLeft(),
  220410. wy - windowBorder.getTop(), ww, wh);
  220411. if (deletionChecker != 0)
  220412. {
  220413. updateBorderSize();
  220414. handleMovedOrResized();
  220415. }
  220416. }
  220417. }
  220418. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220419. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220420. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220421. {
  220422. return relativePosition + getScreenPosition();
  220423. }
  220424. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220425. {
  220426. return screenPosition - getScreenPosition();
  220427. }
  220428. void setMinimised (bool shouldBeMinimised)
  220429. {
  220430. if (shouldBeMinimised)
  220431. {
  220432. Window root = RootWindow (display, DefaultScreen (display));
  220433. XClientMessageEvent clientMsg;
  220434. clientMsg.display = display;
  220435. clientMsg.window = windowH;
  220436. clientMsg.type = ClientMessage;
  220437. clientMsg.format = 32;
  220438. clientMsg.message_type = Atoms::ChangeState;
  220439. clientMsg.data.l[0] = IconicState;
  220440. ScopedXLock xlock;
  220441. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220442. }
  220443. else
  220444. {
  220445. setVisible (true);
  220446. }
  220447. }
  220448. bool isMinimised() const
  220449. {
  220450. bool minimised = false;
  220451. unsigned char* stateProp;
  220452. unsigned long nitems, bytesLeft;
  220453. Atom actualType;
  220454. int actualFormat;
  220455. ScopedXLock xlock;
  220456. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220457. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220458. &stateProp) == Success
  220459. && actualType == Atoms::State
  220460. && actualFormat == 32
  220461. && nitems > 0)
  220462. {
  220463. if (((unsigned long*) stateProp)[0] == IconicState)
  220464. minimised = true;
  220465. XFree (stateProp);
  220466. }
  220467. return minimised;
  220468. }
  220469. void setFullScreen (const bool shouldBeFullScreen)
  220470. {
  220471. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220472. setMinimised (false);
  220473. if (fullScreen != shouldBeFullScreen)
  220474. {
  220475. if (shouldBeFullScreen)
  220476. r = Desktop::getInstance().getMainMonitorArea();
  220477. if (! r.isEmpty())
  220478. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220479. getComponent()->repaint();
  220480. }
  220481. }
  220482. bool isFullScreen() const
  220483. {
  220484. return fullScreen;
  220485. }
  220486. bool isChildWindowOf (Window possibleParent) const
  220487. {
  220488. Window* windowList = 0;
  220489. uint32 windowListSize = 0;
  220490. Window parent, root;
  220491. ScopedXLock xlock;
  220492. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220493. {
  220494. if (windowList != 0)
  220495. XFree (windowList);
  220496. return parent == possibleParent;
  220497. }
  220498. return false;
  220499. }
  220500. bool isFrontWindow() const
  220501. {
  220502. Window* windowList = 0;
  220503. uint32 windowListSize = 0;
  220504. bool result = false;
  220505. ScopedXLock xlock;
  220506. Window parent, root = RootWindow (display, DefaultScreen (display));
  220507. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220508. {
  220509. for (int i = windowListSize; --i >= 0;)
  220510. {
  220511. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220512. if (peer != 0)
  220513. {
  220514. result = (peer == this);
  220515. break;
  220516. }
  220517. }
  220518. }
  220519. if (windowList != 0)
  220520. XFree (windowList);
  220521. return result;
  220522. }
  220523. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220524. {
  220525. int x = position.getX();
  220526. int y = position.getY();
  220527. if (((unsigned int) x) >= (unsigned int) ww
  220528. || ((unsigned int) y) >= (unsigned int) wh)
  220529. return false;
  220530. bool inFront = false;
  220531. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220532. {
  220533. Component* const c = Desktop::getInstance().getComponent (i);
  220534. if (inFront)
  220535. {
  220536. if (c->contains (x + wx - c->getScreenX(),
  220537. y + wy - c->getScreenY()))
  220538. {
  220539. return false;
  220540. }
  220541. }
  220542. else if (c == getComponent())
  220543. {
  220544. inFront = true;
  220545. }
  220546. }
  220547. if (trueIfInAChildWindow)
  220548. return true;
  220549. ::Window root, child;
  220550. unsigned int bw, depth;
  220551. int wx, wy, w, h;
  220552. ScopedXLock xlock;
  220553. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220554. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220555. &bw, &depth))
  220556. {
  220557. return false;
  220558. }
  220559. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220560. return false;
  220561. return child == None;
  220562. }
  220563. const BorderSize getFrameSize() const
  220564. {
  220565. return BorderSize();
  220566. }
  220567. bool setAlwaysOnTop (bool alwaysOnTop)
  220568. {
  220569. return false;
  220570. }
  220571. void toFront (bool makeActive)
  220572. {
  220573. if (makeActive)
  220574. {
  220575. setVisible (true);
  220576. grabFocus();
  220577. }
  220578. XEvent ev;
  220579. ev.xclient.type = ClientMessage;
  220580. ev.xclient.serial = 0;
  220581. ev.xclient.send_event = True;
  220582. ev.xclient.message_type = Atoms::ActiveWin;
  220583. ev.xclient.window = windowH;
  220584. ev.xclient.format = 32;
  220585. ev.xclient.data.l[0] = 2;
  220586. ev.xclient.data.l[1] = CurrentTime;
  220587. ev.xclient.data.l[2] = 0;
  220588. ev.xclient.data.l[3] = 0;
  220589. ev.xclient.data.l[4] = 0;
  220590. {
  220591. ScopedXLock xlock;
  220592. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220593. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220594. XWindowAttributes attr;
  220595. XGetWindowAttributes (display, windowH, &attr);
  220596. if (component->isAlwaysOnTop())
  220597. XRaiseWindow (display, windowH);
  220598. XSync (display, False);
  220599. }
  220600. handleBroughtToFront();
  220601. }
  220602. void toBehind (ComponentPeer* other)
  220603. {
  220604. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220605. jassert (otherPeer != 0); // wrong type of window?
  220606. if (otherPeer != 0)
  220607. {
  220608. setMinimised (false);
  220609. Window newStack[] = { otherPeer->windowH, windowH };
  220610. ScopedXLock xlock;
  220611. XRestackWindows (display, newStack, 2);
  220612. }
  220613. }
  220614. bool isFocused() const
  220615. {
  220616. int revert = 0;
  220617. Window focusedWindow = 0;
  220618. ScopedXLock xlock;
  220619. XGetInputFocus (display, &focusedWindow, &revert);
  220620. return focusedWindow == windowH;
  220621. }
  220622. void grabFocus()
  220623. {
  220624. XWindowAttributes atts;
  220625. ScopedXLock xlock;
  220626. if (windowH != 0
  220627. && XGetWindowAttributes (display, windowH, &atts)
  220628. && atts.map_state == IsViewable
  220629. && ! isFocused())
  220630. {
  220631. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220632. isActiveApplication = true;
  220633. }
  220634. }
  220635. void textInputRequired (const Point<int>&)
  220636. {
  220637. }
  220638. void repaint (const Rectangle<int>& area)
  220639. {
  220640. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220641. }
  220642. void performAnyPendingRepaintsNow()
  220643. {
  220644. repainter->performAnyPendingRepaintsNow();
  220645. }
  220646. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220647. {
  220648. ScopedXLock xlock;
  220649. const int width = image.getWidth();
  220650. const int height = image.getHeight();
  220651. HeapBlock <uint32> colour (width * height);
  220652. int index = 0;
  220653. for (int y = 0; y < height; ++y)
  220654. for (int x = 0; x < width; ++x)
  220655. colour[index++] = image.getPixelAt (x, y).getARGB();
  220656. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220657. 0, reinterpret_cast<char*> (colour.getData()),
  220658. width, height, 32, 0);
  220659. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220660. width, height, 24);
  220661. GC gc = XCreateGC (display, pixmap, 0, 0);
  220662. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220663. XFreeGC (display, gc);
  220664. return pixmap;
  220665. }
  220666. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220667. {
  220668. ScopedXLock xlock;
  220669. const int width = image.getWidth();
  220670. const int height = image.getHeight();
  220671. const int stride = (width + 7) >> 3;
  220672. HeapBlock <char> mask;
  220673. mask.calloc (stride * height);
  220674. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220675. for (int y = 0; y < height; ++y)
  220676. {
  220677. for (int x = 0; x < width; ++x)
  220678. {
  220679. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220680. const int offset = y * stride + (x >> 3);
  220681. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220682. mask[offset] |= bit;
  220683. }
  220684. }
  220685. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220686. mask.getData(), width, height, 1, 0, 1);
  220687. }
  220688. void setIcon (const Image& newIcon)
  220689. {
  220690. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220691. HeapBlock <unsigned long> data (dataSize);
  220692. int index = 0;
  220693. data[index++] = newIcon.getWidth();
  220694. data[index++] = newIcon.getHeight();
  220695. for (int y = 0; y < newIcon.getHeight(); ++y)
  220696. for (int x = 0; x < newIcon.getWidth(); ++x)
  220697. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220698. ScopedXLock xlock;
  220699. XChangeProperty (display, windowH,
  220700. XInternAtom (display, "_NET_WM_ICON", False),
  220701. XA_CARDINAL, 32, PropModeReplace,
  220702. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220703. deleteIconPixmaps();
  220704. XWMHints* wmHints = XGetWMHints (display, windowH);
  220705. if (wmHints == 0)
  220706. wmHints = XAllocWMHints();
  220707. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220708. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220709. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220710. XSetWMHints (display, windowH, wmHints);
  220711. XFree (wmHints);
  220712. XSync (display, False);
  220713. }
  220714. void deleteIconPixmaps()
  220715. {
  220716. ScopedXLock xlock;
  220717. XWMHints* wmHints = XGetWMHints (display, windowH);
  220718. if (wmHints != 0)
  220719. {
  220720. if ((wmHints->flags & IconPixmapHint) != 0)
  220721. {
  220722. wmHints->flags &= ~IconPixmapHint;
  220723. XFreePixmap (display, wmHints->icon_pixmap);
  220724. }
  220725. if ((wmHints->flags & IconMaskHint) != 0)
  220726. {
  220727. wmHints->flags &= ~IconMaskHint;
  220728. XFreePixmap (display, wmHints->icon_mask);
  220729. }
  220730. XSetWMHints (display, windowH, wmHints);
  220731. XFree (wmHints);
  220732. }
  220733. }
  220734. void handleWindowMessage (XEvent* event)
  220735. {
  220736. switch (event->xany.type)
  220737. {
  220738. case 2: // 'KeyPress'
  220739. {
  220740. ScopedXLock xlock;
  220741. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220742. updateKeyStates (keyEvent->keycode, true);
  220743. char utf8 [64];
  220744. zeromem (utf8, sizeof (utf8));
  220745. KeySym sym;
  220746. {
  220747. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220748. ::setlocale (LC_ALL, "");
  220749. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220750. ::setlocale (LC_ALL, oldLocale);
  220751. }
  220752. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220753. int keyCode = (int) unicodeChar;
  220754. if (keyCode < 0x20)
  220755. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220756. const ModifierKeys oldMods (currentModifiers);
  220757. bool keyPressed = false;
  220758. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220759. if ((sym & 0xff00) == 0xff00)
  220760. {
  220761. // Translate keypad
  220762. if (sym == XK_KP_Divide)
  220763. keyCode = XK_slash;
  220764. else if (sym == XK_KP_Multiply)
  220765. keyCode = XK_asterisk;
  220766. else if (sym == XK_KP_Subtract)
  220767. keyCode = XK_hyphen;
  220768. else if (sym == XK_KP_Add)
  220769. keyCode = XK_plus;
  220770. else if (sym == XK_KP_Enter)
  220771. keyCode = XK_Return;
  220772. else if (sym == XK_KP_Decimal)
  220773. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220774. else if (sym == XK_KP_0)
  220775. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220776. else if (sym == XK_KP_1)
  220777. keyCode = Keys::numLock ? XK_1 : XK_End;
  220778. else if (sym == XK_KP_2)
  220779. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220780. else if (sym == XK_KP_3)
  220781. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220782. else if (sym == XK_KP_4)
  220783. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220784. else if (sym == XK_KP_5)
  220785. keyCode = XK_5;
  220786. else if (sym == XK_KP_6)
  220787. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220788. else if (sym == XK_KP_7)
  220789. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220790. else if (sym == XK_KP_8)
  220791. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220792. else if (sym == XK_KP_9)
  220793. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220794. switch (sym)
  220795. {
  220796. case XK_Left:
  220797. case XK_Right:
  220798. case XK_Up:
  220799. case XK_Down:
  220800. case XK_Page_Up:
  220801. case XK_Page_Down:
  220802. case XK_End:
  220803. case XK_Home:
  220804. case XK_Delete:
  220805. case XK_Insert:
  220806. keyPressed = true;
  220807. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220808. break;
  220809. case XK_Tab:
  220810. case XK_Return:
  220811. case XK_Escape:
  220812. case XK_BackSpace:
  220813. keyPressed = true;
  220814. keyCode &= 0xff;
  220815. break;
  220816. default:
  220817. {
  220818. if (sym >= XK_F1 && sym <= XK_F16)
  220819. {
  220820. keyPressed = true;
  220821. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220822. }
  220823. break;
  220824. }
  220825. }
  220826. }
  220827. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220828. keyPressed = true;
  220829. if (oldMods != currentModifiers)
  220830. handleModifierKeysChange();
  220831. if (keyDownChange)
  220832. handleKeyUpOrDown (true);
  220833. if (keyPressed)
  220834. handleKeyPress (keyCode, unicodeChar);
  220835. break;
  220836. }
  220837. case KeyRelease:
  220838. {
  220839. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220840. updateKeyStates (keyEvent->keycode, false);
  220841. KeySym sym;
  220842. {
  220843. ScopedXLock xlock;
  220844. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220845. }
  220846. const ModifierKeys oldMods (currentModifiers);
  220847. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220848. if (oldMods != currentModifiers)
  220849. handleModifierKeysChange();
  220850. if (keyDownChange)
  220851. handleKeyUpOrDown (false);
  220852. break;
  220853. }
  220854. case ButtonPress:
  220855. {
  220856. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220857. updateKeyModifiers (buttonPressEvent->state);
  220858. bool buttonMsg = false;
  220859. const int map = pointerMap [buttonPressEvent->button - Button1];
  220860. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220861. {
  220862. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220863. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220864. }
  220865. if (map == Keys::LeftButton)
  220866. {
  220867. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220868. buttonMsg = true;
  220869. }
  220870. else if (map == Keys::RightButton)
  220871. {
  220872. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220873. buttonMsg = true;
  220874. }
  220875. else if (map == Keys::MiddleButton)
  220876. {
  220877. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220878. buttonMsg = true;
  220879. }
  220880. if (buttonMsg)
  220881. {
  220882. toFront (true);
  220883. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220884. getEventTime (buttonPressEvent->time));
  220885. }
  220886. clearLastMousePos();
  220887. break;
  220888. }
  220889. case ButtonRelease:
  220890. {
  220891. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220892. updateKeyModifiers (buttonRelEvent->state);
  220893. const int map = pointerMap [buttonRelEvent->button - Button1];
  220894. if (map == Keys::LeftButton)
  220895. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220896. else if (map == Keys::RightButton)
  220897. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220898. else if (map == Keys::MiddleButton)
  220899. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220900. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220901. getEventTime (buttonRelEvent->time));
  220902. clearLastMousePos();
  220903. break;
  220904. }
  220905. case MotionNotify:
  220906. {
  220907. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220908. updateKeyModifiers (movedEvent->state);
  220909. const Point<int> mousePos (Desktop::getMousePosition());
  220910. if (lastMousePos != mousePos)
  220911. {
  220912. lastMousePos = mousePos;
  220913. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220914. {
  220915. Window wRoot = 0, wParent = 0;
  220916. {
  220917. ScopedXLock xlock;
  220918. unsigned int numChildren;
  220919. Window* wChild = 0;
  220920. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220921. }
  220922. if (wParent != 0
  220923. && wParent != windowH
  220924. && wParent != wRoot)
  220925. {
  220926. parentWindow = wParent;
  220927. updateBounds();
  220928. }
  220929. else
  220930. {
  220931. parentWindow = 0;
  220932. }
  220933. }
  220934. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220935. }
  220936. break;
  220937. }
  220938. case EnterNotify:
  220939. {
  220940. clearLastMousePos();
  220941. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220942. if (! currentModifiers.isAnyMouseButtonDown())
  220943. {
  220944. updateKeyModifiers (enterEvent->state);
  220945. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220946. }
  220947. break;
  220948. }
  220949. case LeaveNotify:
  220950. {
  220951. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220952. // Suppress the normal leave if we've got a pointer grab, or if
  220953. // it's a bogus one caused by clicking a mouse button when running
  220954. // in a Window manager
  220955. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220956. || leaveEvent->mode == NotifyUngrab)
  220957. {
  220958. updateKeyModifiers (leaveEvent->state);
  220959. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220960. }
  220961. break;
  220962. }
  220963. case FocusIn:
  220964. {
  220965. isActiveApplication = true;
  220966. if (isFocused())
  220967. handleFocusGain();
  220968. break;
  220969. }
  220970. case FocusOut:
  220971. {
  220972. isActiveApplication = false;
  220973. if (! isFocused())
  220974. handleFocusLoss();
  220975. break;
  220976. }
  220977. case Expose:
  220978. {
  220979. // Batch together all pending expose events
  220980. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220981. XEvent nextEvent;
  220982. ScopedXLock xlock;
  220983. if (exposeEvent->window != windowH)
  220984. {
  220985. Window child;
  220986. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220987. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220988. &child);
  220989. }
  220990. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220991. exposeEvent->width, exposeEvent->height));
  220992. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220993. {
  220994. XPeekEvent (display, (XEvent*) &nextEvent);
  220995. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220996. break;
  220997. XNextEvent (display, (XEvent*) &nextEvent);
  220998. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220999. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  221000. nextExposeEvent->width, nextExposeEvent->height));
  221001. }
  221002. break;
  221003. }
  221004. case CirculateNotify:
  221005. case CreateNotify:
  221006. case DestroyNotify:
  221007. // Think we can ignore these
  221008. break;
  221009. case ConfigureNotify:
  221010. {
  221011. updateBounds();
  221012. updateBorderSize();
  221013. handleMovedOrResized();
  221014. // if the native title bar is dragged, need to tell any active menus, etc.
  221015. if ((styleFlags & windowHasTitleBar) != 0
  221016. && component->isCurrentlyBlockedByAnotherModalComponent())
  221017. {
  221018. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  221019. if (currentModalComp != 0)
  221020. currentModalComp->inputAttemptWhenModal();
  221021. }
  221022. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  221023. if (confEvent->window == windowH
  221024. && confEvent->above != 0
  221025. && isFrontWindow())
  221026. {
  221027. handleBroughtToFront();
  221028. }
  221029. break;
  221030. }
  221031. case ReparentNotify:
  221032. {
  221033. parentWindow = 0;
  221034. Window wRoot = 0;
  221035. Window* wChild = 0;
  221036. unsigned int numChildren;
  221037. {
  221038. ScopedXLock xlock;
  221039. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  221040. }
  221041. if (parentWindow == windowH || parentWindow == wRoot)
  221042. parentWindow = 0;
  221043. updateBounds();
  221044. updateBorderSize();
  221045. handleMovedOrResized();
  221046. break;
  221047. }
  221048. case GravityNotify:
  221049. {
  221050. updateBounds();
  221051. updateBorderSize();
  221052. handleMovedOrResized();
  221053. break;
  221054. }
  221055. case MapNotify:
  221056. mapped = true;
  221057. handleBroughtToFront();
  221058. break;
  221059. case UnmapNotify:
  221060. mapped = false;
  221061. break;
  221062. case MappingNotify:
  221063. {
  221064. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  221065. if (mappingEvent->request != MappingPointer)
  221066. {
  221067. // Deal with modifier/keyboard mapping
  221068. ScopedXLock xlock;
  221069. XRefreshKeyboardMapping (mappingEvent);
  221070. updateModifierMappings();
  221071. }
  221072. break;
  221073. }
  221074. case ClientMessage:
  221075. {
  221076. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  221077. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  221078. {
  221079. const Atom atom = (Atom) clientMsg->data.l[0];
  221080. if (atom == Atoms::ProtocolList [Atoms::PING])
  221081. {
  221082. Window root = RootWindow (display, DefaultScreen (display));
  221083. event->xclient.window = root;
  221084. XSendEvent (display, root, False, NoEventMask, event);
  221085. XFlush (display);
  221086. }
  221087. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  221088. {
  221089. XWindowAttributes atts;
  221090. ScopedXLock xlock;
  221091. if (clientMsg->window != 0
  221092. && XGetWindowAttributes (display, clientMsg->window, &atts))
  221093. {
  221094. if (atts.map_state == IsViewable)
  221095. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  221096. }
  221097. }
  221098. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  221099. {
  221100. handleUserClosingWindow();
  221101. }
  221102. }
  221103. else if (clientMsg->message_type == Atoms::XdndEnter)
  221104. {
  221105. handleDragAndDropEnter (clientMsg);
  221106. }
  221107. else if (clientMsg->message_type == Atoms::XdndLeave)
  221108. {
  221109. resetDragAndDrop();
  221110. }
  221111. else if (clientMsg->message_type == Atoms::XdndPosition)
  221112. {
  221113. handleDragAndDropPosition (clientMsg);
  221114. }
  221115. else if (clientMsg->message_type == Atoms::XdndDrop)
  221116. {
  221117. handleDragAndDropDrop (clientMsg);
  221118. }
  221119. else if (clientMsg->message_type == Atoms::XdndStatus)
  221120. {
  221121. handleDragAndDropStatus (clientMsg);
  221122. }
  221123. else if (clientMsg->message_type == Atoms::XdndFinished)
  221124. {
  221125. resetDragAndDrop();
  221126. }
  221127. break;
  221128. }
  221129. case SelectionNotify:
  221130. handleDragAndDropSelection (event);
  221131. break;
  221132. case SelectionClear:
  221133. case SelectionRequest:
  221134. break;
  221135. default:
  221136. #if JUCE_USE_XSHM
  221137. {
  221138. ScopedXLock xlock;
  221139. if (event->xany.type == XShmGetEventBase (display))
  221140. repainter->notifyPaintCompleted();
  221141. }
  221142. #endif
  221143. break;
  221144. }
  221145. }
  221146. void showMouseCursor (Cursor cursor) throw()
  221147. {
  221148. ScopedXLock xlock;
  221149. XDefineCursor (display, windowH, cursor);
  221150. }
  221151. void setTaskBarIcon (const Image& image)
  221152. {
  221153. ScopedXLock xlock;
  221154. taskbarImage = image;
  221155. Screen* const screen = XDefaultScreenOfDisplay (display);
  221156. const int screenNumber = XScreenNumberOfScreen (screen);
  221157. String screenAtom ("_NET_SYSTEM_TRAY_S");
  221158. screenAtom << screenNumber;
  221159. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  221160. XGrabServer (display);
  221161. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  221162. if (managerWin != None)
  221163. XSelectInput (display, managerWin, StructureNotifyMask);
  221164. XUngrabServer (display);
  221165. XFlush (display);
  221166. if (managerWin != None)
  221167. {
  221168. XEvent ev;
  221169. zerostruct (ev);
  221170. ev.xclient.type = ClientMessage;
  221171. ev.xclient.window = managerWin;
  221172. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  221173. ev.xclient.format = 32;
  221174. ev.xclient.data.l[0] = CurrentTime;
  221175. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  221176. ev.xclient.data.l[2] = windowH;
  221177. ev.xclient.data.l[3] = 0;
  221178. ev.xclient.data.l[4] = 0;
  221179. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  221180. XSync (display, False);
  221181. }
  221182. // For older KDE's ...
  221183. long atomData = 1;
  221184. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  221185. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  221186. // For more recent KDE's...
  221187. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  221188. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  221189. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  221190. XSizeHints* hints = XAllocSizeHints();
  221191. hints->flags = PMinSize;
  221192. hints->min_width = 22;
  221193. hints->min_height = 22;
  221194. XSetWMNormalHints (display, windowH, hints);
  221195. XFree (hints);
  221196. }
  221197. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  221198. juce_UseDebuggingNewOperator
  221199. bool dontRepaint;
  221200. static ModifierKeys currentModifiers;
  221201. static bool isActiveApplication;
  221202. private:
  221203. class LinuxRepaintManager : public Timer
  221204. {
  221205. public:
  221206. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  221207. : peer (peer_),
  221208. lastTimeImageUsed (0)
  221209. {
  221210. #if JUCE_USE_XSHM
  221211. shmCompletedDrawing = true;
  221212. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  221213. if (useARGBImagesForRendering)
  221214. {
  221215. ScopedXLock xlock;
  221216. XShmSegmentInfo segmentinfo;
  221217. XImage* const testImage
  221218. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221219. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221220. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221221. XDestroyImage (testImage);
  221222. }
  221223. #endif
  221224. }
  221225. ~LinuxRepaintManager()
  221226. {
  221227. }
  221228. void timerCallback()
  221229. {
  221230. #if JUCE_USE_XSHM
  221231. if (! shmCompletedDrawing)
  221232. return;
  221233. #endif
  221234. if (! regionsNeedingRepaint.isEmpty())
  221235. {
  221236. stopTimer();
  221237. performAnyPendingRepaintsNow();
  221238. }
  221239. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221240. {
  221241. stopTimer();
  221242. image = Image::null;
  221243. }
  221244. }
  221245. void repaint (const Rectangle<int>& area)
  221246. {
  221247. if (! isTimerRunning())
  221248. startTimer (repaintTimerPeriod);
  221249. regionsNeedingRepaint.add (area);
  221250. }
  221251. void performAnyPendingRepaintsNow()
  221252. {
  221253. #if JUCE_USE_XSHM
  221254. if (! shmCompletedDrawing)
  221255. {
  221256. startTimer (repaintTimerPeriod);
  221257. return;
  221258. }
  221259. #endif
  221260. peer->clearMaskedRegion();
  221261. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221262. regionsNeedingRepaint.clear();
  221263. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221264. if (! totalArea.isEmpty())
  221265. {
  221266. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221267. || image.getHeight() < totalArea.getHeight())
  221268. {
  221269. #if JUCE_USE_XSHM
  221270. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221271. : Image::RGB,
  221272. #else
  221273. image = Image (new XBitmapImage (Image::RGB,
  221274. #endif
  221275. (totalArea.getWidth() + 31) & ~31,
  221276. (totalArea.getHeight() + 31) & ~31,
  221277. false, peer->depth, peer->visual));
  221278. }
  221279. startTimer (repaintTimerPeriod);
  221280. RectangleList adjustedList (originalRepaintRegion);
  221281. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221282. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221283. if (peer->depth == 32)
  221284. {
  221285. RectangleList::Iterator i (originalRepaintRegion);
  221286. while (i.next())
  221287. image.clear (*i.getRectangle() - totalArea.getPosition());
  221288. }
  221289. peer->handlePaint (context);
  221290. if (! peer->maskedRegion.isEmpty())
  221291. originalRepaintRegion.subtract (peer->maskedRegion);
  221292. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221293. {
  221294. #if JUCE_USE_XSHM
  221295. shmCompletedDrawing = false;
  221296. #endif
  221297. const Rectangle<int>& r = *i.getRectangle();
  221298. static_cast<XBitmapImage*> (image.getSharedImage())
  221299. ->blitToWindow (peer->windowH,
  221300. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221301. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221302. }
  221303. }
  221304. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221305. startTimer (repaintTimerPeriod);
  221306. }
  221307. #if JUCE_USE_XSHM
  221308. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221309. #endif
  221310. private:
  221311. enum { repaintTimerPeriod = 1000 / 100 };
  221312. LinuxComponentPeer* const peer;
  221313. Image image;
  221314. uint32 lastTimeImageUsed;
  221315. RectangleList regionsNeedingRepaint;
  221316. #if JUCE_USE_XSHM
  221317. bool useARGBImagesForRendering, shmCompletedDrawing;
  221318. #endif
  221319. LinuxRepaintManager (const LinuxRepaintManager&);
  221320. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221321. };
  221322. ScopedPointer <LinuxRepaintManager> repainter;
  221323. friend class LinuxRepaintManager;
  221324. Window windowH, parentWindow;
  221325. int wx, wy, ww, wh;
  221326. Image taskbarImage;
  221327. bool fullScreen, mapped;
  221328. Visual* visual;
  221329. int depth;
  221330. BorderSize windowBorder;
  221331. struct MotifWmHints
  221332. {
  221333. unsigned long flags;
  221334. unsigned long functions;
  221335. unsigned long decorations;
  221336. long input_mode;
  221337. unsigned long status;
  221338. };
  221339. static void updateKeyStates (const int keycode, const bool press) throw()
  221340. {
  221341. const int keybyte = keycode >> 3;
  221342. const int keybit = (1 << (keycode & 7));
  221343. if (press)
  221344. Keys::keyStates [keybyte] |= keybit;
  221345. else
  221346. Keys::keyStates [keybyte] &= ~keybit;
  221347. }
  221348. static void updateKeyModifiers (const int status) throw()
  221349. {
  221350. int keyMods = 0;
  221351. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221352. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221353. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221354. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221355. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221356. Keys::capsLock = ((status & LockMask) != 0);
  221357. }
  221358. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221359. {
  221360. int modifier = 0;
  221361. bool isModifier = true;
  221362. switch (sym)
  221363. {
  221364. case XK_Shift_L:
  221365. case XK_Shift_R:
  221366. modifier = ModifierKeys::shiftModifier;
  221367. break;
  221368. case XK_Control_L:
  221369. case XK_Control_R:
  221370. modifier = ModifierKeys::ctrlModifier;
  221371. break;
  221372. case XK_Alt_L:
  221373. case XK_Alt_R:
  221374. modifier = ModifierKeys::altModifier;
  221375. break;
  221376. case XK_Num_Lock:
  221377. if (press)
  221378. Keys::numLock = ! Keys::numLock;
  221379. break;
  221380. case XK_Caps_Lock:
  221381. if (press)
  221382. Keys::capsLock = ! Keys::capsLock;
  221383. break;
  221384. case XK_Scroll_Lock:
  221385. break;
  221386. default:
  221387. isModifier = false;
  221388. break;
  221389. }
  221390. if (modifier != 0)
  221391. {
  221392. if (press)
  221393. currentModifiers = currentModifiers.withFlags (modifier);
  221394. else
  221395. currentModifiers = currentModifiers.withoutFlags (modifier);
  221396. }
  221397. return isModifier;
  221398. }
  221399. // Alt and Num lock are not defined by standard X
  221400. // modifier constants: check what they're mapped to
  221401. static void updateModifierMappings() throw()
  221402. {
  221403. ScopedXLock xlock;
  221404. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221405. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221406. Keys::AltMask = 0;
  221407. Keys::NumLockMask = 0;
  221408. XModifierKeymap* mapping = XGetModifierMapping (display);
  221409. if (mapping)
  221410. {
  221411. for (int i = 0; i < 8; i++)
  221412. {
  221413. if (mapping->modifiermap [i << 1] == altLeftCode)
  221414. Keys::AltMask = 1 << i;
  221415. else if (mapping->modifiermap [i << 1] == numLockCode)
  221416. Keys::NumLockMask = 1 << i;
  221417. }
  221418. XFreeModifiermap (mapping);
  221419. }
  221420. }
  221421. void removeWindowDecorations (Window wndH)
  221422. {
  221423. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221424. if (hints != None)
  221425. {
  221426. MotifWmHints motifHints;
  221427. zerostruct (motifHints);
  221428. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221429. motifHints.decorations = 0;
  221430. ScopedXLock xlock;
  221431. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221432. (unsigned char*) &motifHints, 4);
  221433. }
  221434. hints = XInternAtom (display, "_WIN_HINTS", True);
  221435. if (hints != None)
  221436. {
  221437. long gnomeHints = 0;
  221438. ScopedXLock xlock;
  221439. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221440. (unsigned char*) &gnomeHints, 1);
  221441. }
  221442. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221443. if (hints != None)
  221444. {
  221445. long kwmHints = 2; /*KDE_tinyDecoration*/
  221446. ScopedXLock xlock;
  221447. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221448. (unsigned char*) &kwmHints, 1);
  221449. }
  221450. }
  221451. void addWindowButtons (Window wndH)
  221452. {
  221453. ScopedXLock xlock;
  221454. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221455. if (hints != None)
  221456. {
  221457. MotifWmHints motifHints;
  221458. zerostruct (motifHints);
  221459. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221460. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221461. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221462. if ((styleFlags & windowHasCloseButton) != 0)
  221463. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221464. if ((styleFlags & windowHasMinimiseButton) != 0)
  221465. {
  221466. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221467. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221468. }
  221469. if ((styleFlags & windowHasMaximiseButton) != 0)
  221470. {
  221471. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221472. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221473. }
  221474. if ((styleFlags & windowIsResizable) != 0)
  221475. {
  221476. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221477. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221478. }
  221479. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221480. }
  221481. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221482. if (hints != None)
  221483. {
  221484. int netHints [6];
  221485. int num = 0;
  221486. if ((styleFlags & windowIsResizable) != 0)
  221487. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221488. if ((styleFlags & windowHasMaximiseButton) != 0)
  221489. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221490. if ((styleFlags & windowHasMinimiseButton) != 0)
  221491. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221492. if ((styleFlags & windowHasCloseButton) != 0)
  221493. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221494. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221495. }
  221496. }
  221497. void setWindowType()
  221498. {
  221499. int netHints [2];
  221500. int numHints = 0;
  221501. if ((styleFlags & windowIsTemporary) != 0
  221502. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221503. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221504. else
  221505. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221506. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221507. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221508. (unsigned char*) &netHints, numHints);
  221509. numHints = 0;
  221510. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221511. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221512. if (component->isAlwaysOnTop())
  221513. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221514. if (numHints > 0)
  221515. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221516. (unsigned char*) &netHints, numHints);
  221517. }
  221518. void createWindow()
  221519. {
  221520. ScopedXLock xlock;
  221521. Atoms::initialiseAtoms();
  221522. resetDragAndDrop();
  221523. // Get defaults for various properties
  221524. const int screen = DefaultScreen (display);
  221525. Window root = RootWindow (display, screen);
  221526. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221527. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221528. if (visual == 0)
  221529. {
  221530. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221531. Process::terminate();
  221532. }
  221533. // Create and install a colormap suitable fr our visual
  221534. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221535. XInstallColormap (display, colormap);
  221536. // Set up the window attributes
  221537. XSetWindowAttributes swa;
  221538. swa.border_pixel = 0;
  221539. swa.background_pixmap = None;
  221540. swa.colormap = colormap;
  221541. swa.event_mask = getAllEventsMask();
  221542. windowH = XCreateWindow (display, root,
  221543. 0, 0, 1, 1,
  221544. 0, depth, InputOutput, visual,
  221545. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221546. &swa);
  221547. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221548. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221549. GrabModeAsync, GrabModeAsync, None, None);
  221550. // Set the window context to identify the window handle object
  221551. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221552. {
  221553. // Failed
  221554. jassertfalse;
  221555. Logger::outputDebugString ("Failed to create context information for window.\n");
  221556. XDestroyWindow (display, windowH);
  221557. windowH = 0;
  221558. return;
  221559. }
  221560. // Set window manager hints
  221561. XWMHints* wmHints = XAllocWMHints();
  221562. wmHints->flags = InputHint | StateHint;
  221563. wmHints->input = True; // Locally active input model
  221564. wmHints->initial_state = NormalState;
  221565. XSetWMHints (display, windowH, wmHints);
  221566. XFree (wmHints);
  221567. // Set the window type
  221568. setWindowType();
  221569. // Define decoration
  221570. if ((styleFlags & windowHasTitleBar) == 0)
  221571. removeWindowDecorations (windowH);
  221572. else
  221573. addWindowButtons (windowH);
  221574. // Set window name
  221575. setWindowTitle (windowH, getComponent()->getName());
  221576. // Associate the PID, allowing to be shut down when something goes wrong
  221577. unsigned long pid = getpid();
  221578. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221579. (unsigned char*) &pid, 1);
  221580. // Set window manager protocols
  221581. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221582. (unsigned char*) Atoms::ProtocolList, 2);
  221583. // Set drag and drop flags
  221584. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221585. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221586. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221587. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221588. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221589. (const unsigned char*) "", 0);
  221590. unsigned long dndVersion = Atoms::DndVersion;
  221591. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221592. (const unsigned char*) &dndVersion, 1);
  221593. // Initialise the pointer and keyboard mapping
  221594. // This is not the same as the logical pointer mapping the X server uses:
  221595. // we don't mess with this.
  221596. static bool mappingInitialised = false;
  221597. if (! mappingInitialised)
  221598. {
  221599. mappingInitialised = true;
  221600. const int numButtons = XGetPointerMapping (display, 0, 0);
  221601. if (numButtons == 2)
  221602. {
  221603. pointerMap[0] = Keys::LeftButton;
  221604. pointerMap[1] = Keys::RightButton;
  221605. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221606. }
  221607. else if (numButtons >= 3)
  221608. {
  221609. pointerMap[0] = Keys::LeftButton;
  221610. pointerMap[1] = Keys::MiddleButton;
  221611. pointerMap[2] = Keys::RightButton;
  221612. if (numButtons >= 5)
  221613. {
  221614. pointerMap[3] = Keys::WheelUp;
  221615. pointerMap[4] = Keys::WheelDown;
  221616. }
  221617. }
  221618. updateModifierMappings();
  221619. }
  221620. }
  221621. void destroyWindow()
  221622. {
  221623. ScopedXLock xlock;
  221624. XPointer handlePointer;
  221625. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221626. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221627. XDestroyWindow (display, windowH);
  221628. // Wait for it to complete and then remove any events for this
  221629. // window from the event queue.
  221630. XSync (display, false);
  221631. XEvent event;
  221632. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221633. {}
  221634. }
  221635. static int getAllEventsMask() throw()
  221636. {
  221637. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221638. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221639. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221640. }
  221641. static int64 getEventTime (::Time t)
  221642. {
  221643. static int64 eventTimeOffset = 0x12345678;
  221644. const int64 thisMessageTime = t;
  221645. if (eventTimeOffset == 0x12345678)
  221646. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221647. return eventTimeOffset + thisMessageTime;
  221648. }
  221649. static void setWindowTitle (Window xwin, const String& title)
  221650. {
  221651. XTextProperty nameProperty;
  221652. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221653. ScopedXLock xlock;
  221654. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221655. {
  221656. XSetWMName (display, xwin, &nameProperty);
  221657. XSetWMIconName (display, xwin, &nameProperty);
  221658. XFree (nameProperty.value);
  221659. }
  221660. }
  221661. void updateBorderSize()
  221662. {
  221663. if ((styleFlags & windowHasTitleBar) == 0)
  221664. {
  221665. windowBorder = BorderSize (0);
  221666. }
  221667. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221668. {
  221669. ScopedXLock xlock;
  221670. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221671. if (hints != None)
  221672. {
  221673. unsigned char* data = 0;
  221674. unsigned long nitems, bytesLeft;
  221675. Atom actualType;
  221676. int actualFormat;
  221677. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221678. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221679. &data) == Success)
  221680. {
  221681. const unsigned long* const sizes = (const unsigned long*) data;
  221682. if (actualFormat == 32)
  221683. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221684. (int) sizes[3], (int) sizes[1]);
  221685. XFree (data);
  221686. }
  221687. }
  221688. }
  221689. }
  221690. void updateBounds()
  221691. {
  221692. jassert (windowH != 0);
  221693. if (windowH != 0)
  221694. {
  221695. Window root, child;
  221696. unsigned int bw, depth;
  221697. ScopedXLock xlock;
  221698. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221699. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221700. &bw, &depth))
  221701. {
  221702. wx = wy = ww = wh = 0;
  221703. }
  221704. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221705. {
  221706. wx = wy = 0;
  221707. }
  221708. }
  221709. }
  221710. void resetDragAndDrop()
  221711. {
  221712. dragAndDropFiles.clear();
  221713. lastDropPos = Point<int> (-1, -1);
  221714. dragAndDropCurrentMimeType = 0;
  221715. dragAndDropSourceWindow = 0;
  221716. srcMimeTypeAtomList.clear();
  221717. }
  221718. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221719. {
  221720. msg.type = ClientMessage;
  221721. msg.display = display;
  221722. msg.window = dragAndDropSourceWindow;
  221723. msg.format = 32;
  221724. msg.data.l[0] = windowH;
  221725. ScopedXLock xlock;
  221726. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221727. }
  221728. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221729. {
  221730. XClientMessageEvent msg;
  221731. zerostruct (msg);
  221732. msg.message_type = Atoms::XdndStatus;
  221733. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221734. msg.data.l[4] = dropAction;
  221735. sendDragAndDropMessage (msg);
  221736. }
  221737. void sendDragAndDropLeave()
  221738. {
  221739. XClientMessageEvent msg;
  221740. zerostruct (msg);
  221741. msg.message_type = Atoms::XdndLeave;
  221742. sendDragAndDropMessage (msg);
  221743. }
  221744. void sendDragAndDropFinish()
  221745. {
  221746. XClientMessageEvent msg;
  221747. zerostruct (msg);
  221748. msg.message_type = Atoms::XdndFinished;
  221749. sendDragAndDropMessage (msg);
  221750. }
  221751. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221752. {
  221753. if ((clientMsg->data.l[1] & 1) == 0)
  221754. {
  221755. sendDragAndDropLeave();
  221756. if (dragAndDropFiles.size() > 0)
  221757. handleFileDragExit (dragAndDropFiles);
  221758. dragAndDropFiles.clear();
  221759. }
  221760. }
  221761. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221762. {
  221763. if (dragAndDropSourceWindow == 0)
  221764. return;
  221765. dragAndDropSourceWindow = clientMsg->data.l[0];
  221766. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221767. (int) clientMsg->data.l[2] & 0xffff);
  221768. dropPos -= getScreenPosition();
  221769. if (lastDropPos != dropPos)
  221770. {
  221771. lastDropPos = dropPos;
  221772. dragAndDropTimestamp = clientMsg->data.l[3];
  221773. Atom targetAction = Atoms::XdndActionCopy;
  221774. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221775. {
  221776. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221777. {
  221778. targetAction = Atoms::allowedActions[i];
  221779. break;
  221780. }
  221781. }
  221782. sendDragAndDropStatus (true, targetAction);
  221783. if (dragAndDropFiles.size() == 0)
  221784. updateDraggedFileList (clientMsg);
  221785. if (dragAndDropFiles.size() > 0)
  221786. handleFileDragMove (dragAndDropFiles, dropPos);
  221787. }
  221788. }
  221789. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221790. {
  221791. if (dragAndDropFiles.size() == 0)
  221792. updateDraggedFileList (clientMsg);
  221793. const StringArray files (dragAndDropFiles);
  221794. const Point<int> lastPos (lastDropPos);
  221795. sendDragAndDropFinish();
  221796. resetDragAndDrop();
  221797. if (files.size() > 0)
  221798. handleFileDragDrop (files, lastPos);
  221799. }
  221800. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221801. {
  221802. dragAndDropFiles.clear();
  221803. srcMimeTypeAtomList.clear();
  221804. dragAndDropCurrentMimeType = 0;
  221805. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221806. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221807. {
  221808. dragAndDropSourceWindow = 0;
  221809. return;
  221810. }
  221811. dragAndDropSourceWindow = clientMsg->data.l[0];
  221812. if ((clientMsg->data.l[1] & 1) != 0)
  221813. {
  221814. Atom actual;
  221815. int format;
  221816. unsigned long count = 0, remaining = 0;
  221817. unsigned char* data = 0;
  221818. ScopedXLock xlock;
  221819. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221820. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221821. &count, &remaining, &data);
  221822. if (data != 0)
  221823. {
  221824. if (actual == XA_ATOM && format == 32 && count != 0)
  221825. {
  221826. const unsigned long* const types = (const unsigned long*) data;
  221827. for (unsigned int i = 0; i < count; ++i)
  221828. if (types[i] != None)
  221829. srcMimeTypeAtomList.add (types[i]);
  221830. }
  221831. XFree (data);
  221832. }
  221833. }
  221834. if (srcMimeTypeAtomList.size() == 0)
  221835. {
  221836. for (int i = 2; i < 5; ++i)
  221837. if (clientMsg->data.l[i] != None)
  221838. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221839. if (srcMimeTypeAtomList.size() == 0)
  221840. {
  221841. dragAndDropSourceWindow = 0;
  221842. return;
  221843. }
  221844. }
  221845. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221846. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221847. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221848. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221849. handleDragAndDropPosition (clientMsg);
  221850. }
  221851. void handleDragAndDropSelection (const XEvent* const evt)
  221852. {
  221853. dragAndDropFiles.clear();
  221854. if (evt->xselection.property != 0)
  221855. {
  221856. StringArray lines;
  221857. {
  221858. MemoryBlock dropData;
  221859. for (;;)
  221860. {
  221861. Atom actual;
  221862. uint8* data = 0;
  221863. unsigned long count = 0, remaining = 0;
  221864. int format = 0;
  221865. ScopedXLock xlock;
  221866. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221867. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221868. &format, &count, &remaining, &data) == Success)
  221869. {
  221870. dropData.append (data, count * format / 8);
  221871. XFree (data);
  221872. if (remaining == 0)
  221873. break;
  221874. }
  221875. else
  221876. {
  221877. XFree (data);
  221878. break;
  221879. }
  221880. }
  221881. lines.addLines (dropData.toString());
  221882. }
  221883. for (int i = 0; i < lines.size(); ++i)
  221884. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221885. dragAndDropFiles.trim();
  221886. dragAndDropFiles.removeEmptyStrings();
  221887. }
  221888. }
  221889. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221890. {
  221891. dragAndDropFiles.clear();
  221892. if (dragAndDropSourceWindow != None
  221893. && dragAndDropCurrentMimeType != 0)
  221894. {
  221895. dragAndDropTimestamp = clientMsg->data.l[2];
  221896. ScopedXLock xlock;
  221897. XConvertSelection (display,
  221898. Atoms::XdndSelection,
  221899. dragAndDropCurrentMimeType,
  221900. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221901. windowH,
  221902. dragAndDropTimestamp);
  221903. }
  221904. }
  221905. StringArray dragAndDropFiles;
  221906. int dragAndDropTimestamp;
  221907. Point<int> lastDropPos;
  221908. Atom dragAndDropCurrentMimeType;
  221909. Window dragAndDropSourceWindow;
  221910. Array <Atom> srcMimeTypeAtomList;
  221911. static int pointerMap[5];
  221912. static Point<int> lastMousePos;
  221913. static void clearLastMousePos() throw()
  221914. {
  221915. lastMousePos = Point<int> (0x100000, 0x100000);
  221916. }
  221917. };
  221918. ModifierKeys LinuxComponentPeer::currentModifiers;
  221919. bool LinuxComponentPeer::isActiveApplication = false;
  221920. int LinuxComponentPeer::pointerMap[5];
  221921. Point<int> LinuxComponentPeer::lastMousePos;
  221922. bool Process::isForegroundProcess()
  221923. {
  221924. return LinuxComponentPeer::isActiveApplication;
  221925. }
  221926. void ModifierKeys::updateCurrentModifiers() throw()
  221927. {
  221928. currentModifiers = LinuxComponentPeer::currentModifiers;
  221929. }
  221930. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221931. {
  221932. Window root, child;
  221933. int x, y, winx, winy;
  221934. unsigned int mask;
  221935. int mouseMods = 0;
  221936. ScopedXLock xlock;
  221937. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221938. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221939. {
  221940. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221941. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221942. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221943. }
  221944. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221945. return LinuxComponentPeer::currentModifiers;
  221946. }
  221947. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221948. {
  221949. if (enableOrDisable)
  221950. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221951. }
  221952. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221953. {
  221954. return new LinuxComponentPeer (this, styleFlags);
  221955. }
  221956. // (this callback is hooked up in the messaging code)
  221957. void juce_windowMessageReceive (XEvent* event)
  221958. {
  221959. if (event->xany.window != None)
  221960. {
  221961. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221962. if (ComponentPeer::isValidPeer (peer))
  221963. peer->handleWindowMessage (event);
  221964. }
  221965. else
  221966. {
  221967. switch (event->xany.type)
  221968. {
  221969. case KeymapNotify:
  221970. {
  221971. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221972. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221973. break;
  221974. }
  221975. default:
  221976. break;
  221977. }
  221978. }
  221979. }
  221980. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221981. {
  221982. if (display == 0)
  221983. return;
  221984. #if JUCE_USE_XINERAMA
  221985. int major_opcode, first_event, first_error;
  221986. ScopedXLock xlock;
  221987. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221988. {
  221989. typedef Bool (*tXineramaIsActive) (Display*);
  221990. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221991. static tXineramaIsActive xXineramaIsActive = 0;
  221992. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221993. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221994. {
  221995. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221996. if (h == 0)
  221997. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221998. if (h != 0)
  221999. {
  222000. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  222001. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  222002. }
  222003. }
  222004. if (xXineramaIsActive != 0
  222005. && xXineramaQueryScreens != 0
  222006. && xXineramaIsActive (display))
  222007. {
  222008. int numMonitors = 0;
  222009. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  222010. if (screens != 0)
  222011. {
  222012. for (int i = numMonitors; --i >= 0;)
  222013. {
  222014. int index = screens[i].screen_number;
  222015. if (index >= 0)
  222016. {
  222017. while (monitorCoords.size() < index)
  222018. monitorCoords.add (Rectangle<int>());
  222019. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  222020. screens[i].y_org,
  222021. screens[i].width,
  222022. screens[i].height));
  222023. }
  222024. }
  222025. XFree (screens);
  222026. }
  222027. }
  222028. }
  222029. if (monitorCoords.size() == 0)
  222030. #endif
  222031. {
  222032. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  222033. if (hints != None)
  222034. {
  222035. const int numMonitors = ScreenCount (display);
  222036. for (int i = 0; i < numMonitors; ++i)
  222037. {
  222038. Window root = RootWindow (display, i);
  222039. unsigned long nitems, bytesLeft;
  222040. Atom actualType;
  222041. int actualFormat;
  222042. unsigned char* data = 0;
  222043. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  222044. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  222045. &data) == Success)
  222046. {
  222047. const long* const position = (const long*) data;
  222048. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  222049. monitorCoords.add (Rectangle<int> (position[0], position[1],
  222050. position[2], position[3]));
  222051. XFree (data);
  222052. }
  222053. }
  222054. }
  222055. if (monitorCoords.size() == 0)
  222056. {
  222057. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  222058. DisplayHeight (display, DefaultScreen (display))));
  222059. }
  222060. }
  222061. }
  222062. void Desktop::createMouseInputSources()
  222063. {
  222064. mouseSources.add (new MouseInputSource (0, true));
  222065. }
  222066. bool Desktop::canUseSemiTransparentWindows() throw()
  222067. {
  222068. int matchedDepth = 0;
  222069. const int desiredDepth = 32;
  222070. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  222071. && (matchedDepth == desiredDepth);
  222072. }
  222073. const Point<int> Desktop::getMousePosition()
  222074. {
  222075. Window root, child;
  222076. int x, y, winx, winy;
  222077. unsigned int mask;
  222078. ScopedXLock xlock;
  222079. if (XQueryPointer (display,
  222080. RootWindow (display, DefaultScreen (display)),
  222081. &root, &child,
  222082. &x, &y, &winx, &winy, &mask) == False)
  222083. {
  222084. // Pointer not on the default screen
  222085. x = y = -1;
  222086. }
  222087. return Point<int> (x, y);
  222088. }
  222089. void Desktop::setMousePosition (const Point<int>& newPosition)
  222090. {
  222091. ScopedXLock xlock;
  222092. Window root = RootWindow (display, DefaultScreen (display));
  222093. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  222094. }
  222095. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  222096. {
  222097. return upright;
  222098. }
  222099. static bool screenSaverAllowed = true;
  222100. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  222101. {
  222102. if (screenSaverAllowed != isEnabled)
  222103. {
  222104. screenSaverAllowed = isEnabled;
  222105. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  222106. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  222107. if (xScreenSaverSuspend == 0)
  222108. {
  222109. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  222110. if (h != 0)
  222111. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  222112. }
  222113. ScopedXLock xlock;
  222114. if (xScreenSaverSuspend != 0)
  222115. xScreenSaverSuspend (display, ! isEnabled);
  222116. }
  222117. }
  222118. bool Desktop::isScreenSaverEnabled()
  222119. {
  222120. return screenSaverAllowed;
  222121. }
  222122. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  222123. {
  222124. ScopedXLock xlock;
  222125. const unsigned int imageW = image.getWidth();
  222126. const unsigned int imageH = image.getHeight();
  222127. #if JUCE_USE_XCURSOR
  222128. {
  222129. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  222130. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  222131. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  222132. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  222133. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  222134. static tXcursorImageCreate xXcursorImageCreate = 0;
  222135. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  222136. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  222137. static bool hasBeenLoaded = false;
  222138. if (! hasBeenLoaded)
  222139. {
  222140. hasBeenLoaded = true;
  222141. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  222142. if (h != 0)
  222143. {
  222144. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  222145. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  222146. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  222147. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  222148. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  222149. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  222150. || ! xXcursorSupportsARGB (display))
  222151. xXcursorSupportsARGB = 0;
  222152. }
  222153. }
  222154. if (xXcursorSupportsARGB != 0)
  222155. {
  222156. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  222157. if (xcImage != 0)
  222158. {
  222159. xcImage->xhot = hotspotX;
  222160. xcImage->yhot = hotspotY;
  222161. XcursorPixel* dest = xcImage->pixels;
  222162. for (int y = 0; y < (int) imageH; ++y)
  222163. for (int x = 0; x < (int) imageW; ++x)
  222164. *dest++ = image.getPixelAt (x, y).getARGB();
  222165. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  222166. xXcursorImageDestroy (xcImage);
  222167. if (result != 0)
  222168. return result;
  222169. }
  222170. }
  222171. }
  222172. #endif
  222173. Window root = RootWindow (display, DefaultScreen (display));
  222174. unsigned int cursorW, cursorH;
  222175. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  222176. return 0;
  222177. Image im (Image::ARGB, cursorW, cursorH, true);
  222178. {
  222179. Graphics g (im);
  222180. if (imageW > cursorW || imageH > cursorH)
  222181. {
  222182. hotspotX = (hotspotX * cursorW) / imageW;
  222183. hotspotY = (hotspotY * cursorH) / imageH;
  222184. g.drawImageWithin (image, 0, 0, imageW, imageH,
  222185. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222186. false);
  222187. }
  222188. else
  222189. {
  222190. g.drawImageAt (image, 0, 0);
  222191. }
  222192. }
  222193. const int stride = (cursorW + 7) >> 3;
  222194. HeapBlock <char> maskPlane, sourcePlane;
  222195. maskPlane.calloc (stride * cursorH);
  222196. sourcePlane.calloc (stride * cursorH);
  222197. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222198. for (int y = cursorH; --y >= 0;)
  222199. {
  222200. for (int x = cursorW; --x >= 0;)
  222201. {
  222202. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222203. const int offset = y * stride + (x >> 3);
  222204. const Colour c (im.getPixelAt (x, y));
  222205. if (c.getAlpha() >= 128)
  222206. maskPlane[offset] |= mask;
  222207. if (c.getBrightness() >= 0.5f)
  222208. sourcePlane[offset] |= mask;
  222209. }
  222210. }
  222211. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222212. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222213. XColor white, black;
  222214. black.red = black.green = black.blue = 0;
  222215. white.red = white.green = white.blue = 0xffff;
  222216. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222217. XFreePixmap (display, sourcePixmap);
  222218. XFreePixmap (display, maskPixmap);
  222219. return result;
  222220. }
  222221. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222222. {
  222223. ScopedXLock xlock;
  222224. if (cursorHandle != 0)
  222225. XFreeCursor (display, (Cursor) cursorHandle);
  222226. }
  222227. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222228. {
  222229. unsigned int shape;
  222230. switch (type)
  222231. {
  222232. case NormalCursor: return None; // Use parent cursor
  222233. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222234. case WaitCursor: shape = XC_watch; break;
  222235. case IBeamCursor: shape = XC_xterm; break;
  222236. case PointingHandCursor: shape = XC_hand2; break;
  222237. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222238. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222239. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222240. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222241. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222242. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222243. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222244. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222245. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222246. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222247. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222248. case CrosshairCursor: shape = XC_crosshair; break;
  222249. case DraggingHandCursor:
  222250. {
  222251. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222252. 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,
  222253. 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 };
  222254. const int dragHandDataSize = 99;
  222255. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222256. }
  222257. case CopyingCursor:
  222258. {
  222259. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222260. 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,
  222261. 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,
  222262. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222263. const int copyCursorSize = 119;
  222264. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222265. }
  222266. default:
  222267. jassertfalse;
  222268. return None;
  222269. }
  222270. ScopedXLock xlock;
  222271. return (void*) XCreateFontCursor (display, shape);
  222272. }
  222273. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222274. {
  222275. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222276. if (lp != 0)
  222277. lp->showMouseCursor ((Cursor) getHandle());
  222278. }
  222279. void MouseCursor::showInAllWindows() const
  222280. {
  222281. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222282. showInWindow (ComponentPeer::getPeer (i));
  222283. }
  222284. const Image juce_createIconForFile (const File& file)
  222285. {
  222286. return Image::null;
  222287. }
  222288. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222289. {
  222290. return createSoftwareImage (format, width, height, clearImage);
  222291. }
  222292. #if JUCE_OPENGL
  222293. class WindowedGLContext : public OpenGLContext
  222294. {
  222295. public:
  222296. WindowedGLContext (Component* const component,
  222297. const OpenGLPixelFormat& pixelFormat_,
  222298. GLXContext sharedContext)
  222299. : renderContext (0),
  222300. embeddedWindow (0),
  222301. pixelFormat (pixelFormat_),
  222302. swapInterval (0)
  222303. {
  222304. jassert (component != 0);
  222305. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222306. if (peer == 0)
  222307. return;
  222308. ScopedXLock xlock;
  222309. XSync (display, False);
  222310. GLint attribs [64];
  222311. int n = 0;
  222312. attribs[n++] = GLX_RGBA;
  222313. attribs[n++] = GLX_DOUBLEBUFFER;
  222314. attribs[n++] = GLX_RED_SIZE;
  222315. attribs[n++] = pixelFormat.redBits;
  222316. attribs[n++] = GLX_GREEN_SIZE;
  222317. attribs[n++] = pixelFormat.greenBits;
  222318. attribs[n++] = GLX_BLUE_SIZE;
  222319. attribs[n++] = pixelFormat.blueBits;
  222320. attribs[n++] = GLX_ALPHA_SIZE;
  222321. attribs[n++] = pixelFormat.alphaBits;
  222322. attribs[n++] = GLX_DEPTH_SIZE;
  222323. attribs[n++] = pixelFormat.depthBufferBits;
  222324. attribs[n++] = GLX_STENCIL_SIZE;
  222325. attribs[n++] = pixelFormat.stencilBufferBits;
  222326. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222327. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222328. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222329. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222330. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222331. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222332. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222333. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222334. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222335. attribs[n++] = None;
  222336. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222337. if (bestVisual == 0)
  222338. return;
  222339. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222340. Window windowH = (Window) peer->getNativeHandle();
  222341. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222342. XSetWindowAttributes swa;
  222343. swa.colormap = colourMap;
  222344. swa.border_pixel = 0;
  222345. swa.event_mask = ExposureMask | StructureNotifyMask;
  222346. embeddedWindow = XCreateWindow (display, windowH,
  222347. 0, 0, 1, 1, 0,
  222348. bestVisual->depth,
  222349. InputOutput,
  222350. bestVisual->visual,
  222351. CWBorderPixel | CWColormap | CWEventMask,
  222352. &swa);
  222353. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222354. XMapWindow (display, embeddedWindow);
  222355. XFreeColormap (display, colourMap);
  222356. XFree (bestVisual);
  222357. XSync (display, False);
  222358. }
  222359. ~WindowedGLContext()
  222360. {
  222361. ScopedXLock xlock;
  222362. deleteContext();
  222363. XUnmapWindow (display, embeddedWindow);
  222364. XDestroyWindow (display, embeddedWindow);
  222365. }
  222366. void deleteContext()
  222367. {
  222368. makeInactive();
  222369. if (renderContext != 0)
  222370. {
  222371. ScopedXLock xlock;
  222372. glXDestroyContext (display, renderContext);
  222373. renderContext = 0;
  222374. }
  222375. }
  222376. bool makeActive() const throw()
  222377. {
  222378. jassert (renderContext != 0);
  222379. ScopedXLock xlock;
  222380. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222381. && XSync (display, False);
  222382. }
  222383. bool makeInactive() const throw()
  222384. {
  222385. ScopedXLock xlock;
  222386. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222387. }
  222388. bool isActive() const throw()
  222389. {
  222390. ScopedXLock xlock;
  222391. return glXGetCurrentContext() == renderContext;
  222392. }
  222393. const OpenGLPixelFormat getPixelFormat() const
  222394. {
  222395. return pixelFormat;
  222396. }
  222397. void* getRawContext() const throw()
  222398. {
  222399. return renderContext;
  222400. }
  222401. void updateWindowPosition (int x, int y, int w, int h, int)
  222402. {
  222403. ScopedXLock xlock;
  222404. XMoveResizeWindow (display, embeddedWindow,
  222405. x, y, jmax (1, w), jmax (1, h));
  222406. }
  222407. void swapBuffers()
  222408. {
  222409. ScopedXLock xlock;
  222410. glXSwapBuffers (display, embeddedWindow);
  222411. }
  222412. bool setSwapInterval (const int numFramesPerSwap)
  222413. {
  222414. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222415. if (GLXSwapIntervalSGI != 0)
  222416. {
  222417. swapInterval = numFramesPerSwap;
  222418. GLXSwapIntervalSGI (numFramesPerSwap);
  222419. return true;
  222420. }
  222421. return false;
  222422. }
  222423. int getSwapInterval() const
  222424. {
  222425. return swapInterval;
  222426. }
  222427. void repaint()
  222428. {
  222429. }
  222430. juce_UseDebuggingNewOperator
  222431. GLXContext renderContext;
  222432. private:
  222433. Window embeddedWindow;
  222434. OpenGLPixelFormat pixelFormat;
  222435. int swapInterval;
  222436. WindowedGLContext (const WindowedGLContext&);
  222437. WindowedGLContext& operator= (const WindowedGLContext&);
  222438. };
  222439. OpenGLContext* OpenGLComponent::createContext()
  222440. {
  222441. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222442. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222443. return (c->renderContext != 0) ? c.release() : 0;
  222444. }
  222445. void juce_glViewport (const int w, const int h)
  222446. {
  222447. glViewport (0, 0, w, h);
  222448. }
  222449. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222450. OwnedArray <OpenGLPixelFormat>& results)
  222451. {
  222452. results.add (new OpenGLPixelFormat()); // xxx
  222453. }
  222454. #endif
  222455. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222456. {
  222457. jassertfalse; // not implemented!
  222458. return false;
  222459. }
  222460. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222461. {
  222462. jassertfalse; // not implemented!
  222463. return false;
  222464. }
  222465. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222466. {
  222467. if (! isOnDesktop ())
  222468. addToDesktop (0);
  222469. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222470. if (wp != 0)
  222471. {
  222472. wp->setTaskBarIcon (newImage);
  222473. setVisible (true);
  222474. toFront (false);
  222475. repaint();
  222476. }
  222477. }
  222478. void SystemTrayIconComponent::paint (Graphics& g)
  222479. {
  222480. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222481. if (wp != 0)
  222482. {
  222483. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222484. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222485. false);
  222486. }
  222487. }
  222488. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222489. {
  222490. // xxx not yet implemented!
  222491. }
  222492. void PlatformUtilities::beep()
  222493. {
  222494. std::cout << "\a" << std::flush;
  222495. }
  222496. bool AlertWindow::showNativeDialogBox (const String& title,
  222497. const String& bodyText,
  222498. bool isOkCancel)
  222499. {
  222500. // use a non-native one for the time being..
  222501. if (isOkCancel)
  222502. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222503. else
  222504. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222505. return true;
  222506. }
  222507. const int KeyPress::spaceKey = XK_space & 0xff;
  222508. const int KeyPress::returnKey = XK_Return & 0xff;
  222509. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222510. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222511. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222512. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222513. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222514. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222515. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222516. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222517. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222518. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222519. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222520. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222521. const int KeyPress::tabKey = XK_Tab & 0xff;
  222522. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222523. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222524. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222525. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222526. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222527. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222528. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222529. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222530. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222531. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222532. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222533. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222534. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222535. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222536. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222537. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222538. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222539. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222540. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222541. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222542. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222543. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222544. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222545. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222546. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222547. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222548. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222549. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222550. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222551. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222552. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222553. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222554. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222555. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222556. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222557. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222558. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222559. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222560. #endif
  222561. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222562. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222563. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222564. // compiled on its own).
  222565. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222566. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222567. {
  222568. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222569. snd_pcm_hw_params_t* hwParams;
  222570. snd_pcm_hw_params_alloca (&hwParams);
  222571. for (int i = 0; ratesToTry[i] != 0; ++i)
  222572. {
  222573. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222574. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222575. {
  222576. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222577. }
  222578. }
  222579. }
  222580. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222581. {
  222582. snd_pcm_hw_params_t *params;
  222583. snd_pcm_hw_params_alloca (&params);
  222584. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222585. {
  222586. snd_pcm_hw_params_get_channels_min (params, minChans);
  222587. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222588. }
  222589. }
  222590. static void getDeviceProperties (const String& deviceID,
  222591. unsigned int& minChansOut,
  222592. unsigned int& maxChansOut,
  222593. unsigned int& minChansIn,
  222594. unsigned int& maxChansIn,
  222595. Array <int>& rates)
  222596. {
  222597. if (deviceID.isEmpty())
  222598. return;
  222599. snd_ctl_t* handle;
  222600. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222601. {
  222602. snd_pcm_info_t* info;
  222603. snd_pcm_info_alloca (&info);
  222604. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222605. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222606. snd_pcm_info_set_subdevice (info, 0);
  222607. if (snd_ctl_pcm_info (handle, info) >= 0)
  222608. {
  222609. snd_pcm_t* pcmHandle;
  222610. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222611. {
  222612. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222613. getDeviceSampleRates (pcmHandle, rates);
  222614. snd_pcm_close (pcmHandle);
  222615. }
  222616. }
  222617. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222618. if (snd_ctl_pcm_info (handle, info) >= 0)
  222619. {
  222620. snd_pcm_t* pcmHandle;
  222621. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222622. {
  222623. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222624. if (rates.size() == 0)
  222625. getDeviceSampleRates (pcmHandle, rates);
  222626. snd_pcm_close (pcmHandle);
  222627. }
  222628. }
  222629. snd_ctl_close (handle);
  222630. }
  222631. }
  222632. class ALSADevice
  222633. {
  222634. public:
  222635. ALSADevice (const String& deviceID, bool forInput)
  222636. : handle (0),
  222637. bitDepth (16),
  222638. numChannelsRunning (0),
  222639. latency (0),
  222640. isInput (forInput)
  222641. {
  222642. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222643. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222644. SND_PCM_ASYNC));
  222645. }
  222646. ~ALSADevice()
  222647. {
  222648. if (handle != 0)
  222649. snd_pcm_close (handle);
  222650. }
  222651. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222652. {
  222653. if (handle == 0)
  222654. return false;
  222655. snd_pcm_hw_params_t* hwParams;
  222656. snd_pcm_hw_params_alloca (&hwParams);
  222657. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222658. return false;
  222659. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222660. isInterleaved = false;
  222661. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222662. isInterleaved = true;
  222663. else
  222664. {
  222665. jassertfalse;
  222666. return false;
  222667. }
  222668. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222669. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222670. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222671. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222672. SND_PCM_FORMAT_S32_BE, 32,
  222673. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222674. SND_PCM_FORMAT_S24_3BE, 24,
  222675. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222676. SND_PCM_FORMAT_S16_BE, 16 };
  222677. bitDepth = 0;
  222678. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222679. {
  222680. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222681. {
  222682. bitDepth = formatsToTry [i + 1] & 255;
  222683. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222684. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222685. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222686. break;
  222687. }
  222688. }
  222689. if (bitDepth == 0)
  222690. {
  222691. error = "device doesn't support a compatible PCM format";
  222692. DBG ("ALSA error: " + error + "\n");
  222693. return false;
  222694. }
  222695. int dir = 0;
  222696. unsigned int periods = 4;
  222697. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222698. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222699. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222700. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222701. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222702. || failed (snd_pcm_hw_params (handle, hwParams)))
  222703. {
  222704. return false;
  222705. }
  222706. snd_pcm_uframes_t frames = 0;
  222707. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222708. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222709. latency = 0;
  222710. else
  222711. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222712. snd_pcm_sw_params_t* swParams;
  222713. snd_pcm_sw_params_alloca (&swParams);
  222714. snd_pcm_uframes_t boundary;
  222715. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222716. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222717. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222718. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222719. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222720. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222721. || failed (snd_pcm_sw_params (handle, swParams)))
  222722. {
  222723. return false;
  222724. }
  222725. /*
  222726. #if JUCE_DEBUG
  222727. // enable this to dump the config of the devices that get opened
  222728. snd_output_t* out;
  222729. snd_output_stdio_attach (&out, stderr, 0);
  222730. snd_pcm_hw_params_dump (hwParams, out);
  222731. snd_pcm_sw_params_dump (swParams, out);
  222732. #endif
  222733. */
  222734. numChannelsRunning = numChannels;
  222735. return true;
  222736. }
  222737. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222738. {
  222739. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222740. float** const data = outputChannelBuffer.getArrayOfChannels();
  222741. snd_pcm_sframes_t numDone = 0;
  222742. if (isInterleaved)
  222743. {
  222744. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222745. for (int i = 0; i < numChannelsRunning; ++i)
  222746. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222747. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222748. }
  222749. else
  222750. {
  222751. for (int i = 0; i < numChannelsRunning; ++i)
  222752. converter->convertSamples (data[i], data[i], numSamples);
  222753. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222754. }
  222755. if (failed (numDone))
  222756. {
  222757. if (numDone == -EPIPE)
  222758. {
  222759. if (failed (snd_pcm_prepare (handle)))
  222760. return false;
  222761. }
  222762. else if (numDone != -ESTRPIPE)
  222763. return false;
  222764. }
  222765. return true;
  222766. }
  222767. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222768. {
  222769. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222770. float** const data = inputChannelBuffer.getArrayOfChannels();
  222771. if (isInterleaved)
  222772. {
  222773. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222774. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222775. if (failed (num))
  222776. {
  222777. if (num == -EPIPE)
  222778. {
  222779. if (failed (snd_pcm_prepare (handle)))
  222780. return false;
  222781. }
  222782. else if (num != -ESTRPIPE)
  222783. return false;
  222784. }
  222785. for (int i = 0; i < numChannelsRunning; ++i)
  222786. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222787. }
  222788. else
  222789. {
  222790. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222791. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222792. return false;
  222793. for (int i = 0; i < numChannelsRunning; ++i)
  222794. converter->convertSamples (data[i], data[i], numSamples);
  222795. }
  222796. return true;
  222797. }
  222798. juce_UseDebuggingNewOperator
  222799. snd_pcm_t* handle;
  222800. String error;
  222801. int bitDepth, numChannelsRunning, latency;
  222802. private:
  222803. const bool isInput;
  222804. bool isInterleaved;
  222805. MemoryBlock scratch;
  222806. ScopedPointer<AudioData::Converter> converter;
  222807. template <class SampleType>
  222808. struct ConverterHelper
  222809. {
  222810. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222811. {
  222812. if (forInput)
  222813. {
  222814. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222815. if (isLittleEndian)
  222816. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222817. else
  222818. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222819. }
  222820. else
  222821. {
  222822. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222823. if (isLittleEndian)
  222824. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222825. else
  222826. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222827. }
  222828. }
  222829. };
  222830. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222831. {
  222832. switch (bitDepth)
  222833. {
  222834. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222835. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222836. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222837. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222838. default: jassertfalse; break; // unsupported format!
  222839. }
  222840. return 0;
  222841. }
  222842. bool failed (const int errorNum)
  222843. {
  222844. if (errorNum >= 0)
  222845. return false;
  222846. error = snd_strerror (errorNum);
  222847. DBG ("ALSA error: " + error + "\n");
  222848. return true;
  222849. }
  222850. };
  222851. class ALSAThread : public Thread
  222852. {
  222853. public:
  222854. ALSAThread (const String& inputId_,
  222855. const String& outputId_)
  222856. : Thread ("Juce ALSA"),
  222857. sampleRate (0),
  222858. bufferSize (0),
  222859. outputLatency (0),
  222860. inputLatency (0),
  222861. callback (0),
  222862. inputId (inputId_),
  222863. outputId (outputId_),
  222864. numCallbacks (0),
  222865. inputChannelBuffer (1, 1),
  222866. outputChannelBuffer (1, 1)
  222867. {
  222868. initialiseRatesAndChannels();
  222869. }
  222870. ~ALSAThread()
  222871. {
  222872. close();
  222873. }
  222874. void open (BigInteger inputChannels,
  222875. BigInteger outputChannels,
  222876. const double sampleRate_,
  222877. const int bufferSize_)
  222878. {
  222879. close();
  222880. error = String::empty;
  222881. sampleRate = sampleRate_;
  222882. bufferSize = bufferSize_;
  222883. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222884. inputChannelBuffer.clear();
  222885. inputChannelDataForCallback.clear();
  222886. currentInputChans.clear();
  222887. if (inputChannels.getHighestBit() >= 0)
  222888. {
  222889. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222890. {
  222891. if (inputChannels[i])
  222892. {
  222893. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222894. currentInputChans.setBit (i);
  222895. }
  222896. }
  222897. }
  222898. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222899. outputChannelBuffer.clear();
  222900. outputChannelDataForCallback.clear();
  222901. currentOutputChans.clear();
  222902. if (outputChannels.getHighestBit() >= 0)
  222903. {
  222904. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222905. {
  222906. if (outputChannels[i])
  222907. {
  222908. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222909. currentOutputChans.setBit (i);
  222910. }
  222911. }
  222912. }
  222913. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222914. {
  222915. outputDevice = new ALSADevice (outputId, false);
  222916. if (outputDevice->error.isNotEmpty())
  222917. {
  222918. error = outputDevice->error;
  222919. outputDevice = 0;
  222920. return;
  222921. }
  222922. currentOutputChans.setRange (0, minChansOut, true);
  222923. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222924. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222925. bufferSize))
  222926. {
  222927. error = outputDevice->error;
  222928. outputDevice = 0;
  222929. return;
  222930. }
  222931. outputLatency = outputDevice->latency;
  222932. }
  222933. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222934. {
  222935. inputDevice = new ALSADevice (inputId, true);
  222936. if (inputDevice->error.isNotEmpty())
  222937. {
  222938. error = inputDevice->error;
  222939. inputDevice = 0;
  222940. return;
  222941. }
  222942. currentInputChans.setRange (0, minChansIn, true);
  222943. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222944. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222945. bufferSize))
  222946. {
  222947. error = inputDevice->error;
  222948. inputDevice = 0;
  222949. return;
  222950. }
  222951. inputLatency = inputDevice->latency;
  222952. }
  222953. if (outputDevice == 0 && inputDevice == 0)
  222954. {
  222955. error = "no channels";
  222956. return;
  222957. }
  222958. if (outputDevice != 0 && inputDevice != 0)
  222959. {
  222960. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222961. }
  222962. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222963. return;
  222964. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222965. return;
  222966. startThread (9);
  222967. int count = 1000;
  222968. while (numCallbacks == 0)
  222969. {
  222970. sleep (5);
  222971. if (--count < 0 || ! isThreadRunning())
  222972. {
  222973. error = "device didn't start";
  222974. break;
  222975. }
  222976. }
  222977. }
  222978. void close()
  222979. {
  222980. stopThread (6000);
  222981. inputDevice = 0;
  222982. outputDevice = 0;
  222983. inputChannelBuffer.setSize (1, 1);
  222984. outputChannelBuffer.setSize (1, 1);
  222985. numCallbacks = 0;
  222986. }
  222987. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222988. {
  222989. const ScopedLock sl (callbackLock);
  222990. callback = newCallback;
  222991. }
  222992. void run()
  222993. {
  222994. while (! threadShouldExit())
  222995. {
  222996. if (inputDevice != 0)
  222997. {
  222998. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222999. {
  223000. DBG ("ALSA: read failure");
  223001. break;
  223002. }
  223003. }
  223004. if (threadShouldExit())
  223005. break;
  223006. {
  223007. const ScopedLock sl (callbackLock);
  223008. ++numCallbacks;
  223009. if (callback != 0)
  223010. {
  223011. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  223012. inputChannelDataForCallback.size(),
  223013. outputChannelDataForCallback.getRawDataPointer(),
  223014. outputChannelDataForCallback.size(),
  223015. bufferSize);
  223016. }
  223017. else
  223018. {
  223019. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  223020. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  223021. }
  223022. }
  223023. if (outputDevice != 0)
  223024. {
  223025. failed (snd_pcm_wait (outputDevice->handle, 2000));
  223026. if (threadShouldExit())
  223027. break;
  223028. failed (snd_pcm_avail_update (outputDevice->handle));
  223029. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  223030. {
  223031. DBG ("ALSA: write failure");
  223032. break;
  223033. }
  223034. }
  223035. }
  223036. }
  223037. int getBitDepth() const throw()
  223038. {
  223039. if (outputDevice != 0)
  223040. return outputDevice->bitDepth;
  223041. if (inputDevice != 0)
  223042. return inputDevice->bitDepth;
  223043. return 16;
  223044. }
  223045. juce_UseDebuggingNewOperator
  223046. String error;
  223047. double sampleRate;
  223048. int bufferSize, outputLatency, inputLatency;
  223049. BigInteger currentInputChans, currentOutputChans;
  223050. Array <int> sampleRates;
  223051. StringArray channelNamesOut, channelNamesIn;
  223052. AudioIODeviceCallback* callback;
  223053. private:
  223054. const String inputId, outputId;
  223055. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  223056. int numCallbacks;
  223057. CriticalSection callbackLock;
  223058. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  223059. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  223060. unsigned int minChansOut, maxChansOut;
  223061. unsigned int minChansIn, maxChansIn;
  223062. bool failed (const int errorNum)
  223063. {
  223064. if (errorNum >= 0)
  223065. return false;
  223066. error = snd_strerror (errorNum);
  223067. DBG ("ALSA error: " + error + "\n");
  223068. return true;
  223069. }
  223070. void initialiseRatesAndChannels()
  223071. {
  223072. sampleRates.clear();
  223073. channelNamesOut.clear();
  223074. channelNamesIn.clear();
  223075. minChansOut = 0;
  223076. maxChansOut = 0;
  223077. minChansIn = 0;
  223078. maxChansIn = 0;
  223079. unsigned int dummy = 0;
  223080. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  223081. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  223082. unsigned int i;
  223083. for (i = 0; i < maxChansOut; ++i)
  223084. channelNamesOut.add ("channel " + String ((int) i + 1));
  223085. for (i = 0; i < maxChansIn; ++i)
  223086. channelNamesIn.add ("channel " + String ((int) i + 1));
  223087. }
  223088. };
  223089. class ALSAAudioIODevice : public AudioIODevice
  223090. {
  223091. public:
  223092. ALSAAudioIODevice (const String& deviceName,
  223093. const String& inputId_,
  223094. const String& outputId_)
  223095. : AudioIODevice (deviceName, "ALSA"),
  223096. inputId (inputId_),
  223097. outputId (outputId_),
  223098. isOpen_ (false),
  223099. isStarted (false),
  223100. internal (inputId_, outputId_)
  223101. {
  223102. }
  223103. ~ALSAAudioIODevice()
  223104. {
  223105. }
  223106. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  223107. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  223108. int getNumSampleRates() { return internal.sampleRates.size(); }
  223109. double getSampleRate (int index) { return internal.sampleRates [index]; }
  223110. int getDefaultBufferSize() { return 512; }
  223111. int getNumBufferSizesAvailable() { return 50; }
  223112. int getBufferSizeSamples (int index)
  223113. {
  223114. int n = 16;
  223115. for (int i = 0; i < index; ++i)
  223116. n += n < 64 ? 16
  223117. : (n < 512 ? 32
  223118. : (n < 1024 ? 64
  223119. : (n < 2048 ? 128 : 256)));
  223120. return n;
  223121. }
  223122. const String open (const BigInteger& inputChannels,
  223123. const BigInteger& outputChannels,
  223124. double sampleRate,
  223125. int bufferSizeSamples)
  223126. {
  223127. close();
  223128. if (bufferSizeSamples <= 0)
  223129. bufferSizeSamples = getDefaultBufferSize();
  223130. if (sampleRate <= 0)
  223131. {
  223132. for (int i = 0; i < getNumSampleRates(); ++i)
  223133. {
  223134. if (getSampleRate (i) >= 44100)
  223135. {
  223136. sampleRate = getSampleRate (i);
  223137. break;
  223138. }
  223139. }
  223140. }
  223141. internal.open (inputChannels, outputChannels,
  223142. sampleRate, bufferSizeSamples);
  223143. isOpen_ = internal.error.isEmpty();
  223144. return internal.error;
  223145. }
  223146. void close()
  223147. {
  223148. stop();
  223149. internal.close();
  223150. isOpen_ = false;
  223151. }
  223152. bool isOpen() { return isOpen_; }
  223153. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  223154. const String getLastError() { return internal.error; }
  223155. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  223156. double getCurrentSampleRate() { return internal.sampleRate; }
  223157. int getCurrentBitDepth() { return internal.getBitDepth(); }
  223158. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  223159. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  223160. int getOutputLatencyInSamples() { return internal.outputLatency; }
  223161. int getInputLatencyInSamples() { return internal.inputLatency; }
  223162. void start (AudioIODeviceCallback* callback)
  223163. {
  223164. if (! isOpen_)
  223165. callback = 0;
  223166. if (callback != 0)
  223167. callback->audioDeviceAboutToStart (this);
  223168. internal.setCallback (callback);
  223169. isStarted = (callback != 0);
  223170. }
  223171. void stop()
  223172. {
  223173. AudioIODeviceCallback* const oldCallback = internal.callback;
  223174. start (0);
  223175. if (oldCallback != 0)
  223176. oldCallback->audioDeviceStopped();
  223177. }
  223178. String inputId, outputId;
  223179. private:
  223180. bool isOpen_, isStarted;
  223181. ALSAThread internal;
  223182. };
  223183. class ALSAAudioIODeviceType : public AudioIODeviceType
  223184. {
  223185. public:
  223186. ALSAAudioIODeviceType()
  223187. : AudioIODeviceType ("ALSA"),
  223188. hasScanned (false)
  223189. {
  223190. }
  223191. ~ALSAAudioIODeviceType()
  223192. {
  223193. }
  223194. void scanForDevices()
  223195. {
  223196. if (hasScanned)
  223197. return;
  223198. hasScanned = true;
  223199. inputNames.clear();
  223200. inputIds.clear();
  223201. outputNames.clear();
  223202. outputIds.clear();
  223203. /* void** hints = 0;
  223204. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  223205. {
  223206. for (void** hint = hints; *hint != 0; ++hint)
  223207. {
  223208. const String name (getHint (*hint, "NAME"));
  223209. if (name.isNotEmpty())
  223210. {
  223211. const String ioid (getHint (*hint, "IOID"));
  223212. String desc (getHint (*hint, "DESC"));
  223213. if (desc.isEmpty())
  223214. desc = name;
  223215. desc = desc.replaceCharacters ("\n\r", " ");
  223216. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  223217. if (ioid.isEmpty() || ioid == "Input")
  223218. {
  223219. inputNames.add (desc);
  223220. inputIds.add (name);
  223221. }
  223222. if (ioid.isEmpty() || ioid == "Output")
  223223. {
  223224. outputNames.add (desc);
  223225. outputIds.add (name);
  223226. }
  223227. }
  223228. }
  223229. snd_device_name_free_hint (hints);
  223230. }
  223231. */
  223232. snd_ctl_t* handle = 0;
  223233. snd_ctl_card_info_t* info = 0;
  223234. snd_ctl_card_info_alloca (&info);
  223235. int cardNum = -1;
  223236. while (outputIds.size() + inputIds.size() <= 32)
  223237. {
  223238. snd_card_next (&cardNum);
  223239. if (cardNum < 0)
  223240. break;
  223241. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223242. {
  223243. if (snd_ctl_card_info (handle, info) >= 0)
  223244. {
  223245. String cardId (snd_ctl_card_info_get_id (info));
  223246. if (cardId.removeCharacters ("0123456789").isEmpty())
  223247. cardId = String (cardNum);
  223248. int device = -1;
  223249. for (;;)
  223250. {
  223251. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223252. break;
  223253. String id, name;
  223254. id << "hw:" << cardId << ',' << device;
  223255. bool isInput, isOutput;
  223256. if (testDevice (id, isInput, isOutput))
  223257. {
  223258. name << snd_ctl_card_info_get_name (info);
  223259. if (name.isEmpty())
  223260. name = id;
  223261. if (isInput)
  223262. {
  223263. inputNames.add (name);
  223264. inputIds.add (id);
  223265. }
  223266. if (isOutput)
  223267. {
  223268. outputNames.add (name);
  223269. outputIds.add (id);
  223270. }
  223271. }
  223272. }
  223273. }
  223274. snd_ctl_close (handle);
  223275. }
  223276. }
  223277. inputNames.appendNumbersToDuplicates (false, true);
  223278. outputNames.appendNumbersToDuplicates (false, true);
  223279. }
  223280. const StringArray getDeviceNames (bool wantInputNames) const
  223281. {
  223282. jassert (hasScanned); // need to call scanForDevices() before doing this
  223283. return wantInputNames ? inputNames : outputNames;
  223284. }
  223285. int getDefaultDeviceIndex (bool forInput) const
  223286. {
  223287. jassert (hasScanned); // need to call scanForDevices() before doing this
  223288. return 0;
  223289. }
  223290. bool hasSeparateInputsAndOutputs() const { return true; }
  223291. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223292. {
  223293. jassert (hasScanned); // need to call scanForDevices() before doing this
  223294. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223295. if (d == 0)
  223296. return -1;
  223297. return asInput ? inputIds.indexOf (d->inputId)
  223298. : outputIds.indexOf (d->outputId);
  223299. }
  223300. AudioIODevice* createDevice (const String& outputDeviceName,
  223301. const String& inputDeviceName)
  223302. {
  223303. jassert (hasScanned); // need to call scanForDevices() before doing this
  223304. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223305. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223306. String deviceName (outputIndex >= 0 ? outputDeviceName
  223307. : inputDeviceName);
  223308. if (inputIndex >= 0 || outputIndex >= 0)
  223309. return new ALSAAudioIODevice (deviceName,
  223310. inputIds [inputIndex],
  223311. outputIds [outputIndex]);
  223312. return 0;
  223313. }
  223314. juce_UseDebuggingNewOperator
  223315. private:
  223316. StringArray inputNames, outputNames, inputIds, outputIds;
  223317. bool hasScanned;
  223318. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223319. {
  223320. unsigned int minChansOut = 0, maxChansOut = 0;
  223321. unsigned int minChansIn = 0, maxChansIn = 0;
  223322. Array <int> rates;
  223323. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223324. DBG ("ALSA device: " + id
  223325. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223326. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223327. + " rates=" + String (rates.size()));
  223328. isInput = maxChansIn > 0;
  223329. isOutput = maxChansOut > 0;
  223330. return (isInput || isOutput) && rates.size() > 0;
  223331. }
  223332. /*static const String getHint (void* hint, const char* type)
  223333. {
  223334. char* const n = snd_device_name_get_hint (hint, type);
  223335. const String s ((const char*) n);
  223336. free (n);
  223337. return s;
  223338. }*/
  223339. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223340. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223341. };
  223342. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223343. {
  223344. return new ALSAAudioIODeviceType();
  223345. }
  223346. #endif
  223347. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223348. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223349. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223350. // compiled on its own).
  223351. #ifdef JUCE_INCLUDED_FILE
  223352. #if JUCE_JACK
  223353. static void* juce_libjack_handle = 0;
  223354. void* juce_load_jack_function (const char* const name)
  223355. {
  223356. if (juce_libjack_handle == 0)
  223357. return 0;
  223358. return dlsym (juce_libjack_handle, name);
  223359. }
  223360. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223361. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223362. return_type fn_name argument_types { \
  223363. static fn_name##_ptr_t fn = 0; \
  223364. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223365. if (fn) return (*fn)arguments; \
  223366. else return 0; \
  223367. }
  223368. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223369. typedef void (*fn_name##_ptr_t)argument_types; \
  223370. void fn_name argument_types { \
  223371. static fn_name##_ptr_t fn = 0; \
  223372. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223373. if (fn) (*fn)arguments; \
  223374. }
  223375. 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));
  223376. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223377. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223378. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223379. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223380. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223381. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223382. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223383. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223384. 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));
  223385. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223386. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223387. 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));
  223388. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223389. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223390. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223391. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223392. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223393. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223394. #if JUCE_DEBUG
  223395. #define JACK_LOGGING_ENABLED 1
  223396. #endif
  223397. #if JACK_LOGGING_ENABLED
  223398. static void jack_Log (const String& s)
  223399. {
  223400. std::cerr << s << std::endl;
  223401. }
  223402. static void dumpJackErrorMessage (const jack_status_t status)
  223403. {
  223404. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223405. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223406. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223407. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223408. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223409. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223410. }
  223411. #else
  223412. #define dumpJackErrorMessage(a) {}
  223413. #define jack_Log(...) {}
  223414. #endif
  223415. #ifndef JUCE_JACK_CLIENT_NAME
  223416. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223417. #endif
  223418. class JackAudioIODevice : public AudioIODevice
  223419. {
  223420. public:
  223421. JackAudioIODevice (const String& deviceName,
  223422. const String& inputId_,
  223423. const String& outputId_)
  223424. : AudioIODevice (deviceName, "JACK"),
  223425. inputId (inputId_),
  223426. outputId (outputId_),
  223427. isOpen_ (false),
  223428. callback (0),
  223429. totalNumberOfInputChannels (0),
  223430. totalNumberOfOutputChannels (0)
  223431. {
  223432. jassert (deviceName.isNotEmpty());
  223433. jack_status_t status;
  223434. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223435. if (client == 0)
  223436. {
  223437. dumpJackErrorMessage (status);
  223438. }
  223439. else
  223440. {
  223441. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223442. // open input ports
  223443. const StringArray inputChannels (getInputChannelNames());
  223444. for (int i = 0; i < inputChannels.size(); i++)
  223445. {
  223446. String inputName;
  223447. inputName << "in_" << ++totalNumberOfInputChannels;
  223448. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223449. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223450. }
  223451. // open output ports
  223452. const StringArray outputChannels (getOutputChannelNames());
  223453. for (int i = 0; i < outputChannels.size (); i++)
  223454. {
  223455. String outputName;
  223456. outputName << "out_" << ++totalNumberOfOutputChannels;
  223457. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223458. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223459. }
  223460. inChans.calloc (totalNumberOfInputChannels + 2);
  223461. outChans.calloc (totalNumberOfOutputChannels + 2);
  223462. }
  223463. }
  223464. ~JackAudioIODevice()
  223465. {
  223466. close();
  223467. if (client != 0)
  223468. {
  223469. JUCE_NAMESPACE::jack_client_close (client);
  223470. client = 0;
  223471. }
  223472. }
  223473. const StringArray getChannelNames (bool forInput) const
  223474. {
  223475. StringArray names;
  223476. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223477. forInput ? JackPortIsInput : JackPortIsOutput);
  223478. if (ports != 0)
  223479. {
  223480. int j = 0;
  223481. while (ports[j] != 0)
  223482. {
  223483. const String portName (ports [j++]);
  223484. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223485. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223486. }
  223487. free (ports);
  223488. }
  223489. return names;
  223490. }
  223491. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223492. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223493. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223494. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223495. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223496. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223497. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223498. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223499. double sampleRate, int bufferSizeSamples)
  223500. {
  223501. if (client == 0)
  223502. {
  223503. lastError = "No JACK client running";
  223504. return lastError;
  223505. }
  223506. lastError = String::empty;
  223507. close();
  223508. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223509. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223510. JUCE_NAMESPACE::jack_activate (client);
  223511. isOpen_ = true;
  223512. if (! inputChannels.isZero())
  223513. {
  223514. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223515. if (ports != 0)
  223516. {
  223517. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223518. for (int i = 0; i < numInputChannels; ++i)
  223519. {
  223520. const String portName (ports[i]);
  223521. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223522. {
  223523. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223524. if (error != 0)
  223525. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223526. }
  223527. }
  223528. free (ports);
  223529. }
  223530. }
  223531. if (! outputChannels.isZero())
  223532. {
  223533. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223534. if (ports != 0)
  223535. {
  223536. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223537. for (int i = 0; i < numOutputChannels; ++i)
  223538. {
  223539. const String portName (ports[i]);
  223540. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223541. {
  223542. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223543. if (error != 0)
  223544. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223545. }
  223546. }
  223547. free (ports);
  223548. }
  223549. }
  223550. return lastError;
  223551. }
  223552. void close()
  223553. {
  223554. stop();
  223555. if (client != 0)
  223556. {
  223557. JUCE_NAMESPACE::jack_deactivate (client);
  223558. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223559. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223560. }
  223561. isOpen_ = false;
  223562. }
  223563. void start (AudioIODeviceCallback* newCallback)
  223564. {
  223565. if (isOpen_ && newCallback != callback)
  223566. {
  223567. if (newCallback != 0)
  223568. newCallback->audioDeviceAboutToStart (this);
  223569. AudioIODeviceCallback* const oldCallback = callback;
  223570. {
  223571. const ScopedLock sl (callbackLock);
  223572. callback = newCallback;
  223573. }
  223574. if (oldCallback != 0)
  223575. oldCallback->audioDeviceStopped();
  223576. }
  223577. }
  223578. void stop()
  223579. {
  223580. start (0);
  223581. }
  223582. bool isOpen() { return isOpen_; }
  223583. bool isPlaying() { return callback != 0; }
  223584. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223585. double getCurrentSampleRate() { return getSampleRate (0); }
  223586. int getCurrentBitDepth() { return 32; }
  223587. const String getLastError() { return lastError; }
  223588. const BigInteger getActiveOutputChannels() const
  223589. {
  223590. BigInteger outputBits;
  223591. for (int i = 0; i < outputPorts.size(); i++)
  223592. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223593. outputBits.setBit (i);
  223594. return outputBits;
  223595. }
  223596. const BigInteger getActiveInputChannels() const
  223597. {
  223598. BigInteger inputBits;
  223599. for (int i = 0; i < inputPorts.size(); i++)
  223600. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223601. inputBits.setBit (i);
  223602. return inputBits;
  223603. }
  223604. int getOutputLatencyInSamples()
  223605. {
  223606. int latency = 0;
  223607. for (int i = 0; i < outputPorts.size(); i++)
  223608. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223609. return latency;
  223610. }
  223611. int getInputLatencyInSamples()
  223612. {
  223613. int latency = 0;
  223614. for (int i = 0; i < inputPorts.size(); i++)
  223615. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223616. return latency;
  223617. }
  223618. String inputId, outputId;
  223619. private:
  223620. void process (const int numSamples)
  223621. {
  223622. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223623. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223624. {
  223625. jack_default_audio_sample_t* in
  223626. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223627. if (in != 0)
  223628. inChans [numActiveInChans++] = (float*) in;
  223629. }
  223630. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223631. {
  223632. jack_default_audio_sample_t* out
  223633. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223634. if (out != 0)
  223635. outChans [numActiveOutChans++] = (float*) out;
  223636. }
  223637. const ScopedLock sl (callbackLock);
  223638. if (callback != 0)
  223639. {
  223640. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223641. outChans, numActiveOutChans, numSamples);
  223642. }
  223643. else
  223644. {
  223645. for (i = 0; i < numActiveOutChans; ++i)
  223646. zeromem (outChans[i], sizeof (float) * numSamples);
  223647. }
  223648. }
  223649. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223650. {
  223651. if (callbackArgument != 0)
  223652. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223653. return 0;
  223654. }
  223655. static void threadInitCallback (void* callbackArgument)
  223656. {
  223657. jack_Log ("JackAudioIODevice::initialise");
  223658. }
  223659. static void shutdownCallback (void* callbackArgument)
  223660. {
  223661. jack_Log ("JackAudioIODevice::shutdown");
  223662. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223663. if (device != 0)
  223664. {
  223665. device->client = 0;
  223666. device->close();
  223667. }
  223668. }
  223669. static void errorCallback (const char* msg)
  223670. {
  223671. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223672. }
  223673. bool isOpen_;
  223674. jack_client_t* client;
  223675. String lastError;
  223676. AudioIODeviceCallback* callback;
  223677. CriticalSection callbackLock;
  223678. HeapBlock <float*> inChans, outChans;
  223679. int totalNumberOfInputChannels;
  223680. int totalNumberOfOutputChannels;
  223681. Array<void*> inputPorts, outputPorts;
  223682. };
  223683. class JackAudioIODeviceType : public AudioIODeviceType
  223684. {
  223685. public:
  223686. JackAudioIODeviceType()
  223687. : AudioIODeviceType ("JACK"),
  223688. hasScanned (false)
  223689. {
  223690. }
  223691. ~JackAudioIODeviceType()
  223692. {
  223693. }
  223694. void scanForDevices()
  223695. {
  223696. hasScanned = true;
  223697. inputNames.clear();
  223698. inputIds.clear();
  223699. outputNames.clear();
  223700. outputIds.clear();
  223701. if (juce_libjack_handle == 0)
  223702. {
  223703. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223704. if (juce_libjack_handle == 0)
  223705. return;
  223706. }
  223707. // open a dummy client
  223708. jack_status_t status;
  223709. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223710. if (client == 0)
  223711. {
  223712. dumpJackErrorMessage (status);
  223713. }
  223714. else
  223715. {
  223716. // scan for output devices
  223717. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223718. if (ports != 0)
  223719. {
  223720. int j = 0;
  223721. while (ports[j] != 0)
  223722. {
  223723. String clientName (ports[j]);
  223724. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223725. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223726. && ! inputNames.contains (clientName))
  223727. {
  223728. inputNames.add (clientName);
  223729. inputIds.add (ports [j]);
  223730. }
  223731. ++j;
  223732. }
  223733. free (ports);
  223734. }
  223735. // scan for input devices
  223736. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223737. if (ports != 0)
  223738. {
  223739. int j = 0;
  223740. while (ports[j] != 0)
  223741. {
  223742. String clientName (ports[j]);
  223743. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223744. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223745. && ! outputNames.contains (clientName))
  223746. {
  223747. outputNames.add (clientName);
  223748. outputIds.add (ports [j]);
  223749. }
  223750. ++j;
  223751. }
  223752. free (ports);
  223753. }
  223754. JUCE_NAMESPACE::jack_client_close (client);
  223755. }
  223756. }
  223757. const StringArray getDeviceNames (bool wantInputNames) const
  223758. {
  223759. jassert (hasScanned); // need to call scanForDevices() before doing this
  223760. return wantInputNames ? inputNames : outputNames;
  223761. }
  223762. int getDefaultDeviceIndex (bool forInput) const
  223763. {
  223764. jassert (hasScanned); // need to call scanForDevices() before doing this
  223765. return 0;
  223766. }
  223767. bool hasSeparateInputsAndOutputs() const { return true; }
  223768. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223769. {
  223770. jassert (hasScanned); // need to call scanForDevices() before doing this
  223771. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223772. if (d == 0)
  223773. return -1;
  223774. return asInput ? inputIds.indexOf (d->inputId)
  223775. : outputIds.indexOf (d->outputId);
  223776. }
  223777. AudioIODevice* createDevice (const String& outputDeviceName,
  223778. const String& inputDeviceName)
  223779. {
  223780. jassert (hasScanned); // need to call scanForDevices() before doing this
  223781. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223782. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223783. if (inputIndex >= 0 || outputIndex >= 0)
  223784. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223785. : inputDeviceName,
  223786. inputIds [inputIndex],
  223787. outputIds [outputIndex]);
  223788. return 0;
  223789. }
  223790. juce_UseDebuggingNewOperator
  223791. private:
  223792. StringArray inputNames, outputNames, inputIds, outputIds;
  223793. bool hasScanned;
  223794. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223795. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223796. };
  223797. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223798. {
  223799. return new JackAudioIODeviceType();
  223800. }
  223801. #else // if JACK is turned off..
  223802. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223803. #endif
  223804. #endif
  223805. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223806. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223807. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223808. // compiled on its own).
  223809. #if JUCE_INCLUDED_FILE
  223810. #if JUCE_ALSA
  223811. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223812. StringArray& deviceNamesFound,
  223813. const int deviceIndexToOpen)
  223814. {
  223815. snd_seq_t* returnedHandle = 0;
  223816. snd_seq_t* seqHandle;
  223817. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223818. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223819. {
  223820. snd_seq_system_info_t* systemInfo;
  223821. snd_seq_client_info_t* clientInfo;
  223822. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223823. {
  223824. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223825. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223826. {
  223827. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223828. while (--numClients >= 0 && returnedHandle == 0)
  223829. {
  223830. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223831. {
  223832. snd_seq_port_info_t* portInfo;
  223833. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223834. {
  223835. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223836. const int client = snd_seq_client_info_get_client (clientInfo);
  223837. snd_seq_port_info_set_client (portInfo, client);
  223838. snd_seq_port_info_set_port (portInfo, -1);
  223839. while (--numPorts >= 0)
  223840. {
  223841. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223842. && (snd_seq_port_info_get_capability (portInfo)
  223843. & (forInput ? SND_SEQ_PORT_CAP_READ
  223844. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223845. {
  223846. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223847. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223848. {
  223849. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223850. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223851. if (sourcePort != -1)
  223852. {
  223853. snd_seq_set_client_name (seqHandle,
  223854. forInput ? "Juce Midi Input"
  223855. : "Juce Midi Output");
  223856. const int portId
  223857. = snd_seq_create_simple_port (seqHandle,
  223858. forInput ? "Juce Midi In Port"
  223859. : "Juce Midi Out Port",
  223860. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223861. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223862. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223863. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223864. returnedHandle = seqHandle;
  223865. }
  223866. }
  223867. }
  223868. }
  223869. snd_seq_port_info_free (portInfo);
  223870. }
  223871. }
  223872. }
  223873. snd_seq_client_info_free (clientInfo);
  223874. }
  223875. snd_seq_system_info_free (systemInfo);
  223876. }
  223877. if (returnedHandle == 0)
  223878. snd_seq_close (seqHandle);
  223879. }
  223880. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223881. return returnedHandle;
  223882. }
  223883. static snd_seq_t* createMidiDevice (const bool forInput,
  223884. const String& deviceNameToOpen)
  223885. {
  223886. snd_seq_t* seqHandle = 0;
  223887. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223888. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223889. {
  223890. snd_seq_set_client_name (seqHandle,
  223891. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223892. const int portId
  223893. = snd_seq_create_simple_port (seqHandle,
  223894. forInput ? "in"
  223895. : "out",
  223896. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223897. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223898. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223899. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223900. if (portId < 0)
  223901. {
  223902. snd_seq_close (seqHandle);
  223903. seqHandle = 0;
  223904. }
  223905. }
  223906. return seqHandle;
  223907. }
  223908. class MidiOutputDevice
  223909. {
  223910. public:
  223911. MidiOutputDevice (MidiOutput* const midiOutput_,
  223912. snd_seq_t* const seqHandle_)
  223913. :
  223914. midiOutput (midiOutput_),
  223915. seqHandle (seqHandle_),
  223916. maxEventSize (16 * 1024)
  223917. {
  223918. jassert (seqHandle != 0 && midiOutput != 0);
  223919. snd_midi_event_new (maxEventSize, &midiParser);
  223920. }
  223921. ~MidiOutputDevice()
  223922. {
  223923. snd_midi_event_free (midiParser);
  223924. snd_seq_close (seqHandle);
  223925. }
  223926. void sendMessageNow (const MidiMessage& message)
  223927. {
  223928. if (message.getRawDataSize() > maxEventSize)
  223929. {
  223930. maxEventSize = message.getRawDataSize();
  223931. snd_midi_event_free (midiParser);
  223932. snd_midi_event_new (maxEventSize, &midiParser);
  223933. }
  223934. snd_seq_event_t event;
  223935. snd_seq_ev_clear (&event);
  223936. snd_midi_event_encode (midiParser,
  223937. message.getRawData(),
  223938. message.getRawDataSize(),
  223939. &event);
  223940. snd_midi_event_reset_encode (midiParser);
  223941. snd_seq_ev_set_source (&event, 0);
  223942. snd_seq_ev_set_subs (&event);
  223943. snd_seq_ev_set_direct (&event);
  223944. snd_seq_event_output (seqHandle, &event);
  223945. snd_seq_drain_output (seqHandle);
  223946. }
  223947. juce_UseDebuggingNewOperator
  223948. private:
  223949. MidiOutput* const midiOutput;
  223950. snd_seq_t* const seqHandle;
  223951. snd_midi_event_t* midiParser;
  223952. int maxEventSize;
  223953. };
  223954. const StringArray MidiOutput::getDevices()
  223955. {
  223956. StringArray devices;
  223957. iterateMidiDevices (false, devices, -1);
  223958. return devices;
  223959. }
  223960. int MidiOutput::getDefaultDeviceIndex()
  223961. {
  223962. return 0;
  223963. }
  223964. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223965. {
  223966. MidiOutput* newDevice = 0;
  223967. StringArray devices;
  223968. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223969. if (handle != 0)
  223970. {
  223971. newDevice = new MidiOutput();
  223972. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223973. }
  223974. return newDevice;
  223975. }
  223976. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223977. {
  223978. MidiOutput* newDevice = 0;
  223979. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223980. if (handle != 0)
  223981. {
  223982. newDevice = new MidiOutput();
  223983. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223984. }
  223985. return newDevice;
  223986. }
  223987. MidiOutput::~MidiOutput()
  223988. {
  223989. delete static_cast <MidiOutputDevice*> (internal);
  223990. }
  223991. void MidiOutput::reset()
  223992. {
  223993. }
  223994. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223995. {
  223996. return false;
  223997. }
  223998. void MidiOutput::setVolume (float leftVol, float rightVol)
  223999. {
  224000. }
  224001. void MidiOutput::sendMessageNow (const MidiMessage& message)
  224002. {
  224003. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  224004. }
  224005. class MidiInputThread : public Thread
  224006. {
  224007. public:
  224008. MidiInputThread (MidiInput* const midiInput_,
  224009. snd_seq_t* const seqHandle_,
  224010. MidiInputCallback* const callback_)
  224011. : Thread ("Juce MIDI Input"),
  224012. midiInput (midiInput_),
  224013. seqHandle (seqHandle_),
  224014. callback (callback_)
  224015. {
  224016. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  224017. }
  224018. ~MidiInputThread()
  224019. {
  224020. snd_seq_close (seqHandle);
  224021. }
  224022. void run()
  224023. {
  224024. const int maxEventSize = 16 * 1024;
  224025. snd_midi_event_t* midiParser;
  224026. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  224027. {
  224028. HeapBlock <uint8> buffer (maxEventSize);
  224029. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  224030. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  224031. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  224032. while (! threadShouldExit())
  224033. {
  224034. if (poll (pfd, numPfds, 500) > 0)
  224035. {
  224036. snd_seq_event_t* inputEvent = 0;
  224037. snd_seq_nonblock (seqHandle, 1);
  224038. do
  224039. {
  224040. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  224041. {
  224042. // xxx what about SYSEXes that are too big for the buffer?
  224043. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  224044. snd_midi_event_reset_decode (midiParser);
  224045. if (numBytes > 0)
  224046. {
  224047. const MidiMessage message ((const uint8*) buffer,
  224048. numBytes,
  224049. Time::getMillisecondCounter() * 0.001);
  224050. callback->handleIncomingMidiMessage (midiInput, message);
  224051. }
  224052. snd_seq_free_event (inputEvent);
  224053. }
  224054. }
  224055. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  224056. snd_seq_free_event (inputEvent);
  224057. }
  224058. }
  224059. snd_midi_event_free (midiParser);
  224060. }
  224061. };
  224062. juce_UseDebuggingNewOperator
  224063. private:
  224064. MidiInput* const midiInput;
  224065. snd_seq_t* const seqHandle;
  224066. MidiInputCallback* const callback;
  224067. };
  224068. MidiInput::MidiInput (const String& name_)
  224069. : name (name_),
  224070. internal (0)
  224071. {
  224072. }
  224073. MidiInput::~MidiInput()
  224074. {
  224075. stop();
  224076. delete static_cast <MidiInputThread*> (internal);
  224077. }
  224078. void MidiInput::start()
  224079. {
  224080. static_cast <MidiInputThread*> (internal)->startThread();
  224081. }
  224082. void MidiInput::stop()
  224083. {
  224084. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  224085. }
  224086. int MidiInput::getDefaultDeviceIndex()
  224087. {
  224088. return 0;
  224089. }
  224090. const StringArray MidiInput::getDevices()
  224091. {
  224092. StringArray devices;
  224093. iterateMidiDevices (true, devices, -1);
  224094. return devices;
  224095. }
  224096. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  224097. {
  224098. MidiInput* newDevice = 0;
  224099. StringArray devices;
  224100. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  224101. if (handle != 0)
  224102. {
  224103. newDevice = new MidiInput (devices [deviceIndex]);
  224104. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224105. }
  224106. return newDevice;
  224107. }
  224108. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  224109. {
  224110. MidiInput* newDevice = 0;
  224111. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  224112. if (handle != 0)
  224113. {
  224114. newDevice = new MidiInput (deviceName);
  224115. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224116. }
  224117. return newDevice;
  224118. }
  224119. #else
  224120. // (These are just stub functions if ALSA is unavailable...)
  224121. const StringArray MidiOutput::getDevices() { return StringArray(); }
  224122. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  224123. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  224124. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  224125. MidiOutput::~MidiOutput() {}
  224126. void MidiOutput::reset() {}
  224127. bool MidiOutput::getVolume (float&, float&) { return false; }
  224128. void MidiOutput::setVolume (float, float) {}
  224129. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  224130. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  224131. MidiInput::~MidiInput() {}
  224132. void MidiInput::start() {}
  224133. void MidiInput::stop() {}
  224134. int MidiInput::getDefaultDeviceIndex() { return 0; }
  224135. const StringArray MidiInput::getDevices() { return StringArray(); }
  224136. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  224137. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  224138. #endif
  224139. #endif
  224140. /*** End of inlined file: juce_linux_Midi.cpp ***/
  224141. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  224142. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224143. // compiled on its own).
  224144. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  224145. AudioCDReader::AudioCDReader()
  224146. : AudioFormatReader (0, "CD Audio")
  224147. {
  224148. }
  224149. const StringArray AudioCDReader::getAvailableCDNames()
  224150. {
  224151. StringArray names;
  224152. return names;
  224153. }
  224154. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  224155. {
  224156. return 0;
  224157. }
  224158. AudioCDReader::~AudioCDReader()
  224159. {
  224160. }
  224161. void AudioCDReader::refreshTrackLengths()
  224162. {
  224163. }
  224164. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  224165. int64 startSampleInFile, int numSamples)
  224166. {
  224167. return false;
  224168. }
  224169. bool AudioCDReader::isCDStillPresent() const
  224170. {
  224171. return false;
  224172. }
  224173. bool AudioCDReader::isTrackAudio (int trackNum) const
  224174. {
  224175. return false;
  224176. }
  224177. void AudioCDReader::enableIndexScanning (bool b)
  224178. {
  224179. }
  224180. int AudioCDReader::getLastIndex() const
  224181. {
  224182. return 0;
  224183. }
  224184. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  224185. {
  224186. return Array<int>();
  224187. }
  224188. #endif
  224189. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  224190. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  224191. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224192. // compiled on its own).
  224193. #if JUCE_INCLUDED_FILE
  224194. void FileChooser::showPlatformDialog (Array<File>& results,
  224195. const String& title,
  224196. const File& file,
  224197. const String& filters,
  224198. bool isDirectory,
  224199. bool selectsFiles,
  224200. bool isSave,
  224201. bool warnAboutOverwritingExistingFiles,
  224202. bool selectMultipleFiles,
  224203. FilePreviewComponent* previewComponent)
  224204. {
  224205. const String separator (":");
  224206. String command ("zenity --file-selection");
  224207. if (title.isNotEmpty())
  224208. command << " --title=\"" << title << "\"";
  224209. if (file != File::nonexistent)
  224210. command << " --filename=\"" << file.getFullPathName () << "\"";
  224211. if (isDirectory)
  224212. command << " --directory";
  224213. if (isSave)
  224214. command << " --save";
  224215. if (selectMultipleFiles)
  224216. command << " --multiple --separator=\"" << separator << "\"";
  224217. command << " 2>&1";
  224218. MemoryOutputStream result;
  224219. int status = -1;
  224220. FILE* stream = popen (command.toUTF8(), "r");
  224221. if (stream != 0)
  224222. {
  224223. for (;;)
  224224. {
  224225. char buffer [1024];
  224226. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224227. if (bytesRead <= 0)
  224228. break;
  224229. result.write (buffer, bytesRead);
  224230. }
  224231. status = pclose (stream);
  224232. }
  224233. if (status == 0)
  224234. {
  224235. StringArray tokens;
  224236. if (selectMultipleFiles)
  224237. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224238. else
  224239. tokens.add (result.toUTF8());
  224240. for (int i = 0; i < tokens.size(); i++)
  224241. results.add (File (tokens[i]));
  224242. return;
  224243. }
  224244. //xxx ain't got one!
  224245. jassertfalse;
  224246. }
  224247. #endif
  224248. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224249. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224250. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224251. // compiled on its own).
  224252. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224253. /*
  224254. Sorry.. This class isn't implemented on Linux!
  224255. */
  224256. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224257. : browser (0),
  224258. blankPageShown (false),
  224259. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224260. {
  224261. setOpaque (true);
  224262. }
  224263. WebBrowserComponent::~WebBrowserComponent()
  224264. {
  224265. }
  224266. void WebBrowserComponent::goToURL (const String& url,
  224267. const StringArray* headers,
  224268. const MemoryBlock* postData)
  224269. {
  224270. lastURL = url;
  224271. lastHeaders.clear();
  224272. if (headers != 0)
  224273. lastHeaders = *headers;
  224274. lastPostData.setSize (0);
  224275. if (postData != 0)
  224276. lastPostData = *postData;
  224277. blankPageShown = false;
  224278. }
  224279. void WebBrowserComponent::stop()
  224280. {
  224281. }
  224282. void WebBrowserComponent::goBack()
  224283. {
  224284. lastURL = String::empty;
  224285. blankPageShown = false;
  224286. }
  224287. void WebBrowserComponent::goForward()
  224288. {
  224289. lastURL = String::empty;
  224290. }
  224291. void WebBrowserComponent::refresh()
  224292. {
  224293. }
  224294. void WebBrowserComponent::paint (Graphics& g)
  224295. {
  224296. g.fillAll (Colours::white);
  224297. }
  224298. void WebBrowserComponent::checkWindowAssociation()
  224299. {
  224300. }
  224301. void WebBrowserComponent::reloadLastURL()
  224302. {
  224303. if (lastURL.isNotEmpty())
  224304. {
  224305. goToURL (lastURL, &lastHeaders, &lastPostData);
  224306. lastURL = String::empty;
  224307. }
  224308. }
  224309. void WebBrowserComponent::parentHierarchyChanged()
  224310. {
  224311. checkWindowAssociation();
  224312. }
  224313. void WebBrowserComponent::resized()
  224314. {
  224315. }
  224316. void WebBrowserComponent::visibilityChanged()
  224317. {
  224318. checkWindowAssociation();
  224319. }
  224320. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224321. {
  224322. return true;
  224323. }
  224324. #endif
  224325. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224326. #endif
  224327. END_JUCE_NAMESPACE
  224328. #endif
  224329. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224330. #endif
  224331. #if JUCE_MAC || JUCE_IPHONE
  224332. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224333. /*
  224334. This file wraps together all the mac-specific code, so that
  224335. we can include all the native headers just once, and compile all our
  224336. platform-specific stuff in one big lump, keeping it out of the way of
  224337. the rest of the codebase.
  224338. */
  224339. #if JUCE_MAC || JUCE_IOS
  224340. BEGIN_JUCE_NAMESPACE
  224341. #undef Point
  224342. template <class RectType>
  224343. static const Rectangle<int> convertToRectInt (const RectType& r)
  224344. {
  224345. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  224346. }
  224347. template <class RectType>
  224348. static const Rectangle<float> convertToRectFloat (const RectType& r)
  224349. {
  224350. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  224351. }
  224352. template <class RectType>
  224353. static CGRect convertToCGRect (const RectType& r)
  224354. {
  224355. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  224356. }
  224357. #define JUCE_INCLUDED_FILE 1
  224358. // Now include the actual code files..
  224359. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224360. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224361. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224362. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224363. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224364. actually calling into a similarly named class in the other module's address space.
  224365. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224366. have unique names, and should avoid this problem.
  224367. If you're using the amalgamated version, you can just set this macro to something unique before
  224368. you include juce_amalgamated.cpp.
  224369. */
  224370. #ifndef JUCE_ObjCExtraSuffix
  224371. #define JUCE_ObjCExtraSuffix 3
  224372. #endif
  224373. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224374. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224375. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224376. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224377. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224378. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224379. // compiled on its own).
  224380. #if JUCE_INCLUDED_FILE
  224381. static const String nsStringToJuce (NSString* s)
  224382. {
  224383. return String::fromUTF8 ([s UTF8String]);
  224384. }
  224385. static NSString* juceStringToNS (const String& s)
  224386. {
  224387. return [NSString stringWithUTF8String: s.toUTF8()];
  224388. }
  224389. static const String convertUTF16ToString (const UniChar* utf16)
  224390. {
  224391. String s;
  224392. while (*utf16 != 0)
  224393. s += (juce_wchar) *utf16++;
  224394. return s;
  224395. }
  224396. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224397. {
  224398. String result;
  224399. if (cfString != 0)
  224400. {
  224401. CFRange range = { 0, CFStringGetLength (cfString) };
  224402. HeapBlock <UniChar> u (range.length + 1);
  224403. CFStringGetCharacters (cfString, range, u);
  224404. u[range.length] = 0;
  224405. result = convertUTF16ToString (u);
  224406. }
  224407. return result;
  224408. }
  224409. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224410. {
  224411. const int len = s.length();
  224412. HeapBlock <UniChar> temp (len + 2);
  224413. for (int i = 0; i <= len; ++i)
  224414. temp[i] = s[i];
  224415. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224416. }
  224417. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224418. {
  224419. #if JUCE_IOS
  224420. const ScopedAutoReleasePool pool;
  224421. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224422. #else
  224423. UnicodeMapping map;
  224424. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224425. kUnicodeNoSubset,
  224426. kTextEncodingDefaultFormat);
  224427. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224428. kUnicodeCanonicalCompVariant,
  224429. kTextEncodingDefaultFormat);
  224430. map.mappingVersion = kUnicodeUseLatestMapping;
  224431. UnicodeToTextInfo conversionInfo = 0;
  224432. String result;
  224433. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224434. {
  224435. const int len = s.length();
  224436. HeapBlock <UniChar> tempIn, tempOut;
  224437. tempIn.calloc (len + 2);
  224438. tempOut.calloc (len + 2);
  224439. for (int i = 0; i <= len; ++i)
  224440. tempIn[i] = s[i];
  224441. ByteCount bytesRead = 0;
  224442. ByteCount outputBufferSize = 0;
  224443. if (ConvertFromUnicodeToText (conversionInfo,
  224444. len * sizeof (UniChar), tempIn,
  224445. kUnicodeDefaultDirectionMask,
  224446. 0, 0, 0, 0,
  224447. len * sizeof (UniChar), &bytesRead,
  224448. &outputBufferSize, tempOut) == noErr)
  224449. {
  224450. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224451. juce_wchar* t = result;
  224452. unsigned int i;
  224453. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224454. t[i] = (juce_wchar) tempOut[i];
  224455. t[i] = 0;
  224456. }
  224457. DisposeUnicodeToTextInfo (&conversionInfo);
  224458. }
  224459. return result;
  224460. #endif
  224461. }
  224462. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224463. void SystemClipboard::copyTextToClipboard (const String& text)
  224464. {
  224465. #if JUCE_IOS
  224466. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224467. forPasteboardType: @"public.text"];
  224468. #else
  224469. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224470. owner: nil];
  224471. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224472. forType: NSStringPboardType];
  224473. #endif
  224474. }
  224475. const String SystemClipboard::getTextFromClipboard()
  224476. {
  224477. #if JUCE_IOS
  224478. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224479. #else
  224480. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224481. #endif
  224482. return text == 0 ? String::empty
  224483. : nsStringToJuce (text);
  224484. }
  224485. #endif
  224486. #endif
  224487. /*** End of inlined file: juce_mac_Strings.mm ***/
  224488. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224489. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224490. // compiled on its own).
  224491. #if JUCE_INCLUDED_FILE
  224492. namespace SystemStatsHelpers
  224493. {
  224494. static int64 highResTimerFrequency = 0;
  224495. static double highResTimerToMillisecRatio = 0;
  224496. #if JUCE_INTEL
  224497. static void juce_getCpuVendor (char* const v) throw()
  224498. {
  224499. int vendor[4];
  224500. zerostruct (vendor);
  224501. int dummy = 0;
  224502. asm ("mov %%ebx, %%esi \n\t"
  224503. "cpuid \n\t"
  224504. "xchg %%esi, %%ebx"
  224505. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224506. memcpy (v, vendor, 16);
  224507. }
  224508. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224509. {
  224510. unsigned int cpu = 0;
  224511. unsigned int ext = 0;
  224512. unsigned int family = 0;
  224513. unsigned int dummy = 0;
  224514. asm ("mov %%ebx, %%esi \n\t"
  224515. "cpuid \n\t"
  224516. "xchg %%esi, %%ebx"
  224517. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224518. familyModel = family;
  224519. extFeatures = ext;
  224520. return cpu;
  224521. }
  224522. #endif
  224523. }
  224524. void SystemStats::initialiseStats()
  224525. {
  224526. using namespace SystemStatsHelpers;
  224527. static bool initialised = false;
  224528. if (! initialised)
  224529. {
  224530. initialised = true;
  224531. #if JUCE_MAC
  224532. [NSApplication sharedApplication];
  224533. #endif
  224534. #if JUCE_INTEL
  224535. unsigned int familyModel, extFeatures;
  224536. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224537. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224538. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224539. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224540. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224541. #else
  224542. cpuFlags.hasMMX = false;
  224543. cpuFlags.hasSSE = false;
  224544. cpuFlags.hasSSE2 = false;
  224545. cpuFlags.has3DNow = false;
  224546. #endif
  224547. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224548. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224549. #else
  224550. cpuFlags.numCpus = (int) MPProcessors();
  224551. #endif
  224552. mach_timebase_info_data_t timebase;
  224553. (void) mach_timebase_info (&timebase);
  224554. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224555. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224556. String s (SystemStats::getJUCEVersion());
  224557. rlimit lim;
  224558. getrlimit (RLIMIT_NOFILE, &lim);
  224559. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224560. setrlimit (RLIMIT_NOFILE, &lim);
  224561. }
  224562. }
  224563. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224564. {
  224565. return MacOSX;
  224566. }
  224567. const String SystemStats::getOperatingSystemName()
  224568. {
  224569. return "Mac OS X";
  224570. }
  224571. #if ! JUCE_IOS
  224572. int PlatformUtilities::getOSXMinorVersionNumber()
  224573. {
  224574. SInt32 versionMinor = 0;
  224575. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224576. (void) err;
  224577. jassert (err == noErr);
  224578. return (int) versionMinor;
  224579. }
  224580. #endif
  224581. bool SystemStats::isOperatingSystem64Bit()
  224582. {
  224583. #if JUCE_IOS
  224584. return false;
  224585. #elif JUCE_64BIT
  224586. return true;
  224587. #else
  224588. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224589. #endif
  224590. }
  224591. int SystemStats::getMemorySizeInMegabytes()
  224592. {
  224593. uint64 mem = 0;
  224594. size_t memSize = sizeof (mem);
  224595. int mib[] = { CTL_HW, HW_MEMSIZE };
  224596. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224597. return (int) (mem / (1024 * 1024));
  224598. }
  224599. const String SystemStats::getCpuVendor()
  224600. {
  224601. #if JUCE_INTEL
  224602. char v [16];
  224603. SystemStatsHelpers::juce_getCpuVendor (v);
  224604. return String (v, 16);
  224605. #else
  224606. return String::empty;
  224607. #endif
  224608. }
  224609. int SystemStats::getCpuSpeedInMegaherz()
  224610. {
  224611. uint64 speedHz = 0;
  224612. size_t speedSize = sizeof (speedHz);
  224613. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224614. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224615. #if JUCE_BIG_ENDIAN
  224616. if (speedSize == 4)
  224617. speedHz >>= 32;
  224618. #endif
  224619. return (int) (speedHz / 1000000);
  224620. }
  224621. const String SystemStats::getLogonName()
  224622. {
  224623. return nsStringToJuce (NSUserName());
  224624. }
  224625. const String SystemStats::getFullUserName()
  224626. {
  224627. return nsStringToJuce (NSFullUserName());
  224628. }
  224629. uint32 juce_millisecondsSinceStartup() throw()
  224630. {
  224631. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224632. }
  224633. double Time::getMillisecondCounterHiRes() throw()
  224634. {
  224635. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224636. }
  224637. int64 Time::getHighResolutionTicks() throw()
  224638. {
  224639. return (int64) mach_absolute_time();
  224640. }
  224641. int64 Time::getHighResolutionTicksPerSecond() throw()
  224642. {
  224643. return SystemStatsHelpers::highResTimerFrequency;
  224644. }
  224645. bool Time::setSystemTimeToThisTime() const
  224646. {
  224647. jassertfalse;
  224648. return false;
  224649. }
  224650. int SystemStats::getPageSize()
  224651. {
  224652. return (int) NSPageSize();
  224653. }
  224654. void PlatformUtilities::fpuReset()
  224655. {
  224656. }
  224657. #endif
  224658. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224659. /*** Start of inlined file: juce_mac_Network.mm ***/
  224660. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224661. // compiled on its own).
  224662. #if JUCE_INCLUDED_FILE
  224663. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224664. {
  224665. #ifndef IFT_ETHER
  224666. #define IFT_ETHER 6
  224667. #endif
  224668. ifaddrs* addrs = 0;
  224669. int numResults = 0;
  224670. if (getifaddrs (&addrs) == 0)
  224671. {
  224672. const ifaddrs* cursor = addrs;
  224673. while (cursor != 0 && numResults < maxNum)
  224674. {
  224675. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224676. if (sto->ss_family == AF_LINK)
  224677. {
  224678. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224679. if (sadd->sdl_type == IFT_ETHER)
  224680. {
  224681. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224682. uint64 a = 0;
  224683. for (int i = 6; --i >= 0;)
  224684. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224685. *addresses++ = (int64) a;
  224686. ++numResults;
  224687. }
  224688. }
  224689. cursor = cursor->ifa_next;
  224690. }
  224691. freeifaddrs (addrs);
  224692. }
  224693. return numResults;
  224694. }
  224695. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224696. const String& emailSubject,
  224697. const String& bodyText,
  224698. const StringArray& filesToAttach)
  224699. {
  224700. #if JUCE_IOS
  224701. //xxx probably need to use MFMailComposeViewController
  224702. jassertfalse;
  224703. return false;
  224704. #else
  224705. const ScopedAutoReleasePool pool;
  224706. String script;
  224707. script << "tell application \"Mail\"\r\n"
  224708. "set newMessage to make new outgoing message with properties {subject:\""
  224709. << emailSubject.replace ("\"", "\\\"")
  224710. << "\", content:\""
  224711. << bodyText.replace ("\"", "\\\"")
  224712. << "\" & return & return}\r\n"
  224713. "tell newMessage\r\n"
  224714. "set visible to true\r\n"
  224715. "set sender to \"sdfsdfsdfewf\"\r\n"
  224716. "make new to recipient at end of to recipients with properties {address:\""
  224717. << targetEmailAddress
  224718. << "\"}\r\n";
  224719. for (int i = 0; i < filesToAttach.size(); ++i)
  224720. {
  224721. script << "tell content\r\n"
  224722. "make new attachment with properties {file name:\""
  224723. << filesToAttach[i].replace ("\"", "\\\"")
  224724. << "\"} at after the last paragraph\r\n"
  224725. "end tell\r\n";
  224726. }
  224727. script << "end tell\r\n"
  224728. "end tell\r\n";
  224729. NSAppleScript* s = [[NSAppleScript alloc]
  224730. initWithSource: juceStringToNS (script)];
  224731. NSDictionary* error = 0;
  224732. const bool ok = [s executeAndReturnError: &error] != nil;
  224733. [s release];
  224734. return ok;
  224735. #endif
  224736. }
  224737. END_JUCE_NAMESPACE
  224738. using namespace JUCE_NAMESPACE;
  224739. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224740. @interface JuceURLConnection : NSObject
  224741. {
  224742. @public
  224743. NSURLRequest* request;
  224744. NSURLConnection* connection;
  224745. NSMutableData* data;
  224746. Thread* runLoopThread;
  224747. bool initialised, hasFailed, hasFinished;
  224748. int position;
  224749. int64 contentLength;
  224750. NSDictionary* headers;
  224751. NSLock* dataLock;
  224752. }
  224753. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224754. - (void) dealloc;
  224755. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224756. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224757. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224758. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224759. - (BOOL) isOpen;
  224760. - (int) read: (char*) dest numBytes: (int) num;
  224761. - (int) readPosition;
  224762. - (void) stop;
  224763. - (void) createConnection;
  224764. @end
  224765. class JuceURLConnectionMessageThread : public Thread
  224766. {
  224767. JuceURLConnection* owner;
  224768. public:
  224769. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224770. : Thread ("http connection"),
  224771. owner (owner_)
  224772. {
  224773. }
  224774. ~JuceURLConnectionMessageThread()
  224775. {
  224776. stopThread (10000);
  224777. }
  224778. void run()
  224779. {
  224780. [owner createConnection];
  224781. while (! threadShouldExit())
  224782. {
  224783. const ScopedAutoReleasePool pool;
  224784. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224785. }
  224786. }
  224787. };
  224788. @implementation JuceURLConnection
  224789. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224790. withCallback: (URL::OpenStreamProgressCallback*) callback
  224791. withContext: (void*) context;
  224792. {
  224793. [super init];
  224794. request = req;
  224795. [request retain];
  224796. data = [[NSMutableData data] retain];
  224797. dataLock = [[NSLock alloc] init];
  224798. connection = 0;
  224799. initialised = false;
  224800. hasFailed = false;
  224801. hasFinished = false;
  224802. contentLength = -1;
  224803. headers = 0;
  224804. runLoopThread = new JuceURLConnectionMessageThread (self);
  224805. runLoopThread->startThread();
  224806. while (runLoopThread->isThreadRunning() && ! initialised)
  224807. {
  224808. if (callback != 0)
  224809. callback (context, -1, (int) [[request HTTPBody] length]);
  224810. Thread::sleep (1);
  224811. }
  224812. return self;
  224813. }
  224814. - (void) dealloc
  224815. {
  224816. [self stop];
  224817. deleteAndZero (runLoopThread);
  224818. [connection release];
  224819. [data release];
  224820. [dataLock release];
  224821. [request release];
  224822. [headers release];
  224823. [super dealloc];
  224824. }
  224825. - (void) createConnection
  224826. {
  224827. NSUInteger oldRetainCount = [self retainCount];
  224828. connection = [[NSURLConnection alloc] initWithRequest: request
  224829. delegate: self];
  224830. if (oldRetainCount == [self retainCount])
  224831. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224832. if (connection == nil)
  224833. runLoopThread->signalThreadShouldExit();
  224834. }
  224835. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224836. {
  224837. (void) conn;
  224838. [dataLock lock];
  224839. [data setLength: 0];
  224840. [dataLock unlock];
  224841. initialised = true;
  224842. contentLength = [response expectedContentLength];
  224843. [headers release];
  224844. headers = 0;
  224845. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224846. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224847. }
  224848. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224849. {
  224850. (void) conn;
  224851. DBG (nsStringToJuce ([error description]));
  224852. hasFailed = true;
  224853. initialised = true;
  224854. if (runLoopThread != 0)
  224855. runLoopThread->signalThreadShouldExit();
  224856. }
  224857. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224858. {
  224859. (void) conn;
  224860. [dataLock lock];
  224861. [data appendData: newData];
  224862. [dataLock unlock];
  224863. initialised = true;
  224864. }
  224865. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224866. {
  224867. (void) conn;
  224868. hasFinished = true;
  224869. initialised = true;
  224870. if (runLoopThread != 0)
  224871. runLoopThread->signalThreadShouldExit();
  224872. }
  224873. - (BOOL) isOpen
  224874. {
  224875. return connection != 0 && ! hasFailed;
  224876. }
  224877. - (int) readPosition
  224878. {
  224879. return position;
  224880. }
  224881. - (int) read: (char*) dest numBytes: (int) numNeeded
  224882. {
  224883. int numDone = 0;
  224884. while (numNeeded > 0)
  224885. {
  224886. int available = jmin (numNeeded, (int) [data length]);
  224887. if (available > 0)
  224888. {
  224889. [dataLock lock];
  224890. [data getBytes: dest length: available];
  224891. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224892. [dataLock unlock];
  224893. numDone += available;
  224894. numNeeded -= available;
  224895. dest += available;
  224896. }
  224897. else
  224898. {
  224899. if (hasFailed || hasFinished)
  224900. break;
  224901. Thread::sleep (1);
  224902. }
  224903. }
  224904. position += numDone;
  224905. return numDone;
  224906. }
  224907. - (void) stop
  224908. {
  224909. [connection cancel];
  224910. if (runLoopThread != 0)
  224911. runLoopThread->stopThread (10000);
  224912. }
  224913. @end
  224914. BEGIN_JUCE_NAMESPACE
  224915. void* juce_openInternetFile (const String& url,
  224916. const String& headers,
  224917. const MemoryBlock& postData,
  224918. const bool isPost,
  224919. URL::OpenStreamProgressCallback* callback,
  224920. void* callbackContext,
  224921. int timeOutMs)
  224922. {
  224923. const ScopedAutoReleasePool pool;
  224924. NSMutableURLRequest* req = [NSMutableURLRequest
  224925. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224926. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224927. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224928. if (req == nil)
  224929. return 0;
  224930. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224931. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224932. StringArray headerLines;
  224933. headerLines.addLines (headers);
  224934. headerLines.removeEmptyStrings (true);
  224935. for (int i = 0; i < headerLines.size(); ++i)
  224936. {
  224937. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224938. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224939. if (key.isNotEmpty() && value.isNotEmpty())
  224940. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224941. }
  224942. if (isPost && postData.getSize() > 0)
  224943. {
  224944. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224945. length: postData.getSize()]];
  224946. }
  224947. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224948. withCallback: callback
  224949. withContext: callbackContext];
  224950. if ([s isOpen])
  224951. return s;
  224952. [s release];
  224953. return 0;
  224954. }
  224955. void juce_closeInternetFile (void* handle)
  224956. {
  224957. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224958. if (s != 0)
  224959. {
  224960. const ScopedAutoReleasePool pool;
  224961. [s stop];
  224962. [s release];
  224963. }
  224964. }
  224965. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224966. {
  224967. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224968. if (s != 0)
  224969. {
  224970. const ScopedAutoReleasePool pool;
  224971. return [s read: (char*) buffer numBytes: bytesToRead];
  224972. }
  224973. return 0;
  224974. }
  224975. int64 juce_getInternetFileContentLength (void* handle)
  224976. {
  224977. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224978. if (s != 0)
  224979. return s->contentLength;
  224980. return -1;
  224981. }
  224982. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224983. {
  224984. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224985. if (s != 0 && s->headers != 0)
  224986. {
  224987. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224988. NSString* key;
  224989. while ((key = [enumerator nextObject]) != nil)
  224990. headers.set (nsStringToJuce (key),
  224991. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224992. }
  224993. }
  224994. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224995. {
  224996. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224997. if (s != 0)
  224998. return [s readPosition];
  224999. return 0;
  225000. }
  225001. #endif
  225002. /*** End of inlined file: juce_mac_Network.mm ***/
  225003. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  225004. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225005. // compiled on its own).
  225006. #if JUCE_INCLUDED_FILE
  225007. struct NamedPipeInternal
  225008. {
  225009. String pipeInName, pipeOutName;
  225010. int pipeIn, pipeOut;
  225011. bool volatile createdPipe, blocked, stopReadOperation;
  225012. static void signalHandler (int) {}
  225013. };
  225014. void NamedPipe::cancelPendingReads()
  225015. {
  225016. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  225017. {
  225018. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225019. intern->stopReadOperation = true;
  225020. char buffer [1] = { 0 };
  225021. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  225022. (void) bytesWritten;
  225023. int timeout = 2000;
  225024. while (intern->blocked && --timeout >= 0)
  225025. Thread::sleep (2);
  225026. intern->stopReadOperation = false;
  225027. }
  225028. }
  225029. void NamedPipe::close()
  225030. {
  225031. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225032. if (intern != 0)
  225033. {
  225034. internal = 0;
  225035. if (intern->pipeIn != -1)
  225036. ::close (intern->pipeIn);
  225037. if (intern->pipeOut != -1)
  225038. ::close (intern->pipeOut);
  225039. if (intern->createdPipe)
  225040. {
  225041. unlink (intern->pipeInName.toUTF8());
  225042. unlink (intern->pipeOutName.toUTF8());
  225043. }
  225044. delete intern;
  225045. }
  225046. }
  225047. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  225048. {
  225049. close();
  225050. NamedPipeInternal* const intern = new NamedPipeInternal();
  225051. internal = intern;
  225052. intern->createdPipe = createPipe;
  225053. intern->blocked = false;
  225054. intern->stopReadOperation = false;
  225055. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  225056. siginterrupt (SIGPIPE, 1);
  225057. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  225058. intern->pipeInName = pipePath + "_in";
  225059. intern->pipeOutName = pipePath + "_out";
  225060. intern->pipeIn = -1;
  225061. intern->pipeOut = -1;
  225062. if (createPipe)
  225063. {
  225064. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  225065. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  225066. {
  225067. delete intern;
  225068. internal = 0;
  225069. return false;
  225070. }
  225071. }
  225072. return true;
  225073. }
  225074. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  225075. {
  225076. int bytesRead = -1;
  225077. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225078. if (intern != 0)
  225079. {
  225080. intern->blocked = true;
  225081. if (intern->pipeIn == -1)
  225082. {
  225083. if (intern->createdPipe)
  225084. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  225085. else
  225086. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  225087. if (intern->pipeIn == -1)
  225088. {
  225089. intern->blocked = false;
  225090. return -1;
  225091. }
  225092. }
  225093. bytesRead = 0;
  225094. char* p = static_cast<char*> (destBuffer);
  225095. while (bytesRead < maxBytesToRead)
  225096. {
  225097. const int bytesThisTime = maxBytesToRead - bytesRead;
  225098. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  225099. if (numRead <= 0 || intern->stopReadOperation)
  225100. {
  225101. bytesRead = -1;
  225102. break;
  225103. }
  225104. bytesRead += numRead;
  225105. p += bytesRead;
  225106. }
  225107. intern->blocked = false;
  225108. }
  225109. return bytesRead;
  225110. }
  225111. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  225112. {
  225113. int bytesWritten = -1;
  225114. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225115. if (intern != 0)
  225116. {
  225117. if (intern->pipeOut == -1)
  225118. {
  225119. if (intern->createdPipe)
  225120. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  225121. else
  225122. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  225123. if (intern->pipeOut == -1)
  225124. {
  225125. return -1;
  225126. }
  225127. }
  225128. const char* p = static_cast<const char*> (sourceBuffer);
  225129. bytesWritten = 0;
  225130. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  225131. while (bytesWritten < numBytesToWrite
  225132. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  225133. {
  225134. const int bytesThisTime = numBytesToWrite - bytesWritten;
  225135. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  225136. if (numWritten <= 0)
  225137. {
  225138. bytesWritten = -1;
  225139. break;
  225140. }
  225141. bytesWritten += numWritten;
  225142. p += bytesWritten;
  225143. }
  225144. }
  225145. return bytesWritten;
  225146. }
  225147. #endif
  225148. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  225149. /*** Start of inlined file: juce_mac_Threads.mm ***/
  225150. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225151. // compiled on its own).
  225152. #if JUCE_INCLUDED_FILE
  225153. /*
  225154. Note that a lot of methods that you'd expect to find in this file actually
  225155. live in juce_posix_SharedCode.h!
  225156. */
  225157. bool Process::isForegroundProcess()
  225158. {
  225159. #if JUCE_MAC
  225160. return [NSApp isActive];
  225161. #else
  225162. return true; // xxx change this if more than one app is ever possible on the iPhone!
  225163. #endif
  225164. }
  225165. void Process::raisePrivilege()
  225166. {
  225167. jassertfalse;
  225168. }
  225169. void Process::lowerPrivilege()
  225170. {
  225171. jassertfalse;
  225172. }
  225173. void Process::terminate()
  225174. {
  225175. exit (0);
  225176. }
  225177. void Process::setPriority (ProcessPriority)
  225178. {
  225179. // xxx
  225180. }
  225181. #endif
  225182. /*** End of inlined file: juce_mac_Threads.mm ***/
  225183. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  225184. /*
  225185. This file contains posix routines that are common to both the Linux and Mac builds.
  225186. It gets included directly in the cpp files for these platforms.
  225187. */
  225188. CriticalSection::CriticalSection() throw()
  225189. {
  225190. pthread_mutexattr_t atts;
  225191. pthread_mutexattr_init (&atts);
  225192. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  225193. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225194. pthread_mutex_init (&internal, &atts);
  225195. }
  225196. CriticalSection::~CriticalSection() throw()
  225197. {
  225198. pthread_mutex_destroy (&internal);
  225199. }
  225200. void CriticalSection::enter() const throw()
  225201. {
  225202. pthread_mutex_lock (&internal);
  225203. }
  225204. bool CriticalSection::tryEnter() const throw()
  225205. {
  225206. return pthread_mutex_trylock (&internal) == 0;
  225207. }
  225208. void CriticalSection::exit() const throw()
  225209. {
  225210. pthread_mutex_unlock (&internal);
  225211. }
  225212. class WaitableEventImpl
  225213. {
  225214. public:
  225215. WaitableEventImpl (const bool manualReset_)
  225216. : triggered (false),
  225217. manualReset (manualReset_)
  225218. {
  225219. pthread_cond_init (&condition, 0);
  225220. pthread_mutexattr_t atts;
  225221. pthread_mutexattr_init (&atts);
  225222. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225223. pthread_mutex_init (&mutex, &atts);
  225224. }
  225225. ~WaitableEventImpl()
  225226. {
  225227. pthread_cond_destroy (&condition);
  225228. pthread_mutex_destroy (&mutex);
  225229. }
  225230. bool wait (const int timeOutMillisecs) throw()
  225231. {
  225232. pthread_mutex_lock (&mutex);
  225233. if (! triggered)
  225234. {
  225235. if (timeOutMillisecs < 0)
  225236. {
  225237. do
  225238. {
  225239. pthread_cond_wait (&condition, &mutex);
  225240. }
  225241. while (! triggered);
  225242. }
  225243. else
  225244. {
  225245. struct timeval now;
  225246. gettimeofday (&now, 0);
  225247. struct timespec time;
  225248. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225249. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225250. if (time.tv_nsec >= 1000000000)
  225251. {
  225252. time.tv_nsec -= 1000000000;
  225253. time.tv_sec++;
  225254. }
  225255. do
  225256. {
  225257. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225258. {
  225259. pthread_mutex_unlock (&mutex);
  225260. return false;
  225261. }
  225262. }
  225263. while (! triggered);
  225264. }
  225265. }
  225266. if (! manualReset)
  225267. triggered = false;
  225268. pthread_mutex_unlock (&mutex);
  225269. return true;
  225270. }
  225271. void signal() throw()
  225272. {
  225273. pthread_mutex_lock (&mutex);
  225274. triggered = true;
  225275. pthread_cond_broadcast (&condition);
  225276. pthread_mutex_unlock (&mutex);
  225277. }
  225278. void reset() throw()
  225279. {
  225280. pthread_mutex_lock (&mutex);
  225281. triggered = false;
  225282. pthread_mutex_unlock (&mutex);
  225283. }
  225284. private:
  225285. pthread_cond_t condition;
  225286. pthread_mutex_t mutex;
  225287. bool triggered;
  225288. const bool manualReset;
  225289. WaitableEventImpl (const WaitableEventImpl&);
  225290. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225291. };
  225292. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225293. : internal (new WaitableEventImpl (manualReset))
  225294. {
  225295. }
  225296. WaitableEvent::~WaitableEvent() throw()
  225297. {
  225298. delete static_cast <WaitableEventImpl*> (internal);
  225299. }
  225300. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225301. {
  225302. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225303. }
  225304. void WaitableEvent::signal() const throw()
  225305. {
  225306. static_cast <WaitableEventImpl*> (internal)->signal();
  225307. }
  225308. void WaitableEvent::reset() const throw()
  225309. {
  225310. static_cast <WaitableEventImpl*> (internal)->reset();
  225311. }
  225312. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225313. {
  225314. struct timespec time;
  225315. time.tv_sec = millisecs / 1000;
  225316. time.tv_nsec = (millisecs % 1000) * 1000000;
  225317. nanosleep (&time, 0);
  225318. }
  225319. const juce_wchar File::separator = '/';
  225320. const String File::separatorString ("/");
  225321. const File File::getCurrentWorkingDirectory()
  225322. {
  225323. HeapBlock<char> heapBuffer;
  225324. char localBuffer [1024];
  225325. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225326. int bufferSize = 4096;
  225327. while (cwd == 0 && errno == ERANGE)
  225328. {
  225329. heapBuffer.malloc (bufferSize);
  225330. cwd = getcwd (heapBuffer, bufferSize - 1);
  225331. bufferSize += 1024;
  225332. }
  225333. return File (String::fromUTF8 (cwd));
  225334. }
  225335. bool File::setAsCurrentWorkingDirectory() const
  225336. {
  225337. return chdir (getFullPathName().toUTF8()) == 0;
  225338. }
  225339. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225340. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225341. #else
  225342. typedef struct stat juce_statStruct;
  225343. #endif
  225344. static bool juce_stat (const String& fileName, juce_statStruct& info)
  225345. {
  225346. return fileName.isNotEmpty()
  225347. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225348. && (stat64 (fileName.toUTF8(), &info) == 0);
  225349. #else
  225350. && (stat (fileName.toUTF8(), &info) == 0);
  225351. #endif
  225352. }
  225353. bool File::isDirectory() const
  225354. {
  225355. juce_statStruct info;
  225356. return fullPath.isEmpty()
  225357. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225358. }
  225359. bool File::exists() const
  225360. {
  225361. juce_statStruct info;
  225362. return fullPath.isNotEmpty()
  225363. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225364. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225365. #else
  225366. && (lstat (fullPath.toUTF8(), &info) == 0);
  225367. #endif
  225368. }
  225369. bool File::existsAsFile() const
  225370. {
  225371. return exists() && ! isDirectory();
  225372. }
  225373. int64 File::getSize() const
  225374. {
  225375. juce_statStruct info;
  225376. return juce_stat (fullPath, info) ? info.st_size : 0;
  225377. }
  225378. bool File::hasWriteAccess() const
  225379. {
  225380. if (exists())
  225381. return access (fullPath.toUTF8(), W_OK) == 0;
  225382. if ((! isDirectory()) && fullPath.containsChar (separator))
  225383. return getParentDirectory().hasWriteAccess();
  225384. return false;
  225385. }
  225386. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225387. {
  225388. juce_statStruct info;
  225389. if (! juce_stat (fullPath, info))
  225390. return false;
  225391. info.st_mode &= 0777; // Just permissions
  225392. if (shouldBeReadOnly)
  225393. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225394. else
  225395. // Give everybody write permission?
  225396. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225397. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225398. }
  225399. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225400. {
  225401. modificationTime = 0;
  225402. accessTime = 0;
  225403. creationTime = 0;
  225404. juce_statStruct info;
  225405. if (juce_stat (fullPath, info))
  225406. {
  225407. modificationTime = (int64) info.st_mtime * 1000;
  225408. accessTime = (int64) info.st_atime * 1000;
  225409. creationTime = (int64) info.st_ctime * 1000;
  225410. }
  225411. }
  225412. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225413. {
  225414. struct utimbuf times;
  225415. times.actime = (time_t) (accessTime / 1000);
  225416. times.modtime = (time_t) (modificationTime / 1000);
  225417. return utime (fullPath.toUTF8(), &times) == 0;
  225418. }
  225419. bool File::deleteFile() const
  225420. {
  225421. if (! exists())
  225422. return true;
  225423. else if (isDirectory())
  225424. return rmdir (fullPath.toUTF8()) == 0;
  225425. else
  225426. return remove (fullPath.toUTF8()) == 0;
  225427. }
  225428. bool File::moveInternal (const File& dest) const
  225429. {
  225430. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225431. return true;
  225432. if (hasWriteAccess() && copyInternal (dest))
  225433. {
  225434. if (deleteFile())
  225435. return true;
  225436. dest.deleteFile();
  225437. }
  225438. return false;
  225439. }
  225440. void File::createDirectoryInternal (const String& fileName) const
  225441. {
  225442. mkdir (fileName.toUTF8(), 0777);
  225443. }
  225444. int64 juce_fileSetPosition (void* handle, int64 pos)
  225445. {
  225446. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225447. return pos;
  225448. return -1;
  225449. }
  225450. void FileInputStream::openHandle()
  225451. {
  225452. totalSize = file.getSize();
  225453. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225454. if (f != -1)
  225455. fileHandle = (void*) f;
  225456. }
  225457. void FileInputStream::closeHandle()
  225458. {
  225459. if (fileHandle != 0)
  225460. {
  225461. close ((int) (pointer_sized_int) fileHandle);
  225462. fileHandle = 0;
  225463. }
  225464. }
  225465. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225466. {
  225467. if (fileHandle != 0)
  225468. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225469. return 0;
  225470. }
  225471. void FileOutputStream::openHandle()
  225472. {
  225473. if (file.exists())
  225474. {
  225475. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225476. if (f != -1)
  225477. {
  225478. currentPosition = lseek (f, 0, SEEK_END);
  225479. if (currentPosition >= 0)
  225480. fileHandle = (void*) f;
  225481. else
  225482. close (f);
  225483. }
  225484. }
  225485. else
  225486. {
  225487. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225488. if (f != -1)
  225489. fileHandle = (void*) f;
  225490. }
  225491. }
  225492. void FileOutputStream::closeHandle()
  225493. {
  225494. if (fileHandle != 0)
  225495. {
  225496. close ((int) (pointer_sized_int) fileHandle);
  225497. fileHandle = 0;
  225498. }
  225499. }
  225500. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225501. {
  225502. if (fileHandle != 0)
  225503. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225504. return 0;
  225505. }
  225506. void FileOutputStream::flushInternal()
  225507. {
  225508. if (fileHandle != 0)
  225509. fsync ((int) (pointer_sized_int) fileHandle);
  225510. }
  225511. const File juce_getExecutableFile()
  225512. {
  225513. Dl_info exeInfo;
  225514. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225515. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225516. }
  225517. // if this file doesn't exist, find a parent of it that does..
  225518. static bool juce_doStatFS (File f, struct statfs& result)
  225519. {
  225520. for (int i = 5; --i >= 0;)
  225521. {
  225522. if (f.exists())
  225523. break;
  225524. f = f.getParentDirectory();
  225525. }
  225526. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225527. }
  225528. int64 File::getBytesFreeOnVolume() const
  225529. {
  225530. struct statfs buf;
  225531. if (juce_doStatFS (*this, buf))
  225532. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225533. return 0;
  225534. }
  225535. int64 File::getVolumeTotalSize() const
  225536. {
  225537. struct statfs buf;
  225538. if (juce_doStatFS (*this, buf))
  225539. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225540. return 0;
  225541. }
  225542. const String File::getVolumeLabel() const
  225543. {
  225544. #if JUCE_MAC
  225545. struct VolAttrBuf
  225546. {
  225547. u_int32_t length;
  225548. attrreference_t mountPointRef;
  225549. char mountPointSpace [MAXPATHLEN];
  225550. } attrBuf;
  225551. struct attrlist attrList;
  225552. zerostruct (attrList);
  225553. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225554. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225555. File f (*this);
  225556. for (;;)
  225557. {
  225558. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225559. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225560. (int) attrBuf.mountPointRef.attr_length);
  225561. const File parent (f.getParentDirectory());
  225562. if (f == parent)
  225563. break;
  225564. f = parent;
  225565. }
  225566. #endif
  225567. return String::empty;
  225568. }
  225569. int File::getVolumeSerialNumber() const
  225570. {
  225571. return 0; // xxx
  225572. }
  225573. void juce_runSystemCommand (const String& command)
  225574. {
  225575. int result = system (command.toUTF8());
  225576. (void) result;
  225577. }
  225578. const String juce_getOutputFromCommand (const String& command)
  225579. {
  225580. // slight bodge here, as we just pipe the output into a temp file and read it...
  225581. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225582. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225583. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225584. String result (tempFile.loadFileAsString());
  225585. tempFile.deleteFile();
  225586. return result;
  225587. }
  225588. class InterProcessLock::Pimpl
  225589. {
  225590. public:
  225591. Pimpl (const String& name, const int timeOutMillisecs)
  225592. : handle (0), refCount (1)
  225593. {
  225594. #if JUCE_MAC
  225595. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225596. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225597. #else
  225598. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225599. #endif
  225600. temp.create();
  225601. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225602. if (handle != 0)
  225603. {
  225604. struct flock fl;
  225605. zerostruct (fl);
  225606. fl.l_whence = SEEK_SET;
  225607. fl.l_type = F_WRLCK;
  225608. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225609. for (;;)
  225610. {
  225611. const int result = fcntl (handle, F_SETLK, &fl);
  225612. if (result >= 0)
  225613. return;
  225614. if (errno != EINTR)
  225615. {
  225616. if (timeOutMillisecs == 0
  225617. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225618. break;
  225619. Thread::sleep (10);
  225620. }
  225621. }
  225622. }
  225623. closeFile();
  225624. }
  225625. ~Pimpl()
  225626. {
  225627. closeFile();
  225628. }
  225629. void closeFile()
  225630. {
  225631. if (handle != 0)
  225632. {
  225633. struct flock fl;
  225634. zerostruct (fl);
  225635. fl.l_whence = SEEK_SET;
  225636. fl.l_type = F_UNLCK;
  225637. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225638. {}
  225639. close (handle);
  225640. handle = 0;
  225641. }
  225642. }
  225643. int handle, refCount;
  225644. };
  225645. InterProcessLock::InterProcessLock (const String& name_)
  225646. : name (name_)
  225647. {
  225648. }
  225649. InterProcessLock::~InterProcessLock()
  225650. {
  225651. }
  225652. bool InterProcessLock::enter (const int timeOutMillisecs)
  225653. {
  225654. const ScopedLock sl (lock);
  225655. if (pimpl == 0)
  225656. {
  225657. pimpl = new Pimpl (name, timeOutMillisecs);
  225658. if (pimpl->handle == 0)
  225659. pimpl = 0;
  225660. }
  225661. else
  225662. {
  225663. pimpl->refCount++;
  225664. }
  225665. return pimpl != 0;
  225666. }
  225667. void InterProcessLock::exit()
  225668. {
  225669. const ScopedLock sl (lock);
  225670. // Trying to release the lock too many times!
  225671. jassert (pimpl != 0);
  225672. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225673. pimpl = 0;
  225674. }
  225675. void JUCE_API juce_threadEntryPoint (void*);
  225676. void* threadEntryProc (void* userData)
  225677. {
  225678. JUCE_AUTORELEASEPOOL
  225679. juce_threadEntryPoint (userData);
  225680. return 0;
  225681. }
  225682. void* juce_createThread (void* userData)
  225683. {
  225684. pthread_t handle = 0;
  225685. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225686. {
  225687. pthread_detach (handle);
  225688. return (void*) handle;
  225689. }
  225690. return 0;
  225691. }
  225692. void juce_killThread (void* handle)
  225693. {
  225694. if (handle != 0)
  225695. pthread_cancel ((pthread_t) handle);
  225696. }
  225697. void juce_setCurrentThreadName (const String& /*name*/)
  225698. {
  225699. }
  225700. bool juce_setThreadPriority (void* handle, int priority)
  225701. {
  225702. struct sched_param param;
  225703. int policy;
  225704. priority = jlimit (0, 10, priority);
  225705. if (handle == 0)
  225706. handle = (void*) pthread_self();
  225707. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225708. return false;
  225709. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225710. const int minPriority = sched_get_priority_min (policy);
  225711. const int maxPriority = sched_get_priority_max (policy);
  225712. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225713. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225714. }
  225715. Thread::ThreadID Thread::getCurrentThreadId()
  225716. {
  225717. return (ThreadID) pthread_self();
  225718. }
  225719. void Thread::yield()
  225720. {
  225721. sched_yield();
  225722. }
  225723. /* Remove this macro if you're having problems compiling the cpu affinity
  225724. calls (the API for these has changed about quite a bit in various Linux
  225725. versions, and a lot of distros seem to ship with obsolete versions)
  225726. */
  225727. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225728. #define SUPPORT_AFFINITIES 1
  225729. #endif
  225730. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225731. {
  225732. #if SUPPORT_AFFINITIES
  225733. cpu_set_t affinity;
  225734. CPU_ZERO (&affinity);
  225735. for (int i = 0; i < 32; ++i)
  225736. if ((affinityMask & (1 << i)) != 0)
  225737. CPU_SET (i, &affinity);
  225738. /*
  225739. N.B. If this line causes a compile error, then you've probably not got the latest
  225740. version of glibc installed.
  225741. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225742. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225743. */
  225744. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225745. sched_yield();
  225746. #else
  225747. /* affinities aren't supported because either the appropriate header files weren't found,
  225748. or the SUPPORT_AFFINITIES macro was turned off
  225749. */
  225750. jassertfalse;
  225751. #endif
  225752. }
  225753. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225754. /*** Start of inlined file: juce_mac_Files.mm ***/
  225755. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225756. // compiled on its own).
  225757. #if JUCE_INCLUDED_FILE
  225758. /*
  225759. Note that a lot of methods that you'd expect to find in this file actually
  225760. live in juce_posix_SharedCode.h!
  225761. */
  225762. bool File::copyInternal (const File& dest) const
  225763. {
  225764. const ScopedAutoReleasePool pool;
  225765. NSFileManager* fm = [NSFileManager defaultManager];
  225766. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225767. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225768. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225769. toPath: juceStringToNS (dest.getFullPathName())
  225770. error: nil];
  225771. #else
  225772. && [fm copyPath: juceStringToNS (fullPath)
  225773. toPath: juceStringToNS (dest.getFullPathName())
  225774. handler: nil];
  225775. #endif
  225776. }
  225777. void File::findFileSystemRoots (Array<File>& destArray)
  225778. {
  225779. destArray.add (File ("/"));
  225780. }
  225781. static bool isFileOnDriveType (const File& f, const char* const* types)
  225782. {
  225783. struct statfs buf;
  225784. if (juce_doStatFS (f, buf))
  225785. {
  225786. const String type (buf.f_fstypename);
  225787. while (*types != 0)
  225788. if (type.equalsIgnoreCase (*types++))
  225789. return true;
  225790. }
  225791. return false;
  225792. }
  225793. bool File::isOnCDRomDrive() const
  225794. {
  225795. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225796. return isFileOnDriveType (*this, cdTypes);
  225797. }
  225798. bool File::isOnHardDisk() const
  225799. {
  225800. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225801. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225802. }
  225803. bool File::isOnRemovableDrive() const
  225804. {
  225805. #if JUCE_IOS
  225806. return false; // xxx is this possible?
  225807. #else
  225808. const ScopedAutoReleasePool pool;
  225809. BOOL removable = false;
  225810. [[NSWorkspace sharedWorkspace]
  225811. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225812. isRemovable: &removable
  225813. isWritable: nil
  225814. isUnmountable: nil
  225815. description: nil
  225816. type: nil];
  225817. return removable;
  225818. #endif
  225819. }
  225820. static bool juce_isHiddenFile (const String& path)
  225821. {
  225822. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225823. const ScopedAutoReleasePool pool;
  225824. NSNumber* hidden = nil;
  225825. NSError* err = nil;
  225826. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225827. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225828. && [hidden boolValue];
  225829. #else
  225830. #if JUCE_IOS
  225831. return File (path).getFileName().startsWithChar ('.');
  225832. #else
  225833. FSRef ref;
  225834. LSItemInfoRecord info;
  225835. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225836. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225837. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225838. #endif
  225839. #endif
  225840. }
  225841. bool File::isHidden() const
  225842. {
  225843. return juce_isHiddenFile (getFullPathName());
  225844. }
  225845. #if JUCE_IOS
  225846. static const String getIOSSystemLocation (NSSearchPathDirectory type)
  225847. {
  225848. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225849. objectAtIndex: 0]);
  225850. }
  225851. #endif
  225852. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225853. const File File::getSpecialLocation (const SpecialLocationType type)
  225854. {
  225855. const ScopedAutoReleasePool pool;
  225856. String resultPath;
  225857. switch (type)
  225858. {
  225859. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225860. #if JUCE_IOS
  225861. case userDocumentsDirectory: resultPath = getIOSSystemLocation (NSDocumentDirectory); break;
  225862. case userDesktopDirectory: resultPath = getIOSSystemLocation (NSDesktopDirectory); break;
  225863. case tempDirectory:
  225864. {
  225865. File tmp (getIOSSystemLocation (NSCachesDirectory));
  225866. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225867. tmp.createDirectory();
  225868. return tmp.getFullPathName();
  225869. }
  225870. #else
  225871. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225872. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225873. case tempDirectory:
  225874. {
  225875. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225876. tmp.createDirectory();
  225877. return tmp.getFullPathName();
  225878. }
  225879. #endif
  225880. case userMusicDirectory: resultPath = "~/Music"; break;
  225881. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225882. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225883. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225884. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225885. case invokedExecutableFile:
  225886. if (juce_Argv0 != 0)
  225887. return File (String::fromUTF8 (juce_Argv0));
  225888. // deliberate fall-through...
  225889. case currentExecutableFile:
  225890. return juce_getExecutableFile();
  225891. case currentApplicationFile:
  225892. {
  225893. const File exe (juce_getExecutableFile());
  225894. const File parent (exe.getParentDirectory());
  225895. #if JUCE_IOS
  225896. return parent;
  225897. #else
  225898. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225899. ? parent.getParentDirectory().getParentDirectory()
  225900. : exe;
  225901. #endif
  225902. }
  225903. case hostApplicationPath:
  225904. {
  225905. unsigned int size = 8192;
  225906. HeapBlock<char> buffer;
  225907. buffer.calloc (size + 8);
  225908. _NSGetExecutablePath (buffer.getData(), &size);
  225909. return String::fromUTF8 (buffer, size);
  225910. }
  225911. default:
  225912. jassertfalse; // unknown type?
  225913. break;
  225914. }
  225915. if (resultPath.isNotEmpty())
  225916. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225917. return File::nonexistent;
  225918. }
  225919. const String File::getVersion() const
  225920. {
  225921. const ScopedAutoReleasePool pool;
  225922. String result;
  225923. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225924. if (bundle != 0)
  225925. {
  225926. NSDictionary* info = [bundle infoDictionary];
  225927. if (info != 0)
  225928. {
  225929. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225930. if (name != nil)
  225931. result = nsStringToJuce (name);
  225932. }
  225933. }
  225934. return result;
  225935. }
  225936. const File File::getLinkedTarget() const
  225937. {
  225938. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225939. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225940. #else
  225941. // (the cast here avoids a deprecation warning)
  225942. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225943. #endif
  225944. if (dest != nil)
  225945. return File (nsStringToJuce (dest));
  225946. return *this;
  225947. }
  225948. bool File::moveToTrash() const
  225949. {
  225950. if (! exists())
  225951. return true;
  225952. #if JUCE_IOS
  225953. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225954. #else
  225955. const ScopedAutoReleasePool pool;
  225956. NSString* p = juceStringToNS (getFullPathName());
  225957. return [[NSWorkspace sharedWorkspace]
  225958. performFileOperation: NSWorkspaceRecycleOperation
  225959. source: [p stringByDeletingLastPathComponent]
  225960. destination: @""
  225961. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225962. tag: nil ];
  225963. #endif
  225964. }
  225965. class DirectoryIterator::NativeIterator::Pimpl
  225966. {
  225967. public:
  225968. Pimpl (const File& directory, const String& wildCard_)
  225969. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225970. wildCard (wildCard_),
  225971. enumerator (0)
  225972. {
  225973. const ScopedAutoReleasePool pool;
  225974. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225975. wildcardUTF8 = wildCard.toUTF8();
  225976. }
  225977. ~Pimpl()
  225978. {
  225979. [enumerator release];
  225980. }
  225981. bool next (String& filenameFound,
  225982. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225983. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225984. {
  225985. const ScopedAutoReleasePool pool;
  225986. for (;;)
  225987. {
  225988. NSString* file;
  225989. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225990. return false;
  225991. [enumerator skipDescendents];
  225992. filenameFound = nsStringToJuce (file);
  225993. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225994. continue;
  225995. const String path (parentDir + filenameFound);
  225996. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225997. {
  225998. juce_statStruct info;
  225999. const bool statOk = juce_stat (path, info);
  226000. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  226001. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  226002. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  226003. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  226004. }
  226005. if (isHidden != 0)
  226006. *isHidden = juce_isHiddenFile (path);
  226007. if (isReadOnly != 0)
  226008. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  226009. return true;
  226010. }
  226011. }
  226012. private:
  226013. String parentDir, wildCard;
  226014. const char* wildcardUTF8;
  226015. NSDirectoryEnumerator* enumerator;
  226016. Pimpl (const Pimpl&);
  226017. Pimpl& operator= (const Pimpl&);
  226018. };
  226019. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  226020. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  226021. {
  226022. }
  226023. DirectoryIterator::NativeIterator::~NativeIterator()
  226024. {
  226025. }
  226026. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  226027. bool* const isDir, bool* const isHidden, int64* const fileSize,
  226028. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  226029. {
  226030. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  226031. }
  226032. bool juce_launchExecutable (const String& pathAndArguments)
  226033. {
  226034. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  226035. const int cpid = fork();
  226036. if (cpid == 0)
  226037. {
  226038. // Child process
  226039. if (execve (argv[0], (char**) argv, 0) < 0)
  226040. exit (0);
  226041. }
  226042. else
  226043. {
  226044. if (cpid < 0)
  226045. return false;
  226046. }
  226047. return true;
  226048. }
  226049. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  226050. {
  226051. #if JUCE_IOS
  226052. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  226053. #else
  226054. const ScopedAutoReleasePool pool;
  226055. if (parameters.isEmpty())
  226056. {
  226057. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  226058. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  226059. }
  226060. bool ok = false;
  226061. if (PlatformUtilities::isBundle (fileName))
  226062. {
  226063. NSMutableArray* urls = [NSMutableArray array];
  226064. StringArray docs;
  226065. docs.addTokens (parameters, true);
  226066. for (int i = 0; i < docs.size(); ++i)
  226067. [urls addObject: juceStringToNS (docs[i])];
  226068. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  226069. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  226070. options: 0
  226071. additionalEventParamDescriptor: nil
  226072. launchIdentifiers: nil];
  226073. }
  226074. else if (File (fileName).exists())
  226075. {
  226076. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  226077. }
  226078. return ok;
  226079. #endif
  226080. }
  226081. void File::revealToUser() const
  226082. {
  226083. #if ! JUCE_IOS
  226084. if (exists())
  226085. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  226086. else if (getParentDirectory().exists())
  226087. getParentDirectory().revealToUser();
  226088. #endif
  226089. }
  226090. #if ! JUCE_IOS
  226091. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  226092. {
  226093. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  226094. }
  226095. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  226096. {
  226097. char path [2048];
  226098. zerostruct (path);
  226099. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  226100. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  226101. return String::empty;
  226102. }
  226103. #endif
  226104. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  226105. {
  226106. const ScopedAutoReleasePool pool;
  226107. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  226108. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  226109. #else
  226110. // (the cast here avoids a deprecation warning)
  226111. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  226112. #endif
  226113. return [fileDict fileHFSTypeCode];
  226114. }
  226115. bool PlatformUtilities::isBundle (const String& filename)
  226116. {
  226117. #if JUCE_IOS
  226118. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  226119. #else
  226120. const ScopedAutoReleasePool pool;
  226121. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  226122. #endif
  226123. }
  226124. #endif
  226125. /*** End of inlined file: juce_mac_Files.mm ***/
  226126. #if JUCE_IOS
  226127. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  226128. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226129. // compiled on its own).
  226130. #if JUCE_INCLUDED_FILE
  226131. END_JUCE_NAMESPACE
  226132. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  226133. {
  226134. }
  226135. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  226136. - (void) applicationWillTerminate: (UIApplication*) application;
  226137. @end
  226138. @implementation JuceAppStartupDelegate
  226139. - (void) applicationDidFinishLaunching: (UIApplication*) application
  226140. {
  226141. initialiseJuce_GUI();
  226142. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  226143. exit (0);
  226144. }
  226145. - (void) applicationWillTerminate: (UIApplication*) application
  226146. {
  226147. JUCEApplication::appWillTerminateByForce();
  226148. }
  226149. @end
  226150. BEGIN_JUCE_NAMESPACE
  226151. int juce_iOSMain (int argc, const char* argv[])
  226152. {
  226153. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  226154. }
  226155. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226156. {
  226157. pool = [[NSAutoreleasePool alloc] init];
  226158. }
  226159. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226160. {
  226161. [((NSAutoreleasePool*) pool) release];
  226162. }
  226163. void PlatformUtilities::beep()
  226164. {
  226165. //xxx
  226166. //AudioServicesPlaySystemSound ();
  226167. }
  226168. void PlatformUtilities::addItemToDock (const File& file)
  226169. {
  226170. }
  226171. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226172. END_JUCE_NAMESPACE
  226173. @interface JuceAlertBoxDelegate : NSObject
  226174. {
  226175. @public
  226176. bool clickedOk;
  226177. }
  226178. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  226179. @end
  226180. @implementation JuceAlertBoxDelegate
  226181. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  226182. {
  226183. clickedOk = (buttonIndex == 0);
  226184. alertView.hidden = true;
  226185. }
  226186. @end
  226187. BEGIN_JUCE_NAMESPACE
  226188. // (This function is used directly by other bits of code)
  226189. bool juce_iPhoneShowModalAlert (const String& title,
  226190. const String& bodyText,
  226191. NSString* okButtonText,
  226192. NSString* cancelButtonText)
  226193. {
  226194. const ScopedAutoReleasePool pool;
  226195. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  226196. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  226197. message: juceStringToNS (bodyText)
  226198. delegate: callback
  226199. cancelButtonTitle: okButtonText
  226200. otherButtonTitles: cancelButtonText, nil];
  226201. [alert retain];
  226202. [alert show];
  226203. while (! alert.hidden && alert.superview != nil)
  226204. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  226205. const bool result = callback->clickedOk;
  226206. [alert release];
  226207. [callback release];
  226208. return result;
  226209. }
  226210. bool AlertWindow::showNativeDialogBox (const String& title,
  226211. const String& bodyText,
  226212. bool isOkCancel)
  226213. {
  226214. return juce_iPhoneShowModalAlert (title, bodyText,
  226215. @"OK",
  226216. isOkCancel ? @"Cancel" : nil);
  226217. }
  226218. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  226219. {
  226220. jassertfalse; // no such thing on the iphone!
  226221. return false;
  226222. }
  226223. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  226224. {
  226225. jassertfalse; // no such thing on the iphone!
  226226. return false;
  226227. }
  226228. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226229. {
  226230. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  226231. }
  226232. bool Desktop::isScreenSaverEnabled()
  226233. {
  226234. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  226235. }
  226236. #endif
  226237. #endif
  226238. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  226239. #else
  226240. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  226241. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226242. // compiled on its own).
  226243. #if JUCE_INCLUDED_FILE
  226244. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226245. {
  226246. pool = [[NSAutoreleasePool alloc] init];
  226247. }
  226248. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226249. {
  226250. [((NSAutoreleasePool*) pool) release];
  226251. }
  226252. void PlatformUtilities::beep()
  226253. {
  226254. NSBeep();
  226255. }
  226256. void PlatformUtilities::addItemToDock (const File& file)
  226257. {
  226258. // check that it's not already there...
  226259. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226260. .containsIgnoreCase (file.getFullPathName()))
  226261. {
  226262. 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>"
  226263. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226264. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226265. }
  226266. }
  226267. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226268. bool AlertWindow::showNativeDialogBox (const String& title,
  226269. const String& bodyText,
  226270. bool isOkCancel)
  226271. {
  226272. const ScopedAutoReleasePool pool;
  226273. return NSRunAlertPanel (juceStringToNS (title),
  226274. juceStringToNS (bodyText),
  226275. @"Ok",
  226276. isOkCancel ? @"Cancel" : nil,
  226277. nil) == NSAlertDefaultReturn;
  226278. }
  226279. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226280. {
  226281. if (files.size() == 0)
  226282. return false;
  226283. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226284. if (draggingSource == 0)
  226285. {
  226286. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226287. return false;
  226288. }
  226289. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226290. if (sourceComp == 0)
  226291. {
  226292. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226293. return false;
  226294. }
  226295. const ScopedAutoReleasePool pool;
  226296. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226297. if (view == 0)
  226298. return false;
  226299. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226300. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226301. owner: nil];
  226302. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226303. for (int i = 0; i < files.size(); ++i)
  226304. [filesArray addObject: juceStringToNS (files[i])];
  226305. [pboard setPropertyList: filesArray
  226306. forType: NSFilenamesPboardType];
  226307. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226308. fromView: nil];
  226309. dragPosition.x -= 16;
  226310. dragPosition.y -= 16;
  226311. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226312. at: dragPosition
  226313. offset: NSMakeSize (0, 0)
  226314. event: [[view window] currentEvent]
  226315. pasteboard: pboard
  226316. source: view
  226317. slideBack: YES];
  226318. return true;
  226319. }
  226320. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226321. {
  226322. jassertfalse; // not implemented!
  226323. return false;
  226324. }
  226325. bool Desktop::canUseSemiTransparentWindows() throw()
  226326. {
  226327. return true;
  226328. }
  226329. const Point<int> Desktop::getMousePosition()
  226330. {
  226331. const ScopedAutoReleasePool pool;
  226332. const NSPoint p ([NSEvent mouseLocation]);
  226333. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226334. }
  226335. void Desktop::setMousePosition (const Point<int>& newPosition)
  226336. {
  226337. // this rubbish needs to be done around the warp call, to avoid causing a
  226338. // bizarre glitch..
  226339. CGAssociateMouseAndMouseCursorPosition (false);
  226340. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226341. CGAssociateMouseAndMouseCursorPosition (true);
  226342. }
  226343. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  226344. {
  226345. return upright;
  226346. }
  226347. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226348. class ScreenSaverDefeater : public Timer,
  226349. public DeletedAtShutdown
  226350. {
  226351. public:
  226352. ScreenSaverDefeater()
  226353. {
  226354. startTimer (10000);
  226355. timerCallback();
  226356. }
  226357. ~ScreenSaverDefeater() {}
  226358. void timerCallback()
  226359. {
  226360. if (Process::isForegroundProcess())
  226361. UpdateSystemActivity (UsrActivity);
  226362. }
  226363. };
  226364. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226365. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226366. {
  226367. if (isEnabled)
  226368. deleteAndZero (screenSaverDefeater);
  226369. else if (screenSaverDefeater == 0)
  226370. screenSaverDefeater = new ScreenSaverDefeater();
  226371. }
  226372. bool Desktop::isScreenSaverEnabled()
  226373. {
  226374. return screenSaverDefeater == 0;
  226375. }
  226376. #else
  226377. static IOPMAssertionID screenSaverDisablerID = 0;
  226378. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226379. {
  226380. if (isEnabled)
  226381. {
  226382. if (screenSaverDisablerID != 0)
  226383. {
  226384. IOPMAssertionRelease (screenSaverDisablerID);
  226385. screenSaverDisablerID = 0;
  226386. }
  226387. }
  226388. else
  226389. {
  226390. if (screenSaverDisablerID == 0)
  226391. {
  226392. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226393. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226394. CFSTR ("Juce"), &screenSaverDisablerID);
  226395. #else
  226396. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226397. &screenSaverDisablerID);
  226398. #endif
  226399. }
  226400. }
  226401. }
  226402. bool Desktop::isScreenSaverEnabled()
  226403. {
  226404. return screenSaverDisablerID == 0;
  226405. }
  226406. #endif
  226407. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226408. {
  226409. const ScopedAutoReleasePool pool;
  226410. monitorCoords.clear();
  226411. NSArray* screens = [NSScreen screens];
  226412. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226413. for (unsigned int i = 0; i < [screens count]; ++i)
  226414. {
  226415. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226416. NSRect r = clipToWorkArea ? [s visibleFrame]
  226417. : [s frame];
  226418. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  226419. monitorCoords.add (convertToRectInt (r));
  226420. }
  226421. jassert (monitorCoords.size() > 0);
  226422. }
  226423. #endif
  226424. #endif
  226425. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226426. #endif
  226427. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226428. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226429. // compiled on its own).
  226430. #if JUCE_INCLUDED_FILE
  226431. void Logger::outputDebugString (const String& text)
  226432. {
  226433. std::cerr << text << std::endl;
  226434. }
  226435. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  226436. {
  226437. static char testResult = 0;
  226438. if (testResult == 0)
  226439. {
  226440. struct kinfo_proc info;
  226441. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226442. size_t sz = sizeof (info);
  226443. sysctl (m, 4, &info, &sz, 0, 0);
  226444. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226445. }
  226446. return testResult > 0;
  226447. }
  226448. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226449. {
  226450. return juce_isRunningUnderDebugger();
  226451. }
  226452. #endif
  226453. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226454. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226455. #if JUCE_IOS
  226456. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226457. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226458. // compiled on its own).
  226459. #if JUCE_INCLUDED_FILE
  226460. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226461. #define SUPPORT_10_4_FONTS 1
  226462. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226463. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226464. #define SUPPORT_ONLY_10_4_FONTS 1
  226465. #endif
  226466. END_JUCE_NAMESPACE
  226467. @interface NSFont (PrivateHack)
  226468. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226469. @end
  226470. BEGIN_JUCE_NAMESPACE
  226471. #endif
  226472. class MacTypeface : public Typeface
  226473. {
  226474. public:
  226475. MacTypeface (const Font& font)
  226476. : Typeface (font.getTypefaceName())
  226477. {
  226478. const ScopedAutoReleasePool pool;
  226479. renderingTransform = CGAffineTransformIdentity;
  226480. bool needsItalicTransform = false;
  226481. #if JUCE_IOS
  226482. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226483. if (font.isItalic() || font.isBold())
  226484. {
  226485. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226486. for (NSString* i in familyFonts)
  226487. {
  226488. const String fn (nsStringToJuce (i));
  226489. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226490. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226491. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226492. || afterDash.containsIgnoreCase ("italic")
  226493. || fn.endsWithIgnoreCase ("oblique")
  226494. || fn.endsWithIgnoreCase ("italic");
  226495. if (probablyBold == font.isBold()
  226496. && probablyItalic == font.isItalic())
  226497. {
  226498. fontName = i;
  226499. needsItalicTransform = false;
  226500. break;
  226501. }
  226502. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226503. {
  226504. fontName = i;
  226505. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226506. }
  226507. }
  226508. if (needsItalicTransform)
  226509. renderingTransform.c = 0.15f;
  226510. }
  226511. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226512. const int ascender = abs (CGFontGetAscent (fontRef));
  226513. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226514. ascent = ascender / totalHeight;
  226515. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226516. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226517. #else
  226518. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226519. if (font.isItalic())
  226520. {
  226521. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226522. toHaveTrait: NSItalicFontMask];
  226523. if (newFont == nsFont)
  226524. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226525. nsFont = newFont;
  226526. }
  226527. if (font.isBold())
  226528. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226529. [nsFont retain];
  226530. ascent = std::abs ((float) [nsFont ascender]);
  226531. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226532. ascent /= totalSize;
  226533. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226534. if (needsItalicTransform)
  226535. {
  226536. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226537. renderingTransform.c = 0.15f;
  226538. }
  226539. #if SUPPORT_ONLY_10_4_FONTS
  226540. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226541. if (atsFont == 0)
  226542. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226543. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226544. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226545. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226546. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226547. #else
  226548. #if SUPPORT_10_4_FONTS
  226549. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226550. {
  226551. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226552. if (atsFont == 0)
  226553. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226554. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226555. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226556. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226557. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226558. }
  226559. else
  226560. #endif
  226561. {
  226562. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226563. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226564. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226565. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226566. }
  226567. #endif
  226568. #endif
  226569. }
  226570. ~MacTypeface()
  226571. {
  226572. #if ! JUCE_IOS
  226573. [nsFont release];
  226574. #endif
  226575. if (fontRef != 0)
  226576. CGFontRelease (fontRef);
  226577. }
  226578. float getAscent() const
  226579. {
  226580. return ascent;
  226581. }
  226582. float getDescent() const
  226583. {
  226584. return 1.0f - ascent;
  226585. }
  226586. float getStringWidth (const String& text)
  226587. {
  226588. if (fontRef == 0 || text.isEmpty())
  226589. return 0;
  226590. const int length = text.length();
  226591. HeapBlock <CGGlyph> glyphs;
  226592. createGlyphsForString (text, length, glyphs);
  226593. float x = 0;
  226594. #if SUPPORT_ONLY_10_4_FONTS
  226595. HeapBlock <NSSize> advances (length);
  226596. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226597. for (int i = 0; i < length; ++i)
  226598. x += advances[i].width;
  226599. #else
  226600. #if SUPPORT_10_4_FONTS
  226601. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226602. {
  226603. HeapBlock <NSSize> advances (length);
  226604. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226605. for (int i = 0; i < length; ++i)
  226606. x += advances[i].width;
  226607. }
  226608. else
  226609. #endif
  226610. {
  226611. HeapBlock <int> advances (length);
  226612. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226613. for (int i = 0; i < length; ++i)
  226614. x += advances[i];
  226615. }
  226616. #endif
  226617. return x * unitsToHeightScaleFactor;
  226618. }
  226619. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226620. {
  226621. xOffsets.add (0);
  226622. if (fontRef == 0 || text.isEmpty())
  226623. return;
  226624. const int length = text.length();
  226625. HeapBlock <CGGlyph> glyphs;
  226626. createGlyphsForString (text, length, glyphs);
  226627. #if SUPPORT_ONLY_10_4_FONTS
  226628. HeapBlock <NSSize> advances (length);
  226629. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226630. int x = 0;
  226631. for (int i = 0; i < length; ++i)
  226632. {
  226633. x += advances[i].width;
  226634. xOffsets.add (x * unitsToHeightScaleFactor);
  226635. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226636. }
  226637. #else
  226638. #if SUPPORT_10_4_FONTS
  226639. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226640. {
  226641. HeapBlock <NSSize> advances (length);
  226642. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226643. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226644. float x = 0;
  226645. for (int i = 0; i < length; ++i)
  226646. {
  226647. x += advances[i].width;
  226648. xOffsets.add (x * unitsToHeightScaleFactor);
  226649. resultGlyphs.add (nsGlyphs[i]);
  226650. }
  226651. }
  226652. else
  226653. #endif
  226654. {
  226655. HeapBlock <int> advances (length);
  226656. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226657. {
  226658. int x = 0;
  226659. for (int i = 0; i < length; ++i)
  226660. {
  226661. x += advances [i];
  226662. xOffsets.add (x * unitsToHeightScaleFactor);
  226663. resultGlyphs.add (glyphs[i]);
  226664. }
  226665. }
  226666. }
  226667. #endif
  226668. }
  226669. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226670. {
  226671. #if JUCE_IOS
  226672. return false;
  226673. #else
  226674. if (nsFont == 0)
  226675. return false;
  226676. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226677. jassert (path.isEmpty());
  226678. const ScopedAutoReleasePool pool;
  226679. NSBezierPath* bez = [NSBezierPath bezierPath];
  226680. [bez moveToPoint: NSMakePoint (0, 0)];
  226681. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226682. inFont: nsFont];
  226683. for (int i = 0; i < [bez elementCount]; ++i)
  226684. {
  226685. NSPoint p[3];
  226686. switch ([bez elementAtIndex: i associatedPoints: p])
  226687. {
  226688. case NSMoveToBezierPathElement:
  226689. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226690. break;
  226691. case NSLineToBezierPathElement:
  226692. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226693. break;
  226694. case NSCurveToBezierPathElement:
  226695. 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);
  226696. break;
  226697. case NSClosePathBezierPathElement:
  226698. path.closeSubPath();
  226699. break;
  226700. default:
  226701. jassertfalse;
  226702. break;
  226703. }
  226704. }
  226705. path.applyTransform (pathTransform);
  226706. return true;
  226707. #endif
  226708. }
  226709. juce_UseDebuggingNewOperator
  226710. CGFontRef fontRef;
  226711. float fontHeightToCGSizeFactor;
  226712. CGAffineTransform renderingTransform;
  226713. private:
  226714. float ascent, unitsToHeightScaleFactor;
  226715. #if JUCE_IOS
  226716. #else
  226717. NSFont* nsFont;
  226718. AffineTransform pathTransform;
  226719. #endif
  226720. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226721. {
  226722. #if SUPPORT_10_4_FONTS
  226723. #if ! SUPPORT_ONLY_10_4_FONTS
  226724. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226725. #endif
  226726. {
  226727. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226728. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226729. for (int i = 0; i < length; ++i)
  226730. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226731. return;
  226732. }
  226733. #endif
  226734. #if ! SUPPORT_ONLY_10_4_FONTS
  226735. if (charToGlyphMapper == 0)
  226736. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226737. glyphs.malloc (length);
  226738. for (int i = 0; i < length; ++i)
  226739. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226740. #endif
  226741. }
  226742. #if ! SUPPORT_ONLY_10_4_FONTS
  226743. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226744. class CharToGlyphMapper
  226745. {
  226746. public:
  226747. CharToGlyphMapper (CGFontRef fontRef)
  226748. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226749. idRangeOffset (0), glyphIndexes (0)
  226750. {
  226751. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226752. if (cmapTable != 0)
  226753. {
  226754. const int numSubtables = getValue16 (cmapTable, 2);
  226755. for (int i = 0; i < numSubtables; ++i)
  226756. {
  226757. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226758. {
  226759. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226760. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226761. {
  226762. const int length = getValue16 (cmapTable, offset + 2);
  226763. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226764. segCount = segCountX2 / 2;
  226765. const int endCodeOffset = offset + 14;
  226766. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226767. const int idDeltaOffset = startCodeOffset + segCountX2;
  226768. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226769. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226770. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226771. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226772. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226773. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226774. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226775. }
  226776. break;
  226777. }
  226778. }
  226779. CFRelease (cmapTable);
  226780. }
  226781. }
  226782. ~CharToGlyphMapper()
  226783. {
  226784. if (endCode != 0)
  226785. {
  226786. CFRelease (endCode);
  226787. CFRelease (startCode);
  226788. CFRelease (idDelta);
  226789. CFRelease (idRangeOffset);
  226790. CFRelease (glyphIndexes);
  226791. }
  226792. }
  226793. int getGlyphForCharacter (const juce_wchar c) const
  226794. {
  226795. for (int i = 0; i < segCount; ++i)
  226796. {
  226797. if (getValue16 (endCode, i * 2) >= c)
  226798. {
  226799. const int start = getValue16 (startCode, i * 2);
  226800. if (start > c)
  226801. break;
  226802. const int delta = getValue16 (idDelta, i * 2);
  226803. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226804. if (rangeOffset == 0)
  226805. return delta + c;
  226806. else
  226807. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226808. }
  226809. }
  226810. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226811. return jmax (-1, (int) c - 29);
  226812. }
  226813. private:
  226814. int segCount;
  226815. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226816. static uint16 getValue16 (CFDataRef data, const int index)
  226817. {
  226818. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226819. }
  226820. static uint32 getValue32 (CFDataRef data, const int index)
  226821. {
  226822. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226823. }
  226824. };
  226825. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226826. #endif
  226827. MacTypeface (const MacTypeface&);
  226828. MacTypeface& operator= (const MacTypeface&);
  226829. };
  226830. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226831. {
  226832. return new MacTypeface (font);
  226833. }
  226834. const StringArray Font::findAllTypefaceNames()
  226835. {
  226836. StringArray names;
  226837. const ScopedAutoReleasePool pool;
  226838. #if JUCE_IOS
  226839. NSArray* fonts = [UIFont familyNames];
  226840. #else
  226841. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226842. #endif
  226843. for (unsigned int i = 0; i < [fonts count]; ++i)
  226844. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226845. names.sort (true);
  226846. return names;
  226847. }
  226848. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226849. {
  226850. #if JUCE_IOS
  226851. defaultSans = "Helvetica";
  226852. defaultSerif = "Times New Roman";
  226853. defaultFixed = "Courier New";
  226854. #else
  226855. defaultSans = "Lucida Grande";
  226856. defaultSerif = "Times New Roman";
  226857. defaultFixed = "Monaco";
  226858. #endif
  226859. }
  226860. #endif
  226861. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226862. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226863. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226864. // compiled on its own).
  226865. #if JUCE_INCLUDED_FILE
  226866. class CoreGraphicsImage : public Image::SharedImage
  226867. {
  226868. public:
  226869. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226870. : Image::SharedImage (format_, width_, height_)
  226871. {
  226872. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226873. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226874. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226875. imageData = imageDataAllocated;
  226876. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226877. : CGColorSpaceCreateDeviceRGB();
  226878. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226879. colourSpace, getCGImageFlags (format_));
  226880. CGColorSpaceRelease (colourSpace);
  226881. }
  226882. ~CoreGraphicsImage()
  226883. {
  226884. CGContextRelease (context);
  226885. }
  226886. Image::ImageType getType() const { return Image::NativeImage; }
  226887. LowLevelGraphicsContext* createLowLevelContext();
  226888. SharedImage* clone()
  226889. {
  226890. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226891. memcpy (im->imageData, imageData, lineStride * height);
  226892. return im;
  226893. }
  226894. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226895. {
  226896. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226897. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226898. {
  226899. return CGBitmapContextCreateImage (nativeImage->context);
  226900. }
  226901. else
  226902. {
  226903. const Image::BitmapData srcData (juceImage, false);
  226904. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226905. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226906. 8, srcData.pixelStride * 8, srcData.lineStride,
  226907. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226908. 0, true, kCGRenderingIntentDefault);
  226909. CGDataProviderRelease (provider);
  226910. return imageRef;
  226911. }
  226912. }
  226913. #if JUCE_MAC
  226914. static NSImage* createNSImage (const Image& image)
  226915. {
  226916. const ScopedAutoReleasePool pool;
  226917. NSImage* im = [[NSImage alloc] init];
  226918. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226919. [im lockFocus];
  226920. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226921. CGImageRef imageRef = createImage (image, false, colourSpace);
  226922. CGColorSpaceRelease (colourSpace);
  226923. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226924. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226925. CGImageRelease (imageRef);
  226926. [im unlockFocus];
  226927. return im;
  226928. }
  226929. #endif
  226930. CGContextRef context;
  226931. HeapBlock<uint8> imageDataAllocated;
  226932. private:
  226933. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226934. {
  226935. #if JUCE_BIG_ENDIAN
  226936. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226937. #else
  226938. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226939. #endif
  226940. }
  226941. };
  226942. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226943. {
  226944. #if USE_COREGRAPHICS_RENDERING
  226945. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226946. #else
  226947. return createSoftwareImage (format, width, height, clearImage);
  226948. #endif
  226949. }
  226950. class CoreGraphicsContext : public LowLevelGraphicsContext
  226951. {
  226952. public:
  226953. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226954. : context (context_),
  226955. flipHeight (flipHeight_),
  226956. lastClipRectIsValid (false),
  226957. state (new SavedState()),
  226958. numGradientLookupEntries (0)
  226959. {
  226960. CGContextRetain (context);
  226961. CGContextSaveGState(context);
  226962. CGContextSetShouldSmoothFonts (context, true);
  226963. CGContextSetShouldAntialias (context, true);
  226964. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226965. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226966. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226967. gradientCallbacks.version = 0;
  226968. gradientCallbacks.evaluate = gradientCallback;
  226969. gradientCallbacks.releaseInfo = 0;
  226970. setFont (Font());
  226971. }
  226972. ~CoreGraphicsContext()
  226973. {
  226974. CGContextRestoreGState (context);
  226975. CGContextRelease (context);
  226976. CGColorSpaceRelease (rgbColourSpace);
  226977. CGColorSpaceRelease (greyColourSpace);
  226978. }
  226979. bool isVectorDevice() const { return false; }
  226980. void setOrigin (int x, int y)
  226981. {
  226982. CGContextTranslateCTM (context, x, -y);
  226983. if (lastClipRectIsValid)
  226984. lastClipRect.translate (-x, -y);
  226985. }
  226986. bool clipToRectangle (const Rectangle<int>& r)
  226987. {
  226988. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226989. if (lastClipRectIsValid)
  226990. {
  226991. // This is actually incorrect, because the actual clip region may be complex, and
  226992. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226993. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226994. // when calculating the resultant clip bounds, and makes the same mistake!
  226995. lastClipRect = lastClipRect.getIntersection (r);
  226996. return ! lastClipRect.isEmpty();
  226997. }
  226998. return ! isClipEmpty();
  226999. }
  227000. bool clipToRectangleList (const RectangleList& clipRegion)
  227001. {
  227002. if (clipRegion.isEmpty())
  227003. {
  227004. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  227005. lastClipRectIsValid = true;
  227006. lastClipRect = Rectangle<int>();
  227007. return false;
  227008. }
  227009. else
  227010. {
  227011. const int numRects = clipRegion.getNumRectangles();
  227012. HeapBlock <CGRect> rects (numRects);
  227013. for (int i = 0; i < numRects; ++i)
  227014. {
  227015. const Rectangle<int>& r = clipRegion.getRectangle(i);
  227016. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  227017. }
  227018. CGContextClipToRects (context, rects, numRects);
  227019. lastClipRectIsValid = false;
  227020. return ! isClipEmpty();
  227021. }
  227022. }
  227023. void excludeClipRectangle (const Rectangle<int>& r)
  227024. {
  227025. RectangleList remaining (getClipBounds());
  227026. remaining.subtract (r);
  227027. clipToRectangleList (remaining);
  227028. lastClipRectIsValid = false;
  227029. }
  227030. void clipToPath (const Path& path, const AffineTransform& transform)
  227031. {
  227032. createPath (path, transform);
  227033. CGContextClip (context);
  227034. lastClipRectIsValid = false;
  227035. }
  227036. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  227037. {
  227038. if (! transform.isSingularity())
  227039. {
  227040. Image singleChannelImage (sourceImage);
  227041. if (sourceImage.getFormat() != Image::SingleChannel)
  227042. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  227043. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  227044. flip();
  227045. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  227046. applyTransform (t);
  227047. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  227048. CGContextClipToMask (context, r, image);
  227049. applyTransform (t.inverted());
  227050. flip();
  227051. CGImageRelease (image);
  227052. lastClipRectIsValid = false;
  227053. }
  227054. }
  227055. bool clipRegionIntersects (const Rectangle<int>& r)
  227056. {
  227057. return getClipBounds().intersects (r);
  227058. }
  227059. const Rectangle<int> getClipBounds() const
  227060. {
  227061. if (! lastClipRectIsValid)
  227062. {
  227063. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227064. lastClipRectIsValid = true;
  227065. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  227066. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  227067. roundToInt (bounds.size.width),
  227068. roundToInt (bounds.size.height));
  227069. }
  227070. return lastClipRect;
  227071. }
  227072. bool isClipEmpty() const
  227073. {
  227074. return getClipBounds().isEmpty();
  227075. }
  227076. void saveState()
  227077. {
  227078. CGContextSaveGState (context);
  227079. stateStack.add (new SavedState (*state));
  227080. }
  227081. void restoreState()
  227082. {
  227083. CGContextRestoreGState (context);
  227084. SavedState* const top = stateStack.getLast();
  227085. if (top != 0)
  227086. {
  227087. state = top;
  227088. stateStack.removeLast (1, false);
  227089. lastClipRectIsValid = false;
  227090. }
  227091. else
  227092. {
  227093. jassertfalse; // trying to pop with an empty stack!
  227094. }
  227095. }
  227096. void setFill (const FillType& fillType)
  227097. {
  227098. state->fillType = fillType;
  227099. if (fillType.isColour())
  227100. {
  227101. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  227102. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  227103. CGContextSetAlpha (context, 1.0f);
  227104. }
  227105. }
  227106. void setOpacity (float newOpacity)
  227107. {
  227108. state->fillType.setOpacity (newOpacity);
  227109. setFill (state->fillType);
  227110. }
  227111. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  227112. {
  227113. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  227114. ? kCGInterpolationLow
  227115. : kCGInterpolationHigh);
  227116. }
  227117. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  227118. {
  227119. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  227120. }
  227121. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  227122. {
  227123. if (replaceExistingContents)
  227124. {
  227125. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  227126. CGContextClearRect (context, cgRect);
  227127. #else
  227128. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227129. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  227130. CGContextClearRect (context, cgRect);
  227131. else
  227132. #endif
  227133. CGContextSetBlendMode (context, kCGBlendModeCopy);
  227134. #endif
  227135. fillCGRect (cgRect, false);
  227136. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227137. }
  227138. else
  227139. {
  227140. if (state->fillType.isColour())
  227141. {
  227142. CGContextFillRect (context, cgRect);
  227143. }
  227144. else if (state->fillType.isGradient())
  227145. {
  227146. CGContextSaveGState (context);
  227147. CGContextClipToRect (context, cgRect);
  227148. drawGradient();
  227149. CGContextRestoreGState (context);
  227150. }
  227151. else
  227152. {
  227153. CGContextSaveGState (context);
  227154. CGContextClipToRect (context, cgRect);
  227155. drawImage (state->fillType.image, state->fillType.transform, true);
  227156. CGContextRestoreGState (context);
  227157. }
  227158. }
  227159. }
  227160. void fillPath (const Path& path, const AffineTransform& transform)
  227161. {
  227162. CGContextSaveGState (context);
  227163. if (state->fillType.isColour())
  227164. {
  227165. flip();
  227166. applyTransform (transform);
  227167. createPath (path);
  227168. if (path.isUsingNonZeroWinding())
  227169. CGContextFillPath (context);
  227170. else
  227171. CGContextEOFillPath (context);
  227172. }
  227173. else
  227174. {
  227175. createPath (path, transform);
  227176. if (path.isUsingNonZeroWinding())
  227177. CGContextClip (context);
  227178. else
  227179. CGContextEOClip (context);
  227180. if (state->fillType.isGradient())
  227181. drawGradient();
  227182. else
  227183. drawImage (state->fillType.image, state->fillType.transform, true);
  227184. }
  227185. CGContextRestoreGState (context);
  227186. }
  227187. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227188. {
  227189. const int iw = sourceImage.getWidth();
  227190. const int ih = sourceImage.getHeight();
  227191. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227192. CGContextSaveGState (context);
  227193. CGContextSetAlpha (context, state->fillType.getOpacity());
  227194. flip();
  227195. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  227196. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  227197. if (fillEntireClipAsTiles)
  227198. {
  227199. #if JUCE_IOS
  227200. CGContextDrawTiledImage (context, imageRect, image);
  227201. #else
  227202. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227203. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227204. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227205. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227206. CGContextDrawTiledImage (context, imageRect, image);
  227207. else
  227208. #endif
  227209. {
  227210. // Fallback to manually doing a tiled fill on 10.4
  227211. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227212. int x = 0, y = 0;
  227213. while (x > clip.origin.x) x -= iw;
  227214. while (y > clip.origin.y) y -= ih;
  227215. const int right = (int) (clip.origin.x + clip.size.width);
  227216. const int bottom = (int) (clip.origin.y + clip.size.height);
  227217. while (y < bottom)
  227218. {
  227219. for (int x2 = x; x2 < right; x2 += iw)
  227220. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227221. y += ih;
  227222. }
  227223. }
  227224. #endif
  227225. }
  227226. else
  227227. {
  227228. CGContextDrawImage (context, imageRect, image);
  227229. }
  227230. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227231. CGContextRestoreGState (context);
  227232. }
  227233. void drawLine (const Line<float>& line)
  227234. {
  227235. if (state->fillType.isColour())
  227236. {
  227237. CGContextSetLineCap (context, kCGLineCapSquare);
  227238. CGContextSetLineWidth (context, 1.0f);
  227239. CGContextSetRGBStrokeColor (context,
  227240. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227241. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227242. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227243. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227244. CGContextStrokeLineSegments (context, cgLine, 1);
  227245. }
  227246. else
  227247. {
  227248. Path p;
  227249. p.addLineSegment (line, 1.0f);
  227250. fillPath (p, AffineTransform::identity);
  227251. }
  227252. }
  227253. void drawVerticalLine (const int x, float top, float bottom)
  227254. {
  227255. if (state->fillType.isColour())
  227256. {
  227257. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227258. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227259. #else
  227260. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227261. // the x co-ord slightly to trick it..
  227262. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227263. #endif
  227264. }
  227265. else
  227266. {
  227267. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227268. }
  227269. }
  227270. void drawHorizontalLine (const int y, float left, float right)
  227271. {
  227272. if (state->fillType.isColour())
  227273. {
  227274. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227275. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227276. #else
  227277. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227278. // the x co-ord slightly to trick it..
  227279. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227280. #endif
  227281. }
  227282. else
  227283. {
  227284. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227285. }
  227286. }
  227287. void setFont (const Font& newFont)
  227288. {
  227289. if (state->font != newFont)
  227290. {
  227291. state->fontRef = 0;
  227292. state->font = newFont;
  227293. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227294. if (mf != 0)
  227295. {
  227296. state->fontRef = mf->fontRef;
  227297. CGContextSetFont (context, state->fontRef);
  227298. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227299. state->fontTransform = mf->renderingTransform;
  227300. state->fontTransform.a *= state->font.getHorizontalScale();
  227301. CGContextSetTextMatrix (context, state->fontTransform);
  227302. }
  227303. }
  227304. }
  227305. const Font getFont()
  227306. {
  227307. return state->font;
  227308. }
  227309. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227310. {
  227311. if (state->fontRef != 0 && state->fillType.isColour())
  227312. {
  227313. if (transform.isOnlyTranslation())
  227314. {
  227315. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227316. CGGlyph g = glyphNumber;
  227317. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227318. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227319. }
  227320. else
  227321. {
  227322. CGContextSaveGState (context);
  227323. flip();
  227324. applyTransform (transform);
  227325. CGAffineTransform t = state->fontTransform;
  227326. t.d = -t.d;
  227327. CGContextSetTextMatrix (context, t);
  227328. CGGlyph g = glyphNumber;
  227329. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227330. CGContextRestoreGState (context);
  227331. }
  227332. }
  227333. else
  227334. {
  227335. Path p;
  227336. Font& f = state->font;
  227337. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227338. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227339. .followedBy (transform));
  227340. }
  227341. }
  227342. private:
  227343. CGContextRef context;
  227344. const CGFloat flipHeight;
  227345. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227346. CGFunctionCallbacks gradientCallbacks;
  227347. mutable Rectangle<int> lastClipRect;
  227348. mutable bool lastClipRectIsValid;
  227349. struct SavedState
  227350. {
  227351. SavedState()
  227352. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227353. {
  227354. }
  227355. SavedState (const SavedState& other)
  227356. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227357. fontTransform (other.fontTransform)
  227358. {
  227359. }
  227360. ~SavedState()
  227361. {
  227362. }
  227363. FillType fillType;
  227364. Font font;
  227365. CGFontRef fontRef;
  227366. CGAffineTransform fontTransform;
  227367. };
  227368. ScopedPointer <SavedState> state;
  227369. OwnedArray <SavedState> stateStack;
  227370. HeapBlock <PixelARGB> gradientLookupTable;
  227371. int numGradientLookupEntries;
  227372. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227373. {
  227374. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227375. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227376. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227377. colour.unpremultiply();
  227378. outData[0] = colour.getRed() / 255.0f;
  227379. outData[1] = colour.getGreen() / 255.0f;
  227380. outData[2] = colour.getBlue() / 255.0f;
  227381. outData[3] = colour.getAlpha() / 255.0f;
  227382. }
  227383. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227384. {
  227385. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227386. --numGradientLookupEntries;
  227387. CGShadingRef result = 0;
  227388. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227389. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227390. if (gradient.isRadial)
  227391. {
  227392. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227393. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227394. function, true, true);
  227395. }
  227396. else
  227397. {
  227398. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227399. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227400. function, true, true);
  227401. }
  227402. CGFunctionRelease (function);
  227403. return result;
  227404. }
  227405. void drawGradient()
  227406. {
  227407. flip();
  227408. applyTransform (state->fillType.transform);
  227409. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227410. // you draw a gradient with high quality interp enabled).
  227411. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227412. CGContextSetAlpha (context, state->fillType.getOpacity());
  227413. CGContextDrawShading (context, shading);
  227414. CGShadingRelease (shading);
  227415. }
  227416. void createPath (const Path& path) const
  227417. {
  227418. CGContextBeginPath (context);
  227419. Path::Iterator i (path);
  227420. while (i.next())
  227421. {
  227422. switch (i.elementType)
  227423. {
  227424. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227425. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227426. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227427. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227428. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227429. default: jassertfalse; break;
  227430. }
  227431. }
  227432. }
  227433. void createPath (const Path& path, const AffineTransform& transform) const
  227434. {
  227435. CGContextBeginPath (context);
  227436. Path::Iterator i (path);
  227437. while (i.next())
  227438. {
  227439. switch (i.elementType)
  227440. {
  227441. case Path::Iterator::startNewSubPath:
  227442. transform.transformPoint (i.x1, i.y1);
  227443. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227444. break;
  227445. case Path::Iterator::lineTo:
  227446. transform.transformPoint (i.x1, i.y1);
  227447. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227448. break;
  227449. case Path::Iterator::quadraticTo:
  227450. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227451. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227452. break;
  227453. case Path::Iterator::cubicTo:
  227454. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227455. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227456. break;
  227457. case Path::Iterator::closePath:
  227458. CGContextClosePath (context); break;
  227459. default:
  227460. jassertfalse;
  227461. break;
  227462. }
  227463. }
  227464. }
  227465. void flip() const
  227466. {
  227467. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227468. }
  227469. void applyTransform (const AffineTransform& transform) const
  227470. {
  227471. CGAffineTransform t;
  227472. t.a = transform.mat00;
  227473. t.b = transform.mat10;
  227474. t.c = transform.mat01;
  227475. t.d = transform.mat11;
  227476. t.tx = transform.mat02;
  227477. t.ty = transform.mat12;
  227478. CGContextConcatCTM (context, t);
  227479. }
  227480. CoreGraphicsContext (const CoreGraphicsContext&);
  227481. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227482. };
  227483. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227484. {
  227485. return new CoreGraphicsContext (context, height);
  227486. }
  227487. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227488. const Image juce_loadWithCoreImage (InputStream& input)
  227489. {
  227490. MemoryBlock data;
  227491. input.readIntoMemoryBlock (data, -1);
  227492. #if JUCE_IOS
  227493. JUCE_AUTORELEASEPOOL
  227494. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227495. length: data.getSize()
  227496. freeWhenDone: NO]];
  227497. if (image != nil)
  227498. {
  227499. CGImageRef loadedImage = image.CGImage;
  227500. #else
  227501. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227502. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227503. CGDataProviderRelease (provider);
  227504. if (imageSource != 0)
  227505. {
  227506. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227507. CFRelease (imageSource);
  227508. #endif
  227509. if (loadedImage != 0)
  227510. {
  227511. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227512. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227513. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227514. hasAlphaChan, Image::NativeImage);
  227515. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227516. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227517. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227518. CGContextFlush (cgImage->context);
  227519. #if ! JUCE_IOS
  227520. CFRelease (loadedImage);
  227521. #endif
  227522. return image;
  227523. }
  227524. }
  227525. return Image::null;
  227526. }
  227527. #endif
  227528. #endif
  227529. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227530. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227531. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227532. // compiled on its own).
  227533. #if JUCE_INCLUDED_FILE
  227534. class UIViewComponentPeer;
  227535. END_JUCE_NAMESPACE
  227536. #define JuceUIView MakeObjCClassName(JuceUIView)
  227537. @interface JuceUIView : UIView <UITextViewDelegate>
  227538. {
  227539. @public
  227540. UIViewComponentPeer* owner;
  227541. UITextView* hiddenTextView;
  227542. }
  227543. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227544. - (void) dealloc;
  227545. - (void) drawRect: (CGRect) r;
  227546. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227547. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227548. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227549. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227550. - (BOOL) becomeFirstResponder;
  227551. - (BOOL) resignFirstResponder;
  227552. - (BOOL) canBecomeFirstResponder;
  227553. - (void) asyncRepaint: (id) rect;
  227554. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227555. @end
  227556. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227557. @interface JuceUIViewController : UIViewController
  227558. {
  227559. }
  227560. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227561. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227562. @end
  227563. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227564. @interface JuceUIWindow : UIWindow
  227565. {
  227566. @private
  227567. UIViewComponentPeer* owner;
  227568. bool isZooming;
  227569. }
  227570. - (void) setOwner: (UIViewComponentPeer*) owner;
  227571. - (void) becomeKeyWindow;
  227572. @end
  227573. BEGIN_JUCE_NAMESPACE
  227574. class UIViewComponentPeer : public ComponentPeer,
  227575. public FocusChangeListener
  227576. {
  227577. public:
  227578. UIViewComponentPeer (Component* const component,
  227579. const int windowStyleFlags,
  227580. UIView* viewToAttachTo);
  227581. ~UIViewComponentPeer();
  227582. void* getNativeHandle() const;
  227583. void setVisible (bool shouldBeVisible);
  227584. void setTitle (const String& title);
  227585. void setPosition (int x, int y);
  227586. void setSize (int w, int h);
  227587. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227588. const Rectangle<int> getBounds() const;
  227589. const Rectangle<int> getBounds (const bool global) const;
  227590. const Point<int> getScreenPosition() const;
  227591. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227592. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227593. void setMinimised (bool shouldBeMinimised);
  227594. bool isMinimised() const;
  227595. void setFullScreen (bool shouldBeFullScreen);
  227596. bool isFullScreen() const;
  227597. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227598. const BorderSize getFrameSize() const;
  227599. bool setAlwaysOnTop (bool alwaysOnTop);
  227600. void toFront (bool makeActiveWindow);
  227601. void toBehind (ComponentPeer* other);
  227602. void setIcon (const Image& newIcon);
  227603. virtual void drawRect (CGRect r);
  227604. virtual bool canBecomeKeyWindow();
  227605. virtual bool windowShouldClose();
  227606. virtual void redirectMovedOrResized();
  227607. virtual CGRect constrainRect (CGRect r);
  227608. virtual void viewFocusGain();
  227609. virtual void viewFocusLoss();
  227610. bool isFocused() const;
  227611. void grabFocus();
  227612. void textInputRequired (const Point<int>& position);
  227613. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227614. void updateHiddenTextContent (TextInputTarget* target);
  227615. void globalFocusChanged (Component*);
  227616. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227617. virtual void displayRotated();
  227618. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227619. void repaint (const Rectangle<int>& area);
  227620. void performAnyPendingRepaintsNow();
  227621. juce_UseDebuggingNewOperator
  227622. UIWindow* window;
  227623. JuceUIView* view;
  227624. JuceUIViewController* controller;
  227625. bool isSharedWindow, fullScreen, insideDrawRect;
  227626. static ModifierKeys currentModifiers;
  227627. static int64 getMouseTime (UIEvent* e)
  227628. {
  227629. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227630. + (int64) ([e timestamp] * 1000.0);
  227631. }
  227632. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227633. {
  227634. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227635. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227636. {
  227637. case UIInterfaceOrientationPortrait:
  227638. return r;
  227639. case UIInterfaceOrientationPortraitUpsideDown:
  227640. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227641. r.getWidth(), r.getHeight());
  227642. case UIInterfaceOrientationLandscapeLeft:
  227643. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227644. r.getHeight(), r.getWidth());
  227645. case UIInterfaceOrientationLandscapeRight:
  227646. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227647. r.getHeight(), r.getWidth());
  227648. default: jassertfalse; // unknown orientation!
  227649. }
  227650. return r;
  227651. }
  227652. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227653. {
  227654. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227655. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227656. {
  227657. case UIInterfaceOrientationPortrait:
  227658. return r;
  227659. case UIInterfaceOrientationPortraitUpsideDown:
  227660. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227661. r.getWidth(), r.getHeight());
  227662. case UIInterfaceOrientationLandscapeLeft:
  227663. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227664. r.getHeight(), r.getWidth());
  227665. case UIInterfaceOrientationLandscapeRight:
  227666. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227667. r.getHeight(), r.getWidth());
  227668. default: jassertfalse; // unknown orientation!
  227669. }
  227670. return r;
  227671. }
  227672. Array <UITouch*> currentTouches;
  227673. };
  227674. END_JUCE_NAMESPACE
  227675. @implementation JuceUIViewController
  227676. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227677. {
  227678. JuceUIView* juceView = (JuceUIView*) [self view];
  227679. jassert (juceView != 0 && juceView->owner != 0);
  227680. return juceView->owner->shouldRotate (interfaceOrientation);
  227681. }
  227682. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227683. {
  227684. JuceUIView* juceView = (JuceUIView*) [self view];
  227685. jassert (juceView != 0 && juceView->owner != 0);
  227686. juceView->owner->displayRotated();
  227687. }
  227688. @end
  227689. @implementation JuceUIView
  227690. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227691. withFrame: (CGRect) frame
  227692. {
  227693. [super initWithFrame: frame];
  227694. owner = owner_;
  227695. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227696. [self addSubview: hiddenTextView];
  227697. hiddenTextView.delegate = self;
  227698. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227699. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227700. return self;
  227701. }
  227702. - (void) dealloc
  227703. {
  227704. [hiddenTextView removeFromSuperview];
  227705. [hiddenTextView release];
  227706. [super dealloc];
  227707. }
  227708. - (void) drawRect: (CGRect) r
  227709. {
  227710. if (owner != 0)
  227711. owner->drawRect (r);
  227712. }
  227713. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227714. {
  227715. return false;
  227716. }
  227717. ModifierKeys UIViewComponentPeer::currentModifiers;
  227718. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227719. {
  227720. return UIViewComponentPeer::currentModifiers;
  227721. }
  227722. void ModifierKeys::updateCurrentModifiers() throw()
  227723. {
  227724. currentModifiers = UIViewComponentPeer::currentModifiers;
  227725. }
  227726. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227727. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227728. {
  227729. if (owner != 0)
  227730. owner->handleTouches (event, true, false, false);
  227731. }
  227732. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227733. {
  227734. if (owner != 0)
  227735. owner->handleTouches (event, false, false, false);
  227736. }
  227737. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227738. {
  227739. if (owner != 0)
  227740. owner->handleTouches (event, false, true, false);
  227741. }
  227742. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227743. {
  227744. if (owner != 0)
  227745. owner->handleTouches (event, false, true, true);
  227746. [self touchesEnded: touches withEvent: event];
  227747. }
  227748. - (BOOL) becomeFirstResponder
  227749. {
  227750. if (owner != 0)
  227751. owner->viewFocusGain();
  227752. return true;
  227753. }
  227754. - (BOOL) resignFirstResponder
  227755. {
  227756. if (owner != 0)
  227757. owner->viewFocusLoss();
  227758. return true;
  227759. }
  227760. - (BOOL) canBecomeFirstResponder
  227761. {
  227762. return owner != 0 && owner->canBecomeKeyWindow();
  227763. }
  227764. - (void) asyncRepaint: (id) rect
  227765. {
  227766. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227767. [self setNeedsDisplayInRect: *r];
  227768. }
  227769. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227770. {
  227771. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227772. nsStringToJuce (text));
  227773. }
  227774. @end
  227775. @implementation JuceUIWindow
  227776. - (void) setOwner: (UIViewComponentPeer*) owner_
  227777. {
  227778. owner = owner_;
  227779. isZooming = false;
  227780. }
  227781. - (void) becomeKeyWindow
  227782. {
  227783. [super becomeKeyWindow];
  227784. if (owner != 0)
  227785. owner->grabFocus();
  227786. }
  227787. @end
  227788. BEGIN_JUCE_NAMESPACE
  227789. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227790. const int windowStyleFlags,
  227791. UIView* viewToAttachTo)
  227792. : ComponentPeer (component, windowStyleFlags),
  227793. window (0),
  227794. view (0), controller (0),
  227795. isSharedWindow (viewToAttachTo != 0),
  227796. fullScreen (false),
  227797. insideDrawRect (false)
  227798. {
  227799. CGRect r = convertToCGRect (component->getLocalBounds());
  227800. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227801. if (isSharedWindow)
  227802. {
  227803. window = [viewToAttachTo window];
  227804. [viewToAttachTo addSubview: view];
  227805. setVisible (component->isVisible());
  227806. }
  227807. else
  227808. {
  227809. controller = [[JuceUIViewController alloc] init];
  227810. controller.view = view;
  227811. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227812. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227813. window = [[JuceUIWindow alloc] init];
  227814. window.frame = r;
  227815. window.opaque = component->isOpaque();
  227816. view.opaque = component->isOpaque();
  227817. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227818. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227819. [((JuceUIWindow*) window) setOwner: this];
  227820. if (component->isAlwaysOnTop())
  227821. window.windowLevel = UIWindowLevelAlert;
  227822. [window addSubview: view];
  227823. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227824. view.hidden = ! component->isVisible();
  227825. window.hidden = ! component->isVisible();
  227826. view.multipleTouchEnabled = YES;
  227827. }
  227828. setTitle (component->getName());
  227829. Desktop::getInstance().addFocusChangeListener (this);
  227830. }
  227831. UIViewComponentPeer::~UIViewComponentPeer()
  227832. {
  227833. Desktop::getInstance().removeFocusChangeListener (this);
  227834. view->owner = 0;
  227835. [view removeFromSuperview];
  227836. [view release];
  227837. [controller release];
  227838. if (! isSharedWindow)
  227839. {
  227840. [((JuceUIWindow*) window) setOwner: 0];
  227841. [window release];
  227842. }
  227843. }
  227844. void* UIViewComponentPeer::getNativeHandle() const
  227845. {
  227846. return view;
  227847. }
  227848. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227849. {
  227850. view.hidden = ! shouldBeVisible;
  227851. if (! isSharedWindow)
  227852. window.hidden = ! shouldBeVisible;
  227853. }
  227854. void UIViewComponentPeer::setTitle (const String& title)
  227855. {
  227856. // xxx is this possible?
  227857. }
  227858. void UIViewComponentPeer::setPosition (int x, int y)
  227859. {
  227860. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227861. }
  227862. void UIViewComponentPeer::setSize (int w, int h)
  227863. {
  227864. setBounds (component->getX(), component->getY(), w, h, false);
  227865. }
  227866. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227867. {
  227868. fullScreen = isNowFullScreen;
  227869. w = jmax (0, w);
  227870. h = jmax (0, h);
  227871. if (isSharedWindow)
  227872. {
  227873. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227874. if ([view frame].size.width != r.size.width
  227875. || [view frame].size.height != r.size.height)
  227876. [view setNeedsDisplay];
  227877. view.frame = r;
  227878. }
  227879. else
  227880. {
  227881. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227882. window.frame = convertToCGRect (bounds);
  227883. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227884. handleMovedOrResized();
  227885. }
  227886. }
  227887. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227888. {
  227889. CGRect r = [view frame];
  227890. if (global && [view window] != 0)
  227891. {
  227892. r = [view convertRect: r toView: nil];
  227893. CGRect wr = [[view window] frame];
  227894. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227895. r.origin.x = windowBounds.getX();
  227896. r.origin.y = windowBounds.getY();
  227897. }
  227898. return convertToRectInt (r);
  227899. }
  227900. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227901. {
  227902. return getBounds (! isSharedWindow);
  227903. }
  227904. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227905. {
  227906. return getBounds (true).getPosition();
  227907. }
  227908. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227909. {
  227910. return relativePosition + getScreenPosition();
  227911. }
  227912. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227913. {
  227914. return screenPosition - getScreenPosition();
  227915. }
  227916. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227917. {
  227918. if (constrainer != 0)
  227919. {
  227920. CGRect current = [window frame];
  227921. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227922. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227923. Rectangle<int> pos (convertToRectInt (r));
  227924. Rectangle<int> original (convertToRectInt (current));
  227925. constrainer->checkBounds (pos, original,
  227926. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227927. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227928. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227929. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227930. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227931. r.origin.x = pos.getX();
  227932. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227933. r.size.width = pos.getWidth();
  227934. r.size.height = pos.getHeight();
  227935. }
  227936. return r;
  227937. }
  227938. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227939. {
  227940. }
  227941. bool UIViewComponentPeer::isMinimised() const
  227942. {
  227943. return false;
  227944. }
  227945. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227946. {
  227947. if (! isSharedWindow)
  227948. {
  227949. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227950. : lastNonFullscreenBounds);
  227951. if ((! shouldBeFullScreen) && r.isEmpty())
  227952. r = getBounds();
  227953. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227954. if (! r.isEmpty())
  227955. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227956. component->repaint();
  227957. }
  227958. }
  227959. bool UIViewComponentPeer::isFullScreen() const
  227960. {
  227961. return fullScreen;
  227962. }
  227963. static Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227964. {
  227965. switch (interfaceOrientation)
  227966. {
  227967. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227968. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227969. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227970. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227971. default: jassertfalse; // unknown orientation!
  227972. }
  227973. return Desktop::upright;
  227974. }
  227975. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227976. {
  227977. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227978. }
  227979. void UIViewComponentPeer::displayRotated()
  227980. {
  227981. const Rectangle<int> oldArea (component->getBounds());
  227982. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227983. Desktop::getInstance().refreshMonitorSizes();
  227984. if (fullScreen)
  227985. {
  227986. fullScreen = false;
  227987. setFullScreen (true);
  227988. }
  227989. else
  227990. {
  227991. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227992. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227993. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227994. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227995. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227996. setBounds ((int) (l * newDesktop.getWidth()),
  227997. (int) (t * newDesktop.getHeight()),
  227998. (int) ((r - l) * newDesktop.getWidth()),
  227999. (int) ((b - t) * newDesktop.getHeight()),
  228000. false);
  228001. }
  228002. }
  228003. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  228004. {
  228005. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  228006. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  228007. return false;
  228008. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  228009. withEvent: nil];
  228010. if (trueIfInAChildWindow)
  228011. return v != nil;
  228012. return v == view;
  228013. }
  228014. const BorderSize UIViewComponentPeer::getFrameSize() const
  228015. {
  228016. return BorderSize();
  228017. }
  228018. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  228019. {
  228020. if (! isSharedWindow)
  228021. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  228022. return true;
  228023. }
  228024. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  228025. {
  228026. if (isSharedWindow)
  228027. [[view superview] bringSubviewToFront: view];
  228028. if (window != 0 && component->isVisible())
  228029. [window makeKeyAndVisible];
  228030. }
  228031. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  228032. {
  228033. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  228034. jassert (otherPeer != 0); // wrong type of window?
  228035. if (otherPeer != 0)
  228036. {
  228037. if (isSharedWindow)
  228038. {
  228039. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  228040. }
  228041. else
  228042. {
  228043. jassertfalse; // don't know how to do this
  228044. }
  228045. }
  228046. }
  228047. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  228048. {
  228049. // to do..
  228050. }
  228051. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  228052. {
  228053. NSArray* touches = [[event touchesForView: view] allObjects];
  228054. for (unsigned int i = 0; i < [touches count]; ++i)
  228055. {
  228056. UITouch* touch = [touches objectAtIndex: i];
  228057. CGPoint p = [touch locationInView: view];
  228058. const Point<int> pos ((int) p.x, (int) p.y);
  228059. juce_lastMousePos = pos + getScreenPosition();
  228060. const int64 time = getMouseTime (event);
  228061. int touchIndex = currentTouches.indexOf (touch);
  228062. if (touchIndex < 0)
  228063. {
  228064. touchIndex = currentTouches.size();
  228065. currentTouches.add (touch);
  228066. }
  228067. if (isDown)
  228068. {
  228069. currentModifiers = currentModifiers.withoutMouseButtons();
  228070. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  228071. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  228072. }
  228073. else if (isUp)
  228074. {
  228075. currentModifiers = currentModifiers.withoutMouseButtons();
  228076. currentTouches.remove (touchIndex);
  228077. }
  228078. if (isCancel)
  228079. currentTouches.clear();
  228080. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  228081. }
  228082. }
  228083. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  228084. void UIViewComponentPeer::viewFocusGain()
  228085. {
  228086. if (currentlyFocusedPeer != this)
  228087. {
  228088. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  228089. currentlyFocusedPeer->handleFocusLoss();
  228090. currentlyFocusedPeer = this;
  228091. handleFocusGain();
  228092. }
  228093. }
  228094. void UIViewComponentPeer::viewFocusLoss()
  228095. {
  228096. if (currentlyFocusedPeer == this)
  228097. {
  228098. currentlyFocusedPeer = 0;
  228099. handleFocusLoss();
  228100. }
  228101. }
  228102. void juce_HandleProcessFocusChange()
  228103. {
  228104. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  228105. {
  228106. if (Process::isForegroundProcess())
  228107. {
  228108. currentlyFocusedPeer->handleFocusGain();
  228109. ComponentPeer::bringModalComponentToFront();
  228110. }
  228111. else
  228112. {
  228113. currentlyFocusedPeer->handleFocusLoss();
  228114. // turn kiosk mode off if we lose focus..
  228115. Desktop::getInstance().setKioskModeComponent (0);
  228116. }
  228117. }
  228118. }
  228119. bool UIViewComponentPeer::isFocused() const
  228120. {
  228121. return isSharedWindow ? this == currentlyFocusedPeer
  228122. : (window != 0 && [window isKeyWindow]);
  228123. }
  228124. void UIViewComponentPeer::grabFocus()
  228125. {
  228126. if (window != 0)
  228127. {
  228128. [window makeKeyWindow];
  228129. viewFocusGain();
  228130. }
  228131. }
  228132. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  228133. {
  228134. }
  228135. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  228136. {
  228137. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  228138. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  228139. }
  228140. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  228141. {
  228142. TextInputTarget* const target = findCurrentTextInputTarget();
  228143. if (target != 0)
  228144. {
  228145. const Range<int> currentSelection (target->getHighlightedRegion());
  228146. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  228147. if (currentSelection.isEmpty())
  228148. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  228149. target->insertTextAtCaret (text);
  228150. updateHiddenTextContent (target);
  228151. }
  228152. return NO;
  228153. }
  228154. void UIViewComponentPeer::globalFocusChanged (Component*)
  228155. {
  228156. TextInputTarget* const target = findCurrentTextInputTarget();
  228157. if (target != 0)
  228158. {
  228159. Component* comp = dynamic_cast<Component*> (target);
  228160. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  228161. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  228162. updateHiddenTextContent (target);
  228163. [view->hiddenTextView becomeFirstResponder];
  228164. }
  228165. else
  228166. {
  228167. [view->hiddenTextView resignFirstResponder];
  228168. }
  228169. }
  228170. void UIViewComponentPeer::drawRect (CGRect r)
  228171. {
  228172. if (r.size.width < 1.0f || r.size.height < 1.0f)
  228173. return;
  228174. CGContextRef cg = UIGraphicsGetCurrentContext();
  228175. if (! component->isOpaque())
  228176. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  228177. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  228178. CoreGraphicsContext g (cg, view.bounds.size.height);
  228179. insideDrawRect = true;
  228180. handlePaint (g);
  228181. insideDrawRect = false;
  228182. }
  228183. bool UIViewComponentPeer::canBecomeKeyWindow()
  228184. {
  228185. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228186. }
  228187. bool UIViewComponentPeer::windowShouldClose()
  228188. {
  228189. if (! isValidPeer (this))
  228190. return YES;
  228191. handleUserClosingWindow();
  228192. return NO;
  228193. }
  228194. void UIViewComponentPeer::redirectMovedOrResized()
  228195. {
  228196. handleMovedOrResized();
  228197. }
  228198. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228199. {
  228200. }
  228201. class AsyncRepaintMessage : public CallbackMessage
  228202. {
  228203. public:
  228204. UIViewComponentPeer* const peer;
  228205. const Rectangle<int> rect;
  228206. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228207. : peer (peer_), rect (rect_)
  228208. {
  228209. }
  228210. void messageCallback()
  228211. {
  228212. if (ComponentPeer::isValidPeer (peer))
  228213. peer->repaint (rect);
  228214. }
  228215. };
  228216. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  228217. {
  228218. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  228219. {
  228220. (new AsyncRepaintMessage (this, area))->post();
  228221. }
  228222. else
  228223. {
  228224. [view setNeedsDisplayInRect: convertToCGRect (area)];
  228225. }
  228226. }
  228227. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  228228. {
  228229. }
  228230. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228231. {
  228232. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  228233. }
  228234. const Image juce_createIconForFile (const File& file)
  228235. {
  228236. return Image::null;
  228237. }
  228238. void Desktop::createMouseInputSources()
  228239. {
  228240. for (int i = 0; i < 10; ++i)
  228241. mouseSources.add (new MouseInputSource (i, false));
  228242. }
  228243. bool Desktop::canUseSemiTransparentWindows() throw()
  228244. {
  228245. return true;
  228246. }
  228247. const Point<int> Desktop::getMousePosition()
  228248. {
  228249. return juce_lastMousePos;
  228250. }
  228251. void Desktop::setMousePosition (const Point<int>&)
  228252. {
  228253. }
  228254. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  228255. {
  228256. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  228257. }
  228258. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  228259. {
  228260. const ScopedAutoReleasePool pool;
  228261. monitorCoords.clear();
  228262. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  228263. : [[UIScreen mainScreen] bounds];
  228264. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  228265. }
  228266. const int KeyPress::spaceKey = ' ';
  228267. const int KeyPress::returnKey = 0x0d;
  228268. const int KeyPress::escapeKey = 0x1b;
  228269. const int KeyPress::backspaceKey = 0x7f;
  228270. const int KeyPress::leftKey = 0x1000;
  228271. const int KeyPress::rightKey = 0x1001;
  228272. const int KeyPress::upKey = 0x1002;
  228273. const int KeyPress::downKey = 0x1003;
  228274. const int KeyPress::pageUpKey = 0x1004;
  228275. const int KeyPress::pageDownKey = 0x1005;
  228276. const int KeyPress::endKey = 0x1006;
  228277. const int KeyPress::homeKey = 0x1007;
  228278. const int KeyPress::deleteKey = 0x1008;
  228279. const int KeyPress::insertKey = -1;
  228280. const int KeyPress::tabKey = 9;
  228281. const int KeyPress::F1Key = 0x2001;
  228282. const int KeyPress::F2Key = 0x2002;
  228283. const int KeyPress::F3Key = 0x2003;
  228284. const int KeyPress::F4Key = 0x2004;
  228285. const int KeyPress::F5Key = 0x2005;
  228286. const int KeyPress::F6Key = 0x2006;
  228287. const int KeyPress::F7Key = 0x2007;
  228288. const int KeyPress::F8Key = 0x2008;
  228289. const int KeyPress::F9Key = 0x2009;
  228290. const int KeyPress::F10Key = 0x200a;
  228291. const int KeyPress::F11Key = 0x200b;
  228292. const int KeyPress::F12Key = 0x200c;
  228293. const int KeyPress::F13Key = 0x200d;
  228294. const int KeyPress::F14Key = 0x200e;
  228295. const int KeyPress::F15Key = 0x200f;
  228296. const int KeyPress::F16Key = 0x2010;
  228297. const int KeyPress::numberPad0 = 0x30020;
  228298. const int KeyPress::numberPad1 = 0x30021;
  228299. const int KeyPress::numberPad2 = 0x30022;
  228300. const int KeyPress::numberPad3 = 0x30023;
  228301. const int KeyPress::numberPad4 = 0x30024;
  228302. const int KeyPress::numberPad5 = 0x30025;
  228303. const int KeyPress::numberPad6 = 0x30026;
  228304. const int KeyPress::numberPad7 = 0x30027;
  228305. const int KeyPress::numberPad8 = 0x30028;
  228306. const int KeyPress::numberPad9 = 0x30029;
  228307. const int KeyPress::numberPadAdd = 0x3002a;
  228308. const int KeyPress::numberPadSubtract = 0x3002b;
  228309. const int KeyPress::numberPadMultiply = 0x3002c;
  228310. const int KeyPress::numberPadDivide = 0x3002d;
  228311. const int KeyPress::numberPadSeparator = 0x3002e;
  228312. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228313. const int KeyPress::numberPadEquals = 0x30030;
  228314. const int KeyPress::numberPadDelete = 0x30031;
  228315. const int KeyPress::playKey = 0x30000;
  228316. const int KeyPress::stopKey = 0x30001;
  228317. const int KeyPress::fastForwardKey = 0x30002;
  228318. const int KeyPress::rewindKey = 0x30003;
  228319. #endif
  228320. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228321. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228322. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228323. // compiled on its own).
  228324. #if JUCE_INCLUDED_FILE
  228325. struct CallbackMessagePayload
  228326. {
  228327. MessageCallbackFunction* function;
  228328. void* parameter;
  228329. void* volatile result;
  228330. bool volatile hasBeenExecuted;
  228331. };
  228332. END_JUCE_NAMESPACE
  228333. @interface JuceCustomMessageHandler : NSObject
  228334. {
  228335. }
  228336. - (void) performCallback: (id) info;
  228337. @end
  228338. @implementation JuceCustomMessageHandler
  228339. - (void) performCallback: (id) info
  228340. {
  228341. if ([info isKindOfClass: [NSData class]])
  228342. {
  228343. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228344. if (pl != 0)
  228345. {
  228346. pl->result = (*pl->function) (pl->parameter);
  228347. pl->hasBeenExecuted = true;
  228348. }
  228349. }
  228350. else
  228351. {
  228352. jassertfalse; // should never get here!
  228353. }
  228354. }
  228355. @end
  228356. BEGIN_JUCE_NAMESPACE
  228357. void MessageManager::runDispatchLoop()
  228358. {
  228359. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228360. runDispatchLoopUntil (-1);
  228361. }
  228362. void MessageManager::stopDispatchLoop()
  228363. {
  228364. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228365. exit (0); // iPhone apps get no mercy..
  228366. }
  228367. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228368. {
  228369. const ScopedAutoReleasePool pool;
  228370. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228371. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228372. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228373. while (! quitMessagePosted)
  228374. {
  228375. const ScopedAutoReleasePool pool;
  228376. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228377. beforeDate: endDate];
  228378. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228379. break;
  228380. }
  228381. return ! quitMessagePosted;
  228382. }
  228383. static CFRunLoopRef runLoop = 0;
  228384. static CFRunLoopSourceRef runLoopSource = 0;
  228385. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228386. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228387. static void runLoopSourceCallback (void*)
  228388. {
  228389. if (pendingMessages != 0)
  228390. {
  228391. int numDispatched = 0;
  228392. do
  228393. {
  228394. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228395. if (nextMessage == 0)
  228396. return;
  228397. const ScopedAutoReleasePool pool;
  228398. MessageManager::getInstance()->deliverMessage (nextMessage);
  228399. } while (++numDispatched <= 4);
  228400. CFRunLoopSourceSignal (runLoopSource);
  228401. CFRunLoopWakeUp (runLoop);
  228402. }
  228403. }
  228404. void MessageManager::doPlatformSpecificInitialisation()
  228405. {
  228406. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228407. runLoop = CFRunLoopGetCurrent();
  228408. CFRunLoopSourceContext sourceContext;
  228409. zerostruct (sourceContext);
  228410. sourceContext.perform = runLoopSourceCallback;
  228411. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228412. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228413. if (juceCustomMessageHandler == 0)
  228414. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228415. }
  228416. void MessageManager::doPlatformSpecificShutdown()
  228417. {
  228418. CFRunLoopSourceInvalidate (runLoopSource);
  228419. CFRelease (runLoopSource);
  228420. runLoopSource = 0;
  228421. deleteAndZero (pendingMessages);
  228422. if (juceCustomMessageHandler != 0)
  228423. {
  228424. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228425. [juceCustomMessageHandler release];
  228426. juceCustomMessageHandler = 0;
  228427. }
  228428. }
  228429. bool juce_postMessageToSystemQueue (Message* message)
  228430. {
  228431. if (pendingMessages != 0)
  228432. {
  228433. pendingMessages->add (message);
  228434. CFRunLoopSourceSignal (runLoopSource);
  228435. CFRunLoopWakeUp (runLoop);
  228436. }
  228437. return true;
  228438. }
  228439. void MessageManager::broadcastMessage (const String& value)
  228440. {
  228441. }
  228442. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228443. {
  228444. if (isThisTheMessageThread())
  228445. {
  228446. return (*callback) (data);
  228447. }
  228448. else
  228449. {
  228450. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228451. // deadlock because the message manager is blocked from running, so can never
  228452. // call your function..
  228453. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228454. const ScopedAutoReleasePool pool;
  228455. CallbackMessagePayload cmp;
  228456. cmp.function = callback;
  228457. cmp.parameter = data;
  228458. cmp.result = 0;
  228459. cmp.hasBeenExecuted = false;
  228460. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228461. withObject: [NSData dataWithBytesNoCopy: &cmp
  228462. length: sizeof (cmp)
  228463. freeWhenDone: NO]
  228464. waitUntilDone: YES];
  228465. return cmp.result;
  228466. }
  228467. }
  228468. #endif
  228469. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228470. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228471. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228472. // compiled on its own).
  228473. #if JUCE_INCLUDED_FILE
  228474. #if JUCE_MAC
  228475. END_JUCE_NAMESPACE
  228476. using namespace JUCE_NAMESPACE;
  228477. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228478. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228479. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228480. #else
  228481. @interface JuceFileChooserDelegate : NSObject
  228482. #endif
  228483. {
  228484. StringArray* filters;
  228485. }
  228486. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228487. - (void) dealloc;
  228488. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228489. @end
  228490. @implementation JuceFileChooserDelegate
  228491. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228492. {
  228493. [super init];
  228494. filters = filters_;
  228495. return self;
  228496. }
  228497. - (void) dealloc
  228498. {
  228499. delete filters;
  228500. [super dealloc];
  228501. }
  228502. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228503. {
  228504. (void) sender;
  228505. const File f (nsStringToJuce (filename));
  228506. for (int i = filters->size(); --i >= 0;)
  228507. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228508. return true;
  228509. return f.isDirectory();
  228510. }
  228511. @end
  228512. BEGIN_JUCE_NAMESPACE
  228513. void FileChooser::showPlatformDialog (Array<File>& results,
  228514. const String& title,
  228515. const File& currentFileOrDirectory,
  228516. const String& filter,
  228517. bool selectsDirectory,
  228518. bool selectsFiles,
  228519. bool isSaveDialogue,
  228520. bool warnAboutOverwritingExistingFiles,
  228521. bool selectMultipleFiles,
  228522. FilePreviewComponent* extraInfoComponent)
  228523. {
  228524. const ScopedAutoReleasePool pool;
  228525. StringArray* filters = new StringArray();
  228526. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228527. filters->trim();
  228528. filters->removeEmptyStrings();
  228529. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228530. [delegate autorelease];
  228531. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228532. : [NSOpenPanel openPanel];
  228533. [panel setTitle: juceStringToNS (title)];
  228534. if (! isSaveDialogue)
  228535. {
  228536. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228537. [openPanel setCanChooseDirectories: selectsDirectory];
  228538. [openPanel setCanChooseFiles: selectsFiles];
  228539. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228540. }
  228541. [panel setDelegate: delegate];
  228542. if (isSaveDialogue || selectsDirectory)
  228543. [panel setCanCreateDirectories: YES];
  228544. String directory, filename;
  228545. if (currentFileOrDirectory.isDirectory())
  228546. {
  228547. directory = currentFileOrDirectory.getFullPathName();
  228548. }
  228549. else
  228550. {
  228551. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228552. filename = currentFileOrDirectory.getFileName();
  228553. }
  228554. if ([panel runModalForDirectory: juceStringToNS (directory)
  228555. file: juceStringToNS (filename)]
  228556. == NSOKButton)
  228557. {
  228558. if (isSaveDialogue)
  228559. {
  228560. results.add (File (nsStringToJuce ([panel filename])));
  228561. }
  228562. else
  228563. {
  228564. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228565. NSArray* urls = [openPanel filenames];
  228566. for (unsigned int i = 0; i < [urls count]; ++i)
  228567. {
  228568. NSString* f = [urls objectAtIndex: i];
  228569. results.add (File (nsStringToJuce (f)));
  228570. }
  228571. }
  228572. }
  228573. [panel setDelegate: nil];
  228574. }
  228575. #else
  228576. void FileChooser::showPlatformDialog (Array<File>& results,
  228577. const String& title,
  228578. const File& currentFileOrDirectory,
  228579. const String& filter,
  228580. bool selectsDirectory,
  228581. bool selectsFiles,
  228582. bool isSaveDialogue,
  228583. bool warnAboutOverwritingExistingFiles,
  228584. bool selectMultipleFiles,
  228585. FilePreviewComponent* extraInfoComponent)
  228586. {
  228587. const ScopedAutoReleasePool pool;
  228588. jassertfalse; //xxx to do
  228589. }
  228590. #endif
  228591. #endif
  228592. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228593. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228594. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228595. // compiled on its own).
  228596. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228597. #if JUCE_MAC
  228598. END_JUCE_NAMESPACE
  228599. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228600. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228601. {
  228602. CriticalSection* contextLock;
  228603. bool needsUpdate;
  228604. }
  228605. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228606. - (bool) makeActive;
  228607. - (void) makeInactive;
  228608. - (void) reshape;
  228609. @end
  228610. @implementation ThreadSafeNSOpenGLView
  228611. - (id) initWithFrame: (NSRect) frameRect
  228612. pixelFormat: (NSOpenGLPixelFormat*) format
  228613. {
  228614. contextLock = new CriticalSection();
  228615. self = [super initWithFrame: frameRect pixelFormat: format];
  228616. if (self != nil)
  228617. [[NSNotificationCenter defaultCenter] addObserver: self
  228618. selector: @selector (_surfaceNeedsUpdate:)
  228619. name: NSViewGlobalFrameDidChangeNotification
  228620. object: self];
  228621. return self;
  228622. }
  228623. - (void) dealloc
  228624. {
  228625. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228626. delete contextLock;
  228627. [super dealloc];
  228628. }
  228629. - (bool) makeActive
  228630. {
  228631. const ScopedLock sl (*contextLock);
  228632. if ([self openGLContext] == 0)
  228633. return false;
  228634. [[self openGLContext] makeCurrentContext];
  228635. if (needsUpdate)
  228636. {
  228637. [super update];
  228638. needsUpdate = false;
  228639. }
  228640. return true;
  228641. }
  228642. - (void) makeInactive
  228643. {
  228644. const ScopedLock sl (*contextLock);
  228645. [NSOpenGLContext clearCurrentContext];
  228646. }
  228647. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228648. {
  228649. const ScopedLock sl (*contextLock);
  228650. needsUpdate = true;
  228651. }
  228652. - (void) update
  228653. {
  228654. const ScopedLock sl (*contextLock);
  228655. needsUpdate = true;
  228656. }
  228657. - (void) reshape
  228658. {
  228659. const ScopedLock sl (*contextLock);
  228660. needsUpdate = true;
  228661. }
  228662. @end
  228663. BEGIN_JUCE_NAMESPACE
  228664. class WindowedGLContext : public OpenGLContext
  228665. {
  228666. public:
  228667. WindowedGLContext (Component* const component,
  228668. const OpenGLPixelFormat& pixelFormat_,
  228669. NSOpenGLContext* sharedContext)
  228670. : renderContext (0),
  228671. pixelFormat (pixelFormat_)
  228672. {
  228673. jassert (component != 0);
  228674. NSOpenGLPixelFormatAttribute attribs [64];
  228675. int n = 0;
  228676. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228677. attribs[n++] = NSOpenGLPFAAccelerated;
  228678. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228679. attribs[n++] = NSOpenGLPFAColorSize;
  228680. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228681. pixelFormat.greenBits,
  228682. pixelFormat.blueBits);
  228683. attribs[n++] = NSOpenGLPFAAlphaSize;
  228684. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228685. attribs[n++] = NSOpenGLPFADepthSize;
  228686. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228687. attribs[n++] = NSOpenGLPFAStencilSize;
  228688. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228689. attribs[n++] = NSOpenGLPFAAccumSize;
  228690. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228691. pixelFormat.accumulationBufferGreenBits,
  228692. pixelFormat.accumulationBufferBlueBits,
  228693. pixelFormat.accumulationBufferAlphaBits);
  228694. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228695. attribs[n++] = NSOpenGLPFASampleBuffers;
  228696. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228697. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228698. attribs[n++] = NSOpenGLPFANoRecovery;
  228699. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228700. NSOpenGLPixelFormat* format
  228701. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228702. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228703. pixelFormat: format];
  228704. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228705. shareContext: sharedContext] autorelease];
  228706. const GLint swapInterval = 1;
  228707. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228708. [view setOpenGLContext: renderContext];
  228709. [format release];
  228710. viewHolder = new NSViewComponentInternal (view, component);
  228711. }
  228712. ~WindowedGLContext()
  228713. {
  228714. deleteContext();
  228715. viewHolder = 0;
  228716. }
  228717. void deleteContext()
  228718. {
  228719. makeInactive();
  228720. [renderContext clearDrawable];
  228721. [renderContext setView: nil];
  228722. [view setOpenGLContext: nil];
  228723. renderContext = nil;
  228724. }
  228725. bool makeActive() const throw()
  228726. {
  228727. jassert (renderContext != 0);
  228728. if ([renderContext view] != view)
  228729. [renderContext setView: view];
  228730. [view makeActive];
  228731. return isActive();
  228732. }
  228733. bool makeInactive() const throw()
  228734. {
  228735. [view makeInactive];
  228736. return true;
  228737. }
  228738. bool isActive() const throw()
  228739. {
  228740. return [NSOpenGLContext currentContext] == renderContext;
  228741. }
  228742. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228743. void* getRawContext() const throw() { return renderContext; }
  228744. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228745. {
  228746. }
  228747. void swapBuffers()
  228748. {
  228749. [renderContext flushBuffer];
  228750. }
  228751. bool setSwapInterval (const int numFramesPerSwap)
  228752. {
  228753. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228754. forParameter: NSOpenGLCPSwapInterval];
  228755. return true;
  228756. }
  228757. int getSwapInterval() const
  228758. {
  228759. GLint numFrames = 0;
  228760. [renderContext getValues: &numFrames
  228761. forParameter: NSOpenGLCPSwapInterval];
  228762. return numFrames;
  228763. }
  228764. void repaint()
  228765. {
  228766. // we need to invalidate the juce view that holds this gl view, to make it
  228767. // cause a repaint callback
  228768. NSView* v = (NSView*) viewHolder->view;
  228769. NSRect r = [v frame];
  228770. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228771. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228772. // repaint message, thus never causing our paint() callback, and never repainting
  228773. // the comp. So invalidating just a little bit around the edge helps..
  228774. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228775. }
  228776. void* getNativeWindowHandle() const { return viewHolder->view; }
  228777. juce_UseDebuggingNewOperator
  228778. NSOpenGLContext* renderContext;
  228779. ThreadSafeNSOpenGLView* view;
  228780. private:
  228781. OpenGLPixelFormat pixelFormat;
  228782. ScopedPointer <NSViewComponentInternal> viewHolder;
  228783. WindowedGLContext (const WindowedGLContext&);
  228784. WindowedGLContext& operator= (const WindowedGLContext&);
  228785. };
  228786. OpenGLContext* OpenGLComponent::createContext()
  228787. {
  228788. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228789. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228790. return (c->renderContext != 0) ? c.release() : 0;
  228791. }
  228792. void* OpenGLComponent::getNativeWindowHandle() const
  228793. {
  228794. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228795. : 0;
  228796. }
  228797. void juce_glViewport (const int w, const int h)
  228798. {
  228799. glViewport (0, 0, w, h);
  228800. }
  228801. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228802. OwnedArray <OpenGLPixelFormat>& results)
  228803. {
  228804. /* GLint attribs [64];
  228805. int n = 0;
  228806. attribs[n++] = AGL_RGBA;
  228807. attribs[n++] = AGL_DOUBLEBUFFER;
  228808. attribs[n++] = AGL_ACCELERATED;
  228809. attribs[n++] = AGL_NO_RECOVERY;
  228810. attribs[n++] = AGL_NONE;
  228811. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228812. while (p != 0)
  228813. {
  228814. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228815. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228816. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228817. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228818. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228819. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228820. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228821. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228822. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228823. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228824. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228825. results.add (pf);
  228826. p = aglNextPixelFormat (p);
  228827. }*/
  228828. //jassertfalse // can't see how you do this in cocoa!
  228829. }
  228830. #else
  228831. END_JUCE_NAMESPACE
  228832. @interface JuceGLView : UIView
  228833. {
  228834. }
  228835. + (Class) layerClass;
  228836. @end
  228837. @implementation JuceGLView
  228838. + (Class) layerClass
  228839. {
  228840. return [CAEAGLLayer class];
  228841. }
  228842. @end
  228843. BEGIN_JUCE_NAMESPACE
  228844. class GLESContext : public OpenGLContext
  228845. {
  228846. public:
  228847. GLESContext (UIViewComponentPeer* peer,
  228848. Component* const component_,
  228849. const OpenGLPixelFormat& pixelFormat_,
  228850. const GLESContext* const sharedContext,
  228851. NSUInteger apiType)
  228852. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228853. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228854. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228855. {
  228856. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228857. view.opaque = YES;
  228858. view.hidden = NO;
  228859. view.backgroundColor = [UIColor blackColor];
  228860. view.userInteractionEnabled = NO;
  228861. glLayer = (CAEAGLLayer*) [view layer];
  228862. [peer->view addSubview: view];
  228863. if (sharedContext != 0)
  228864. context = [[EAGLContext alloc] initWithAPI: apiType
  228865. sharegroup: [sharedContext->context sharegroup]];
  228866. else
  228867. context = [[EAGLContext alloc] initWithAPI: apiType];
  228868. createGLBuffers();
  228869. }
  228870. ~GLESContext()
  228871. {
  228872. deleteContext();
  228873. [view removeFromSuperview];
  228874. [view release];
  228875. freeGLBuffers();
  228876. }
  228877. void deleteContext()
  228878. {
  228879. makeInactive();
  228880. [context release];
  228881. context = nil;
  228882. }
  228883. bool makeActive() const throw()
  228884. {
  228885. jassert (context != 0);
  228886. [EAGLContext setCurrentContext: context];
  228887. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228888. return true;
  228889. }
  228890. void swapBuffers()
  228891. {
  228892. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228893. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228894. }
  228895. bool makeInactive() const throw()
  228896. {
  228897. return [EAGLContext setCurrentContext: nil];
  228898. }
  228899. bool isActive() const throw()
  228900. {
  228901. return [EAGLContext currentContext] == context;
  228902. }
  228903. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228904. void* getRawContext() const throw() { return glLayer; }
  228905. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228906. {
  228907. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228908. if (lastWidth != w || lastHeight != h)
  228909. {
  228910. lastWidth = w;
  228911. lastHeight = h;
  228912. freeGLBuffers();
  228913. createGLBuffers();
  228914. }
  228915. }
  228916. bool setSwapInterval (const int numFramesPerSwap)
  228917. {
  228918. numFrames = numFramesPerSwap;
  228919. return true;
  228920. }
  228921. int getSwapInterval() const
  228922. {
  228923. return numFrames;
  228924. }
  228925. void repaint()
  228926. {
  228927. }
  228928. void createGLBuffers()
  228929. {
  228930. makeActive();
  228931. glGenFramebuffersOES (1, &frameBufferHandle);
  228932. glGenRenderbuffersOES (1, &colorBufferHandle);
  228933. glGenRenderbuffersOES (1, &depthBufferHandle);
  228934. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228935. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228936. GLint width, height;
  228937. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228938. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228939. if (useDepthBuffer)
  228940. {
  228941. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228942. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228943. }
  228944. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228945. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228946. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228947. if (useDepthBuffer)
  228948. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228949. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228950. }
  228951. void freeGLBuffers()
  228952. {
  228953. if (frameBufferHandle != 0)
  228954. {
  228955. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228956. frameBufferHandle = 0;
  228957. }
  228958. if (colorBufferHandle != 0)
  228959. {
  228960. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228961. colorBufferHandle = 0;
  228962. }
  228963. if (depthBufferHandle != 0)
  228964. {
  228965. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228966. depthBufferHandle = 0;
  228967. }
  228968. }
  228969. juce_UseDebuggingNewOperator
  228970. private:
  228971. Component::SafePointer<Component> component;
  228972. OpenGLPixelFormat pixelFormat;
  228973. JuceGLView* view;
  228974. CAEAGLLayer* glLayer;
  228975. EAGLContext* context;
  228976. bool useDepthBuffer;
  228977. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228978. int numFrames;
  228979. int lastWidth, lastHeight;
  228980. GLESContext (const GLESContext&);
  228981. GLESContext& operator= (const GLESContext&);
  228982. };
  228983. OpenGLContext* OpenGLComponent::createContext()
  228984. {
  228985. ScopedAutoReleasePool pool;
  228986. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228987. if (peer != 0)
  228988. return new GLESContext (peer, this, preferredPixelFormat,
  228989. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228990. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228991. return 0;
  228992. }
  228993. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228994. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228995. {
  228996. }
  228997. void juce_glViewport (const int w, const int h)
  228998. {
  228999. glViewport (0, 0, w, h);
  229000. }
  229001. #endif
  229002. #endif
  229003. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  229004. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  229005. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229006. // compiled on its own).
  229007. #if JUCE_INCLUDED_FILE
  229008. #if JUCE_MAC
  229009. namespace MouseCursorHelpers
  229010. {
  229011. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  229012. {
  229013. NSImage* im = CoreGraphicsImage::createNSImage (image);
  229014. NSCursor* c = [[NSCursor alloc] initWithImage: im
  229015. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  229016. [im release];
  229017. return c;
  229018. }
  229019. static void* fromWebKitFile (const char* filename, float hx, float hy)
  229020. {
  229021. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  229022. BufferedInputStream buf (&fileStream, 4096, false);
  229023. PNGImageFormat pngFormat;
  229024. Image im (pngFormat.decodeImage (buf));
  229025. if (im.isValid())
  229026. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  229027. jassertfalse;
  229028. return 0;
  229029. }
  229030. }
  229031. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  229032. {
  229033. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  229034. }
  229035. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  229036. {
  229037. const ScopedAutoReleasePool pool;
  229038. NSCursor* c = 0;
  229039. switch (type)
  229040. {
  229041. case NormalCursor: c = [NSCursor arrowCursor]; break;
  229042. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  229043. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  229044. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  229045. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  229046. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  229047. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  229048. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  229049. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  229050. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  229051. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  229052. case UpDownResizeCursor:
  229053. case TopEdgeResizeCursor:
  229054. case BottomEdgeResizeCursor:
  229055. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  229056. case TopLeftCornerResizeCursor:
  229057. case BottomRightCornerResizeCursor:
  229058. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  229059. case TopRightCornerResizeCursor:
  229060. case BottomLeftCornerResizeCursor:
  229061. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  229062. case UpDownLeftRightResizeCursor:
  229063. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  229064. default:
  229065. jassertfalse;
  229066. break;
  229067. }
  229068. [c retain];
  229069. return c;
  229070. }
  229071. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  229072. {
  229073. [((NSCursor*) cursorHandle) release];
  229074. }
  229075. void MouseCursor::showInAllWindows() const
  229076. {
  229077. showInWindow (0);
  229078. }
  229079. void MouseCursor::showInWindow (ComponentPeer*) const
  229080. {
  229081. [((NSCursor*) getHandle()) set];
  229082. }
  229083. #else
  229084. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  229085. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  229086. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  229087. void MouseCursor::showInAllWindows() const {}
  229088. void MouseCursor::showInWindow (ComponentPeer*) const {}
  229089. #endif
  229090. #endif
  229091. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  229092. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229093. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229094. // compiled on its own).
  229095. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  229096. #if JUCE_MAC
  229097. END_JUCE_NAMESPACE
  229098. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  229099. @interface DownloadClickDetector : NSObject
  229100. {
  229101. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  229102. }
  229103. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  229104. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229105. request: (NSURLRequest*) request
  229106. frame: (WebFrame*) frame
  229107. decisionListener: (id<WebPolicyDecisionListener>) listener;
  229108. @end
  229109. @implementation DownloadClickDetector
  229110. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  229111. {
  229112. [super init];
  229113. ownerComponent = ownerComponent_;
  229114. return self;
  229115. }
  229116. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229117. request: (NSURLRequest*) request
  229118. frame: (WebFrame*) frame
  229119. decisionListener: (id <WebPolicyDecisionListener>) listener
  229120. {
  229121. (void) sender;
  229122. (void) request;
  229123. (void) frame;
  229124. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  229125. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  229126. [listener use];
  229127. else
  229128. [listener ignore];
  229129. }
  229130. @end
  229131. BEGIN_JUCE_NAMESPACE
  229132. class WebBrowserComponentInternal : public NSViewComponent
  229133. {
  229134. public:
  229135. WebBrowserComponentInternal (WebBrowserComponent* owner)
  229136. {
  229137. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  229138. frameName: @""
  229139. groupName: @""];
  229140. setView (webView);
  229141. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  229142. [webView setPolicyDelegate: clickListener];
  229143. }
  229144. ~WebBrowserComponentInternal()
  229145. {
  229146. [webView setPolicyDelegate: nil];
  229147. [clickListener release];
  229148. setView (0);
  229149. }
  229150. void goToURL (const String& url,
  229151. const StringArray* headers,
  229152. const MemoryBlock* postData)
  229153. {
  229154. NSMutableURLRequest* r
  229155. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  229156. cachePolicy: NSURLRequestUseProtocolCachePolicy
  229157. timeoutInterval: 30.0];
  229158. if (postData != 0 && postData->getSize() > 0)
  229159. {
  229160. [r setHTTPMethod: @"POST"];
  229161. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  229162. length: postData->getSize()]];
  229163. }
  229164. if (headers != 0)
  229165. {
  229166. for (int i = 0; i < headers->size(); ++i)
  229167. {
  229168. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  229169. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  229170. [r setValue: juceStringToNS (headerValue)
  229171. forHTTPHeaderField: juceStringToNS (headerName)];
  229172. }
  229173. }
  229174. stop();
  229175. [[webView mainFrame] loadRequest: r];
  229176. }
  229177. void goBack()
  229178. {
  229179. [webView goBack];
  229180. }
  229181. void goForward()
  229182. {
  229183. [webView goForward];
  229184. }
  229185. void stop()
  229186. {
  229187. [webView stopLoading: nil];
  229188. }
  229189. void refresh()
  229190. {
  229191. [webView reload: nil];
  229192. }
  229193. private:
  229194. WebView* webView;
  229195. DownloadClickDetector* clickListener;
  229196. };
  229197. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229198. : browser (0),
  229199. blankPageShown (false),
  229200. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  229201. {
  229202. setOpaque (true);
  229203. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  229204. }
  229205. WebBrowserComponent::~WebBrowserComponent()
  229206. {
  229207. deleteAndZero (browser);
  229208. }
  229209. void WebBrowserComponent::goToURL (const String& url,
  229210. const StringArray* headers,
  229211. const MemoryBlock* postData)
  229212. {
  229213. lastURL = url;
  229214. lastHeaders.clear();
  229215. if (headers != 0)
  229216. lastHeaders = *headers;
  229217. lastPostData.setSize (0);
  229218. if (postData != 0)
  229219. lastPostData = *postData;
  229220. blankPageShown = false;
  229221. browser->goToURL (url, headers, postData);
  229222. }
  229223. void WebBrowserComponent::stop()
  229224. {
  229225. browser->stop();
  229226. }
  229227. void WebBrowserComponent::goBack()
  229228. {
  229229. lastURL = String::empty;
  229230. blankPageShown = false;
  229231. browser->goBack();
  229232. }
  229233. void WebBrowserComponent::goForward()
  229234. {
  229235. lastURL = String::empty;
  229236. browser->goForward();
  229237. }
  229238. void WebBrowserComponent::refresh()
  229239. {
  229240. browser->refresh();
  229241. }
  229242. void WebBrowserComponent::paint (Graphics&)
  229243. {
  229244. }
  229245. void WebBrowserComponent::checkWindowAssociation()
  229246. {
  229247. if (isShowing())
  229248. {
  229249. if (blankPageShown)
  229250. goBack();
  229251. }
  229252. else
  229253. {
  229254. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  229255. {
  229256. // when the component becomes invisible, some stuff like flash
  229257. // carries on playing audio, so we need to force it onto a blank
  229258. // page to avoid this, (and send it back when it's made visible again).
  229259. blankPageShown = true;
  229260. browser->goToURL ("about:blank", 0, 0);
  229261. }
  229262. }
  229263. }
  229264. void WebBrowserComponent::reloadLastURL()
  229265. {
  229266. if (lastURL.isNotEmpty())
  229267. {
  229268. goToURL (lastURL, &lastHeaders, &lastPostData);
  229269. lastURL = String::empty;
  229270. }
  229271. }
  229272. void WebBrowserComponent::parentHierarchyChanged()
  229273. {
  229274. checkWindowAssociation();
  229275. }
  229276. void WebBrowserComponent::resized()
  229277. {
  229278. browser->setSize (getWidth(), getHeight());
  229279. }
  229280. void WebBrowserComponent::visibilityChanged()
  229281. {
  229282. checkWindowAssociation();
  229283. }
  229284. bool WebBrowserComponent::pageAboutToLoad (const String&)
  229285. {
  229286. return true;
  229287. }
  229288. #else
  229289. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229290. {
  229291. }
  229292. WebBrowserComponent::~WebBrowserComponent()
  229293. {
  229294. }
  229295. void WebBrowserComponent::goToURL (const String& url,
  229296. const StringArray* headers,
  229297. const MemoryBlock* postData)
  229298. {
  229299. }
  229300. void WebBrowserComponent::stop()
  229301. {
  229302. }
  229303. void WebBrowserComponent::goBack()
  229304. {
  229305. }
  229306. void WebBrowserComponent::goForward()
  229307. {
  229308. }
  229309. void WebBrowserComponent::refresh()
  229310. {
  229311. }
  229312. void WebBrowserComponent::paint (Graphics& g)
  229313. {
  229314. }
  229315. void WebBrowserComponent::checkWindowAssociation()
  229316. {
  229317. }
  229318. void WebBrowserComponent::reloadLastURL()
  229319. {
  229320. }
  229321. void WebBrowserComponent::parentHierarchyChanged()
  229322. {
  229323. }
  229324. void WebBrowserComponent::resized()
  229325. {
  229326. }
  229327. void WebBrowserComponent::visibilityChanged()
  229328. {
  229329. }
  229330. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229331. {
  229332. return true;
  229333. }
  229334. #endif
  229335. #endif
  229336. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229337. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229338. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229339. // compiled on its own).
  229340. #if JUCE_INCLUDED_FILE
  229341. class IPhoneAudioIODevice : public AudioIODevice
  229342. {
  229343. public:
  229344. IPhoneAudioIODevice (const String& deviceName)
  229345. : AudioIODevice (deviceName, "Audio"),
  229346. actualBufferSize (0),
  229347. isRunning (false),
  229348. audioUnit (0),
  229349. callback (0),
  229350. floatData (1, 2)
  229351. {
  229352. numInputChannels = 2;
  229353. numOutputChannels = 2;
  229354. preferredBufferSize = 0;
  229355. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229356. updateDeviceInfo();
  229357. }
  229358. ~IPhoneAudioIODevice()
  229359. {
  229360. close();
  229361. }
  229362. const StringArray getOutputChannelNames()
  229363. {
  229364. StringArray s;
  229365. s.add ("Left");
  229366. s.add ("Right");
  229367. return s;
  229368. }
  229369. const StringArray getInputChannelNames()
  229370. {
  229371. StringArray s;
  229372. if (audioInputIsAvailable)
  229373. {
  229374. s.add ("Left");
  229375. s.add ("Right");
  229376. }
  229377. return s;
  229378. }
  229379. int getNumSampleRates()
  229380. {
  229381. return 1;
  229382. }
  229383. double getSampleRate (int index)
  229384. {
  229385. return sampleRate;
  229386. }
  229387. int getNumBufferSizesAvailable()
  229388. {
  229389. return 1;
  229390. }
  229391. int getBufferSizeSamples (int index)
  229392. {
  229393. return getDefaultBufferSize();
  229394. }
  229395. int getDefaultBufferSize()
  229396. {
  229397. return 1024;
  229398. }
  229399. const String open (const BigInteger& inputChannels,
  229400. const BigInteger& outputChannels,
  229401. double sampleRate,
  229402. int bufferSize)
  229403. {
  229404. close();
  229405. lastError = String::empty;
  229406. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229407. // xxx set up channel mapping
  229408. activeOutputChans = outputChannels;
  229409. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229410. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229411. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229412. activeInputChans = inputChannels;
  229413. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229414. numInputChannels = activeInputChans.countNumberOfSetBits();
  229415. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229416. AudioSessionSetActive (true);
  229417. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229418. : kAudioSessionCategory_MediaPlayback;
  229419. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229420. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229421. fixAudioRouteIfSetToReceiver();
  229422. updateDeviceInfo();
  229423. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229424. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229425. actualBufferSize = preferredBufferSize;
  229426. prepareFloatBuffers();
  229427. isRunning = true;
  229428. propertyChanged (0, 0, 0); // creates and starts the AU
  229429. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229430. return lastError;
  229431. }
  229432. void close()
  229433. {
  229434. if (isRunning)
  229435. {
  229436. isRunning = false;
  229437. AudioSessionSetActive (false);
  229438. if (audioUnit != 0)
  229439. {
  229440. AudioComponentInstanceDispose (audioUnit);
  229441. audioUnit = 0;
  229442. }
  229443. }
  229444. }
  229445. bool isOpen()
  229446. {
  229447. return isRunning;
  229448. }
  229449. int getCurrentBufferSizeSamples()
  229450. {
  229451. return actualBufferSize;
  229452. }
  229453. double getCurrentSampleRate()
  229454. {
  229455. return sampleRate;
  229456. }
  229457. int getCurrentBitDepth()
  229458. {
  229459. return 16;
  229460. }
  229461. const BigInteger getActiveOutputChannels() const
  229462. {
  229463. return activeOutputChans;
  229464. }
  229465. const BigInteger getActiveInputChannels() const
  229466. {
  229467. return activeInputChans;
  229468. }
  229469. int getOutputLatencyInSamples()
  229470. {
  229471. return 0; //xxx
  229472. }
  229473. int getInputLatencyInSamples()
  229474. {
  229475. return 0; //xxx
  229476. }
  229477. void start (AudioIODeviceCallback* callback_)
  229478. {
  229479. if (isRunning && callback != callback_)
  229480. {
  229481. if (callback_ != 0)
  229482. callback_->audioDeviceAboutToStart (this);
  229483. const ScopedLock sl (callbackLock);
  229484. callback = callback_;
  229485. }
  229486. }
  229487. void stop()
  229488. {
  229489. if (isRunning)
  229490. {
  229491. AudioIODeviceCallback* lastCallback;
  229492. {
  229493. const ScopedLock sl (callbackLock);
  229494. lastCallback = callback;
  229495. callback = 0;
  229496. }
  229497. if (lastCallback != 0)
  229498. lastCallback->audioDeviceStopped();
  229499. }
  229500. }
  229501. bool isPlaying()
  229502. {
  229503. return isRunning && callback != 0;
  229504. }
  229505. const String getLastError()
  229506. {
  229507. return lastError;
  229508. }
  229509. private:
  229510. CriticalSection callbackLock;
  229511. Float64 sampleRate;
  229512. int numInputChannels, numOutputChannels;
  229513. int preferredBufferSize;
  229514. int actualBufferSize;
  229515. bool isRunning;
  229516. String lastError;
  229517. AudioStreamBasicDescription format;
  229518. AudioUnit audioUnit;
  229519. UInt32 audioInputIsAvailable;
  229520. AudioIODeviceCallback* callback;
  229521. BigInteger activeOutputChans, activeInputChans;
  229522. AudioSampleBuffer floatData;
  229523. float* inputChannels[3];
  229524. float* outputChannels[3];
  229525. bool monoInputChannelNumber, monoOutputChannelNumber;
  229526. void prepareFloatBuffers()
  229527. {
  229528. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229529. zerostruct (inputChannels);
  229530. zerostruct (outputChannels);
  229531. for (int i = 0; i < numInputChannels; ++i)
  229532. inputChannels[i] = floatData.getSampleData (i);
  229533. for (int i = 0; i < numOutputChannels; ++i)
  229534. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229535. }
  229536. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229537. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229538. {
  229539. OSStatus err = noErr;
  229540. if (audioInputIsAvailable)
  229541. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229542. const ScopedLock sl (callbackLock);
  229543. if (callback != 0)
  229544. {
  229545. if (audioInputIsAvailable && numInputChannels > 0)
  229546. {
  229547. short* shortData = (short*) ioData->mBuffers[0].mData;
  229548. if (numInputChannels >= 2)
  229549. {
  229550. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229551. {
  229552. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229553. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229554. }
  229555. }
  229556. else
  229557. {
  229558. if (monoInputChannelNumber > 0)
  229559. ++shortData;
  229560. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229561. {
  229562. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229563. ++shortData;
  229564. }
  229565. }
  229566. }
  229567. else
  229568. {
  229569. for (int i = numInputChannels; --i >= 0;)
  229570. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229571. }
  229572. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229573. outputChannels, numOutputChannels,
  229574. (int) inNumberFrames);
  229575. short* shortData = (short*) ioData->mBuffers[0].mData;
  229576. int n = 0;
  229577. if (numOutputChannels >= 2)
  229578. {
  229579. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229580. {
  229581. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229582. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229583. }
  229584. }
  229585. else if (numOutputChannels == 1)
  229586. {
  229587. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229588. {
  229589. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229590. shortData [n++] = s;
  229591. shortData [n++] = s;
  229592. }
  229593. }
  229594. else
  229595. {
  229596. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229597. }
  229598. }
  229599. else
  229600. {
  229601. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229602. }
  229603. return err;
  229604. }
  229605. void updateDeviceInfo()
  229606. {
  229607. UInt32 size = sizeof (sampleRate);
  229608. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229609. size = sizeof (audioInputIsAvailable);
  229610. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229611. }
  229612. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229613. {
  229614. if (! isRunning)
  229615. return;
  229616. if (inPropertyValue != 0)
  229617. {
  229618. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229619. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229620. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229621. SInt32 routeChangeReason;
  229622. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229623. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229624. fixAudioRouteIfSetToReceiver();
  229625. }
  229626. updateDeviceInfo();
  229627. createAudioUnit();
  229628. AudioSessionSetActive (true);
  229629. if (audioUnit != 0)
  229630. {
  229631. UInt32 formatSize = sizeof (format);
  229632. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229633. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229634. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229635. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229636. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229637. AudioOutputUnitStart (audioUnit);
  229638. }
  229639. }
  229640. void interruptionListener (UInt32 inInterruption)
  229641. {
  229642. /*if (inInterruption == kAudioSessionBeginInterruption)
  229643. {
  229644. isRunning = false;
  229645. AudioOutputUnitStop (audioUnit);
  229646. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229647. "This could have been interrupted by another application or by unplugging a headset",
  229648. @"Resume",
  229649. @"Cancel"))
  229650. {
  229651. isRunning = true;
  229652. propertyChanged (0, 0, 0);
  229653. }
  229654. }*/
  229655. if (inInterruption == kAudioSessionEndInterruption)
  229656. {
  229657. isRunning = true;
  229658. AudioSessionSetActive (true);
  229659. AudioOutputUnitStart (audioUnit);
  229660. }
  229661. }
  229662. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229663. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229664. {
  229665. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229666. }
  229667. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229668. {
  229669. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229670. }
  229671. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229672. {
  229673. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229674. }
  229675. void resetFormat (const int numChannels)
  229676. {
  229677. memset (&format, 0, sizeof (format));
  229678. format.mFormatID = kAudioFormatLinearPCM;
  229679. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229680. format.mBitsPerChannel = 8 * sizeof (short);
  229681. format.mChannelsPerFrame = 2;
  229682. format.mFramesPerPacket = 1;
  229683. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229684. }
  229685. bool createAudioUnit()
  229686. {
  229687. if (audioUnit != 0)
  229688. {
  229689. AudioComponentInstanceDispose (audioUnit);
  229690. audioUnit = 0;
  229691. }
  229692. resetFormat (2);
  229693. AudioComponentDescription desc;
  229694. desc.componentType = kAudioUnitType_Output;
  229695. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229696. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229697. desc.componentFlags = 0;
  229698. desc.componentFlagsMask = 0;
  229699. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229700. AudioComponentInstanceNew (comp, &audioUnit);
  229701. if (audioUnit == 0)
  229702. return false;
  229703. const UInt32 one = 1;
  229704. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229705. AudioChannelLayout layout;
  229706. layout.mChannelBitmap = 0;
  229707. layout.mNumberChannelDescriptions = 0;
  229708. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229709. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229710. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229711. AURenderCallbackStruct inputProc;
  229712. inputProc.inputProc = processStatic;
  229713. inputProc.inputProcRefCon = this;
  229714. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229715. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229716. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229717. AudioUnitInitialize (audioUnit);
  229718. return true;
  229719. }
  229720. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229721. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229722. static void fixAudioRouteIfSetToReceiver()
  229723. {
  229724. CFStringRef audioRoute = 0;
  229725. UInt32 propertySize = sizeof (audioRoute);
  229726. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229727. {
  229728. NSString* route = (NSString*) audioRoute;
  229729. //DBG ("audio route: " + nsStringToJuce (route));
  229730. if ([route hasPrefix: @"Receiver"])
  229731. {
  229732. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229733. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229734. }
  229735. CFRelease (audioRoute);
  229736. }
  229737. }
  229738. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229739. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229740. };
  229741. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229742. {
  229743. public:
  229744. IPhoneAudioIODeviceType()
  229745. : AudioIODeviceType ("iPhone Audio")
  229746. {
  229747. }
  229748. ~IPhoneAudioIODeviceType()
  229749. {
  229750. }
  229751. void scanForDevices()
  229752. {
  229753. }
  229754. const StringArray getDeviceNames (bool wantInputNames) const
  229755. {
  229756. StringArray s;
  229757. s.add ("iPhone Audio");
  229758. return s;
  229759. }
  229760. int getDefaultDeviceIndex (bool forInput) const
  229761. {
  229762. return 0;
  229763. }
  229764. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229765. {
  229766. return device != 0 ? 0 : -1;
  229767. }
  229768. bool hasSeparateInputsAndOutputs() const { return false; }
  229769. AudioIODevice* createDevice (const String& outputDeviceName,
  229770. const String& inputDeviceName)
  229771. {
  229772. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229773. {
  229774. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229775. : inputDeviceName);
  229776. }
  229777. return 0;
  229778. }
  229779. juce_UseDebuggingNewOperator
  229780. private:
  229781. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229782. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229783. };
  229784. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229785. {
  229786. return new IPhoneAudioIODeviceType();
  229787. }
  229788. #endif
  229789. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229790. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229791. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229792. // compiled on its own).
  229793. #if JUCE_INCLUDED_FILE
  229794. #if JUCE_MAC
  229795. namespace CoreMidiHelpers
  229796. {
  229797. static bool logError (const OSStatus err, const int lineNum)
  229798. {
  229799. if (err == noErr)
  229800. return true;
  229801. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229802. jassertfalse;
  229803. return false;
  229804. }
  229805. #undef CHECK_ERROR
  229806. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229807. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229808. {
  229809. String result;
  229810. CFStringRef str = 0;
  229811. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229812. if (str != 0)
  229813. {
  229814. result = PlatformUtilities::cfStringToJuceString (str);
  229815. CFRelease (str);
  229816. str = 0;
  229817. }
  229818. MIDIEntityRef entity = 0;
  229819. MIDIEndpointGetEntity (endpoint, &entity);
  229820. if (entity == 0)
  229821. return result; // probably virtual
  229822. if (result.isEmpty())
  229823. {
  229824. // endpoint name has zero length - try the entity
  229825. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229826. if (str != 0)
  229827. {
  229828. result += PlatformUtilities::cfStringToJuceString (str);
  229829. CFRelease (str);
  229830. str = 0;
  229831. }
  229832. }
  229833. // now consider the device's name
  229834. MIDIDeviceRef device = 0;
  229835. MIDIEntityGetDevice (entity, &device);
  229836. if (device == 0)
  229837. return result;
  229838. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229839. if (str != 0)
  229840. {
  229841. const String s (PlatformUtilities::cfStringToJuceString (str));
  229842. CFRelease (str);
  229843. // if an external device has only one entity, throw away
  229844. // the endpoint name and just use the device name
  229845. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229846. {
  229847. result = s;
  229848. }
  229849. else if (! result.startsWithIgnoreCase (s))
  229850. {
  229851. // prepend the device name to the entity name
  229852. result = (s + " " + result).trimEnd();
  229853. }
  229854. }
  229855. return result;
  229856. }
  229857. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229858. {
  229859. String result;
  229860. // Does the endpoint have connections?
  229861. CFDataRef connections = 0;
  229862. int numConnections = 0;
  229863. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229864. if (connections != 0)
  229865. {
  229866. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229867. if (numConnections > 0)
  229868. {
  229869. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229870. for (int i = 0; i < numConnections; ++i, ++pid)
  229871. {
  229872. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229873. MIDIObjectRef connObject;
  229874. MIDIObjectType connObjectType;
  229875. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229876. if (err == noErr)
  229877. {
  229878. String s;
  229879. if (connObjectType == kMIDIObjectType_ExternalSource
  229880. || connObjectType == kMIDIObjectType_ExternalDestination)
  229881. {
  229882. // Connected to an external device's endpoint (10.3 and later).
  229883. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229884. }
  229885. else
  229886. {
  229887. // Connected to an external device (10.2) (or something else, catch-all)
  229888. CFStringRef str = 0;
  229889. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229890. if (str != 0)
  229891. {
  229892. s = PlatformUtilities::cfStringToJuceString (str);
  229893. CFRelease (str);
  229894. }
  229895. }
  229896. if (s.isNotEmpty())
  229897. {
  229898. if (result.isNotEmpty())
  229899. result += ", ";
  229900. result += s;
  229901. }
  229902. }
  229903. }
  229904. }
  229905. CFRelease (connections);
  229906. }
  229907. if (result.isNotEmpty())
  229908. return result;
  229909. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229910. return getEndpointName (endpoint, false);
  229911. }
  229912. static MIDIClientRef getGlobalMidiClient()
  229913. {
  229914. static MIDIClientRef globalMidiClient = 0;
  229915. if (globalMidiClient == 0)
  229916. {
  229917. String name ("JUCE");
  229918. if (JUCEApplication::getInstance() != 0)
  229919. name = JUCEApplication::getInstance()->getApplicationName();
  229920. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229921. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229922. CFRelease (appName);
  229923. }
  229924. return globalMidiClient;
  229925. }
  229926. class MidiPortAndEndpoint
  229927. {
  229928. public:
  229929. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229930. : port (port_), endPoint (endPoint_)
  229931. {
  229932. }
  229933. ~MidiPortAndEndpoint()
  229934. {
  229935. if (port != 0)
  229936. MIDIPortDispose (port);
  229937. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229938. MIDIEndpointDispose (endPoint);
  229939. }
  229940. void send (const MIDIPacketList* const packets)
  229941. {
  229942. if (port != 0)
  229943. MIDISend (port, endPoint, packets);
  229944. else
  229945. MIDIReceived (endPoint, packets);
  229946. }
  229947. MIDIPortRef port;
  229948. MIDIEndpointRef endPoint;
  229949. };
  229950. class MidiPortAndCallback;
  229951. static CriticalSection callbackLock;
  229952. static Array<MidiPortAndCallback*> activeCallbacks;
  229953. class MidiPortAndCallback
  229954. {
  229955. public:
  229956. MidiPortAndCallback (MidiInputCallback& callback_)
  229957. : input (0), active (false), callback (callback_), concatenator (2048)
  229958. {
  229959. }
  229960. ~MidiPortAndCallback()
  229961. {
  229962. active = false;
  229963. {
  229964. const ScopedLock sl (callbackLock);
  229965. activeCallbacks.removeValue (this);
  229966. }
  229967. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229968. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229969. }
  229970. void handlePackets (const MIDIPacketList* const pktlist)
  229971. {
  229972. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229973. const ScopedLock sl (callbackLock);
  229974. if (activeCallbacks.contains (this) && active)
  229975. {
  229976. const MIDIPacket* packet = &pktlist->packet[0];
  229977. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229978. {
  229979. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229980. input, callback);
  229981. packet = MIDIPacketNext (packet);
  229982. }
  229983. }
  229984. }
  229985. MidiInput* input;
  229986. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229987. volatile bool active;
  229988. private:
  229989. MidiInputCallback& callback;
  229990. MidiDataConcatenator concatenator;
  229991. };
  229992. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229993. {
  229994. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229995. }
  229996. }
  229997. const StringArray MidiOutput::getDevices()
  229998. {
  229999. StringArray s;
  230000. const ItemCount num = MIDIGetNumberOfDestinations();
  230001. for (ItemCount i = 0; i < num; ++i)
  230002. {
  230003. MIDIEndpointRef dest = MIDIGetDestination (i);
  230004. if (dest != 0)
  230005. {
  230006. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  230007. if (name.isEmpty())
  230008. name = "<error>";
  230009. s.add (name);
  230010. }
  230011. else
  230012. {
  230013. s.add ("<error>");
  230014. }
  230015. }
  230016. return s;
  230017. }
  230018. int MidiOutput::getDefaultDeviceIndex()
  230019. {
  230020. return 0;
  230021. }
  230022. MidiOutput* MidiOutput::openDevice (int index)
  230023. {
  230024. MidiOutput* mo = 0;
  230025. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  230026. {
  230027. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  230028. CFStringRef pname;
  230029. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  230030. {
  230031. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  230032. MIDIPortRef port;
  230033. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  230034. {
  230035. mo = new MidiOutput();
  230036. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  230037. }
  230038. CFRelease (pname);
  230039. }
  230040. }
  230041. return mo;
  230042. }
  230043. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  230044. {
  230045. MidiOutput* mo = 0;
  230046. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  230047. MIDIEndpointRef endPoint;
  230048. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  230049. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  230050. {
  230051. mo = new MidiOutput();
  230052. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  230053. }
  230054. CFRelease (name);
  230055. return mo;
  230056. }
  230057. MidiOutput::~MidiOutput()
  230058. {
  230059. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  230060. }
  230061. void MidiOutput::reset()
  230062. {
  230063. }
  230064. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  230065. {
  230066. return false;
  230067. }
  230068. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  230069. {
  230070. }
  230071. void MidiOutput::sendMessageNow (const MidiMessage& message)
  230072. {
  230073. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  230074. if (message.isSysEx())
  230075. {
  230076. const int maxPacketSize = 256;
  230077. int pos = 0, bytesLeft = message.getRawDataSize();
  230078. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  230079. HeapBlock <MIDIPacketList> packets;
  230080. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  230081. packets->numPackets = numPackets;
  230082. MIDIPacket* p = packets->packet;
  230083. for (int i = 0; i < numPackets; ++i)
  230084. {
  230085. p->timeStamp = 0;
  230086. p->length = jmin (maxPacketSize, bytesLeft);
  230087. memcpy (p->data, message.getRawData() + pos, p->length);
  230088. pos += p->length;
  230089. bytesLeft -= p->length;
  230090. p = MIDIPacketNext (p);
  230091. }
  230092. mpe->send (packets);
  230093. }
  230094. else
  230095. {
  230096. MIDIPacketList packets;
  230097. packets.numPackets = 1;
  230098. packets.packet[0].timeStamp = 0;
  230099. packets.packet[0].length = message.getRawDataSize();
  230100. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  230101. mpe->send (&packets);
  230102. }
  230103. }
  230104. const StringArray MidiInput::getDevices()
  230105. {
  230106. StringArray s;
  230107. const ItemCount num = MIDIGetNumberOfSources();
  230108. for (ItemCount i = 0; i < num; ++i)
  230109. {
  230110. MIDIEndpointRef source = MIDIGetSource (i);
  230111. if (source != 0)
  230112. {
  230113. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  230114. if (name.isEmpty())
  230115. name = "<error>";
  230116. s.add (name);
  230117. }
  230118. else
  230119. {
  230120. s.add ("<error>");
  230121. }
  230122. }
  230123. return s;
  230124. }
  230125. int MidiInput::getDefaultDeviceIndex()
  230126. {
  230127. return 0;
  230128. }
  230129. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  230130. {
  230131. jassert (callback != 0);
  230132. using namespace CoreMidiHelpers;
  230133. MidiInput* newInput = 0;
  230134. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  230135. {
  230136. MIDIEndpointRef endPoint = MIDIGetSource (index);
  230137. if (endPoint != 0)
  230138. {
  230139. CFStringRef name;
  230140. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  230141. {
  230142. MIDIClientRef client = getGlobalMidiClient();
  230143. if (client != 0)
  230144. {
  230145. MIDIPortRef port;
  230146. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230147. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  230148. {
  230149. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  230150. {
  230151. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  230152. newInput = new MidiInput (getDevices() [index]);
  230153. mpc->input = newInput;
  230154. newInput->internal = mpc;
  230155. const ScopedLock sl (callbackLock);
  230156. activeCallbacks.add (mpc.release());
  230157. }
  230158. else
  230159. {
  230160. CHECK_ERROR (MIDIPortDispose (port));
  230161. }
  230162. }
  230163. }
  230164. }
  230165. CFRelease (name);
  230166. }
  230167. }
  230168. return newInput;
  230169. }
  230170. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  230171. {
  230172. jassert (callback != 0);
  230173. using namespace CoreMidiHelpers;
  230174. MidiInput* mi = 0;
  230175. MIDIClientRef client = getGlobalMidiClient();
  230176. if (client != 0)
  230177. {
  230178. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230179. mpc->active = false;
  230180. MIDIEndpointRef endPoint;
  230181. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  230182. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  230183. {
  230184. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  230185. mi = new MidiInput (deviceName);
  230186. mpc->input = mi;
  230187. mi->internal = mpc;
  230188. const ScopedLock sl (callbackLock);
  230189. activeCallbacks.add (mpc.release());
  230190. }
  230191. CFRelease (name);
  230192. }
  230193. return mi;
  230194. }
  230195. MidiInput::MidiInput (const String& name_)
  230196. : name (name_)
  230197. {
  230198. }
  230199. MidiInput::~MidiInput()
  230200. {
  230201. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  230202. }
  230203. void MidiInput::start()
  230204. {
  230205. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230206. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  230207. }
  230208. void MidiInput::stop()
  230209. {
  230210. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230211. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  230212. }
  230213. #undef CHECK_ERROR
  230214. #else // Stubs for iOS...
  230215. MidiOutput::~MidiOutput() {}
  230216. void MidiOutput::reset() {}
  230217. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  230218. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  230219. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  230220. const StringArray MidiOutput::getDevices() { return StringArray(); }
  230221. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  230222. const StringArray MidiInput::getDevices() { return StringArray(); }
  230223. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  230224. #endif
  230225. #endif
  230226. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  230227. #else
  230228. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  230229. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230230. // compiled on its own).
  230231. #if JUCE_INCLUDED_FILE
  230232. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230233. #define SUPPORT_10_4_FONTS 1
  230234. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  230235. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230236. #define SUPPORT_ONLY_10_4_FONTS 1
  230237. #endif
  230238. END_JUCE_NAMESPACE
  230239. @interface NSFont (PrivateHack)
  230240. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  230241. @end
  230242. BEGIN_JUCE_NAMESPACE
  230243. #endif
  230244. class MacTypeface : public Typeface
  230245. {
  230246. public:
  230247. MacTypeface (const Font& font)
  230248. : Typeface (font.getTypefaceName())
  230249. {
  230250. const ScopedAutoReleasePool pool;
  230251. renderingTransform = CGAffineTransformIdentity;
  230252. bool needsItalicTransform = false;
  230253. #if JUCE_IOS
  230254. NSString* fontName = juceStringToNS (font.getTypefaceName());
  230255. if (font.isItalic() || font.isBold())
  230256. {
  230257. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  230258. for (NSString* i in familyFonts)
  230259. {
  230260. const String fn (nsStringToJuce (i));
  230261. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  230262. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  230263. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  230264. || afterDash.containsIgnoreCase ("italic")
  230265. || fn.endsWithIgnoreCase ("oblique")
  230266. || fn.endsWithIgnoreCase ("italic");
  230267. if (probablyBold == font.isBold()
  230268. && probablyItalic == font.isItalic())
  230269. {
  230270. fontName = i;
  230271. needsItalicTransform = false;
  230272. break;
  230273. }
  230274. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  230275. {
  230276. fontName = i;
  230277. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  230278. }
  230279. }
  230280. if (needsItalicTransform)
  230281. renderingTransform.c = 0.15f;
  230282. }
  230283. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  230284. const int ascender = abs (CGFontGetAscent (fontRef));
  230285. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  230286. ascent = ascender / totalHeight;
  230287. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230288. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  230289. #else
  230290. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  230291. if (font.isItalic())
  230292. {
  230293. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230294. toHaveTrait: NSItalicFontMask];
  230295. if (newFont == nsFont)
  230296. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230297. nsFont = newFont;
  230298. }
  230299. if (font.isBold())
  230300. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230301. [nsFont retain];
  230302. ascent = std::abs ((float) [nsFont ascender]);
  230303. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230304. ascent /= totalSize;
  230305. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230306. if (needsItalicTransform)
  230307. {
  230308. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230309. renderingTransform.c = 0.15f;
  230310. }
  230311. #if SUPPORT_ONLY_10_4_FONTS
  230312. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230313. if (atsFont == 0)
  230314. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230315. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230316. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230317. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230318. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230319. #else
  230320. #if SUPPORT_10_4_FONTS
  230321. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230322. {
  230323. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230324. if (atsFont == 0)
  230325. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230326. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230327. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230328. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230329. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230330. }
  230331. else
  230332. #endif
  230333. {
  230334. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230335. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230336. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230337. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230338. }
  230339. #endif
  230340. #endif
  230341. }
  230342. ~MacTypeface()
  230343. {
  230344. #if ! JUCE_IOS
  230345. [nsFont release];
  230346. #endif
  230347. if (fontRef != 0)
  230348. CGFontRelease (fontRef);
  230349. }
  230350. float getAscent() const
  230351. {
  230352. return ascent;
  230353. }
  230354. float getDescent() const
  230355. {
  230356. return 1.0f - ascent;
  230357. }
  230358. float getStringWidth (const String& text)
  230359. {
  230360. if (fontRef == 0 || text.isEmpty())
  230361. return 0;
  230362. const int length = text.length();
  230363. HeapBlock <CGGlyph> glyphs;
  230364. createGlyphsForString (text, length, glyphs);
  230365. float x = 0;
  230366. #if SUPPORT_ONLY_10_4_FONTS
  230367. HeapBlock <NSSize> advances (length);
  230368. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230369. for (int i = 0; i < length; ++i)
  230370. x += advances[i].width;
  230371. #else
  230372. #if SUPPORT_10_4_FONTS
  230373. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230374. {
  230375. HeapBlock <NSSize> advances (length);
  230376. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230377. for (int i = 0; i < length; ++i)
  230378. x += advances[i].width;
  230379. }
  230380. else
  230381. #endif
  230382. {
  230383. HeapBlock <int> advances (length);
  230384. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230385. for (int i = 0; i < length; ++i)
  230386. x += advances[i];
  230387. }
  230388. #endif
  230389. return x * unitsToHeightScaleFactor;
  230390. }
  230391. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230392. {
  230393. xOffsets.add (0);
  230394. if (fontRef == 0 || text.isEmpty())
  230395. return;
  230396. const int length = text.length();
  230397. HeapBlock <CGGlyph> glyphs;
  230398. createGlyphsForString (text, length, glyphs);
  230399. #if SUPPORT_ONLY_10_4_FONTS
  230400. HeapBlock <NSSize> advances (length);
  230401. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230402. int x = 0;
  230403. for (int i = 0; i < length; ++i)
  230404. {
  230405. x += advances[i].width;
  230406. xOffsets.add (x * unitsToHeightScaleFactor);
  230407. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230408. }
  230409. #else
  230410. #if SUPPORT_10_4_FONTS
  230411. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230412. {
  230413. HeapBlock <NSSize> advances (length);
  230414. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230415. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230416. float x = 0;
  230417. for (int i = 0; i < length; ++i)
  230418. {
  230419. x += advances[i].width;
  230420. xOffsets.add (x * unitsToHeightScaleFactor);
  230421. resultGlyphs.add (nsGlyphs[i]);
  230422. }
  230423. }
  230424. else
  230425. #endif
  230426. {
  230427. HeapBlock <int> advances (length);
  230428. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230429. {
  230430. int x = 0;
  230431. for (int i = 0; i < length; ++i)
  230432. {
  230433. x += advances [i];
  230434. xOffsets.add (x * unitsToHeightScaleFactor);
  230435. resultGlyphs.add (glyphs[i]);
  230436. }
  230437. }
  230438. }
  230439. #endif
  230440. }
  230441. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230442. {
  230443. #if JUCE_IOS
  230444. return false;
  230445. #else
  230446. if (nsFont == 0)
  230447. return false;
  230448. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230449. jassert (path.isEmpty());
  230450. const ScopedAutoReleasePool pool;
  230451. NSBezierPath* bez = [NSBezierPath bezierPath];
  230452. [bez moveToPoint: NSMakePoint (0, 0)];
  230453. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230454. inFont: nsFont];
  230455. for (int i = 0; i < [bez elementCount]; ++i)
  230456. {
  230457. NSPoint p[3];
  230458. switch ([bez elementAtIndex: i associatedPoints: p])
  230459. {
  230460. case NSMoveToBezierPathElement:
  230461. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230462. break;
  230463. case NSLineToBezierPathElement:
  230464. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230465. break;
  230466. case NSCurveToBezierPathElement:
  230467. 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);
  230468. break;
  230469. case NSClosePathBezierPathElement:
  230470. path.closeSubPath();
  230471. break;
  230472. default:
  230473. jassertfalse;
  230474. break;
  230475. }
  230476. }
  230477. path.applyTransform (pathTransform);
  230478. return true;
  230479. #endif
  230480. }
  230481. juce_UseDebuggingNewOperator
  230482. CGFontRef fontRef;
  230483. float fontHeightToCGSizeFactor;
  230484. CGAffineTransform renderingTransform;
  230485. private:
  230486. float ascent, unitsToHeightScaleFactor;
  230487. #if JUCE_IOS
  230488. #else
  230489. NSFont* nsFont;
  230490. AffineTransform pathTransform;
  230491. #endif
  230492. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230493. {
  230494. #if SUPPORT_10_4_FONTS
  230495. #if ! SUPPORT_ONLY_10_4_FONTS
  230496. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230497. #endif
  230498. {
  230499. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230500. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230501. for (int i = 0; i < length; ++i)
  230502. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230503. return;
  230504. }
  230505. #endif
  230506. #if ! SUPPORT_ONLY_10_4_FONTS
  230507. if (charToGlyphMapper == 0)
  230508. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230509. glyphs.malloc (length);
  230510. for (int i = 0; i < length; ++i)
  230511. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230512. #endif
  230513. }
  230514. #if ! SUPPORT_ONLY_10_4_FONTS
  230515. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230516. class CharToGlyphMapper
  230517. {
  230518. public:
  230519. CharToGlyphMapper (CGFontRef fontRef)
  230520. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230521. idRangeOffset (0), glyphIndexes (0)
  230522. {
  230523. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230524. if (cmapTable != 0)
  230525. {
  230526. const int numSubtables = getValue16 (cmapTable, 2);
  230527. for (int i = 0; i < numSubtables; ++i)
  230528. {
  230529. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230530. {
  230531. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230532. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230533. {
  230534. const int length = getValue16 (cmapTable, offset + 2);
  230535. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230536. segCount = segCountX2 / 2;
  230537. const int endCodeOffset = offset + 14;
  230538. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230539. const int idDeltaOffset = startCodeOffset + segCountX2;
  230540. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230541. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230542. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230543. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230544. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230545. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230546. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230547. }
  230548. break;
  230549. }
  230550. }
  230551. CFRelease (cmapTable);
  230552. }
  230553. }
  230554. ~CharToGlyphMapper()
  230555. {
  230556. if (endCode != 0)
  230557. {
  230558. CFRelease (endCode);
  230559. CFRelease (startCode);
  230560. CFRelease (idDelta);
  230561. CFRelease (idRangeOffset);
  230562. CFRelease (glyphIndexes);
  230563. }
  230564. }
  230565. int getGlyphForCharacter (const juce_wchar c) const
  230566. {
  230567. for (int i = 0; i < segCount; ++i)
  230568. {
  230569. if (getValue16 (endCode, i * 2) >= c)
  230570. {
  230571. const int start = getValue16 (startCode, i * 2);
  230572. if (start > c)
  230573. break;
  230574. const int delta = getValue16 (idDelta, i * 2);
  230575. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230576. if (rangeOffset == 0)
  230577. return delta + c;
  230578. else
  230579. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230580. }
  230581. }
  230582. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230583. return jmax (-1, (int) c - 29);
  230584. }
  230585. private:
  230586. int segCount;
  230587. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230588. static uint16 getValue16 (CFDataRef data, const int index)
  230589. {
  230590. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230591. }
  230592. static uint32 getValue32 (CFDataRef data, const int index)
  230593. {
  230594. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230595. }
  230596. };
  230597. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230598. #endif
  230599. MacTypeface (const MacTypeface&);
  230600. MacTypeface& operator= (const MacTypeface&);
  230601. };
  230602. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230603. {
  230604. return new MacTypeface (font);
  230605. }
  230606. const StringArray Font::findAllTypefaceNames()
  230607. {
  230608. StringArray names;
  230609. const ScopedAutoReleasePool pool;
  230610. #if JUCE_IOS
  230611. NSArray* fonts = [UIFont familyNames];
  230612. #else
  230613. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230614. #endif
  230615. for (unsigned int i = 0; i < [fonts count]; ++i)
  230616. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230617. names.sort (true);
  230618. return names;
  230619. }
  230620. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230621. {
  230622. #if JUCE_IOS
  230623. defaultSans = "Helvetica";
  230624. defaultSerif = "Times New Roman";
  230625. defaultFixed = "Courier New";
  230626. #else
  230627. defaultSans = "Lucida Grande";
  230628. defaultSerif = "Times New Roman";
  230629. defaultFixed = "Monaco";
  230630. #endif
  230631. }
  230632. #endif
  230633. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230634. // (must go before juce_mac_CoreGraphicsContext.mm)
  230635. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230636. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230637. // compiled on its own).
  230638. #if JUCE_INCLUDED_FILE
  230639. class CoreGraphicsImage : public Image::SharedImage
  230640. {
  230641. public:
  230642. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230643. : Image::SharedImage (format_, width_, height_)
  230644. {
  230645. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230646. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230647. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230648. imageData = imageDataAllocated;
  230649. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230650. : CGColorSpaceCreateDeviceRGB();
  230651. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230652. colourSpace, getCGImageFlags (format_));
  230653. CGColorSpaceRelease (colourSpace);
  230654. }
  230655. ~CoreGraphicsImage()
  230656. {
  230657. CGContextRelease (context);
  230658. }
  230659. Image::ImageType getType() const { return Image::NativeImage; }
  230660. LowLevelGraphicsContext* createLowLevelContext();
  230661. SharedImage* clone()
  230662. {
  230663. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230664. memcpy (im->imageData, imageData, lineStride * height);
  230665. return im;
  230666. }
  230667. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230668. {
  230669. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230670. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230671. {
  230672. return CGBitmapContextCreateImage (nativeImage->context);
  230673. }
  230674. else
  230675. {
  230676. const Image::BitmapData srcData (juceImage, false);
  230677. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230678. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230679. 8, srcData.pixelStride * 8, srcData.lineStride,
  230680. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230681. 0, true, kCGRenderingIntentDefault);
  230682. CGDataProviderRelease (provider);
  230683. return imageRef;
  230684. }
  230685. }
  230686. #if JUCE_MAC
  230687. static NSImage* createNSImage (const Image& image)
  230688. {
  230689. const ScopedAutoReleasePool pool;
  230690. NSImage* im = [[NSImage alloc] init];
  230691. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230692. [im lockFocus];
  230693. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230694. CGImageRef imageRef = createImage (image, false, colourSpace);
  230695. CGColorSpaceRelease (colourSpace);
  230696. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230697. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230698. CGImageRelease (imageRef);
  230699. [im unlockFocus];
  230700. return im;
  230701. }
  230702. #endif
  230703. CGContextRef context;
  230704. HeapBlock<uint8> imageDataAllocated;
  230705. private:
  230706. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230707. {
  230708. #if JUCE_BIG_ENDIAN
  230709. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230710. #else
  230711. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230712. #endif
  230713. }
  230714. };
  230715. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230716. {
  230717. #if USE_COREGRAPHICS_RENDERING
  230718. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230719. #else
  230720. return createSoftwareImage (format, width, height, clearImage);
  230721. #endif
  230722. }
  230723. class CoreGraphicsContext : public LowLevelGraphicsContext
  230724. {
  230725. public:
  230726. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230727. : context (context_),
  230728. flipHeight (flipHeight_),
  230729. lastClipRectIsValid (false),
  230730. state (new SavedState()),
  230731. numGradientLookupEntries (0)
  230732. {
  230733. CGContextRetain (context);
  230734. CGContextSaveGState(context);
  230735. CGContextSetShouldSmoothFonts (context, true);
  230736. CGContextSetShouldAntialias (context, true);
  230737. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230738. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230739. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230740. gradientCallbacks.version = 0;
  230741. gradientCallbacks.evaluate = gradientCallback;
  230742. gradientCallbacks.releaseInfo = 0;
  230743. setFont (Font());
  230744. }
  230745. ~CoreGraphicsContext()
  230746. {
  230747. CGContextRestoreGState (context);
  230748. CGContextRelease (context);
  230749. CGColorSpaceRelease (rgbColourSpace);
  230750. CGColorSpaceRelease (greyColourSpace);
  230751. }
  230752. bool isVectorDevice() const { return false; }
  230753. void setOrigin (int x, int y)
  230754. {
  230755. CGContextTranslateCTM (context, x, -y);
  230756. if (lastClipRectIsValid)
  230757. lastClipRect.translate (-x, -y);
  230758. }
  230759. bool clipToRectangle (const Rectangle<int>& r)
  230760. {
  230761. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230762. if (lastClipRectIsValid)
  230763. {
  230764. // This is actually incorrect, because the actual clip region may be complex, and
  230765. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230766. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230767. // when calculating the resultant clip bounds, and makes the same mistake!
  230768. lastClipRect = lastClipRect.getIntersection (r);
  230769. return ! lastClipRect.isEmpty();
  230770. }
  230771. return ! isClipEmpty();
  230772. }
  230773. bool clipToRectangleList (const RectangleList& clipRegion)
  230774. {
  230775. if (clipRegion.isEmpty())
  230776. {
  230777. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230778. lastClipRectIsValid = true;
  230779. lastClipRect = Rectangle<int>();
  230780. return false;
  230781. }
  230782. else
  230783. {
  230784. const int numRects = clipRegion.getNumRectangles();
  230785. HeapBlock <CGRect> rects (numRects);
  230786. for (int i = 0; i < numRects; ++i)
  230787. {
  230788. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230789. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230790. }
  230791. CGContextClipToRects (context, rects, numRects);
  230792. lastClipRectIsValid = false;
  230793. return ! isClipEmpty();
  230794. }
  230795. }
  230796. void excludeClipRectangle (const Rectangle<int>& r)
  230797. {
  230798. RectangleList remaining (getClipBounds());
  230799. remaining.subtract (r);
  230800. clipToRectangleList (remaining);
  230801. lastClipRectIsValid = false;
  230802. }
  230803. void clipToPath (const Path& path, const AffineTransform& transform)
  230804. {
  230805. createPath (path, transform);
  230806. CGContextClip (context);
  230807. lastClipRectIsValid = false;
  230808. }
  230809. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230810. {
  230811. if (! transform.isSingularity())
  230812. {
  230813. Image singleChannelImage (sourceImage);
  230814. if (sourceImage.getFormat() != Image::SingleChannel)
  230815. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230816. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230817. flip();
  230818. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230819. applyTransform (t);
  230820. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230821. CGContextClipToMask (context, r, image);
  230822. applyTransform (t.inverted());
  230823. flip();
  230824. CGImageRelease (image);
  230825. lastClipRectIsValid = false;
  230826. }
  230827. }
  230828. bool clipRegionIntersects (const Rectangle<int>& r)
  230829. {
  230830. return getClipBounds().intersects (r);
  230831. }
  230832. const Rectangle<int> getClipBounds() const
  230833. {
  230834. if (! lastClipRectIsValid)
  230835. {
  230836. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230837. lastClipRectIsValid = true;
  230838. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230839. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230840. roundToInt (bounds.size.width),
  230841. roundToInt (bounds.size.height));
  230842. }
  230843. return lastClipRect;
  230844. }
  230845. bool isClipEmpty() const
  230846. {
  230847. return getClipBounds().isEmpty();
  230848. }
  230849. void saveState()
  230850. {
  230851. CGContextSaveGState (context);
  230852. stateStack.add (new SavedState (*state));
  230853. }
  230854. void restoreState()
  230855. {
  230856. CGContextRestoreGState (context);
  230857. SavedState* const top = stateStack.getLast();
  230858. if (top != 0)
  230859. {
  230860. state = top;
  230861. stateStack.removeLast (1, false);
  230862. lastClipRectIsValid = false;
  230863. }
  230864. else
  230865. {
  230866. jassertfalse; // trying to pop with an empty stack!
  230867. }
  230868. }
  230869. void setFill (const FillType& fillType)
  230870. {
  230871. state->fillType = fillType;
  230872. if (fillType.isColour())
  230873. {
  230874. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230875. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230876. CGContextSetAlpha (context, 1.0f);
  230877. }
  230878. }
  230879. void setOpacity (float newOpacity)
  230880. {
  230881. state->fillType.setOpacity (newOpacity);
  230882. setFill (state->fillType);
  230883. }
  230884. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230885. {
  230886. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230887. ? kCGInterpolationLow
  230888. : kCGInterpolationHigh);
  230889. }
  230890. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230891. {
  230892. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230893. }
  230894. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230895. {
  230896. if (replaceExistingContents)
  230897. {
  230898. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230899. CGContextClearRect (context, cgRect);
  230900. #else
  230901. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230902. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230903. CGContextClearRect (context, cgRect);
  230904. else
  230905. #endif
  230906. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230907. #endif
  230908. fillCGRect (cgRect, false);
  230909. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230910. }
  230911. else
  230912. {
  230913. if (state->fillType.isColour())
  230914. {
  230915. CGContextFillRect (context, cgRect);
  230916. }
  230917. else if (state->fillType.isGradient())
  230918. {
  230919. CGContextSaveGState (context);
  230920. CGContextClipToRect (context, cgRect);
  230921. drawGradient();
  230922. CGContextRestoreGState (context);
  230923. }
  230924. else
  230925. {
  230926. CGContextSaveGState (context);
  230927. CGContextClipToRect (context, cgRect);
  230928. drawImage (state->fillType.image, state->fillType.transform, true);
  230929. CGContextRestoreGState (context);
  230930. }
  230931. }
  230932. }
  230933. void fillPath (const Path& path, const AffineTransform& transform)
  230934. {
  230935. CGContextSaveGState (context);
  230936. if (state->fillType.isColour())
  230937. {
  230938. flip();
  230939. applyTransform (transform);
  230940. createPath (path);
  230941. if (path.isUsingNonZeroWinding())
  230942. CGContextFillPath (context);
  230943. else
  230944. CGContextEOFillPath (context);
  230945. }
  230946. else
  230947. {
  230948. createPath (path, transform);
  230949. if (path.isUsingNonZeroWinding())
  230950. CGContextClip (context);
  230951. else
  230952. CGContextEOClip (context);
  230953. if (state->fillType.isGradient())
  230954. drawGradient();
  230955. else
  230956. drawImage (state->fillType.image, state->fillType.transform, true);
  230957. }
  230958. CGContextRestoreGState (context);
  230959. }
  230960. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230961. {
  230962. const int iw = sourceImage.getWidth();
  230963. const int ih = sourceImage.getHeight();
  230964. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230965. CGContextSaveGState (context);
  230966. CGContextSetAlpha (context, state->fillType.getOpacity());
  230967. flip();
  230968. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230969. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230970. if (fillEntireClipAsTiles)
  230971. {
  230972. #if JUCE_IOS
  230973. CGContextDrawTiledImage (context, imageRect, image);
  230974. #else
  230975. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230976. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230977. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230978. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230979. CGContextDrawTiledImage (context, imageRect, image);
  230980. else
  230981. #endif
  230982. {
  230983. // Fallback to manually doing a tiled fill on 10.4
  230984. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230985. int x = 0, y = 0;
  230986. while (x > clip.origin.x) x -= iw;
  230987. while (y > clip.origin.y) y -= ih;
  230988. const int right = (int) (clip.origin.x + clip.size.width);
  230989. const int bottom = (int) (clip.origin.y + clip.size.height);
  230990. while (y < bottom)
  230991. {
  230992. for (int x2 = x; x2 < right; x2 += iw)
  230993. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230994. y += ih;
  230995. }
  230996. }
  230997. #endif
  230998. }
  230999. else
  231000. {
  231001. CGContextDrawImage (context, imageRect, image);
  231002. }
  231003. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  231004. CGContextRestoreGState (context);
  231005. }
  231006. void drawLine (const Line<float>& line)
  231007. {
  231008. if (state->fillType.isColour())
  231009. {
  231010. CGContextSetLineCap (context, kCGLineCapSquare);
  231011. CGContextSetLineWidth (context, 1.0f);
  231012. CGContextSetRGBStrokeColor (context,
  231013. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  231014. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  231015. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  231016. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  231017. CGContextStrokeLineSegments (context, cgLine, 1);
  231018. }
  231019. else
  231020. {
  231021. Path p;
  231022. p.addLineSegment (line, 1.0f);
  231023. fillPath (p, AffineTransform::identity);
  231024. }
  231025. }
  231026. void drawVerticalLine (const int x, float top, float bottom)
  231027. {
  231028. if (state->fillType.isColour())
  231029. {
  231030. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  231031. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  231032. #else
  231033. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  231034. // the x co-ord slightly to trick it..
  231035. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  231036. #endif
  231037. }
  231038. else
  231039. {
  231040. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  231041. }
  231042. }
  231043. void drawHorizontalLine (const int y, float left, float right)
  231044. {
  231045. if (state->fillType.isColour())
  231046. {
  231047. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  231048. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  231049. #else
  231050. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  231051. // the x co-ord slightly to trick it..
  231052. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  231053. #endif
  231054. }
  231055. else
  231056. {
  231057. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  231058. }
  231059. }
  231060. void setFont (const Font& newFont)
  231061. {
  231062. if (state->font != newFont)
  231063. {
  231064. state->fontRef = 0;
  231065. state->font = newFont;
  231066. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  231067. if (mf != 0)
  231068. {
  231069. state->fontRef = mf->fontRef;
  231070. CGContextSetFont (context, state->fontRef);
  231071. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  231072. state->fontTransform = mf->renderingTransform;
  231073. state->fontTransform.a *= state->font.getHorizontalScale();
  231074. CGContextSetTextMatrix (context, state->fontTransform);
  231075. }
  231076. }
  231077. }
  231078. const Font getFont()
  231079. {
  231080. return state->font;
  231081. }
  231082. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  231083. {
  231084. if (state->fontRef != 0 && state->fillType.isColour())
  231085. {
  231086. if (transform.isOnlyTranslation())
  231087. {
  231088. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  231089. CGGlyph g = glyphNumber;
  231090. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  231091. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  231092. }
  231093. else
  231094. {
  231095. CGContextSaveGState (context);
  231096. flip();
  231097. applyTransform (transform);
  231098. CGAffineTransform t = state->fontTransform;
  231099. t.d = -t.d;
  231100. CGContextSetTextMatrix (context, t);
  231101. CGGlyph g = glyphNumber;
  231102. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  231103. CGContextRestoreGState (context);
  231104. }
  231105. }
  231106. else
  231107. {
  231108. Path p;
  231109. Font& f = state->font;
  231110. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  231111. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  231112. .followedBy (transform));
  231113. }
  231114. }
  231115. private:
  231116. CGContextRef context;
  231117. const CGFloat flipHeight;
  231118. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  231119. CGFunctionCallbacks gradientCallbacks;
  231120. mutable Rectangle<int> lastClipRect;
  231121. mutable bool lastClipRectIsValid;
  231122. struct SavedState
  231123. {
  231124. SavedState()
  231125. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  231126. {
  231127. }
  231128. SavedState (const SavedState& other)
  231129. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  231130. fontTransform (other.fontTransform)
  231131. {
  231132. }
  231133. ~SavedState()
  231134. {
  231135. }
  231136. FillType fillType;
  231137. Font font;
  231138. CGFontRef fontRef;
  231139. CGAffineTransform fontTransform;
  231140. };
  231141. ScopedPointer <SavedState> state;
  231142. OwnedArray <SavedState> stateStack;
  231143. HeapBlock <PixelARGB> gradientLookupTable;
  231144. int numGradientLookupEntries;
  231145. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  231146. {
  231147. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  231148. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  231149. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  231150. colour.unpremultiply();
  231151. outData[0] = colour.getRed() / 255.0f;
  231152. outData[1] = colour.getGreen() / 255.0f;
  231153. outData[2] = colour.getBlue() / 255.0f;
  231154. outData[3] = colour.getAlpha() / 255.0f;
  231155. }
  231156. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  231157. {
  231158. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  231159. --numGradientLookupEntries;
  231160. CGShadingRef result = 0;
  231161. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  231162. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  231163. if (gradient.isRadial)
  231164. {
  231165. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  231166. p1, gradient.point1.getDistanceFrom (gradient.point2),
  231167. function, true, true);
  231168. }
  231169. else
  231170. {
  231171. result = CGShadingCreateAxial (rgbColourSpace, p1,
  231172. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  231173. function, true, true);
  231174. }
  231175. CGFunctionRelease (function);
  231176. return result;
  231177. }
  231178. void drawGradient()
  231179. {
  231180. flip();
  231181. applyTransform (state->fillType.transform);
  231182. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  231183. // you draw a gradient with high quality interp enabled).
  231184. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  231185. CGContextSetAlpha (context, state->fillType.getOpacity());
  231186. CGContextDrawShading (context, shading);
  231187. CGShadingRelease (shading);
  231188. }
  231189. void createPath (const Path& path) const
  231190. {
  231191. CGContextBeginPath (context);
  231192. Path::Iterator i (path);
  231193. while (i.next())
  231194. {
  231195. switch (i.elementType)
  231196. {
  231197. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  231198. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  231199. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  231200. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  231201. case Path::Iterator::closePath: CGContextClosePath (context); break;
  231202. default: jassertfalse; break;
  231203. }
  231204. }
  231205. }
  231206. void createPath (const Path& path, const AffineTransform& transform) const
  231207. {
  231208. CGContextBeginPath (context);
  231209. Path::Iterator i (path);
  231210. while (i.next())
  231211. {
  231212. switch (i.elementType)
  231213. {
  231214. case Path::Iterator::startNewSubPath:
  231215. transform.transformPoint (i.x1, i.y1);
  231216. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  231217. break;
  231218. case Path::Iterator::lineTo:
  231219. transform.transformPoint (i.x1, i.y1);
  231220. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  231221. break;
  231222. case Path::Iterator::quadraticTo:
  231223. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  231224. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  231225. break;
  231226. case Path::Iterator::cubicTo:
  231227. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  231228. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  231229. break;
  231230. case Path::Iterator::closePath:
  231231. CGContextClosePath (context); break;
  231232. default:
  231233. jassertfalse;
  231234. break;
  231235. }
  231236. }
  231237. }
  231238. void flip() const
  231239. {
  231240. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  231241. }
  231242. void applyTransform (const AffineTransform& transform) const
  231243. {
  231244. CGAffineTransform t;
  231245. t.a = transform.mat00;
  231246. t.b = transform.mat10;
  231247. t.c = transform.mat01;
  231248. t.d = transform.mat11;
  231249. t.tx = transform.mat02;
  231250. t.ty = transform.mat12;
  231251. CGContextConcatCTM (context, t);
  231252. }
  231253. CoreGraphicsContext (const CoreGraphicsContext&);
  231254. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  231255. };
  231256. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  231257. {
  231258. return new CoreGraphicsContext (context, height);
  231259. }
  231260. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  231261. const Image juce_loadWithCoreImage (InputStream& input)
  231262. {
  231263. MemoryBlock data;
  231264. input.readIntoMemoryBlock (data, -1);
  231265. #if JUCE_IOS
  231266. JUCE_AUTORELEASEPOOL
  231267. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  231268. length: data.getSize()
  231269. freeWhenDone: NO]];
  231270. if (image != nil)
  231271. {
  231272. CGImageRef loadedImage = image.CGImage;
  231273. #else
  231274. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  231275. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  231276. CGDataProviderRelease (provider);
  231277. if (imageSource != 0)
  231278. {
  231279. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  231280. CFRelease (imageSource);
  231281. #endif
  231282. if (loadedImage != 0)
  231283. {
  231284. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  231285. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  231286. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231287. hasAlphaChan, Image::NativeImage);
  231288. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231289. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231290. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231291. CGContextFlush (cgImage->context);
  231292. #if ! JUCE_IOS
  231293. CFRelease (loadedImage);
  231294. #endif
  231295. return image;
  231296. }
  231297. }
  231298. return Image::null;
  231299. }
  231300. #endif
  231301. #endif
  231302. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231303. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231304. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231305. // compiled on its own).
  231306. #if JUCE_INCLUDED_FILE
  231307. class NSViewComponentPeer;
  231308. END_JUCE_NAMESPACE
  231309. @interface NSEvent (JuceDeviceDelta)
  231310. - (float) deviceDeltaX;
  231311. - (float) deviceDeltaY;
  231312. @end
  231313. #define JuceNSView MakeObjCClassName(JuceNSView)
  231314. @interface JuceNSView : NSView<NSTextInput>
  231315. {
  231316. @public
  231317. NSViewComponentPeer* owner;
  231318. NSNotificationCenter* notificationCenter;
  231319. String* stringBeingComposed;
  231320. bool textWasInserted;
  231321. }
  231322. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231323. - (void) dealloc;
  231324. - (BOOL) isOpaque;
  231325. - (void) drawRect: (NSRect) r;
  231326. - (void) mouseDown: (NSEvent*) ev;
  231327. - (void) asyncMouseDown: (NSEvent*) ev;
  231328. - (void) mouseUp: (NSEvent*) ev;
  231329. - (void) asyncMouseUp: (NSEvent*) ev;
  231330. - (void) mouseDragged: (NSEvent*) ev;
  231331. - (void) mouseMoved: (NSEvent*) ev;
  231332. - (void) mouseEntered: (NSEvent*) ev;
  231333. - (void) mouseExited: (NSEvent*) ev;
  231334. - (void) rightMouseDown: (NSEvent*) ev;
  231335. - (void) rightMouseDragged: (NSEvent*) ev;
  231336. - (void) rightMouseUp: (NSEvent*) ev;
  231337. - (void) otherMouseDown: (NSEvent*) ev;
  231338. - (void) otherMouseDragged: (NSEvent*) ev;
  231339. - (void) otherMouseUp: (NSEvent*) ev;
  231340. - (void) scrollWheel: (NSEvent*) ev;
  231341. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231342. - (void) frameChanged: (NSNotification*) n;
  231343. - (void) viewDidMoveToWindow;
  231344. - (void) keyDown: (NSEvent*) ev;
  231345. - (void) keyUp: (NSEvent*) ev;
  231346. // NSTextInput Methods
  231347. - (void) insertText: (id) aString;
  231348. - (void) doCommandBySelector: (SEL) aSelector;
  231349. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231350. - (void) unmarkText;
  231351. - (BOOL) hasMarkedText;
  231352. - (long) conversationIdentifier;
  231353. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231354. - (NSRange) markedRange;
  231355. - (NSRange) selectedRange;
  231356. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231357. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231358. - (NSArray*) validAttributesForMarkedText;
  231359. - (void) flagsChanged: (NSEvent*) ev;
  231360. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231361. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231362. #endif
  231363. - (BOOL) becomeFirstResponder;
  231364. - (BOOL) resignFirstResponder;
  231365. - (BOOL) acceptsFirstResponder;
  231366. - (void) asyncRepaint: (id) rect;
  231367. - (NSArray*) getSupportedDragTypes;
  231368. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231369. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231370. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231371. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231372. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231373. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231374. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231375. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231376. @end
  231377. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231378. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231379. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231380. #else
  231381. @interface JuceNSWindow : NSWindow
  231382. #endif
  231383. {
  231384. @private
  231385. NSViewComponentPeer* owner;
  231386. bool isZooming;
  231387. }
  231388. - (void) setOwner: (NSViewComponentPeer*) owner;
  231389. - (BOOL) canBecomeKeyWindow;
  231390. - (void) becomeKeyWindow;
  231391. - (BOOL) windowShouldClose: (id) window;
  231392. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231393. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231394. - (void) zoom: (id) sender;
  231395. @end
  231396. BEGIN_JUCE_NAMESPACE
  231397. class NSViewComponentPeer : public ComponentPeer
  231398. {
  231399. public:
  231400. NSViewComponentPeer (Component* const component,
  231401. const int windowStyleFlags,
  231402. NSView* viewToAttachTo);
  231403. ~NSViewComponentPeer();
  231404. void* getNativeHandle() const;
  231405. void setVisible (bool shouldBeVisible);
  231406. void setTitle (const String& title);
  231407. void setPosition (int x, int y);
  231408. void setSize (int w, int h);
  231409. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231410. const Rectangle<int> getBounds (const bool global) const;
  231411. const Rectangle<int> getBounds() const;
  231412. const Point<int> getScreenPosition() const;
  231413. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231414. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231415. void setMinimised (bool shouldBeMinimised);
  231416. bool isMinimised() const;
  231417. void setFullScreen (bool shouldBeFullScreen);
  231418. bool isFullScreen() const;
  231419. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231420. const BorderSize getFrameSize() const;
  231421. bool setAlwaysOnTop (bool alwaysOnTop);
  231422. void toFront (bool makeActiveWindow);
  231423. void toBehind (ComponentPeer* other);
  231424. void setIcon (const Image& newIcon);
  231425. const StringArray getAvailableRenderingEngines();
  231426. int getCurrentRenderingEngine() throw();
  231427. void setCurrentRenderingEngine (int index);
  231428. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231429. for example having more than one juce plugin loaded into a host, then when a
  231430. method is called, the actual code that runs might actually be in a different module
  231431. than the one you expect... So any calls to library functions or statics that are
  231432. made inside obj-c methods will probably end up getting executed in a different DLL's
  231433. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231434. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231435. virtual methods of an object that's known to live inside the right module's space.
  231436. */
  231437. virtual void redirectMouseDown (NSEvent* ev);
  231438. virtual void redirectMouseUp (NSEvent* ev);
  231439. virtual void redirectMouseDrag (NSEvent* ev);
  231440. virtual void redirectMouseMove (NSEvent* ev);
  231441. virtual void redirectMouseEnter (NSEvent* ev);
  231442. virtual void redirectMouseExit (NSEvent* ev);
  231443. virtual void redirectMouseWheel (NSEvent* ev);
  231444. void sendMouseEvent (NSEvent* ev);
  231445. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231446. virtual bool redirectKeyDown (NSEvent* ev);
  231447. virtual bool redirectKeyUp (NSEvent* ev);
  231448. virtual void redirectModKeyChange (NSEvent* ev);
  231449. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231450. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231451. #endif
  231452. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231453. virtual bool isOpaque();
  231454. virtual void drawRect (NSRect r);
  231455. virtual bool canBecomeKeyWindow();
  231456. virtual bool windowShouldClose();
  231457. virtual void redirectMovedOrResized();
  231458. virtual void viewMovedToWindow();
  231459. virtual NSRect constrainRect (NSRect r);
  231460. static void showArrowCursorIfNeeded();
  231461. static void updateModifiers (NSEvent* e);
  231462. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231463. static int getKeyCodeFromEvent (NSEvent* ev)
  231464. {
  231465. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231466. int keyCode = unmodified[0];
  231467. if (keyCode == 0x19) // (backwards-tab)
  231468. keyCode = '\t';
  231469. else if (keyCode == 0x03) // (enter)
  231470. keyCode = '\r';
  231471. else
  231472. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231473. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231474. {
  231475. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231476. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231477. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231478. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231479. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231480. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231481. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231482. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231483. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231484. if (keyCode == numPadConversions [i])
  231485. keyCode = numPadConversions [i + 1];
  231486. }
  231487. return keyCode;
  231488. }
  231489. static int64 getMouseTime (NSEvent* e)
  231490. {
  231491. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231492. + (int64) ([e timestamp] * 1000.0);
  231493. }
  231494. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231495. {
  231496. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231497. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231498. }
  231499. static int getModifierForButtonNumber (const NSInteger num)
  231500. {
  231501. return num == 0 ? ModifierKeys::leftButtonModifier
  231502. : (num == 1 ? ModifierKeys::rightButtonModifier
  231503. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231504. }
  231505. virtual void viewFocusGain();
  231506. virtual void viewFocusLoss();
  231507. bool isFocused() const;
  231508. void grabFocus();
  231509. void textInputRequired (const Point<int>& position);
  231510. void repaint (const Rectangle<int>& area);
  231511. void performAnyPendingRepaintsNow();
  231512. juce_UseDebuggingNewOperator
  231513. NSWindow* window;
  231514. JuceNSView* view;
  231515. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231516. static ModifierKeys currentModifiers;
  231517. static ComponentPeer* currentlyFocusedPeer;
  231518. static Array<int> keysCurrentlyDown;
  231519. };
  231520. END_JUCE_NAMESPACE
  231521. @implementation JuceNSView
  231522. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231523. withFrame: (NSRect) frame
  231524. {
  231525. [super initWithFrame: frame];
  231526. owner = owner_;
  231527. stringBeingComposed = 0;
  231528. textWasInserted = false;
  231529. notificationCenter = [NSNotificationCenter defaultCenter];
  231530. [notificationCenter addObserver: self
  231531. selector: @selector (frameChanged:)
  231532. name: NSViewFrameDidChangeNotification
  231533. object: self];
  231534. if (! owner_->isSharedWindow)
  231535. {
  231536. [notificationCenter addObserver: self
  231537. selector: @selector (frameChanged:)
  231538. name: NSWindowDidMoveNotification
  231539. object: owner_->window];
  231540. }
  231541. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231542. return self;
  231543. }
  231544. - (void) dealloc
  231545. {
  231546. [notificationCenter removeObserver: self];
  231547. delete stringBeingComposed;
  231548. [super dealloc];
  231549. }
  231550. - (void) drawRect: (NSRect) r
  231551. {
  231552. if (owner != 0)
  231553. owner->drawRect (r);
  231554. }
  231555. - (BOOL) isOpaque
  231556. {
  231557. return owner == 0 || owner->isOpaque();
  231558. }
  231559. - (void) mouseDown: (NSEvent*) ev
  231560. {
  231561. if (JUCEApplication::isStandaloneApp())
  231562. [self asyncMouseDown: ev];
  231563. else
  231564. // In some host situations, the host will stop modal loops from working
  231565. // correctly if they're called from a mouse event, so we'll trigger
  231566. // the event asynchronously..
  231567. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231568. withObject: ev
  231569. waitUntilDone: NO];
  231570. }
  231571. - (void) asyncMouseDown: (NSEvent*) ev
  231572. {
  231573. if (owner != 0)
  231574. owner->redirectMouseDown (ev);
  231575. }
  231576. - (void) mouseUp: (NSEvent*) ev
  231577. {
  231578. if (! JUCEApplication::isStandaloneApp())
  231579. [self asyncMouseUp: ev];
  231580. else
  231581. // In some host situations, the host will stop modal loops from working
  231582. // correctly if they're called from a mouse event, so we'll trigger
  231583. // the event asynchronously..
  231584. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231585. withObject: ev
  231586. waitUntilDone: NO];
  231587. }
  231588. - (void) asyncMouseUp: (NSEvent*) ev
  231589. {
  231590. if (owner != 0)
  231591. owner->redirectMouseUp (ev);
  231592. }
  231593. - (void) mouseDragged: (NSEvent*) ev
  231594. {
  231595. if (owner != 0)
  231596. owner->redirectMouseDrag (ev);
  231597. }
  231598. - (void) mouseMoved: (NSEvent*) ev
  231599. {
  231600. if (owner != 0)
  231601. owner->redirectMouseMove (ev);
  231602. }
  231603. - (void) mouseEntered: (NSEvent*) ev
  231604. {
  231605. if (owner != 0)
  231606. owner->redirectMouseEnter (ev);
  231607. }
  231608. - (void) mouseExited: (NSEvent*) ev
  231609. {
  231610. if (owner != 0)
  231611. owner->redirectMouseExit (ev);
  231612. }
  231613. - (void) rightMouseDown: (NSEvent*) ev
  231614. {
  231615. [self mouseDown: ev];
  231616. }
  231617. - (void) rightMouseDragged: (NSEvent*) ev
  231618. {
  231619. [self mouseDragged: ev];
  231620. }
  231621. - (void) rightMouseUp: (NSEvent*) ev
  231622. {
  231623. [self mouseUp: ev];
  231624. }
  231625. - (void) otherMouseDown: (NSEvent*) ev
  231626. {
  231627. [self mouseDown: ev];
  231628. }
  231629. - (void) otherMouseDragged: (NSEvent*) ev
  231630. {
  231631. [self mouseDragged: ev];
  231632. }
  231633. - (void) otherMouseUp: (NSEvent*) ev
  231634. {
  231635. [self mouseUp: ev];
  231636. }
  231637. - (void) scrollWheel: (NSEvent*) ev
  231638. {
  231639. if (owner != 0)
  231640. owner->redirectMouseWheel (ev);
  231641. }
  231642. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231643. {
  231644. (void) ev;
  231645. return YES;
  231646. }
  231647. - (void) frameChanged: (NSNotification*) n
  231648. {
  231649. (void) n;
  231650. if (owner != 0)
  231651. owner->redirectMovedOrResized();
  231652. }
  231653. - (void) viewDidMoveToWindow
  231654. {
  231655. if (owner != 0)
  231656. owner->viewMovedToWindow();
  231657. }
  231658. - (void) asyncRepaint: (id) rect
  231659. {
  231660. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231661. [self setNeedsDisplayInRect: *r];
  231662. }
  231663. - (void) keyDown: (NSEvent*) ev
  231664. {
  231665. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231666. textWasInserted = false;
  231667. if (target != 0)
  231668. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231669. else
  231670. deleteAndZero (stringBeingComposed);
  231671. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231672. [super keyDown: ev];
  231673. }
  231674. - (void) keyUp: (NSEvent*) ev
  231675. {
  231676. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231677. [super keyUp: ev];
  231678. }
  231679. - (void) insertText: (id) aString
  231680. {
  231681. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231682. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231683. if ([newText length] > 0)
  231684. {
  231685. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231686. if (target != 0)
  231687. {
  231688. target->insertTextAtCaret (nsStringToJuce (newText));
  231689. textWasInserted = true;
  231690. }
  231691. }
  231692. deleteAndZero (stringBeingComposed);
  231693. }
  231694. - (void) doCommandBySelector: (SEL) aSelector
  231695. {
  231696. (void) aSelector;
  231697. }
  231698. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231699. {
  231700. (void) selectionRange;
  231701. if (stringBeingComposed == 0)
  231702. stringBeingComposed = new String();
  231703. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231704. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231705. if (target != 0)
  231706. {
  231707. const Range<int> currentHighlight (target->getHighlightedRegion());
  231708. target->insertTextAtCaret (*stringBeingComposed);
  231709. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231710. textWasInserted = true;
  231711. }
  231712. }
  231713. - (void) unmarkText
  231714. {
  231715. if (stringBeingComposed != 0)
  231716. {
  231717. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231718. if (target != 0)
  231719. {
  231720. target->insertTextAtCaret (*stringBeingComposed);
  231721. textWasInserted = true;
  231722. }
  231723. }
  231724. deleteAndZero (stringBeingComposed);
  231725. }
  231726. - (BOOL) hasMarkedText
  231727. {
  231728. return stringBeingComposed != 0;
  231729. }
  231730. - (long) conversationIdentifier
  231731. {
  231732. return (long) (pointer_sized_int) self;
  231733. }
  231734. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231735. {
  231736. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231737. if (target != 0)
  231738. {
  231739. const Range<int> r ((int) theRange.location,
  231740. (int) (theRange.location + theRange.length));
  231741. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231742. }
  231743. return nil;
  231744. }
  231745. - (NSRange) markedRange
  231746. {
  231747. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231748. : NSMakeRange (NSNotFound, 0);
  231749. }
  231750. - (NSRange) selectedRange
  231751. {
  231752. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231753. if (target != 0)
  231754. {
  231755. const Range<int> highlight (target->getHighlightedRegion());
  231756. if (! highlight.isEmpty())
  231757. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231758. }
  231759. return NSMakeRange (NSNotFound, 0);
  231760. }
  231761. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231762. {
  231763. (void) theRange;
  231764. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231765. if (comp == 0)
  231766. return NSMakeRect (0, 0, 0, 0);
  231767. const Rectangle<int> bounds (comp->getScreenBounds());
  231768. return NSMakeRect (bounds.getX(),
  231769. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231770. bounds.getWidth(),
  231771. bounds.getHeight());
  231772. }
  231773. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231774. {
  231775. (void) thePoint;
  231776. return NSNotFound;
  231777. }
  231778. - (NSArray*) validAttributesForMarkedText
  231779. {
  231780. return [NSArray array];
  231781. }
  231782. - (void) flagsChanged: (NSEvent*) ev
  231783. {
  231784. if (owner != 0)
  231785. owner->redirectModKeyChange (ev);
  231786. }
  231787. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231788. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231789. {
  231790. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231791. return true;
  231792. return [super performKeyEquivalent: ev];
  231793. }
  231794. #endif
  231795. - (BOOL) becomeFirstResponder
  231796. {
  231797. if (owner != 0)
  231798. owner->viewFocusGain();
  231799. return true;
  231800. }
  231801. - (BOOL) resignFirstResponder
  231802. {
  231803. if (owner != 0)
  231804. owner->viewFocusLoss();
  231805. return true;
  231806. }
  231807. - (BOOL) acceptsFirstResponder
  231808. {
  231809. return owner != 0 && owner->canBecomeKeyWindow();
  231810. }
  231811. - (NSArray*) getSupportedDragTypes
  231812. {
  231813. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231814. }
  231815. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231816. {
  231817. return owner != 0 && owner->sendDragCallback (type, sender);
  231818. }
  231819. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231820. {
  231821. if ([self sendDragCallback: 0 sender: sender])
  231822. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231823. else
  231824. return NSDragOperationNone;
  231825. }
  231826. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231827. {
  231828. if ([self sendDragCallback: 0 sender: sender])
  231829. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231830. else
  231831. return NSDragOperationNone;
  231832. }
  231833. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231834. {
  231835. [self sendDragCallback: 1 sender: sender];
  231836. }
  231837. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231838. {
  231839. [self sendDragCallback: 1 sender: sender];
  231840. }
  231841. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231842. {
  231843. (void) sender;
  231844. return YES;
  231845. }
  231846. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231847. {
  231848. return [self sendDragCallback: 2 sender: sender];
  231849. }
  231850. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231851. {
  231852. (void) sender;
  231853. }
  231854. @end
  231855. @implementation JuceNSWindow
  231856. - (void) setOwner: (NSViewComponentPeer*) owner_
  231857. {
  231858. owner = owner_;
  231859. isZooming = false;
  231860. }
  231861. - (BOOL) canBecomeKeyWindow
  231862. {
  231863. return owner != 0 && owner->canBecomeKeyWindow();
  231864. }
  231865. - (void) becomeKeyWindow
  231866. {
  231867. [super becomeKeyWindow];
  231868. if (owner != 0)
  231869. owner->grabFocus();
  231870. }
  231871. - (BOOL) windowShouldClose: (id) window
  231872. {
  231873. (void) window;
  231874. return owner == 0 || owner->windowShouldClose();
  231875. }
  231876. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231877. {
  231878. (void) screen;
  231879. if (owner != 0)
  231880. frameRect = owner->constrainRect (frameRect);
  231881. return frameRect;
  231882. }
  231883. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231884. {
  231885. (void) window;
  231886. if (isZooming)
  231887. return proposedFrameSize;
  231888. NSRect frameRect = [self frame];
  231889. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231890. frameRect.size = proposedFrameSize;
  231891. if (owner != 0)
  231892. frameRect = owner->constrainRect (frameRect);
  231893. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231894. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231895. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231896. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231897. return frameRect.size;
  231898. }
  231899. - (void) zoom: (id) sender
  231900. {
  231901. isZooming = true;
  231902. [super zoom: sender];
  231903. isZooming = false;
  231904. }
  231905. - (void) windowWillMove: (NSNotification*) notification
  231906. {
  231907. (void) notification;
  231908. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231909. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231910. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231911. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231912. }
  231913. @end
  231914. BEGIN_JUCE_NAMESPACE
  231915. ModifierKeys NSViewComponentPeer::currentModifiers;
  231916. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231917. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231918. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231919. {
  231920. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231921. return true;
  231922. if (keyCode >= 'A' && keyCode <= 'Z'
  231923. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231924. return true;
  231925. if (keyCode >= 'a' && keyCode <= 'z'
  231926. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231927. return true;
  231928. return false;
  231929. }
  231930. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231931. {
  231932. int m = 0;
  231933. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231934. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231935. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231936. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231937. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231938. }
  231939. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231940. {
  231941. updateModifiers (ev);
  231942. int keyCode = getKeyCodeFromEvent (ev);
  231943. if (keyCode != 0)
  231944. {
  231945. if (isKeyDown)
  231946. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231947. else
  231948. keysCurrentlyDown.removeValue (keyCode);
  231949. }
  231950. }
  231951. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231952. {
  231953. return NSViewComponentPeer::currentModifiers;
  231954. }
  231955. void ModifierKeys::updateCurrentModifiers() throw()
  231956. {
  231957. currentModifiers = NSViewComponentPeer::currentModifiers;
  231958. }
  231959. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231960. const int windowStyleFlags,
  231961. NSView* viewToAttachTo)
  231962. : ComponentPeer (component_, windowStyleFlags),
  231963. window (0),
  231964. view (0),
  231965. isSharedWindow (viewToAttachTo != 0),
  231966. fullScreen (false),
  231967. insideDrawRect (false),
  231968. #if USE_COREGRAPHICS_RENDERING
  231969. usingCoreGraphics (true),
  231970. #else
  231971. usingCoreGraphics (false),
  231972. #endif
  231973. recursiveToFrontCall (false)
  231974. {
  231975. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231976. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231977. [view setPostsFrameChangedNotifications: YES];
  231978. if (isSharedWindow)
  231979. {
  231980. window = [viewToAttachTo window];
  231981. [viewToAttachTo addSubview: view];
  231982. setVisible (component->isVisible());
  231983. }
  231984. else
  231985. {
  231986. r.origin.x = (float) component->getX();
  231987. r.origin.y = (float) component->getY();
  231988. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231989. unsigned int style = 0;
  231990. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231991. style = NSBorderlessWindowMask;
  231992. else
  231993. style = NSTitledWindowMask;
  231994. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231995. style |= NSMiniaturizableWindowMask;
  231996. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231997. style |= NSClosableWindowMask;
  231998. if ((windowStyleFlags & windowIsResizable) != 0)
  231999. style |= NSResizableWindowMask;
  232000. window = [[JuceNSWindow alloc] initWithContentRect: r
  232001. styleMask: style
  232002. backing: NSBackingStoreBuffered
  232003. defer: YES];
  232004. [((JuceNSWindow*) window) setOwner: this];
  232005. [window orderOut: nil];
  232006. [window setDelegate: (JuceNSWindow*) window];
  232007. [window setOpaque: component->isOpaque()];
  232008. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  232009. if (component->isAlwaysOnTop())
  232010. [window setLevel: NSFloatingWindowLevel];
  232011. [window setContentView: view];
  232012. [window setAutodisplay: YES];
  232013. [window setAcceptsMouseMovedEvents: YES];
  232014. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  232015. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  232016. [window setReleasedWhenClosed: YES];
  232017. [window retain];
  232018. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  232019. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  232020. }
  232021. setTitle (component->getName());
  232022. }
  232023. NSViewComponentPeer::~NSViewComponentPeer()
  232024. {
  232025. view->owner = 0;
  232026. [view removeFromSuperview];
  232027. [view release];
  232028. if (! isSharedWindow)
  232029. {
  232030. [((JuceNSWindow*) window) setOwner: 0];
  232031. [window close];
  232032. [window release];
  232033. }
  232034. }
  232035. void* NSViewComponentPeer::getNativeHandle() const
  232036. {
  232037. return view;
  232038. }
  232039. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  232040. {
  232041. if (isSharedWindow)
  232042. {
  232043. [view setHidden: ! shouldBeVisible];
  232044. }
  232045. else
  232046. {
  232047. if (shouldBeVisible)
  232048. {
  232049. [window orderFront: nil];
  232050. handleBroughtToFront();
  232051. }
  232052. else
  232053. {
  232054. [window orderOut: nil];
  232055. }
  232056. }
  232057. }
  232058. void NSViewComponentPeer::setTitle (const String& title)
  232059. {
  232060. const ScopedAutoReleasePool pool;
  232061. if (! isSharedWindow)
  232062. [window setTitle: juceStringToNS (title)];
  232063. }
  232064. void NSViewComponentPeer::setPosition (int x, int y)
  232065. {
  232066. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  232067. }
  232068. void NSViewComponentPeer::setSize (int w, int h)
  232069. {
  232070. setBounds (component->getX(), component->getY(), w, h, false);
  232071. }
  232072. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  232073. {
  232074. fullScreen = isNowFullScreen;
  232075. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  232076. if (isSharedWindow)
  232077. {
  232078. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232079. if ([view frame].size.width != r.size.width
  232080. || [view frame].size.height != r.size.height)
  232081. [view setNeedsDisplay: true];
  232082. [view setFrame: r];
  232083. }
  232084. else
  232085. {
  232086. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  232087. [window setFrame: [window frameRectForContentRect: r]
  232088. display: true];
  232089. }
  232090. }
  232091. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  232092. {
  232093. NSRect r = [view frame];
  232094. if (global && [view window] != 0)
  232095. {
  232096. r = [view convertRect: r toView: nil];
  232097. NSRect wr = [[view window] frame];
  232098. r.origin.x += wr.origin.x;
  232099. r.origin.y += wr.origin.y;
  232100. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232101. }
  232102. else
  232103. {
  232104. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  232105. }
  232106. return Rectangle<int> (convertToRectInt (r));
  232107. }
  232108. const Rectangle<int> NSViewComponentPeer::getBounds() const
  232109. {
  232110. return getBounds (! isSharedWindow);
  232111. }
  232112. const Point<int> NSViewComponentPeer::getScreenPosition() const
  232113. {
  232114. return getBounds (true).getPosition();
  232115. }
  232116. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  232117. {
  232118. return relativePosition + getScreenPosition();
  232119. }
  232120. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  232121. {
  232122. return screenPosition - getScreenPosition();
  232123. }
  232124. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  232125. {
  232126. if (constrainer != 0)
  232127. {
  232128. NSRect current = [window frame];
  232129. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  232130. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232131. Rectangle<int> pos (convertToRectInt (r));
  232132. Rectangle<int> original (convertToRectInt (current));
  232133. if ([window inLiveResize])
  232134. {
  232135. constrainer->checkBounds (pos, original,
  232136. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232137. false, false, true, true);
  232138. }
  232139. else
  232140. {
  232141. constrainer->checkBounds (pos, original,
  232142. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232143. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  232144. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  232145. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  232146. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  232147. }
  232148. r.origin.x = pos.getX();
  232149. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  232150. r.size.width = pos.getWidth();
  232151. r.size.height = pos.getHeight();
  232152. }
  232153. return r;
  232154. }
  232155. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  232156. {
  232157. if (! isSharedWindow)
  232158. {
  232159. if (shouldBeMinimised)
  232160. [window miniaturize: nil];
  232161. else
  232162. [window deminiaturize: nil];
  232163. }
  232164. }
  232165. bool NSViewComponentPeer::isMinimised() const
  232166. {
  232167. return window != 0 && [window isMiniaturized];
  232168. }
  232169. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  232170. {
  232171. if (! isSharedWindow)
  232172. {
  232173. Rectangle<int> r (lastNonFullscreenBounds);
  232174. setMinimised (false);
  232175. if (fullScreen != shouldBeFullScreen)
  232176. {
  232177. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  232178. {
  232179. fullScreen = true;
  232180. [window performZoom: nil];
  232181. }
  232182. else
  232183. {
  232184. if (shouldBeFullScreen)
  232185. r = Desktop::getInstance().getMainMonitorArea();
  232186. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  232187. if (r != getComponent()->getBounds() && ! r.isEmpty())
  232188. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  232189. }
  232190. }
  232191. }
  232192. }
  232193. bool NSViewComponentPeer::isFullScreen() const
  232194. {
  232195. return fullScreen;
  232196. }
  232197. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  232198. {
  232199. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  232200. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  232201. return false;
  232202. NSPoint p;
  232203. p.x = (float) position.getX();
  232204. p.y = (float) position.getY();
  232205. NSView* v = [view hitTest: p];
  232206. if (trueIfInAChildWindow)
  232207. return v != nil;
  232208. return v == view;
  232209. }
  232210. const BorderSize NSViewComponentPeer::getFrameSize() const
  232211. {
  232212. BorderSize b;
  232213. if (! isSharedWindow)
  232214. {
  232215. NSRect v = [view convertRect: [view frame] toView: nil];
  232216. NSRect w = [window frame];
  232217. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  232218. b.setBottom ((int) v.origin.y);
  232219. b.setLeft ((int) v.origin.x);
  232220. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  232221. }
  232222. return b;
  232223. }
  232224. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  232225. {
  232226. if (! isSharedWindow)
  232227. {
  232228. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  232229. : NSNormalWindowLevel];
  232230. }
  232231. return true;
  232232. }
  232233. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  232234. {
  232235. if (isSharedWindow)
  232236. {
  232237. [[view superview] addSubview: view
  232238. positioned: NSWindowAbove
  232239. relativeTo: nil];
  232240. }
  232241. if (window != 0 && component->isVisible())
  232242. {
  232243. if (makeActiveWindow)
  232244. [window makeKeyAndOrderFront: nil];
  232245. else
  232246. [window orderFront: nil];
  232247. if (! recursiveToFrontCall)
  232248. {
  232249. recursiveToFrontCall = true;
  232250. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232251. handleBroughtToFront();
  232252. recursiveToFrontCall = false;
  232253. }
  232254. }
  232255. }
  232256. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  232257. {
  232258. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  232259. jassert (otherPeer != 0); // wrong type of window?
  232260. if (otherPeer != 0)
  232261. {
  232262. if (isSharedWindow)
  232263. {
  232264. [[view superview] addSubview: view
  232265. positioned: NSWindowBelow
  232266. relativeTo: otherPeer->view];
  232267. }
  232268. else
  232269. {
  232270. [window orderWindow: NSWindowBelow
  232271. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232272. : nil ];
  232273. }
  232274. }
  232275. }
  232276. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232277. {
  232278. // to do..
  232279. }
  232280. void NSViewComponentPeer::viewFocusGain()
  232281. {
  232282. if (currentlyFocusedPeer != this)
  232283. {
  232284. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232285. currentlyFocusedPeer->handleFocusLoss();
  232286. currentlyFocusedPeer = this;
  232287. handleFocusGain();
  232288. }
  232289. }
  232290. void NSViewComponentPeer::viewFocusLoss()
  232291. {
  232292. if (currentlyFocusedPeer == this)
  232293. {
  232294. currentlyFocusedPeer = 0;
  232295. handleFocusLoss();
  232296. }
  232297. }
  232298. void juce_HandleProcessFocusChange()
  232299. {
  232300. NSViewComponentPeer::keysCurrentlyDown.clear();
  232301. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232302. {
  232303. if (Process::isForegroundProcess())
  232304. {
  232305. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232306. ComponentPeer::bringModalComponentToFront();
  232307. }
  232308. else
  232309. {
  232310. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232311. // turn kiosk mode off if we lose focus..
  232312. Desktop::getInstance().setKioskModeComponent (0);
  232313. }
  232314. }
  232315. }
  232316. bool NSViewComponentPeer::isFocused() const
  232317. {
  232318. return isSharedWindow ? this == currentlyFocusedPeer
  232319. : (window != 0 && [window isKeyWindow]);
  232320. }
  232321. void NSViewComponentPeer::grabFocus()
  232322. {
  232323. if (window != 0)
  232324. {
  232325. [window makeKeyWindow];
  232326. [window makeFirstResponder: view];
  232327. viewFocusGain();
  232328. }
  232329. }
  232330. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232331. {
  232332. }
  232333. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232334. {
  232335. String unicode (nsStringToJuce ([ev characters]));
  232336. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232337. int keyCode = getKeyCodeFromEvent (ev);
  232338. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232339. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232340. if (unicode.isNotEmpty() || keyCode != 0)
  232341. {
  232342. if (isKeyDown)
  232343. {
  232344. bool used = false;
  232345. while (unicode.length() > 0)
  232346. {
  232347. juce_wchar textCharacter = unicode[0];
  232348. unicode = unicode.substring (1);
  232349. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232350. textCharacter = 0;
  232351. used = handleKeyUpOrDown (true) || used;
  232352. used = handleKeyPress (keyCode, textCharacter) || used;
  232353. }
  232354. return used;
  232355. }
  232356. else
  232357. {
  232358. if (handleKeyUpOrDown (false))
  232359. return true;
  232360. }
  232361. }
  232362. return false;
  232363. }
  232364. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232365. {
  232366. updateKeysDown (ev, true);
  232367. bool used = handleKeyEvent (ev, true);
  232368. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232369. {
  232370. // for command keys, the key-up event is thrown away, so simulate one..
  232371. updateKeysDown (ev, false);
  232372. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232373. }
  232374. // (If we're running modally, don't allow unused keystrokes to be passed
  232375. // along to other blocked views..)
  232376. if (Component::getCurrentlyModalComponent() != 0)
  232377. used = true;
  232378. return used;
  232379. }
  232380. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232381. {
  232382. updateKeysDown (ev, false);
  232383. return handleKeyEvent (ev, false)
  232384. || Component::getCurrentlyModalComponent() != 0;
  232385. }
  232386. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232387. {
  232388. keysCurrentlyDown.clear();
  232389. handleKeyUpOrDown (true);
  232390. updateModifiers (ev);
  232391. handleModifierKeysChange();
  232392. }
  232393. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232394. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232395. {
  232396. if ([ev type] == NSKeyDown)
  232397. return redirectKeyDown (ev);
  232398. else if ([ev type] == NSKeyUp)
  232399. return redirectKeyUp (ev);
  232400. return false;
  232401. }
  232402. #endif
  232403. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232404. {
  232405. updateModifiers (ev);
  232406. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232407. }
  232408. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232409. {
  232410. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232411. sendMouseEvent (ev);
  232412. }
  232413. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232414. {
  232415. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232416. sendMouseEvent (ev);
  232417. showArrowCursorIfNeeded();
  232418. }
  232419. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232420. {
  232421. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232422. sendMouseEvent (ev);
  232423. }
  232424. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232425. {
  232426. currentModifiers = currentModifiers.withoutMouseButtons();
  232427. sendMouseEvent (ev);
  232428. showArrowCursorIfNeeded();
  232429. }
  232430. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232431. {
  232432. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232433. currentModifiers = currentModifiers.withoutMouseButtons();
  232434. sendMouseEvent (ev);
  232435. }
  232436. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232437. {
  232438. currentModifiers = currentModifiers.withoutMouseButtons();
  232439. sendMouseEvent (ev);
  232440. }
  232441. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232442. {
  232443. updateModifiers (ev);
  232444. float x = 0, y = 0;
  232445. @try
  232446. {
  232447. x = [ev deviceDeltaX] * 0.5f;
  232448. y = [ev deviceDeltaY] * 0.5f;
  232449. }
  232450. @catch (...)
  232451. {}
  232452. if (x == 0 && y == 0)
  232453. {
  232454. x = [ev deltaX] * 10.0f;
  232455. y = [ev deltaY] * 10.0f;
  232456. }
  232457. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232458. }
  232459. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232460. {
  232461. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232462. if (mouse.getComponentUnderMouse() == 0
  232463. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232464. {
  232465. [[NSCursor arrowCursor] set];
  232466. }
  232467. }
  232468. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232469. {
  232470. NSString* bestType
  232471. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232472. if (bestType == nil)
  232473. return false;
  232474. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232475. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232476. StringArray files;
  232477. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232478. if (list == nil)
  232479. return false;
  232480. if ([list isKindOfClass: [NSArray class]])
  232481. {
  232482. NSArray* items = (NSArray*) list;
  232483. for (unsigned int i = 0; i < [items count]; ++i)
  232484. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232485. }
  232486. if (files.size() == 0)
  232487. return false;
  232488. if (type == 0)
  232489. handleFileDragMove (files, pos);
  232490. else if (type == 1)
  232491. handleFileDragExit (files);
  232492. else if (type == 2)
  232493. handleFileDragDrop (files, pos);
  232494. return true;
  232495. }
  232496. bool NSViewComponentPeer::isOpaque()
  232497. {
  232498. return component == 0 || component->isOpaque();
  232499. }
  232500. void NSViewComponentPeer::drawRect (NSRect r)
  232501. {
  232502. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232503. return;
  232504. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232505. if (! component->isOpaque())
  232506. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232507. #if USE_COREGRAPHICS_RENDERING
  232508. if (usingCoreGraphics)
  232509. {
  232510. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232511. insideDrawRect = true;
  232512. handlePaint (context);
  232513. insideDrawRect = false;
  232514. }
  232515. else
  232516. #endif
  232517. {
  232518. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232519. (int) (r.size.width + 0.5f),
  232520. (int) (r.size.height + 0.5f),
  232521. ! getComponent()->isOpaque());
  232522. const int xOffset = -roundToInt (r.origin.x);
  232523. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232524. const NSRect* rects = 0;
  232525. NSInteger numRects = 0;
  232526. [view getRectsBeingDrawn: &rects count: &numRects];
  232527. const Rectangle<int> clipBounds (temp.getBounds());
  232528. RectangleList clip;
  232529. for (int i = 0; i < numRects; ++i)
  232530. {
  232531. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232532. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232533. roundToInt (rects[i].size.width),
  232534. roundToInt (rects[i].size.height))));
  232535. }
  232536. if (! clip.isEmpty())
  232537. {
  232538. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232539. insideDrawRect = true;
  232540. handlePaint (context);
  232541. insideDrawRect = false;
  232542. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232543. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232544. CGColorSpaceRelease (colourSpace);
  232545. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232546. CGImageRelease (image);
  232547. }
  232548. }
  232549. }
  232550. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232551. {
  232552. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232553. #if USE_COREGRAPHICS_RENDERING
  232554. s.add ("CoreGraphics Renderer");
  232555. #endif
  232556. return s;
  232557. }
  232558. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232559. {
  232560. return usingCoreGraphics ? 1 : 0;
  232561. }
  232562. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232563. {
  232564. #if USE_COREGRAPHICS_RENDERING
  232565. if (usingCoreGraphics != (index > 0))
  232566. {
  232567. usingCoreGraphics = index > 0;
  232568. [view setNeedsDisplay: true];
  232569. }
  232570. #endif
  232571. }
  232572. bool NSViewComponentPeer::canBecomeKeyWindow()
  232573. {
  232574. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232575. }
  232576. bool NSViewComponentPeer::windowShouldClose()
  232577. {
  232578. if (! isValidPeer (this))
  232579. return YES;
  232580. handleUserClosingWindow();
  232581. return NO;
  232582. }
  232583. void NSViewComponentPeer::redirectMovedOrResized()
  232584. {
  232585. handleMovedOrResized();
  232586. }
  232587. void NSViewComponentPeer::viewMovedToWindow()
  232588. {
  232589. if (isSharedWindow)
  232590. window = [view window];
  232591. }
  232592. void Desktop::createMouseInputSources()
  232593. {
  232594. mouseSources.add (new MouseInputSource (0, true));
  232595. }
  232596. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232597. {
  232598. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232599. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232600. // is apparently still available in 64-bit apps..
  232601. if (enableOrDisable)
  232602. {
  232603. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232604. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232605. }
  232606. else
  232607. {
  232608. SetSystemUIMode (kUIModeNormal, 0);
  232609. }
  232610. }
  232611. class AsyncRepaintMessage : public CallbackMessage
  232612. {
  232613. public:
  232614. NSViewComponentPeer* const peer;
  232615. const Rectangle<int> rect;
  232616. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232617. : peer (peer_), rect (rect_)
  232618. {
  232619. }
  232620. void messageCallback()
  232621. {
  232622. if (ComponentPeer::isValidPeer (peer))
  232623. peer->repaint (rect);
  232624. }
  232625. };
  232626. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232627. {
  232628. if (insideDrawRect)
  232629. {
  232630. (new AsyncRepaintMessage (this, area))->post();
  232631. }
  232632. else
  232633. {
  232634. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232635. (float) area.getWidth(), (float) area.getHeight())];
  232636. }
  232637. }
  232638. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232639. {
  232640. [view displayIfNeeded];
  232641. }
  232642. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232643. {
  232644. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232645. }
  232646. const Image juce_createIconForFile (const File& file)
  232647. {
  232648. const ScopedAutoReleasePool pool;
  232649. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232650. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232651. [NSGraphicsContext saveGraphicsState];
  232652. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232653. [image drawAtPoint: NSMakePoint (0, 0)
  232654. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232655. operation: NSCompositeSourceOver fraction: 1.0f];
  232656. [[NSGraphicsContext currentContext] flushGraphics];
  232657. [NSGraphicsContext restoreGraphicsState];
  232658. return Image (result);
  232659. }
  232660. const int KeyPress::spaceKey = ' ';
  232661. const int KeyPress::returnKey = 0x0d;
  232662. const int KeyPress::escapeKey = 0x1b;
  232663. const int KeyPress::backspaceKey = 0x7f;
  232664. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232665. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232666. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232667. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232668. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232669. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232670. const int KeyPress::endKey = NSEndFunctionKey;
  232671. const int KeyPress::homeKey = NSHomeFunctionKey;
  232672. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232673. const int KeyPress::insertKey = -1;
  232674. const int KeyPress::tabKey = 9;
  232675. const int KeyPress::F1Key = NSF1FunctionKey;
  232676. const int KeyPress::F2Key = NSF2FunctionKey;
  232677. const int KeyPress::F3Key = NSF3FunctionKey;
  232678. const int KeyPress::F4Key = NSF4FunctionKey;
  232679. const int KeyPress::F5Key = NSF5FunctionKey;
  232680. const int KeyPress::F6Key = NSF6FunctionKey;
  232681. const int KeyPress::F7Key = NSF7FunctionKey;
  232682. const int KeyPress::F8Key = NSF8FunctionKey;
  232683. const int KeyPress::F9Key = NSF9FunctionKey;
  232684. const int KeyPress::F10Key = NSF10FunctionKey;
  232685. const int KeyPress::F11Key = NSF1FunctionKey;
  232686. const int KeyPress::F12Key = NSF12FunctionKey;
  232687. const int KeyPress::F13Key = NSF13FunctionKey;
  232688. const int KeyPress::F14Key = NSF14FunctionKey;
  232689. const int KeyPress::F15Key = NSF15FunctionKey;
  232690. const int KeyPress::F16Key = NSF16FunctionKey;
  232691. const int KeyPress::numberPad0 = 0x30020;
  232692. const int KeyPress::numberPad1 = 0x30021;
  232693. const int KeyPress::numberPad2 = 0x30022;
  232694. const int KeyPress::numberPad3 = 0x30023;
  232695. const int KeyPress::numberPad4 = 0x30024;
  232696. const int KeyPress::numberPad5 = 0x30025;
  232697. const int KeyPress::numberPad6 = 0x30026;
  232698. const int KeyPress::numberPad7 = 0x30027;
  232699. const int KeyPress::numberPad8 = 0x30028;
  232700. const int KeyPress::numberPad9 = 0x30029;
  232701. const int KeyPress::numberPadAdd = 0x3002a;
  232702. const int KeyPress::numberPadSubtract = 0x3002b;
  232703. const int KeyPress::numberPadMultiply = 0x3002c;
  232704. const int KeyPress::numberPadDivide = 0x3002d;
  232705. const int KeyPress::numberPadSeparator = 0x3002e;
  232706. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232707. const int KeyPress::numberPadEquals = 0x30030;
  232708. const int KeyPress::numberPadDelete = 0x30031;
  232709. const int KeyPress::playKey = 0x30000;
  232710. const int KeyPress::stopKey = 0x30001;
  232711. const int KeyPress::fastForwardKey = 0x30002;
  232712. const int KeyPress::rewindKey = 0x30003;
  232713. #endif
  232714. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232715. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232716. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232717. // compiled on its own).
  232718. #if JUCE_INCLUDED_FILE
  232719. #if JUCE_MAC
  232720. namespace MouseCursorHelpers
  232721. {
  232722. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232723. {
  232724. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232725. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232726. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232727. [im release];
  232728. return c;
  232729. }
  232730. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232731. {
  232732. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232733. BufferedInputStream buf (&fileStream, 4096, false);
  232734. PNGImageFormat pngFormat;
  232735. Image im (pngFormat.decodeImage (buf));
  232736. if (im.isValid())
  232737. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232738. jassertfalse;
  232739. return 0;
  232740. }
  232741. }
  232742. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232743. {
  232744. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232745. }
  232746. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232747. {
  232748. const ScopedAutoReleasePool pool;
  232749. NSCursor* c = 0;
  232750. switch (type)
  232751. {
  232752. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232753. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232754. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232755. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232756. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232757. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232758. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232759. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232760. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232761. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232762. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232763. case UpDownResizeCursor:
  232764. case TopEdgeResizeCursor:
  232765. case BottomEdgeResizeCursor:
  232766. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232767. case TopLeftCornerResizeCursor:
  232768. case BottomRightCornerResizeCursor:
  232769. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232770. case TopRightCornerResizeCursor:
  232771. case BottomLeftCornerResizeCursor:
  232772. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232773. case UpDownLeftRightResizeCursor:
  232774. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232775. default:
  232776. jassertfalse;
  232777. break;
  232778. }
  232779. [c retain];
  232780. return c;
  232781. }
  232782. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232783. {
  232784. [((NSCursor*) cursorHandle) release];
  232785. }
  232786. void MouseCursor::showInAllWindows() const
  232787. {
  232788. showInWindow (0);
  232789. }
  232790. void MouseCursor::showInWindow (ComponentPeer*) const
  232791. {
  232792. [((NSCursor*) getHandle()) set];
  232793. }
  232794. #else
  232795. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232796. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232797. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232798. void MouseCursor::showInAllWindows() const {}
  232799. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232800. #endif
  232801. #endif
  232802. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232803. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232804. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232805. // compiled on its own).
  232806. #if JUCE_INCLUDED_FILE
  232807. class NSViewComponentInternal : public ComponentMovementWatcher
  232808. {
  232809. Component* const owner;
  232810. NSViewComponentPeer* currentPeer;
  232811. bool wasShowing;
  232812. public:
  232813. NSView* const view;
  232814. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232815. : ComponentMovementWatcher (owner_),
  232816. owner (owner_),
  232817. currentPeer (0),
  232818. wasShowing (false),
  232819. view (view_)
  232820. {
  232821. [view_ retain];
  232822. if (owner_->isShowing())
  232823. componentPeerChanged();
  232824. }
  232825. ~NSViewComponentInternal()
  232826. {
  232827. [view removeFromSuperview];
  232828. [view release];
  232829. }
  232830. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232831. {
  232832. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232833. // The ComponentMovementWatcher version of this method avoids calling
  232834. // us when the top-level comp is resized, but for an NSView we need to know this
  232835. // because with inverted co-ords, we need to update the position even if the
  232836. // top-left pos hasn't changed
  232837. if (comp.isOnDesktop() && wasResized)
  232838. componentMovedOrResized (wasMoved, wasResized);
  232839. }
  232840. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232841. {
  232842. Component* const topComp = owner->getTopLevelComponent();
  232843. if (topComp->getPeer() != 0)
  232844. {
  232845. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232846. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232847. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232848. [view setFrame: r];
  232849. }
  232850. }
  232851. void componentPeerChanged()
  232852. {
  232853. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232854. if (currentPeer != peer)
  232855. {
  232856. if ([view superview] != nil)
  232857. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232858. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232859. currentPeer = peer;
  232860. if (peer != 0)
  232861. {
  232862. [peer->view addSubview: view];
  232863. componentMovedOrResized (false, false);
  232864. }
  232865. }
  232866. [view setHidden: ! owner->isShowing()];
  232867. }
  232868. void componentVisibilityChanged (Component&)
  232869. {
  232870. componentPeerChanged();
  232871. }
  232872. const Rectangle<int> getViewBounds() const
  232873. {
  232874. NSRect r = [view frame];
  232875. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232876. }
  232877. juce_UseDebuggingNewOperator
  232878. private:
  232879. NSViewComponentInternal (const NSViewComponentInternal&);
  232880. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232881. };
  232882. NSViewComponent::NSViewComponent()
  232883. {
  232884. }
  232885. NSViewComponent::~NSViewComponent()
  232886. {
  232887. }
  232888. void NSViewComponent::setView (void* view)
  232889. {
  232890. if (view != getView())
  232891. {
  232892. if (view != 0)
  232893. info = new NSViewComponentInternal ((NSView*) view, this);
  232894. else
  232895. info = 0;
  232896. }
  232897. }
  232898. void* NSViewComponent::getView() const
  232899. {
  232900. return info == 0 ? 0 : info->view;
  232901. }
  232902. void NSViewComponent::resizeToFitView()
  232903. {
  232904. if (info != 0)
  232905. setBounds (info->getViewBounds());
  232906. }
  232907. void NSViewComponent::paint (Graphics&)
  232908. {
  232909. }
  232910. #endif
  232911. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232912. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232913. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232914. // compiled on its own).
  232915. #if JUCE_INCLUDED_FILE
  232916. AppleRemoteDevice::AppleRemoteDevice()
  232917. : device (0),
  232918. queue (0),
  232919. remoteId (0)
  232920. {
  232921. }
  232922. AppleRemoteDevice::~AppleRemoteDevice()
  232923. {
  232924. stop();
  232925. }
  232926. static io_object_t getAppleRemoteDevice()
  232927. {
  232928. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232929. io_iterator_t iter = 0;
  232930. io_object_t iod = 0;
  232931. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232932. && iter != 0)
  232933. {
  232934. iod = IOIteratorNext (iter);
  232935. }
  232936. IOObjectRelease (iter);
  232937. return iod;
  232938. }
  232939. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232940. {
  232941. jassert (*device == 0);
  232942. io_name_t classname;
  232943. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232944. {
  232945. IOCFPlugInInterface** cfPlugInInterface = 0;
  232946. SInt32 score = 0;
  232947. if (IOCreatePlugInInterfaceForService (iod,
  232948. kIOHIDDeviceUserClientTypeID,
  232949. kIOCFPlugInInterfaceID,
  232950. &cfPlugInInterface,
  232951. &score) == kIOReturnSuccess)
  232952. {
  232953. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232954. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232955. device);
  232956. (void) hr;
  232957. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232958. }
  232959. }
  232960. return *device != 0;
  232961. }
  232962. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232963. {
  232964. if (queue != 0)
  232965. return true;
  232966. stop();
  232967. bool result = false;
  232968. io_object_t iod = getAppleRemoteDevice();
  232969. if (iod != 0)
  232970. {
  232971. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232972. result = true;
  232973. else
  232974. stop();
  232975. IOObjectRelease (iod);
  232976. }
  232977. return result;
  232978. }
  232979. void AppleRemoteDevice::stop()
  232980. {
  232981. if (queue != 0)
  232982. {
  232983. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232984. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232985. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232986. queue = 0;
  232987. }
  232988. if (device != 0)
  232989. {
  232990. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232991. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232992. device = 0;
  232993. }
  232994. }
  232995. bool AppleRemoteDevice::isActive() const
  232996. {
  232997. return queue != 0;
  232998. }
  232999. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  233000. {
  233001. if (result == kIOReturnSuccess)
  233002. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  233003. }
  233004. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  233005. {
  233006. Array <int> cookies;
  233007. CFArrayRef elements;
  233008. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  233009. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  233010. return false;
  233011. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  233012. {
  233013. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  233014. // get the cookie
  233015. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  233016. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  233017. continue;
  233018. long number;
  233019. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  233020. continue;
  233021. cookies.add ((int) number);
  233022. }
  233023. CFRelease (elements);
  233024. if ((*(IOHIDDeviceInterface**) device)
  233025. ->open ((IOHIDDeviceInterface**) device,
  233026. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  233027. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  233028. {
  233029. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  233030. if (queue != 0)
  233031. {
  233032. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  233033. for (int i = 0; i < cookies.size(); ++i)
  233034. {
  233035. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  233036. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  233037. }
  233038. CFRunLoopSourceRef eventSource;
  233039. if ((*(IOHIDQueueInterface**) queue)
  233040. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  233041. {
  233042. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  233043. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  233044. {
  233045. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  233046. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  233047. return true;
  233048. }
  233049. }
  233050. }
  233051. }
  233052. return false;
  233053. }
  233054. void AppleRemoteDevice::handleCallbackInternal()
  233055. {
  233056. int totalValues = 0;
  233057. AbsoluteTime nullTime = { 0, 0 };
  233058. char cookies [12];
  233059. int numCookies = 0;
  233060. while (numCookies < numElementsInArray (cookies))
  233061. {
  233062. IOHIDEventStruct e;
  233063. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  233064. break;
  233065. if ((int) e.elementCookie == 19)
  233066. {
  233067. remoteId = e.value;
  233068. buttonPressed (switched, false);
  233069. }
  233070. else
  233071. {
  233072. totalValues += e.value;
  233073. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  233074. }
  233075. }
  233076. cookies [numCookies++] = 0;
  233077. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  233078. static const char buttonPatterns[] =
  233079. {
  233080. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  233081. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  233082. 0x1f, 0x1d, 0x1c, 0x12, 0,
  233083. 0x1f, 0x1e, 0x1c, 0x12, 0,
  233084. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  233085. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  233086. 0x1f, 0x12, 0x04, 0x02, 0,
  233087. 0x1f, 0x12, 0x03, 0x02, 0,
  233088. 0x1f, 0x12, 0x1f, 0x12, 0,
  233089. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  233090. 19, 0
  233091. };
  233092. int buttonNum = (int) menuButton;
  233093. int i = 0;
  233094. while (i < numElementsInArray (buttonPatterns))
  233095. {
  233096. if (strcmp (cookies, buttonPatterns + i) == 0)
  233097. {
  233098. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  233099. break;
  233100. }
  233101. i += (int) strlen (buttonPatterns + i) + 1;
  233102. ++buttonNum;
  233103. }
  233104. }
  233105. #endif
  233106. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  233107. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  233108. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233109. // compiled on its own).
  233110. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  233111. #if JUCE_MAC
  233112. END_JUCE_NAMESPACE
  233113. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  233114. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  233115. {
  233116. CriticalSection* contextLock;
  233117. bool needsUpdate;
  233118. }
  233119. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  233120. - (bool) makeActive;
  233121. - (void) makeInactive;
  233122. - (void) reshape;
  233123. @end
  233124. @implementation ThreadSafeNSOpenGLView
  233125. - (id) initWithFrame: (NSRect) frameRect
  233126. pixelFormat: (NSOpenGLPixelFormat*) format
  233127. {
  233128. contextLock = new CriticalSection();
  233129. self = [super initWithFrame: frameRect pixelFormat: format];
  233130. if (self != nil)
  233131. [[NSNotificationCenter defaultCenter] addObserver: self
  233132. selector: @selector (_surfaceNeedsUpdate:)
  233133. name: NSViewGlobalFrameDidChangeNotification
  233134. object: self];
  233135. return self;
  233136. }
  233137. - (void) dealloc
  233138. {
  233139. [[NSNotificationCenter defaultCenter] removeObserver: self];
  233140. delete contextLock;
  233141. [super dealloc];
  233142. }
  233143. - (bool) makeActive
  233144. {
  233145. const ScopedLock sl (*contextLock);
  233146. if ([self openGLContext] == 0)
  233147. return false;
  233148. [[self openGLContext] makeCurrentContext];
  233149. if (needsUpdate)
  233150. {
  233151. [super update];
  233152. needsUpdate = false;
  233153. }
  233154. return true;
  233155. }
  233156. - (void) makeInactive
  233157. {
  233158. const ScopedLock sl (*contextLock);
  233159. [NSOpenGLContext clearCurrentContext];
  233160. }
  233161. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  233162. {
  233163. const ScopedLock sl (*contextLock);
  233164. needsUpdate = true;
  233165. }
  233166. - (void) update
  233167. {
  233168. const ScopedLock sl (*contextLock);
  233169. needsUpdate = true;
  233170. }
  233171. - (void) reshape
  233172. {
  233173. const ScopedLock sl (*contextLock);
  233174. needsUpdate = true;
  233175. }
  233176. @end
  233177. BEGIN_JUCE_NAMESPACE
  233178. class WindowedGLContext : public OpenGLContext
  233179. {
  233180. public:
  233181. WindowedGLContext (Component* const component,
  233182. const OpenGLPixelFormat& pixelFormat_,
  233183. NSOpenGLContext* sharedContext)
  233184. : renderContext (0),
  233185. pixelFormat (pixelFormat_)
  233186. {
  233187. jassert (component != 0);
  233188. NSOpenGLPixelFormatAttribute attribs [64];
  233189. int n = 0;
  233190. attribs[n++] = NSOpenGLPFADoubleBuffer;
  233191. attribs[n++] = NSOpenGLPFAAccelerated;
  233192. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  233193. attribs[n++] = NSOpenGLPFAColorSize;
  233194. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  233195. pixelFormat.greenBits,
  233196. pixelFormat.blueBits);
  233197. attribs[n++] = NSOpenGLPFAAlphaSize;
  233198. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  233199. attribs[n++] = NSOpenGLPFADepthSize;
  233200. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  233201. attribs[n++] = NSOpenGLPFAStencilSize;
  233202. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  233203. attribs[n++] = NSOpenGLPFAAccumSize;
  233204. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  233205. pixelFormat.accumulationBufferGreenBits,
  233206. pixelFormat.accumulationBufferBlueBits,
  233207. pixelFormat.accumulationBufferAlphaBits);
  233208. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  233209. attribs[n++] = NSOpenGLPFASampleBuffers;
  233210. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  233211. attribs[n++] = NSOpenGLPFAClosestPolicy;
  233212. attribs[n++] = NSOpenGLPFANoRecovery;
  233213. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  233214. NSOpenGLPixelFormat* format
  233215. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  233216. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233217. pixelFormat: format];
  233218. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  233219. shareContext: sharedContext] autorelease];
  233220. const GLint swapInterval = 1;
  233221. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  233222. [view setOpenGLContext: renderContext];
  233223. [format release];
  233224. viewHolder = new NSViewComponentInternal (view, component);
  233225. }
  233226. ~WindowedGLContext()
  233227. {
  233228. deleteContext();
  233229. viewHolder = 0;
  233230. }
  233231. void deleteContext()
  233232. {
  233233. makeInactive();
  233234. [renderContext clearDrawable];
  233235. [renderContext setView: nil];
  233236. [view setOpenGLContext: nil];
  233237. renderContext = nil;
  233238. }
  233239. bool makeActive() const throw()
  233240. {
  233241. jassert (renderContext != 0);
  233242. if ([renderContext view] != view)
  233243. [renderContext setView: view];
  233244. [view makeActive];
  233245. return isActive();
  233246. }
  233247. bool makeInactive() const throw()
  233248. {
  233249. [view makeInactive];
  233250. return true;
  233251. }
  233252. bool isActive() const throw()
  233253. {
  233254. return [NSOpenGLContext currentContext] == renderContext;
  233255. }
  233256. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233257. void* getRawContext() const throw() { return renderContext; }
  233258. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233259. {
  233260. }
  233261. void swapBuffers()
  233262. {
  233263. [renderContext flushBuffer];
  233264. }
  233265. bool setSwapInterval (const int numFramesPerSwap)
  233266. {
  233267. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233268. forParameter: NSOpenGLCPSwapInterval];
  233269. return true;
  233270. }
  233271. int getSwapInterval() const
  233272. {
  233273. GLint numFrames = 0;
  233274. [renderContext getValues: &numFrames
  233275. forParameter: NSOpenGLCPSwapInterval];
  233276. return numFrames;
  233277. }
  233278. void repaint()
  233279. {
  233280. // we need to invalidate the juce view that holds this gl view, to make it
  233281. // cause a repaint callback
  233282. NSView* v = (NSView*) viewHolder->view;
  233283. NSRect r = [v frame];
  233284. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233285. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233286. // repaint message, thus never causing our paint() callback, and never repainting
  233287. // the comp. So invalidating just a little bit around the edge helps..
  233288. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233289. }
  233290. void* getNativeWindowHandle() const { return viewHolder->view; }
  233291. juce_UseDebuggingNewOperator
  233292. NSOpenGLContext* renderContext;
  233293. ThreadSafeNSOpenGLView* view;
  233294. private:
  233295. OpenGLPixelFormat pixelFormat;
  233296. ScopedPointer <NSViewComponentInternal> viewHolder;
  233297. WindowedGLContext (const WindowedGLContext&);
  233298. WindowedGLContext& operator= (const WindowedGLContext&);
  233299. };
  233300. OpenGLContext* OpenGLComponent::createContext()
  233301. {
  233302. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233303. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233304. return (c->renderContext != 0) ? c.release() : 0;
  233305. }
  233306. void* OpenGLComponent::getNativeWindowHandle() const
  233307. {
  233308. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233309. : 0;
  233310. }
  233311. void juce_glViewport (const int w, const int h)
  233312. {
  233313. glViewport (0, 0, w, h);
  233314. }
  233315. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233316. OwnedArray <OpenGLPixelFormat>& results)
  233317. {
  233318. /* GLint attribs [64];
  233319. int n = 0;
  233320. attribs[n++] = AGL_RGBA;
  233321. attribs[n++] = AGL_DOUBLEBUFFER;
  233322. attribs[n++] = AGL_ACCELERATED;
  233323. attribs[n++] = AGL_NO_RECOVERY;
  233324. attribs[n++] = AGL_NONE;
  233325. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233326. while (p != 0)
  233327. {
  233328. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233329. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233330. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233331. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233332. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233333. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233334. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233335. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233336. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233337. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233338. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233339. results.add (pf);
  233340. p = aglNextPixelFormat (p);
  233341. }*/
  233342. //jassertfalse // can't see how you do this in cocoa!
  233343. }
  233344. #else
  233345. END_JUCE_NAMESPACE
  233346. @interface JuceGLView : UIView
  233347. {
  233348. }
  233349. + (Class) layerClass;
  233350. @end
  233351. @implementation JuceGLView
  233352. + (Class) layerClass
  233353. {
  233354. return [CAEAGLLayer class];
  233355. }
  233356. @end
  233357. BEGIN_JUCE_NAMESPACE
  233358. class GLESContext : public OpenGLContext
  233359. {
  233360. public:
  233361. GLESContext (UIViewComponentPeer* peer,
  233362. Component* const component_,
  233363. const OpenGLPixelFormat& pixelFormat_,
  233364. const GLESContext* const sharedContext,
  233365. NSUInteger apiType)
  233366. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233367. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233368. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233369. {
  233370. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233371. view.opaque = YES;
  233372. view.hidden = NO;
  233373. view.backgroundColor = [UIColor blackColor];
  233374. view.userInteractionEnabled = NO;
  233375. glLayer = (CAEAGLLayer*) [view layer];
  233376. [peer->view addSubview: view];
  233377. if (sharedContext != 0)
  233378. context = [[EAGLContext alloc] initWithAPI: apiType
  233379. sharegroup: [sharedContext->context sharegroup]];
  233380. else
  233381. context = [[EAGLContext alloc] initWithAPI: apiType];
  233382. createGLBuffers();
  233383. }
  233384. ~GLESContext()
  233385. {
  233386. deleteContext();
  233387. [view removeFromSuperview];
  233388. [view release];
  233389. freeGLBuffers();
  233390. }
  233391. void deleteContext()
  233392. {
  233393. makeInactive();
  233394. [context release];
  233395. context = nil;
  233396. }
  233397. bool makeActive() const throw()
  233398. {
  233399. jassert (context != 0);
  233400. [EAGLContext setCurrentContext: context];
  233401. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233402. return true;
  233403. }
  233404. void swapBuffers()
  233405. {
  233406. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233407. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233408. }
  233409. bool makeInactive() const throw()
  233410. {
  233411. return [EAGLContext setCurrentContext: nil];
  233412. }
  233413. bool isActive() const throw()
  233414. {
  233415. return [EAGLContext currentContext] == context;
  233416. }
  233417. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233418. void* getRawContext() const throw() { return glLayer; }
  233419. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233420. {
  233421. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233422. if (lastWidth != w || lastHeight != h)
  233423. {
  233424. lastWidth = w;
  233425. lastHeight = h;
  233426. freeGLBuffers();
  233427. createGLBuffers();
  233428. }
  233429. }
  233430. bool setSwapInterval (const int numFramesPerSwap)
  233431. {
  233432. numFrames = numFramesPerSwap;
  233433. return true;
  233434. }
  233435. int getSwapInterval() const
  233436. {
  233437. return numFrames;
  233438. }
  233439. void repaint()
  233440. {
  233441. }
  233442. void createGLBuffers()
  233443. {
  233444. makeActive();
  233445. glGenFramebuffersOES (1, &frameBufferHandle);
  233446. glGenRenderbuffersOES (1, &colorBufferHandle);
  233447. glGenRenderbuffersOES (1, &depthBufferHandle);
  233448. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233449. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233450. GLint width, height;
  233451. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233452. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233453. if (useDepthBuffer)
  233454. {
  233455. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233456. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233457. }
  233458. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233459. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233460. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233461. if (useDepthBuffer)
  233462. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233463. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233464. }
  233465. void freeGLBuffers()
  233466. {
  233467. if (frameBufferHandle != 0)
  233468. {
  233469. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233470. frameBufferHandle = 0;
  233471. }
  233472. if (colorBufferHandle != 0)
  233473. {
  233474. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233475. colorBufferHandle = 0;
  233476. }
  233477. if (depthBufferHandle != 0)
  233478. {
  233479. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233480. depthBufferHandle = 0;
  233481. }
  233482. }
  233483. juce_UseDebuggingNewOperator
  233484. private:
  233485. Component::SafePointer<Component> component;
  233486. OpenGLPixelFormat pixelFormat;
  233487. JuceGLView* view;
  233488. CAEAGLLayer* glLayer;
  233489. EAGLContext* context;
  233490. bool useDepthBuffer;
  233491. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233492. int numFrames;
  233493. int lastWidth, lastHeight;
  233494. GLESContext (const GLESContext&);
  233495. GLESContext& operator= (const GLESContext&);
  233496. };
  233497. OpenGLContext* OpenGLComponent::createContext()
  233498. {
  233499. ScopedAutoReleasePool pool;
  233500. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233501. if (peer != 0)
  233502. return new GLESContext (peer, this, preferredPixelFormat,
  233503. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233504. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233505. return 0;
  233506. }
  233507. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233508. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233509. {
  233510. }
  233511. void juce_glViewport (const int w, const int h)
  233512. {
  233513. glViewport (0, 0, w, h);
  233514. }
  233515. #endif
  233516. #endif
  233517. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233518. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233519. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233520. // compiled on its own).
  233521. #if JUCE_INCLUDED_FILE
  233522. class JuceMainMenuHandler;
  233523. END_JUCE_NAMESPACE
  233524. using namespace JUCE_NAMESPACE;
  233525. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233526. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233527. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233528. #else
  233529. @interface JuceMenuCallback : NSObject
  233530. #endif
  233531. {
  233532. JuceMainMenuHandler* owner;
  233533. }
  233534. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233535. - (void) dealloc;
  233536. - (void) menuItemInvoked: (id) menu;
  233537. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233538. @end
  233539. BEGIN_JUCE_NAMESPACE
  233540. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233541. private DeletedAtShutdown
  233542. {
  233543. public:
  233544. static JuceMainMenuHandler* instance;
  233545. JuceMainMenuHandler()
  233546. : currentModel (0),
  233547. lastUpdateTime (0)
  233548. {
  233549. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233550. }
  233551. ~JuceMainMenuHandler()
  233552. {
  233553. setMenu (0);
  233554. jassert (instance == this);
  233555. instance = 0;
  233556. [callback release];
  233557. }
  233558. void setMenu (MenuBarModel* const newMenuBarModel)
  233559. {
  233560. if (currentModel != newMenuBarModel)
  233561. {
  233562. if (currentModel != 0)
  233563. currentModel->removeListener (this);
  233564. currentModel = newMenuBarModel;
  233565. if (currentModel != 0)
  233566. currentModel->addListener (this);
  233567. menuBarItemsChanged (0);
  233568. }
  233569. }
  233570. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233571. const String& name, const int menuId, const int tag)
  233572. {
  233573. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233574. action: nil
  233575. keyEquivalent: @""];
  233576. [item setTag: tag];
  233577. NSMenu* sub = createMenu (child, name, menuId, tag);
  233578. [parent setSubmenu: sub forItem: item];
  233579. [sub setAutoenablesItems: false];
  233580. [sub release];
  233581. }
  233582. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233583. const String& name, const int menuId, const int tag)
  233584. {
  233585. [parentItem setTag: tag];
  233586. NSMenu* menu = [parentItem submenu];
  233587. [menu setTitle: juceStringToNS (name)];
  233588. while ([menu numberOfItems] > 0)
  233589. [menu removeItemAtIndex: 0];
  233590. PopupMenu::MenuItemIterator iter (menuToCopy);
  233591. while (iter.next())
  233592. addMenuItem (iter, menu, menuId, tag);
  233593. [menu setAutoenablesItems: false];
  233594. [menu update];
  233595. }
  233596. void menuBarItemsChanged (MenuBarModel*)
  233597. {
  233598. lastUpdateTime = Time::getMillisecondCounter();
  233599. StringArray menuNames;
  233600. if (currentModel != 0)
  233601. menuNames = currentModel->getMenuBarNames();
  233602. NSMenu* menuBar = [NSApp mainMenu];
  233603. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233604. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233605. int menuId = 1;
  233606. for (int i = 0; i < menuNames.size(); ++i)
  233607. {
  233608. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233609. if (i >= [menuBar numberOfItems] - 1)
  233610. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233611. else
  233612. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233613. }
  233614. }
  233615. static void flashMenuBar (NSMenu* menu)
  233616. {
  233617. if ([[menu title] isEqualToString: @"Apple"])
  233618. return;
  233619. [menu retain];
  233620. const unichar f35Key = NSF35FunctionKey;
  233621. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233622. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233623. action: nil
  233624. keyEquivalent: f35String];
  233625. [item setTarget: nil];
  233626. [menu insertItem: item atIndex: [menu numberOfItems]];
  233627. [item release];
  233628. if ([menu indexOfItem: item] >= 0)
  233629. {
  233630. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233631. location: NSZeroPoint
  233632. modifierFlags: NSCommandKeyMask
  233633. timestamp: 0
  233634. windowNumber: 0
  233635. context: [NSGraphicsContext currentContext]
  233636. characters: f35String
  233637. charactersIgnoringModifiers: f35String
  233638. isARepeat: NO
  233639. keyCode: 0];
  233640. [menu performKeyEquivalent: f35Event];
  233641. if ([menu indexOfItem: item] >= 0)
  233642. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233643. }
  233644. [menu release];
  233645. }
  233646. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233647. {
  233648. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233649. {
  233650. NSMenuItem* m = [menu itemAtIndex: i];
  233651. if ([m tag] == info.commandID)
  233652. return m;
  233653. if ([m submenu] != 0)
  233654. {
  233655. NSMenuItem* found = findMenuItem ([m submenu], info);
  233656. if (found != 0)
  233657. return found;
  233658. }
  233659. }
  233660. return 0;
  233661. }
  233662. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233663. {
  233664. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233665. if (item != 0)
  233666. flashMenuBar ([item menu]);
  233667. }
  233668. void updateMenus()
  233669. {
  233670. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233671. menuBarItemsChanged (0);
  233672. }
  233673. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233674. {
  233675. if (currentModel != 0)
  233676. {
  233677. if (commandManager != 0)
  233678. {
  233679. ApplicationCommandTarget::InvocationInfo info (commandId);
  233680. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233681. commandManager->invoke (info, true);
  233682. }
  233683. currentModel->menuItemSelected (commandId, topLevelIndex);
  233684. }
  233685. }
  233686. MenuBarModel* currentModel;
  233687. uint32 lastUpdateTime;
  233688. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233689. const int topLevelMenuId, const int topLevelIndex)
  233690. {
  233691. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233692. if (text == 0)
  233693. text = @"";
  233694. if (iter.isSeparator)
  233695. {
  233696. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233697. }
  233698. else if (iter.isSectionHeader)
  233699. {
  233700. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233701. action: nil
  233702. keyEquivalent: @""];
  233703. [item setEnabled: false];
  233704. }
  233705. else if (iter.subMenu != 0)
  233706. {
  233707. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233708. action: nil
  233709. keyEquivalent: @""];
  233710. [item setTag: iter.itemId];
  233711. [item setEnabled: iter.isEnabled];
  233712. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233713. [sub setDelegate: nil];
  233714. [menuToAddTo setSubmenu: sub forItem: item];
  233715. [sub release];
  233716. }
  233717. else
  233718. {
  233719. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233720. action: @selector (menuItemInvoked:)
  233721. keyEquivalent: @""];
  233722. [item setTag: iter.itemId];
  233723. [item setEnabled: iter.isEnabled];
  233724. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233725. [item setTarget: (id) callback];
  233726. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233727. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233728. [item setRepresentedObject: info];
  233729. if (iter.commandManager != 0)
  233730. {
  233731. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233732. ->getKeyPressesAssignedToCommand (iter.itemId));
  233733. if (keyPresses.size() > 0)
  233734. {
  233735. const KeyPress& kp = keyPresses.getReference(0);
  233736. if (kp.getKeyCode() != KeyPress::backspaceKey
  233737. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233738. // every time you press the key while editing text)
  233739. {
  233740. juce_wchar key = kp.getTextCharacter();
  233741. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233742. key = NSBackspaceCharacter;
  233743. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233744. key = NSDeleteCharacter;
  233745. else if (key == 0)
  233746. key = (juce_wchar) kp.getKeyCode();
  233747. unsigned int mods = 0;
  233748. if (kp.getModifiers().isShiftDown())
  233749. mods |= NSShiftKeyMask;
  233750. if (kp.getModifiers().isCtrlDown())
  233751. mods |= NSControlKeyMask;
  233752. if (kp.getModifiers().isAltDown())
  233753. mods |= NSAlternateKeyMask;
  233754. if (kp.getModifiers().isCommandDown())
  233755. mods |= NSCommandKeyMask;
  233756. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233757. [item setKeyEquivalentModifierMask: mods];
  233758. }
  233759. }
  233760. }
  233761. }
  233762. }
  233763. JuceMenuCallback* callback;
  233764. private:
  233765. NSMenu* createMenu (const PopupMenu menu,
  233766. const String& menuName,
  233767. const int topLevelMenuId,
  233768. const int topLevelIndex)
  233769. {
  233770. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233771. [m setAutoenablesItems: false];
  233772. [m setDelegate: callback];
  233773. PopupMenu::MenuItemIterator iter (menu);
  233774. while (iter.next())
  233775. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233776. [m update];
  233777. return m;
  233778. }
  233779. };
  233780. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233781. END_JUCE_NAMESPACE
  233782. @implementation JuceMenuCallback
  233783. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233784. {
  233785. [super init];
  233786. owner = owner_;
  233787. return self;
  233788. }
  233789. - (void) dealloc
  233790. {
  233791. [super dealloc];
  233792. }
  233793. - (void) menuItemInvoked: (id) menu
  233794. {
  233795. NSMenuItem* item = (NSMenuItem*) menu;
  233796. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233797. {
  233798. // 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
  233799. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233800. // into the focused component and let it trigger the menu item indirectly.
  233801. NSEvent* e = [NSApp currentEvent];
  233802. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233803. {
  233804. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233805. {
  233806. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233807. if (peer != 0)
  233808. {
  233809. if ([e type] == NSKeyDown)
  233810. peer->redirectKeyDown (e);
  233811. else
  233812. peer->redirectKeyUp (e);
  233813. return;
  233814. }
  233815. }
  233816. }
  233817. NSArray* info = (NSArray*) [item representedObject];
  233818. owner->invoke ((int) [item tag],
  233819. (ApplicationCommandManager*) (pointer_sized_int)
  233820. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233821. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233822. }
  233823. }
  233824. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233825. {
  233826. (void) menu;
  233827. if (JuceMainMenuHandler::instance != 0)
  233828. JuceMainMenuHandler::instance->updateMenus();
  233829. }
  233830. @end
  233831. BEGIN_JUCE_NAMESPACE
  233832. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233833. const PopupMenu* extraItems)
  233834. {
  233835. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233836. {
  233837. PopupMenu::MenuItemIterator iter (*extraItems);
  233838. while (iter.next())
  233839. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233840. [menu addItem: [NSMenuItem separatorItem]];
  233841. }
  233842. NSMenuItem* item;
  233843. // Services...
  233844. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233845. action: nil keyEquivalent: @""];
  233846. [menu addItem: item];
  233847. [item release];
  233848. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233849. [menu setSubmenu: servicesMenu forItem: item];
  233850. [NSApp setServicesMenu: servicesMenu];
  233851. [servicesMenu release];
  233852. [menu addItem: [NSMenuItem separatorItem]];
  233853. // Hide + Show stuff...
  233854. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233855. action: @selector (hide:) keyEquivalent: @"h"];
  233856. [item setTarget: NSApp];
  233857. [menu addItem: item];
  233858. [item release];
  233859. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233860. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233861. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233862. [item setTarget: NSApp];
  233863. [menu addItem: item];
  233864. [item release];
  233865. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233866. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233867. [item setTarget: NSApp];
  233868. [menu addItem: item];
  233869. [item release];
  233870. [menu addItem: [NSMenuItem separatorItem]];
  233871. // Quit item....
  233872. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233873. action: @selector (terminate:) keyEquivalent: @"q"];
  233874. [item setTarget: NSApp];
  233875. [menu addItem: item];
  233876. [item release];
  233877. return menu;
  233878. }
  233879. // Since our app has no NIB, this initialises a standard app menu...
  233880. static void rebuildMainMenu (const PopupMenu* extraItems)
  233881. {
  233882. // this can't be used in a plugin!
  233883. jassert (JUCEApplication::isStandaloneApp());
  233884. if (JUCEApplication::getInstance() != 0)
  233885. {
  233886. const ScopedAutoReleasePool pool;
  233887. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233888. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233889. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233890. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233891. [mainMenu setSubmenu: appMenu forItem: item];
  233892. [NSApp setMainMenu: mainMenu];
  233893. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233894. [appMenu release];
  233895. [mainMenu release];
  233896. }
  233897. }
  233898. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233899. const PopupMenu* extraAppleMenuItems)
  233900. {
  233901. if (getMacMainMenu() != newMenuBarModel)
  233902. {
  233903. const ScopedAutoReleasePool pool;
  233904. if (newMenuBarModel == 0)
  233905. {
  233906. delete JuceMainMenuHandler::instance;
  233907. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233908. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233909. extraAppleMenuItems = 0;
  233910. }
  233911. else
  233912. {
  233913. if (JuceMainMenuHandler::instance == 0)
  233914. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233915. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233916. }
  233917. }
  233918. rebuildMainMenu (extraAppleMenuItems);
  233919. if (newMenuBarModel != 0)
  233920. newMenuBarModel->menuItemsChanged();
  233921. }
  233922. MenuBarModel* MenuBarModel::getMacMainMenu()
  233923. {
  233924. return JuceMainMenuHandler::instance != 0
  233925. ? JuceMainMenuHandler::instance->currentModel : 0;
  233926. }
  233927. void juce_initialiseMacMainMenu()
  233928. {
  233929. if (JuceMainMenuHandler::instance == 0)
  233930. rebuildMainMenu (0);
  233931. }
  233932. #endif
  233933. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233934. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233935. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233936. // compiled on its own).
  233937. #if JUCE_INCLUDED_FILE
  233938. #if JUCE_MAC
  233939. END_JUCE_NAMESPACE
  233940. using namespace JUCE_NAMESPACE;
  233941. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233942. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233943. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233944. #else
  233945. @interface JuceFileChooserDelegate : NSObject
  233946. #endif
  233947. {
  233948. StringArray* filters;
  233949. }
  233950. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233951. - (void) dealloc;
  233952. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233953. @end
  233954. @implementation JuceFileChooserDelegate
  233955. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233956. {
  233957. [super init];
  233958. filters = filters_;
  233959. return self;
  233960. }
  233961. - (void) dealloc
  233962. {
  233963. delete filters;
  233964. [super dealloc];
  233965. }
  233966. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233967. {
  233968. (void) sender;
  233969. const File f (nsStringToJuce (filename));
  233970. for (int i = filters->size(); --i >= 0;)
  233971. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233972. return true;
  233973. return f.isDirectory();
  233974. }
  233975. @end
  233976. BEGIN_JUCE_NAMESPACE
  233977. void FileChooser::showPlatformDialog (Array<File>& results,
  233978. const String& title,
  233979. const File& currentFileOrDirectory,
  233980. const String& filter,
  233981. bool selectsDirectory,
  233982. bool selectsFiles,
  233983. bool isSaveDialogue,
  233984. bool warnAboutOverwritingExistingFiles,
  233985. bool selectMultipleFiles,
  233986. FilePreviewComponent* extraInfoComponent)
  233987. {
  233988. const ScopedAutoReleasePool pool;
  233989. StringArray* filters = new StringArray();
  233990. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233991. filters->trim();
  233992. filters->removeEmptyStrings();
  233993. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233994. [delegate autorelease];
  233995. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233996. : [NSOpenPanel openPanel];
  233997. [panel setTitle: juceStringToNS (title)];
  233998. if (! isSaveDialogue)
  233999. {
  234000. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  234001. [openPanel setCanChooseDirectories: selectsDirectory];
  234002. [openPanel setCanChooseFiles: selectsFiles];
  234003. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  234004. }
  234005. [panel setDelegate: delegate];
  234006. if (isSaveDialogue || selectsDirectory)
  234007. [panel setCanCreateDirectories: YES];
  234008. String directory, filename;
  234009. if (currentFileOrDirectory.isDirectory())
  234010. {
  234011. directory = currentFileOrDirectory.getFullPathName();
  234012. }
  234013. else
  234014. {
  234015. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  234016. filename = currentFileOrDirectory.getFileName();
  234017. }
  234018. if ([panel runModalForDirectory: juceStringToNS (directory)
  234019. file: juceStringToNS (filename)]
  234020. == NSOKButton)
  234021. {
  234022. if (isSaveDialogue)
  234023. {
  234024. results.add (File (nsStringToJuce ([panel filename])));
  234025. }
  234026. else
  234027. {
  234028. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  234029. NSArray* urls = [openPanel filenames];
  234030. for (unsigned int i = 0; i < [urls count]; ++i)
  234031. {
  234032. NSString* f = [urls objectAtIndex: i];
  234033. results.add (File (nsStringToJuce (f)));
  234034. }
  234035. }
  234036. }
  234037. [panel setDelegate: nil];
  234038. }
  234039. #else
  234040. void FileChooser::showPlatformDialog (Array<File>& results,
  234041. const String& title,
  234042. const File& currentFileOrDirectory,
  234043. const String& filter,
  234044. bool selectsDirectory,
  234045. bool selectsFiles,
  234046. bool isSaveDialogue,
  234047. bool warnAboutOverwritingExistingFiles,
  234048. bool selectMultipleFiles,
  234049. FilePreviewComponent* extraInfoComponent)
  234050. {
  234051. const ScopedAutoReleasePool pool;
  234052. jassertfalse; //xxx to do
  234053. }
  234054. #endif
  234055. #endif
  234056. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  234057. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234058. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234059. // compiled on its own).
  234060. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  234061. END_JUCE_NAMESPACE
  234062. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  234063. @interface NonInterceptingQTMovieView : QTMovieView
  234064. {
  234065. }
  234066. - (id) initWithFrame: (NSRect) frame;
  234067. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  234068. - (NSView*) hitTest: (NSPoint) p;
  234069. @end
  234070. @implementation NonInterceptingQTMovieView
  234071. - (id) initWithFrame: (NSRect) frame
  234072. {
  234073. self = [super initWithFrame: frame];
  234074. [self setNextResponder: [self superview]];
  234075. return self;
  234076. }
  234077. - (void) dealloc
  234078. {
  234079. [super dealloc];
  234080. }
  234081. - (NSView*) hitTest: (NSPoint) point
  234082. {
  234083. return [self isControllerVisible] ? [super hitTest: point] : nil;
  234084. }
  234085. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  234086. {
  234087. return YES;
  234088. }
  234089. @end
  234090. BEGIN_JUCE_NAMESPACE
  234091. #define theMovie (static_cast <QTMovie*> (movie))
  234092. QuickTimeMovieComponent::QuickTimeMovieComponent()
  234093. : movie (0)
  234094. {
  234095. setOpaque (true);
  234096. setVisible (true);
  234097. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  234098. setView (view);
  234099. [view release];
  234100. }
  234101. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  234102. {
  234103. closeMovie();
  234104. setView (0);
  234105. }
  234106. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  234107. {
  234108. return true;
  234109. }
  234110. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  234111. {
  234112. // unfortunately, QTMovie objects can only be created on the main thread..
  234113. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234114. QTMovie* movie = 0;
  234115. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  234116. if (fin != 0)
  234117. {
  234118. movieFile = fin->getFile();
  234119. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  234120. error: nil];
  234121. }
  234122. else
  234123. {
  234124. MemoryBlock temp;
  234125. movieStream->readIntoMemoryBlock (temp);
  234126. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  234127. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  234128. {
  234129. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  234130. length: temp.getSize()]
  234131. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  234132. MIMEType: @""]
  234133. error: nil];
  234134. if (movie != 0)
  234135. break;
  234136. }
  234137. }
  234138. return movie;
  234139. }
  234140. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  234141. const bool isControllerVisible_)
  234142. {
  234143. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  234144. }
  234145. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  234146. const bool controllerVisible_)
  234147. {
  234148. closeMovie();
  234149. if (getPeer() == 0)
  234150. {
  234151. // To open a movie, this component must be visible inside a functioning window, so that
  234152. // the QT control can be assigned to the window.
  234153. jassertfalse;
  234154. return false;
  234155. }
  234156. movie = openMovieFromStream (movieStream, movieFile);
  234157. [theMovie retain];
  234158. QTMovieView* view = (QTMovieView*) getView();
  234159. [view setMovie: theMovie];
  234160. [view setControllerVisible: controllerVisible_];
  234161. setLooping (looping);
  234162. return movie != nil;
  234163. }
  234164. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  234165. const bool isControllerVisible_)
  234166. {
  234167. // unfortunately, QTMovie objects can only be created on the main thread..
  234168. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234169. closeMovie();
  234170. if (getPeer() == 0)
  234171. {
  234172. // To open a movie, this component must be visible inside a functioning window, so that
  234173. // the QT control can be assigned to the window.
  234174. jassertfalse;
  234175. return false;
  234176. }
  234177. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  234178. NSError* err;
  234179. if ([QTMovie canInitWithURL: url])
  234180. movie = [QTMovie movieWithURL: url error: &err];
  234181. [theMovie retain];
  234182. QTMovieView* view = (QTMovieView*) getView();
  234183. [view setMovie: theMovie];
  234184. [view setControllerVisible: controllerVisible];
  234185. setLooping (looping);
  234186. return movie != nil;
  234187. }
  234188. void QuickTimeMovieComponent::closeMovie()
  234189. {
  234190. stop();
  234191. QTMovieView* view = (QTMovieView*) getView();
  234192. [view setMovie: nil];
  234193. [theMovie release];
  234194. movie = 0;
  234195. movieFile = File::nonexistent;
  234196. }
  234197. bool QuickTimeMovieComponent::isMovieOpen() const
  234198. {
  234199. return movie != nil;
  234200. }
  234201. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  234202. {
  234203. return movieFile;
  234204. }
  234205. void QuickTimeMovieComponent::play()
  234206. {
  234207. [theMovie play];
  234208. }
  234209. void QuickTimeMovieComponent::stop()
  234210. {
  234211. [theMovie stop];
  234212. }
  234213. bool QuickTimeMovieComponent::isPlaying() const
  234214. {
  234215. return movie != 0 && [theMovie rate] != 0;
  234216. }
  234217. void QuickTimeMovieComponent::setPosition (const double seconds)
  234218. {
  234219. if (movie != 0)
  234220. {
  234221. QTTime t;
  234222. t.timeValue = (uint64) (100000.0 * seconds);
  234223. t.timeScale = 100000;
  234224. t.flags = 0;
  234225. [theMovie setCurrentTime: t];
  234226. }
  234227. }
  234228. double QuickTimeMovieComponent::getPosition() const
  234229. {
  234230. if (movie == 0)
  234231. return 0.0;
  234232. QTTime t = [theMovie currentTime];
  234233. return t.timeValue / (double) t.timeScale;
  234234. }
  234235. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  234236. {
  234237. [theMovie setRate: newSpeed];
  234238. }
  234239. double QuickTimeMovieComponent::getMovieDuration() const
  234240. {
  234241. if (movie == 0)
  234242. return 0.0;
  234243. QTTime t = [theMovie duration];
  234244. return t.timeValue / (double) t.timeScale;
  234245. }
  234246. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  234247. {
  234248. looping = shouldLoop;
  234249. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  234250. forKey: QTMovieLoopsAttribute];
  234251. }
  234252. bool QuickTimeMovieComponent::isLooping() const
  234253. {
  234254. return looping;
  234255. }
  234256. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  234257. {
  234258. [theMovie setVolume: newVolume];
  234259. }
  234260. float QuickTimeMovieComponent::getMovieVolume() const
  234261. {
  234262. return movie != 0 ? [theMovie volume] : 0.0f;
  234263. }
  234264. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234265. {
  234266. width = 0;
  234267. height = 0;
  234268. if (movie != 0)
  234269. {
  234270. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234271. width = (int) s.width;
  234272. height = (int) s.height;
  234273. }
  234274. }
  234275. void QuickTimeMovieComponent::paint (Graphics& g)
  234276. {
  234277. if (movie == 0)
  234278. g.fillAll (Colours::black);
  234279. }
  234280. bool QuickTimeMovieComponent::isControllerVisible() const
  234281. {
  234282. return controllerVisible;
  234283. }
  234284. void QuickTimeMovieComponent::goToStart()
  234285. {
  234286. setPosition (0.0);
  234287. }
  234288. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234289. const RectanglePlacement& placement)
  234290. {
  234291. int normalWidth, normalHeight;
  234292. getMovieNormalSize (normalWidth, normalHeight);
  234293. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234294. {
  234295. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234296. placement.applyTo (x, y, w, h,
  234297. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234298. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234299. if (w > 0 && h > 0)
  234300. {
  234301. setBounds (roundToInt (x), roundToInt (y),
  234302. roundToInt (w), roundToInt (h));
  234303. }
  234304. }
  234305. else
  234306. {
  234307. setBounds (spaceToFitWithin);
  234308. }
  234309. }
  234310. #if ! (JUCE_MAC && JUCE_64BIT)
  234311. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234312. {
  234313. if (movieStream == 0)
  234314. return false;
  234315. File file;
  234316. QTMovie* movie = openMovieFromStream (movieStream, file);
  234317. if (movie != nil)
  234318. result = [movie quickTimeMovie];
  234319. return movie != nil;
  234320. }
  234321. #endif
  234322. #endif
  234323. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234324. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234325. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234326. // compiled on its own).
  234327. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234328. const int kilobytesPerSecond1x = 176;
  234329. END_JUCE_NAMESPACE
  234330. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234331. @interface OpenDiskDevice : NSObject
  234332. {
  234333. @public
  234334. DRDevice* device;
  234335. NSMutableArray* tracks;
  234336. bool underrunProtection;
  234337. }
  234338. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234339. - (void) dealloc;
  234340. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234341. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234342. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234343. @end
  234344. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234345. @interface AudioTrackProducer : NSObject
  234346. {
  234347. JUCE_NAMESPACE::AudioSource* source;
  234348. int readPosition, lengthInFrames;
  234349. }
  234350. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234351. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234352. - (void) dealloc;
  234353. - (void) setupTrackProperties: (DRTrack*) track;
  234354. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234355. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234356. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234357. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234358. toMedia:(NSDictionary*)mediaInfo;
  234359. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234360. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234361. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234362. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234363. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234364. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234365. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234366. ioFlags:(uint32_t*)flags;
  234367. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234368. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234369. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234370. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234371. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234372. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234373. ioFlags:(uint32_t*)flags;
  234374. @end
  234375. @implementation OpenDiskDevice
  234376. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234377. {
  234378. [super init];
  234379. device = device_;
  234380. tracks = [[NSMutableArray alloc] init];
  234381. underrunProtection = true;
  234382. return self;
  234383. }
  234384. - (void) dealloc
  234385. {
  234386. [tracks release];
  234387. [super dealloc];
  234388. }
  234389. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234390. {
  234391. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234392. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234393. [p setupTrackProperties: t];
  234394. [tracks addObject: t];
  234395. [t release];
  234396. [p release];
  234397. }
  234398. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234399. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234400. {
  234401. DRBurn* burn = [DRBurn burnForDevice: device];
  234402. if (! [device acquireExclusiveAccess])
  234403. {
  234404. *error = "Couldn't open or write to the CD device";
  234405. return;
  234406. }
  234407. [device acquireMediaReservation];
  234408. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234409. [d autorelease];
  234410. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234411. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234412. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234413. if (burnSpeed > 0)
  234414. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234415. if (! underrunProtection)
  234416. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234417. [burn setProperties: d];
  234418. [burn writeLayout: tracks];
  234419. for (;;)
  234420. {
  234421. JUCE_NAMESPACE::Thread::sleep (300);
  234422. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234423. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234424. {
  234425. [burn abort];
  234426. *error = "User cancelled the write operation";
  234427. break;
  234428. }
  234429. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234430. {
  234431. *error = "Write operation failed";
  234432. break;
  234433. }
  234434. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234435. {
  234436. break;
  234437. }
  234438. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234439. objectForKey: DRErrorStatusErrorStringKey];
  234440. if ([err length] > 0)
  234441. {
  234442. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234443. break;
  234444. }
  234445. }
  234446. [device releaseMediaReservation];
  234447. [device releaseExclusiveAccess];
  234448. }
  234449. @end
  234450. @implementation AudioTrackProducer
  234451. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234452. {
  234453. lengthInFrames = lengthInFrames_;
  234454. readPosition = 0;
  234455. return self;
  234456. }
  234457. - (void) setupTrackProperties: (DRTrack*) track
  234458. {
  234459. NSMutableDictionary* p = [[track properties] mutableCopy];
  234460. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234461. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234462. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234463. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234464. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234465. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234466. [track setProperties: p];
  234467. [p release];
  234468. }
  234469. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234470. {
  234471. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234472. if (s != nil)
  234473. s->source = source_;
  234474. return s;
  234475. }
  234476. - (void) dealloc
  234477. {
  234478. if (source != 0)
  234479. {
  234480. source->releaseResources();
  234481. delete source;
  234482. }
  234483. [super dealloc];
  234484. }
  234485. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234486. {
  234487. }
  234488. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234489. {
  234490. return true;
  234491. }
  234492. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234493. {
  234494. return lengthInFrames;
  234495. }
  234496. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234497. toMedia: (NSDictionary*) mediaInfo
  234498. {
  234499. if (source != 0)
  234500. source->prepareToPlay (44100 / 75, 44100);
  234501. readPosition = 0;
  234502. return true;
  234503. }
  234504. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234505. {
  234506. if (source != 0)
  234507. source->prepareToPlay (44100 / 75, 44100);
  234508. return true;
  234509. }
  234510. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234511. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234512. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234513. {
  234514. if (source != 0)
  234515. {
  234516. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234517. if (numSamples > 0)
  234518. {
  234519. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234520. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234521. info.buffer = &tempBuffer;
  234522. info.startSample = 0;
  234523. info.numSamples = numSamples;
  234524. source->getNextAudioBlock (info);
  234525. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234526. JUCE_NAMESPACE::AudioData::LittleEndian,
  234527. JUCE_NAMESPACE::AudioData::Interleaved,
  234528. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234529. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234530. JUCE_NAMESPACE::AudioData::NativeEndian,
  234531. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234532. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234533. CDSampleFormat left (buffer, 2);
  234534. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234535. CDSampleFormat right (buffer + 2, 2);
  234536. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234537. readPosition += numSamples;
  234538. }
  234539. return numSamples * 4;
  234540. }
  234541. return 0;
  234542. }
  234543. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234544. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234545. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234546. ioFlags: (uint32_t*) flags
  234547. {
  234548. zeromem (buffer, bufferLength);
  234549. return bufferLength;
  234550. }
  234551. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234552. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234553. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234554. {
  234555. return true;
  234556. }
  234557. @end
  234558. BEGIN_JUCE_NAMESPACE
  234559. class AudioCDBurner::Pimpl : public Timer
  234560. {
  234561. public:
  234562. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234563. : device (0), owner (owner_)
  234564. {
  234565. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234566. if (dev != 0)
  234567. {
  234568. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234569. lastState = getDiskState();
  234570. startTimer (1000);
  234571. }
  234572. }
  234573. ~Pimpl()
  234574. {
  234575. stopTimer();
  234576. [device release];
  234577. }
  234578. void timerCallback()
  234579. {
  234580. const DiskState state = getDiskState();
  234581. if (state != lastState)
  234582. {
  234583. lastState = state;
  234584. owner.sendChangeMessage (&owner);
  234585. }
  234586. }
  234587. DiskState getDiskState() const
  234588. {
  234589. if ([device->device isValid])
  234590. {
  234591. NSDictionary* status = [device->device status];
  234592. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234593. if ([state isEqualTo: DRDeviceMediaStateNone])
  234594. {
  234595. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234596. return trayOpen;
  234597. return noDisc;
  234598. }
  234599. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234600. {
  234601. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234602. return writableDiskPresent;
  234603. else
  234604. return readOnlyDiskPresent;
  234605. }
  234606. }
  234607. return unknown;
  234608. }
  234609. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234610. const Array<int> getAvailableWriteSpeeds() const
  234611. {
  234612. Array<int> results;
  234613. if ([device->device isValid])
  234614. {
  234615. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234616. for (unsigned int i = 0; i < [speeds count]; ++i)
  234617. {
  234618. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234619. results.add (kbPerSec / kilobytesPerSecond1x);
  234620. }
  234621. }
  234622. return results;
  234623. }
  234624. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234625. {
  234626. if ([device->device isValid])
  234627. {
  234628. device->underrunProtection = shouldBeEnabled;
  234629. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234630. }
  234631. return false;
  234632. }
  234633. int getNumAvailableAudioBlocks() const
  234634. {
  234635. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234636. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234637. }
  234638. OpenDiskDevice* device;
  234639. private:
  234640. DiskState lastState;
  234641. AudioCDBurner& owner;
  234642. };
  234643. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234644. {
  234645. pimpl = new Pimpl (*this, deviceIndex);
  234646. }
  234647. AudioCDBurner::~AudioCDBurner()
  234648. {
  234649. }
  234650. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234651. {
  234652. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234653. if (b->pimpl->device == 0)
  234654. b = 0;
  234655. return b.release();
  234656. }
  234657. static NSArray* findDiskBurnerDevices()
  234658. {
  234659. NSMutableArray* results = [NSMutableArray array];
  234660. NSArray* devs = [DRDevice devices];
  234661. for (int i = 0; i < [devs count]; ++i)
  234662. {
  234663. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234664. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234665. if (name != nil)
  234666. [results addObject: name];
  234667. }
  234668. return results;
  234669. }
  234670. const StringArray AudioCDBurner::findAvailableDevices()
  234671. {
  234672. NSArray* names = findDiskBurnerDevices();
  234673. StringArray s;
  234674. for (unsigned int i = 0; i < [names count]; ++i)
  234675. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234676. return s;
  234677. }
  234678. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234679. {
  234680. return pimpl->getDiskState();
  234681. }
  234682. bool AudioCDBurner::isDiskPresent() const
  234683. {
  234684. return getDiskState() == writableDiskPresent;
  234685. }
  234686. bool AudioCDBurner::openTray()
  234687. {
  234688. return pimpl->openTray();
  234689. }
  234690. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234691. {
  234692. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234693. DiskState oldState = getDiskState();
  234694. DiskState newState = oldState;
  234695. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234696. {
  234697. newState = getDiskState();
  234698. Thread::sleep (100);
  234699. }
  234700. return newState;
  234701. }
  234702. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234703. {
  234704. return pimpl->getAvailableWriteSpeeds();
  234705. }
  234706. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234707. {
  234708. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234709. }
  234710. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234711. {
  234712. return pimpl->getNumAvailableAudioBlocks();
  234713. }
  234714. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234715. {
  234716. if ([pimpl->device->device isValid])
  234717. {
  234718. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234719. return true;
  234720. }
  234721. return false;
  234722. }
  234723. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234724. bool ejectDiscAfterwards,
  234725. bool performFakeBurnForTesting,
  234726. int writeSpeed)
  234727. {
  234728. String error ("Couldn't open or write to the CD device");
  234729. if ([pimpl->device->device isValid])
  234730. {
  234731. error = String::empty;
  234732. [pimpl->device burn: listener
  234733. errorString: &error
  234734. ejectAfterwards: ejectDiscAfterwards
  234735. isFake: performFakeBurnForTesting
  234736. speed: writeSpeed];
  234737. }
  234738. return error;
  234739. }
  234740. #endif
  234741. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234742. void AudioCDReader::ejectDisk()
  234743. {
  234744. const ScopedAutoReleasePool p;
  234745. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234746. }
  234747. #endif
  234748. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234749. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234750. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234751. // compiled on its own).
  234752. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234753. namespace CDReaderHelpers
  234754. {
  234755. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234756. {
  234757. forEachXmlChildElementWithTagName (xml, child, "key")
  234758. if (child->getAllSubText().trim() == key)
  234759. return child->getNextElement();
  234760. return 0;
  234761. }
  234762. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234763. {
  234764. const XmlElement* const block = getElementForKey (xml, key);
  234765. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234766. }
  234767. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234768. // Returns NULL on success, otherwise a const char* representing an error.
  234769. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234770. {
  234771. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234772. if (xml == 0)
  234773. return "Couldn't parse XML in file";
  234774. const XmlElement* const dict = xml->getChildByName ("dict");
  234775. if (dict == 0)
  234776. return "Couldn't get top level dictionary";
  234777. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234778. if (sessions == 0)
  234779. return "Couldn't find sessions key";
  234780. const XmlElement* const session = sessions->getFirstChildElement();
  234781. if (session == 0)
  234782. return "Couldn't find first session";
  234783. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234784. if (leadOut < 0)
  234785. return "Couldn't find Leadout Block";
  234786. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234787. if (trackArray == 0)
  234788. return "Couldn't find Track Array";
  234789. forEachXmlChildElement (*trackArray, track)
  234790. {
  234791. const int trackValue = getIntValueForKey (*track, "Start Block");
  234792. if (trackValue < 0)
  234793. return "Couldn't find Start Block in the track";
  234794. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234795. }
  234796. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234797. return 0;
  234798. }
  234799. static void findDevices (Array<File>& cds)
  234800. {
  234801. File volumes ("/Volumes");
  234802. volumes.findChildFiles (cds, File::findDirectories, false);
  234803. for (int i = cds.size(); --i >= 0;)
  234804. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234805. cds.remove (i);
  234806. }
  234807. struct TrackSorter
  234808. {
  234809. static int getCDTrackNumber (const File& file)
  234810. {
  234811. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234812. }
  234813. static int compareElements (const File& first, const File& second)
  234814. {
  234815. const int firstTrack = getCDTrackNumber (first);
  234816. const int secondTrack = getCDTrackNumber (second);
  234817. jassert (firstTrack > 0 && secondTrack > 0);
  234818. return firstTrack - secondTrack;
  234819. }
  234820. };
  234821. }
  234822. const StringArray AudioCDReader::getAvailableCDNames()
  234823. {
  234824. Array<File> cds;
  234825. CDReaderHelpers::findDevices (cds);
  234826. StringArray names;
  234827. for (int i = 0; i < cds.size(); ++i)
  234828. names.add (cds.getReference(i).getFileName());
  234829. return names;
  234830. }
  234831. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234832. {
  234833. Array<File> cds;
  234834. CDReaderHelpers::findDevices (cds);
  234835. if (cds[index].exists())
  234836. return new AudioCDReader (cds[index]);
  234837. return 0;
  234838. }
  234839. AudioCDReader::AudioCDReader (const File& volume)
  234840. : AudioFormatReader (0, "CD Audio"),
  234841. volumeDir (volume),
  234842. currentReaderTrack (-1),
  234843. reader (0)
  234844. {
  234845. sampleRate = 44100.0;
  234846. bitsPerSample = 16;
  234847. numChannels = 2;
  234848. usesFloatingPointData = false;
  234849. refreshTrackLengths();
  234850. }
  234851. AudioCDReader::~AudioCDReader()
  234852. {
  234853. }
  234854. void AudioCDReader::refreshTrackLengths()
  234855. {
  234856. tracks.clear();
  234857. trackStartSamples.clear();
  234858. lengthInSamples = 0;
  234859. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234860. CDReaderHelpers::TrackSorter sorter;
  234861. tracks.sort (sorter);
  234862. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234863. if (toc.exists())
  234864. {
  234865. XmlDocument doc (toc);
  234866. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234867. (void) error; // could be logged..
  234868. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234869. }
  234870. }
  234871. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234872. int64 startSampleInFile, int numSamples)
  234873. {
  234874. while (numSamples > 0)
  234875. {
  234876. int track = -1;
  234877. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234878. {
  234879. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234880. {
  234881. track = i;
  234882. break;
  234883. }
  234884. }
  234885. if (track < 0)
  234886. return false;
  234887. if (track != currentReaderTrack)
  234888. {
  234889. reader = 0;
  234890. FileInputStream* const in = tracks [track].createInputStream();
  234891. if (in != 0)
  234892. {
  234893. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234894. AiffAudioFormat format;
  234895. reader = format.createReaderFor (bin, true);
  234896. if (reader == 0)
  234897. currentReaderTrack = -1;
  234898. else
  234899. currentReaderTrack = track;
  234900. }
  234901. }
  234902. if (reader == 0)
  234903. return false;
  234904. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234905. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234906. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234907. numSamples -= numAvailable;
  234908. startSampleInFile += numAvailable;
  234909. }
  234910. return true;
  234911. }
  234912. bool AudioCDReader::isCDStillPresent() const
  234913. {
  234914. return volumeDir.exists();
  234915. }
  234916. bool AudioCDReader::isTrackAudio (int trackNum) const
  234917. {
  234918. return tracks [trackNum].hasFileExtension (".aiff");
  234919. }
  234920. void AudioCDReader::enableIndexScanning (bool b)
  234921. {
  234922. // any way to do this on a Mac??
  234923. }
  234924. int AudioCDReader::getLastIndex() const
  234925. {
  234926. return 0;
  234927. }
  234928. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234929. {
  234930. return Array <int>();
  234931. }
  234932. #endif
  234933. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234934. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234935. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234936. // compiled on its own).
  234937. #if JUCE_INCLUDED_FILE
  234938. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234939. for example having more than one juce plugin loaded into a host, then when a
  234940. method is called, the actual code that runs might actually be in a different module
  234941. than the one you expect... So any calls to library functions or statics that are
  234942. made inside obj-c methods will probably end up getting executed in a different DLL's
  234943. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234944. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234945. virtual methods of an object that's known to live inside the right module's space.
  234946. */
  234947. class AppDelegateRedirector
  234948. {
  234949. public:
  234950. AppDelegateRedirector()
  234951. {
  234952. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234953. runLoop = CFRunLoopGetMain();
  234954. #else
  234955. runLoop = CFRunLoopGetCurrent();
  234956. #endif
  234957. CFRunLoopSourceContext sourceContext;
  234958. zerostruct (sourceContext);
  234959. sourceContext.info = this;
  234960. sourceContext.perform = runLoopSourceCallback;
  234961. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234962. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234963. }
  234964. virtual ~AppDelegateRedirector()
  234965. {
  234966. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234967. CFRunLoopSourceInvalidate (runLoopSource);
  234968. CFRelease (runLoopSource);
  234969. }
  234970. virtual NSApplicationTerminateReply shouldTerminate()
  234971. {
  234972. if (JUCEApplication::getInstance() != 0)
  234973. {
  234974. JUCEApplication::getInstance()->systemRequestedQuit();
  234975. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234976. return NSTerminateCancel;
  234977. }
  234978. return NSTerminateNow;
  234979. }
  234980. virtual void willTerminate()
  234981. {
  234982. JUCEApplication::appWillTerminateByForce();
  234983. }
  234984. virtual BOOL openFile (NSString* filename)
  234985. {
  234986. if (JUCEApplication::getInstance() != 0)
  234987. {
  234988. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234989. return YES;
  234990. }
  234991. return NO;
  234992. }
  234993. virtual void openFiles (NSArray* filenames)
  234994. {
  234995. StringArray files;
  234996. for (unsigned int i = 0; i < [filenames count]; ++i)
  234997. {
  234998. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234999. if (filename.containsChar (' '))
  235000. filename = filename.quoted('"');
  235001. files.add (filename);
  235002. }
  235003. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  235004. {
  235005. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  235006. }
  235007. }
  235008. virtual void focusChanged()
  235009. {
  235010. juce_HandleProcessFocusChange();
  235011. }
  235012. struct CallbackMessagePayload
  235013. {
  235014. MessageCallbackFunction* function;
  235015. void* parameter;
  235016. void* volatile result;
  235017. bool volatile hasBeenExecuted;
  235018. };
  235019. virtual void performCallback (CallbackMessagePayload* pl)
  235020. {
  235021. pl->result = (*pl->function) (pl->parameter);
  235022. pl->hasBeenExecuted = true;
  235023. }
  235024. virtual void deleteSelf()
  235025. {
  235026. delete this;
  235027. }
  235028. void postMessage (Message* const m)
  235029. {
  235030. messages.add (m);
  235031. CFRunLoopSourceSignal (runLoopSource);
  235032. CFRunLoopWakeUp (runLoop);
  235033. }
  235034. private:
  235035. CFRunLoopRef runLoop;
  235036. CFRunLoopSourceRef runLoopSource;
  235037. OwnedArray <Message, CriticalSection> messages;
  235038. void runLoopCallback()
  235039. {
  235040. int numDispatched = 0;
  235041. do
  235042. {
  235043. Message* const nextMessage = messages.removeAndReturn (0);
  235044. if (nextMessage == 0)
  235045. return;
  235046. const ScopedAutoReleasePool pool;
  235047. MessageManager::getInstance()->deliverMessage (nextMessage);
  235048. } while (++numDispatched <= 4);
  235049. CFRunLoopSourceSignal (runLoopSource);
  235050. CFRunLoopWakeUp (runLoop);
  235051. }
  235052. static void runLoopSourceCallback (void* info)
  235053. {
  235054. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  235055. }
  235056. };
  235057. END_JUCE_NAMESPACE
  235058. using namespace JUCE_NAMESPACE;
  235059. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  235060. @interface JuceAppDelegate : NSObject
  235061. {
  235062. @private
  235063. id oldDelegate;
  235064. @public
  235065. AppDelegateRedirector* redirector;
  235066. }
  235067. - (JuceAppDelegate*) init;
  235068. - (void) dealloc;
  235069. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  235070. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  235071. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  235072. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  235073. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  235074. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  235075. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  235076. - (void) performCallback: (id) info;
  235077. - (void) dummyMethod;
  235078. @end
  235079. @implementation JuceAppDelegate
  235080. - (JuceAppDelegate*) init
  235081. {
  235082. [super init];
  235083. redirector = new AppDelegateRedirector();
  235084. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  235085. if (JUCEApplication::isStandaloneApp())
  235086. {
  235087. oldDelegate = [NSApp delegate];
  235088. [NSApp setDelegate: self];
  235089. }
  235090. else
  235091. {
  235092. oldDelegate = 0;
  235093. [center addObserver: self selector: @selector (applicationDidResignActive:)
  235094. name: NSApplicationDidResignActiveNotification object: NSApp];
  235095. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  235096. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  235097. [center addObserver: self selector: @selector (applicationWillUnhide:)
  235098. name: NSApplicationWillUnhideNotification object: NSApp];
  235099. }
  235100. return self;
  235101. }
  235102. - (void) dealloc
  235103. {
  235104. if (oldDelegate != 0)
  235105. [NSApp setDelegate: oldDelegate];
  235106. redirector->deleteSelf();
  235107. [super dealloc];
  235108. }
  235109. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  235110. {
  235111. (void) app;
  235112. return redirector->shouldTerminate();
  235113. }
  235114. - (void) applicationWillTerminate: (NSNotification*) aNotification
  235115. {
  235116. (void) aNotification;
  235117. redirector->willTerminate();
  235118. }
  235119. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  235120. {
  235121. (void) app;
  235122. return redirector->openFile (filename);
  235123. }
  235124. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  235125. {
  235126. (void) sender;
  235127. return redirector->openFiles (filenames);
  235128. }
  235129. - (void) applicationDidBecomeActive: (NSNotification*) notification
  235130. {
  235131. (void) notification;
  235132. redirector->focusChanged();
  235133. }
  235134. - (void) applicationDidResignActive: (NSNotification*) notification
  235135. {
  235136. (void) notification;
  235137. redirector->focusChanged();
  235138. }
  235139. - (void) applicationWillUnhide: (NSNotification*) notification
  235140. {
  235141. (void) notification;
  235142. redirector->focusChanged();
  235143. }
  235144. - (void) performCallback: (id) info
  235145. {
  235146. if ([info isKindOfClass: [NSData class]])
  235147. {
  235148. AppDelegateRedirector::CallbackMessagePayload* pl
  235149. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  235150. if (pl != 0)
  235151. redirector->performCallback (pl);
  235152. }
  235153. else
  235154. {
  235155. jassertfalse; // should never get here!
  235156. }
  235157. }
  235158. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  235159. @end
  235160. BEGIN_JUCE_NAMESPACE
  235161. static JuceAppDelegate* juceAppDelegate = 0;
  235162. void MessageManager::runDispatchLoop()
  235163. {
  235164. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  235165. {
  235166. const ScopedAutoReleasePool pool;
  235167. // must only be called by the message thread!
  235168. jassert (isThisTheMessageThread());
  235169. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  235170. @try
  235171. {
  235172. [NSApp run];
  235173. }
  235174. @catch (NSException* e)
  235175. {
  235176. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  235177. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  235178. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  235179. }
  235180. @finally
  235181. {
  235182. }
  235183. #else
  235184. [NSApp run];
  235185. #endif
  235186. }
  235187. }
  235188. void MessageManager::stopDispatchLoop()
  235189. {
  235190. quitMessagePosted = true;
  235191. [NSApp stop: nil];
  235192. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  235193. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  235194. }
  235195. static bool isEventBlockedByModalComps (NSEvent* e)
  235196. {
  235197. if (Component::getNumCurrentlyModalComponents() == 0)
  235198. return false;
  235199. NSWindow* const w = [e window];
  235200. if (w == 0 || [w worksWhenModal])
  235201. return false;
  235202. bool isKey = false, isInputAttempt = false;
  235203. switch ([e type])
  235204. {
  235205. case NSKeyDown:
  235206. case NSKeyUp:
  235207. isKey = isInputAttempt = true;
  235208. break;
  235209. case NSLeftMouseDown:
  235210. case NSRightMouseDown:
  235211. case NSOtherMouseDown:
  235212. isInputAttempt = true;
  235213. break;
  235214. case NSLeftMouseDragged:
  235215. case NSRightMouseDragged:
  235216. case NSLeftMouseUp:
  235217. case NSRightMouseUp:
  235218. case NSOtherMouseUp:
  235219. case NSOtherMouseDragged:
  235220. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  235221. return false;
  235222. break;
  235223. case NSMouseMoved:
  235224. case NSMouseEntered:
  235225. case NSMouseExited:
  235226. case NSCursorUpdate:
  235227. case NSScrollWheel:
  235228. case NSTabletPoint:
  235229. case NSTabletProximity:
  235230. break;
  235231. default:
  235232. return false;
  235233. }
  235234. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  235235. {
  235236. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  235237. NSView* const compView = (NSView*) peer->getNativeHandle();
  235238. if ([compView window] == w)
  235239. {
  235240. if (isKey)
  235241. {
  235242. if (compView == [w firstResponder])
  235243. return false;
  235244. }
  235245. else
  235246. {
  235247. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  235248. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  235249. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  235250. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  235251. return false;
  235252. }
  235253. }
  235254. }
  235255. if (isInputAttempt)
  235256. {
  235257. if (! [NSApp isActive])
  235258. [NSApp activateIgnoringOtherApps: YES];
  235259. Component* const modal = Component::getCurrentlyModalComponent (0);
  235260. if (modal != 0)
  235261. modal->inputAttemptWhenModal();
  235262. }
  235263. return true;
  235264. }
  235265. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235266. {
  235267. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235268. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235269. while (! quitMessagePosted)
  235270. {
  235271. const ScopedAutoReleasePool pool;
  235272. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235273. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235274. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235275. inMode: NSDefaultRunLoopMode
  235276. dequeue: YES];
  235277. if (e != 0 && ! isEventBlockedByModalComps (e))
  235278. [NSApp sendEvent: e];
  235279. if (Time::getMillisecondCounter() >= endTime)
  235280. break;
  235281. }
  235282. return ! quitMessagePosted;
  235283. }
  235284. void MessageManager::doPlatformSpecificInitialisation()
  235285. {
  235286. if (juceAppDelegate == 0)
  235287. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235288. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235289. // correctly (needed prior to 10.5)
  235290. if (! [NSThread isMultiThreaded])
  235291. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235292. toTarget: juceAppDelegate
  235293. withObject: nil];
  235294. }
  235295. void MessageManager::doPlatformSpecificShutdown()
  235296. {
  235297. if (juceAppDelegate != 0)
  235298. {
  235299. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235300. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235301. [juceAppDelegate release];
  235302. juceAppDelegate = 0;
  235303. }
  235304. }
  235305. bool juce_postMessageToSystemQueue (Message* message)
  235306. {
  235307. juceAppDelegate->redirector->postMessage (message);
  235308. return true;
  235309. }
  235310. void MessageManager::broadcastMessage (const String& value)
  235311. {
  235312. }
  235313. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235314. {
  235315. if (isThisTheMessageThread())
  235316. {
  235317. return (*callback) (data);
  235318. }
  235319. else
  235320. {
  235321. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235322. // deadlock because the message manager is blocked from running, so can never
  235323. // call your function..
  235324. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235325. const ScopedAutoReleasePool pool;
  235326. AppDelegateRedirector::CallbackMessagePayload cmp;
  235327. cmp.function = callback;
  235328. cmp.parameter = data;
  235329. cmp.result = 0;
  235330. cmp.hasBeenExecuted = false;
  235331. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235332. withObject: [NSData dataWithBytesNoCopy: &cmp
  235333. length: sizeof (cmp)
  235334. freeWhenDone: NO]
  235335. waitUntilDone: YES];
  235336. return cmp.result;
  235337. }
  235338. }
  235339. #endif
  235340. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235341. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235343. // compiled on its own).
  235344. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235345. #if JUCE_MAC
  235346. END_JUCE_NAMESPACE
  235347. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235348. @interface DownloadClickDetector : NSObject
  235349. {
  235350. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235351. }
  235352. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235353. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235354. request: (NSURLRequest*) request
  235355. frame: (WebFrame*) frame
  235356. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235357. @end
  235358. @implementation DownloadClickDetector
  235359. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235360. {
  235361. [super init];
  235362. ownerComponent = ownerComponent_;
  235363. return self;
  235364. }
  235365. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235366. request: (NSURLRequest*) request
  235367. frame: (WebFrame*) frame
  235368. decisionListener: (id <WebPolicyDecisionListener>) listener
  235369. {
  235370. (void) sender;
  235371. (void) request;
  235372. (void) frame;
  235373. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235374. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235375. [listener use];
  235376. else
  235377. [listener ignore];
  235378. }
  235379. @end
  235380. BEGIN_JUCE_NAMESPACE
  235381. class WebBrowserComponentInternal : public NSViewComponent
  235382. {
  235383. public:
  235384. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235385. {
  235386. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235387. frameName: @""
  235388. groupName: @""];
  235389. setView (webView);
  235390. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235391. [webView setPolicyDelegate: clickListener];
  235392. }
  235393. ~WebBrowserComponentInternal()
  235394. {
  235395. [webView setPolicyDelegate: nil];
  235396. [clickListener release];
  235397. setView (0);
  235398. }
  235399. void goToURL (const String& url,
  235400. const StringArray* headers,
  235401. const MemoryBlock* postData)
  235402. {
  235403. NSMutableURLRequest* r
  235404. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235405. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235406. timeoutInterval: 30.0];
  235407. if (postData != 0 && postData->getSize() > 0)
  235408. {
  235409. [r setHTTPMethod: @"POST"];
  235410. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235411. length: postData->getSize()]];
  235412. }
  235413. if (headers != 0)
  235414. {
  235415. for (int i = 0; i < headers->size(); ++i)
  235416. {
  235417. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235418. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235419. [r setValue: juceStringToNS (headerValue)
  235420. forHTTPHeaderField: juceStringToNS (headerName)];
  235421. }
  235422. }
  235423. stop();
  235424. [[webView mainFrame] loadRequest: r];
  235425. }
  235426. void goBack()
  235427. {
  235428. [webView goBack];
  235429. }
  235430. void goForward()
  235431. {
  235432. [webView goForward];
  235433. }
  235434. void stop()
  235435. {
  235436. [webView stopLoading: nil];
  235437. }
  235438. void refresh()
  235439. {
  235440. [webView reload: nil];
  235441. }
  235442. private:
  235443. WebView* webView;
  235444. DownloadClickDetector* clickListener;
  235445. };
  235446. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235447. : browser (0),
  235448. blankPageShown (false),
  235449. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235450. {
  235451. setOpaque (true);
  235452. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235453. }
  235454. WebBrowserComponent::~WebBrowserComponent()
  235455. {
  235456. deleteAndZero (browser);
  235457. }
  235458. void WebBrowserComponent::goToURL (const String& url,
  235459. const StringArray* headers,
  235460. const MemoryBlock* postData)
  235461. {
  235462. lastURL = url;
  235463. lastHeaders.clear();
  235464. if (headers != 0)
  235465. lastHeaders = *headers;
  235466. lastPostData.setSize (0);
  235467. if (postData != 0)
  235468. lastPostData = *postData;
  235469. blankPageShown = false;
  235470. browser->goToURL (url, headers, postData);
  235471. }
  235472. void WebBrowserComponent::stop()
  235473. {
  235474. browser->stop();
  235475. }
  235476. void WebBrowserComponent::goBack()
  235477. {
  235478. lastURL = String::empty;
  235479. blankPageShown = false;
  235480. browser->goBack();
  235481. }
  235482. void WebBrowserComponent::goForward()
  235483. {
  235484. lastURL = String::empty;
  235485. browser->goForward();
  235486. }
  235487. void WebBrowserComponent::refresh()
  235488. {
  235489. browser->refresh();
  235490. }
  235491. void WebBrowserComponent::paint (Graphics&)
  235492. {
  235493. }
  235494. void WebBrowserComponent::checkWindowAssociation()
  235495. {
  235496. if (isShowing())
  235497. {
  235498. if (blankPageShown)
  235499. goBack();
  235500. }
  235501. else
  235502. {
  235503. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235504. {
  235505. // when the component becomes invisible, some stuff like flash
  235506. // carries on playing audio, so we need to force it onto a blank
  235507. // page to avoid this, (and send it back when it's made visible again).
  235508. blankPageShown = true;
  235509. browser->goToURL ("about:blank", 0, 0);
  235510. }
  235511. }
  235512. }
  235513. void WebBrowserComponent::reloadLastURL()
  235514. {
  235515. if (lastURL.isNotEmpty())
  235516. {
  235517. goToURL (lastURL, &lastHeaders, &lastPostData);
  235518. lastURL = String::empty;
  235519. }
  235520. }
  235521. void WebBrowserComponent::parentHierarchyChanged()
  235522. {
  235523. checkWindowAssociation();
  235524. }
  235525. void WebBrowserComponent::resized()
  235526. {
  235527. browser->setSize (getWidth(), getHeight());
  235528. }
  235529. void WebBrowserComponent::visibilityChanged()
  235530. {
  235531. checkWindowAssociation();
  235532. }
  235533. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235534. {
  235535. return true;
  235536. }
  235537. #else
  235538. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235539. {
  235540. }
  235541. WebBrowserComponent::~WebBrowserComponent()
  235542. {
  235543. }
  235544. void WebBrowserComponent::goToURL (const String& url,
  235545. const StringArray* headers,
  235546. const MemoryBlock* postData)
  235547. {
  235548. }
  235549. void WebBrowserComponent::stop()
  235550. {
  235551. }
  235552. void WebBrowserComponent::goBack()
  235553. {
  235554. }
  235555. void WebBrowserComponent::goForward()
  235556. {
  235557. }
  235558. void WebBrowserComponent::refresh()
  235559. {
  235560. }
  235561. void WebBrowserComponent::paint (Graphics& g)
  235562. {
  235563. }
  235564. void WebBrowserComponent::checkWindowAssociation()
  235565. {
  235566. }
  235567. void WebBrowserComponent::reloadLastURL()
  235568. {
  235569. }
  235570. void WebBrowserComponent::parentHierarchyChanged()
  235571. {
  235572. }
  235573. void WebBrowserComponent::resized()
  235574. {
  235575. }
  235576. void WebBrowserComponent::visibilityChanged()
  235577. {
  235578. }
  235579. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235580. {
  235581. return true;
  235582. }
  235583. #endif
  235584. #endif
  235585. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235586. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235587. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235588. // compiled on its own).
  235589. #if JUCE_INCLUDED_FILE
  235590. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235591. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235592. #endif
  235593. #undef log
  235594. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235595. #define log(a) Logger::writeToLog (a)
  235596. #else
  235597. #define log(a)
  235598. #endif
  235599. #undef OK
  235600. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235601. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235602. {
  235603. if (err == noErr)
  235604. return true;
  235605. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235606. jassertfalse;
  235607. return false;
  235608. }
  235609. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235610. #else
  235611. #define OK(a) (a == noErr)
  235612. #endif
  235613. class CoreAudioInternal : public Timer
  235614. {
  235615. public:
  235616. CoreAudioInternal (AudioDeviceID id)
  235617. : inputLatency (0),
  235618. outputLatency (0),
  235619. callback (0),
  235620. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235621. audioProcID (0),
  235622. #endif
  235623. isSlaveDevice (false),
  235624. deviceID (id),
  235625. started (false),
  235626. sampleRate (0),
  235627. bufferSize (512),
  235628. numInputChans (0),
  235629. numOutputChans (0),
  235630. callbacksAllowed (true),
  235631. numInputChannelInfos (0),
  235632. numOutputChannelInfos (0)
  235633. {
  235634. jassert (deviceID != 0);
  235635. updateDetailsFromDevice();
  235636. AudioObjectPropertyAddress pa;
  235637. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235638. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235639. pa.mElement = kAudioObjectPropertyElementWildcard;
  235640. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235641. }
  235642. ~CoreAudioInternal()
  235643. {
  235644. AudioObjectPropertyAddress pa;
  235645. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235646. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235647. pa.mElement = kAudioObjectPropertyElementWildcard;
  235648. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235649. stop (false);
  235650. }
  235651. void allocateTempBuffers()
  235652. {
  235653. const int tempBufSize = bufferSize + 4;
  235654. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235655. tempInputBuffers.calloc (numInputChans + 2);
  235656. tempOutputBuffers.calloc (numOutputChans + 2);
  235657. int i, count = 0;
  235658. for (i = 0; i < numInputChans; ++i)
  235659. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235660. for (i = 0; i < numOutputChans; ++i)
  235661. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235662. }
  235663. // returns the number of actual available channels
  235664. void fillInChannelInfo (const bool input)
  235665. {
  235666. int chanNum = 0;
  235667. UInt32 size;
  235668. AudioObjectPropertyAddress pa;
  235669. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235670. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235671. pa.mElement = kAudioObjectPropertyElementMaster;
  235672. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235673. {
  235674. HeapBlock <AudioBufferList> bufList;
  235675. bufList.calloc (size, 1);
  235676. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235677. {
  235678. const int numStreams = bufList->mNumberBuffers;
  235679. for (int i = 0; i < numStreams; ++i)
  235680. {
  235681. const AudioBuffer& b = bufList->mBuffers[i];
  235682. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235683. {
  235684. String name;
  235685. {
  235686. char channelName [256];
  235687. zerostruct (channelName);
  235688. UInt32 nameSize = sizeof (channelName);
  235689. UInt32 channelNum = chanNum + 1;
  235690. pa.mSelector = kAudioDevicePropertyChannelName;
  235691. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235692. name = String::fromUTF8 (channelName, nameSize);
  235693. }
  235694. if (input)
  235695. {
  235696. if (activeInputChans[chanNum])
  235697. {
  235698. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235699. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235700. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235701. ++numInputChannelInfos;
  235702. }
  235703. if (name.isEmpty())
  235704. name << "Input " << (chanNum + 1);
  235705. inChanNames.add (name);
  235706. }
  235707. else
  235708. {
  235709. if (activeOutputChans[chanNum])
  235710. {
  235711. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235712. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235713. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235714. ++numOutputChannelInfos;
  235715. }
  235716. if (name.isEmpty())
  235717. name << "Output " << (chanNum + 1);
  235718. outChanNames.add (name);
  235719. }
  235720. ++chanNum;
  235721. }
  235722. }
  235723. }
  235724. }
  235725. }
  235726. void updateDetailsFromDevice()
  235727. {
  235728. stopTimer();
  235729. if (deviceID == 0)
  235730. return;
  235731. const ScopedLock sl (callbackLock);
  235732. Float64 sr;
  235733. UInt32 size = sizeof (Float64);
  235734. AudioObjectPropertyAddress pa;
  235735. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235736. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235737. pa.mElement = kAudioObjectPropertyElementMaster;
  235738. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235739. sampleRate = sr;
  235740. UInt32 framesPerBuf;
  235741. size = sizeof (framesPerBuf);
  235742. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235743. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235744. {
  235745. bufferSize = framesPerBuf;
  235746. allocateTempBuffers();
  235747. }
  235748. bufferSizes.clear();
  235749. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235750. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235751. {
  235752. HeapBlock <AudioValueRange> ranges;
  235753. ranges.calloc (size, 1);
  235754. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235755. {
  235756. bufferSizes.add ((int) ranges[0].mMinimum);
  235757. for (int i = 32; i < 2048; i += 32)
  235758. {
  235759. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235760. {
  235761. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235762. {
  235763. bufferSizes.addIfNotAlreadyThere (i);
  235764. break;
  235765. }
  235766. }
  235767. }
  235768. if (bufferSize > 0)
  235769. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235770. }
  235771. }
  235772. if (bufferSizes.size() == 0 && bufferSize > 0)
  235773. bufferSizes.add (bufferSize);
  235774. sampleRates.clear();
  235775. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235776. String rates;
  235777. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235778. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235779. {
  235780. HeapBlock <AudioValueRange> ranges;
  235781. ranges.calloc (size, 1);
  235782. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235783. {
  235784. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235785. {
  235786. bool ok = false;
  235787. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235788. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235789. ok = true;
  235790. if (ok)
  235791. {
  235792. sampleRates.add (possibleRates[i]);
  235793. rates << possibleRates[i] << ' ';
  235794. }
  235795. }
  235796. }
  235797. }
  235798. if (sampleRates.size() == 0 && sampleRate > 0)
  235799. {
  235800. sampleRates.add (sampleRate);
  235801. rates << sampleRate;
  235802. }
  235803. log ("sr: " + rates);
  235804. inputLatency = 0;
  235805. outputLatency = 0;
  235806. UInt32 lat;
  235807. size = sizeof (lat);
  235808. pa.mSelector = kAudioDevicePropertyLatency;
  235809. pa.mScope = kAudioDevicePropertyScopeInput;
  235810. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235811. inputLatency = (int) lat;
  235812. pa.mScope = kAudioDevicePropertyScopeOutput;
  235813. size = sizeof (lat);
  235814. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235815. outputLatency = (int) lat;
  235816. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235817. inChanNames.clear();
  235818. outChanNames.clear();
  235819. inputChannelInfo.calloc (numInputChans + 2);
  235820. numInputChannelInfos = 0;
  235821. outputChannelInfo.calloc (numOutputChans + 2);
  235822. numOutputChannelInfos = 0;
  235823. fillInChannelInfo (true);
  235824. fillInChannelInfo (false);
  235825. }
  235826. const StringArray getSources (bool input)
  235827. {
  235828. StringArray s;
  235829. HeapBlock <OSType> types;
  235830. const int num = getAllDataSourcesForDevice (deviceID, types);
  235831. for (int i = 0; i < num; ++i)
  235832. {
  235833. AudioValueTranslation avt;
  235834. char buffer[256];
  235835. avt.mInputData = &(types[i]);
  235836. avt.mInputDataSize = sizeof (UInt32);
  235837. avt.mOutputData = buffer;
  235838. avt.mOutputDataSize = 256;
  235839. UInt32 transSize = sizeof (avt);
  235840. AudioObjectPropertyAddress pa;
  235841. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235842. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235843. pa.mElement = kAudioObjectPropertyElementMaster;
  235844. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235845. {
  235846. DBG (buffer);
  235847. s.add (buffer);
  235848. }
  235849. }
  235850. return s;
  235851. }
  235852. int getCurrentSourceIndex (bool input) const
  235853. {
  235854. OSType currentSourceID = 0;
  235855. UInt32 size = sizeof (currentSourceID);
  235856. int result = -1;
  235857. AudioObjectPropertyAddress pa;
  235858. pa.mSelector = kAudioDevicePropertyDataSource;
  235859. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235860. pa.mElement = kAudioObjectPropertyElementMaster;
  235861. if (deviceID != 0)
  235862. {
  235863. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235864. {
  235865. HeapBlock <OSType> types;
  235866. const int num = getAllDataSourcesForDevice (deviceID, types);
  235867. for (int i = 0; i < num; ++i)
  235868. {
  235869. if (types[num] == currentSourceID)
  235870. {
  235871. result = i;
  235872. break;
  235873. }
  235874. }
  235875. }
  235876. }
  235877. return result;
  235878. }
  235879. void setCurrentSourceIndex (int index, bool input)
  235880. {
  235881. if (deviceID != 0)
  235882. {
  235883. HeapBlock <OSType> types;
  235884. const int num = getAllDataSourcesForDevice (deviceID, types);
  235885. if (((unsigned int) index) < (unsigned int) num)
  235886. {
  235887. AudioObjectPropertyAddress pa;
  235888. pa.mSelector = kAudioDevicePropertyDataSource;
  235889. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235890. pa.mElement = kAudioObjectPropertyElementMaster;
  235891. OSType typeId = types[index];
  235892. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235893. }
  235894. }
  235895. }
  235896. const String reopen (const BigInteger& inputChannels,
  235897. const BigInteger& outputChannels,
  235898. double newSampleRate,
  235899. int bufferSizeSamples)
  235900. {
  235901. String error;
  235902. log ("CoreAudio reopen");
  235903. callbacksAllowed = false;
  235904. stopTimer();
  235905. stop (false);
  235906. activeInputChans = inputChannels;
  235907. activeInputChans.setRange (inChanNames.size(),
  235908. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235909. false);
  235910. activeOutputChans = outputChannels;
  235911. activeOutputChans.setRange (outChanNames.size(),
  235912. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235913. false);
  235914. numInputChans = activeInputChans.countNumberOfSetBits();
  235915. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235916. // set sample rate
  235917. AudioObjectPropertyAddress pa;
  235918. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235919. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235920. pa.mElement = kAudioObjectPropertyElementMaster;
  235921. Float64 sr = newSampleRate;
  235922. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235923. {
  235924. error = "Couldn't change sample rate";
  235925. }
  235926. else
  235927. {
  235928. // change buffer size
  235929. UInt32 framesPerBuf = bufferSizeSamples;
  235930. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235931. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235932. {
  235933. error = "Couldn't change buffer size";
  235934. }
  235935. else
  235936. {
  235937. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235938. // correctly report their new settings until some random time in the future, so
  235939. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235940. // to make sure we're using the correct numbers..
  235941. updateDetailsFromDevice();
  235942. sampleRate = newSampleRate;
  235943. bufferSize = bufferSizeSamples;
  235944. if (sampleRates.size() == 0)
  235945. error = "Device has no available sample-rates";
  235946. else if (bufferSizes.size() == 0)
  235947. error = "Device has no available buffer-sizes";
  235948. else if (inputDevice != 0)
  235949. error = inputDevice->reopen (inputChannels,
  235950. outputChannels,
  235951. newSampleRate,
  235952. bufferSizeSamples);
  235953. }
  235954. }
  235955. callbacksAllowed = true;
  235956. return error;
  235957. }
  235958. bool start (AudioIODeviceCallback* cb)
  235959. {
  235960. if (! started)
  235961. {
  235962. callback = 0;
  235963. if (deviceID != 0)
  235964. {
  235965. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235966. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235967. #else
  235968. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235969. #endif
  235970. {
  235971. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235972. {
  235973. started = true;
  235974. }
  235975. else
  235976. {
  235977. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235978. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235979. #else
  235980. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235981. audioProcID = 0;
  235982. #endif
  235983. }
  235984. }
  235985. }
  235986. }
  235987. if (started)
  235988. {
  235989. const ScopedLock sl (callbackLock);
  235990. callback = cb;
  235991. }
  235992. if (inputDevice != 0)
  235993. return started && inputDevice->start (cb);
  235994. else
  235995. return started;
  235996. }
  235997. void stop (bool leaveInterruptRunning)
  235998. {
  235999. {
  236000. const ScopedLock sl (callbackLock);
  236001. callback = 0;
  236002. }
  236003. if (started
  236004. && (deviceID != 0)
  236005. && ! leaveInterruptRunning)
  236006. {
  236007. OK (AudioDeviceStop (deviceID, audioIOProc));
  236008. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  236009. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  236010. #else
  236011. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  236012. audioProcID = 0;
  236013. #endif
  236014. started = false;
  236015. { const ScopedLock sl (callbackLock); }
  236016. // wait until it's definately stopped calling back..
  236017. for (int i = 40; --i >= 0;)
  236018. {
  236019. Thread::sleep (50);
  236020. UInt32 running = 0;
  236021. UInt32 size = sizeof (running);
  236022. AudioObjectPropertyAddress pa;
  236023. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  236024. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236025. pa.mElement = kAudioObjectPropertyElementMaster;
  236026. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  236027. if (running == 0)
  236028. break;
  236029. }
  236030. const ScopedLock sl (callbackLock);
  236031. }
  236032. if (inputDevice != 0)
  236033. inputDevice->stop (leaveInterruptRunning);
  236034. }
  236035. double getSampleRate() const
  236036. {
  236037. return sampleRate;
  236038. }
  236039. int getBufferSize() const
  236040. {
  236041. return bufferSize;
  236042. }
  236043. void audioCallback (const AudioBufferList* inInputData,
  236044. AudioBufferList* outOutputData)
  236045. {
  236046. int i;
  236047. const ScopedLock sl (callbackLock);
  236048. if (callback != 0)
  236049. {
  236050. if (inputDevice == 0)
  236051. {
  236052. for (i = numInputChans; --i >= 0;)
  236053. {
  236054. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  236055. float* dest = tempInputBuffers [i];
  236056. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  236057. + info.dataOffsetSamples;
  236058. const int stride = info.dataStrideSamples;
  236059. if (stride != 0) // if this is zero, info is invalid
  236060. {
  236061. for (int j = bufferSize; --j >= 0;)
  236062. {
  236063. *dest++ = *src;
  236064. src += stride;
  236065. }
  236066. }
  236067. }
  236068. }
  236069. if (! isSlaveDevice)
  236070. {
  236071. if (inputDevice == 0)
  236072. {
  236073. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  236074. numInputChans,
  236075. tempOutputBuffers,
  236076. numOutputChans,
  236077. bufferSize);
  236078. }
  236079. else
  236080. {
  236081. jassert (inputDevice->bufferSize == bufferSize);
  236082. // Sometimes the two linked devices seem to get their callbacks in
  236083. // parallel, so we need to lock both devices to stop the input data being
  236084. // changed while inside our callback..
  236085. const ScopedLock sl2 (inputDevice->callbackLock);
  236086. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  236087. inputDevice->numInputChans,
  236088. tempOutputBuffers,
  236089. numOutputChans,
  236090. bufferSize);
  236091. }
  236092. for (i = numOutputChans; --i >= 0;)
  236093. {
  236094. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236095. const float* src = tempOutputBuffers [i];
  236096. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236097. + info.dataOffsetSamples;
  236098. const int stride = info.dataStrideSamples;
  236099. if (stride != 0) // if this is zero, info is invalid
  236100. {
  236101. for (int j = bufferSize; --j >= 0;)
  236102. {
  236103. *dest = *src++;
  236104. dest += stride;
  236105. }
  236106. }
  236107. }
  236108. }
  236109. }
  236110. else
  236111. {
  236112. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  236113. {
  236114. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236115. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236116. + info.dataOffsetSamples;
  236117. const int stride = info.dataStrideSamples;
  236118. if (stride != 0) // if this is zero, info is invalid
  236119. {
  236120. for (int j = bufferSize; --j >= 0;)
  236121. {
  236122. *dest = 0.0f;
  236123. dest += stride;
  236124. }
  236125. }
  236126. }
  236127. }
  236128. }
  236129. // called by callbacks
  236130. void deviceDetailsChanged()
  236131. {
  236132. if (callbacksAllowed)
  236133. startTimer (100);
  236134. }
  236135. void timerCallback()
  236136. {
  236137. stopTimer();
  236138. log ("CoreAudio device changed callback");
  236139. const double oldSampleRate = sampleRate;
  236140. const int oldBufferSize = bufferSize;
  236141. updateDetailsFromDevice();
  236142. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  236143. {
  236144. callbacksAllowed = false;
  236145. stop (false);
  236146. updateDetailsFromDevice();
  236147. callbacksAllowed = true;
  236148. }
  236149. }
  236150. CoreAudioInternal* getRelatedDevice() const
  236151. {
  236152. UInt32 size = 0;
  236153. ScopedPointer <CoreAudioInternal> result;
  236154. AudioObjectPropertyAddress pa;
  236155. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  236156. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236157. pa.mElement = kAudioObjectPropertyElementMaster;
  236158. if (deviceID != 0
  236159. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  236160. && size > 0)
  236161. {
  236162. HeapBlock <AudioDeviceID> devs;
  236163. devs.calloc (size, 1);
  236164. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  236165. {
  236166. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  236167. {
  236168. if (devs[i] != deviceID && devs[i] != 0)
  236169. {
  236170. result = new CoreAudioInternal (devs[i]);
  236171. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  236172. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  236173. if (thisIsInput != otherIsInput
  236174. || (inChanNames.size() + outChanNames.size() == 0)
  236175. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  236176. break;
  236177. result = 0;
  236178. }
  236179. }
  236180. }
  236181. }
  236182. return result.release();
  236183. }
  236184. juce_UseDebuggingNewOperator
  236185. int inputLatency, outputLatency;
  236186. BigInteger activeInputChans, activeOutputChans;
  236187. StringArray inChanNames, outChanNames;
  236188. Array <double> sampleRates;
  236189. Array <int> bufferSizes;
  236190. AudioIODeviceCallback* callback;
  236191. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  236192. AudioDeviceIOProcID audioProcID;
  236193. #endif
  236194. ScopedPointer<CoreAudioInternal> inputDevice;
  236195. bool isSlaveDevice;
  236196. private:
  236197. CriticalSection callbackLock;
  236198. AudioDeviceID deviceID;
  236199. bool started;
  236200. double sampleRate;
  236201. int bufferSize;
  236202. HeapBlock <float> audioBuffer;
  236203. int numInputChans, numOutputChans;
  236204. bool callbacksAllowed;
  236205. struct CallbackDetailsForChannel
  236206. {
  236207. int streamNum;
  236208. int dataOffsetSamples;
  236209. int dataStrideSamples;
  236210. };
  236211. int numInputChannelInfos, numOutputChannelInfos;
  236212. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  236213. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  236214. CoreAudioInternal (const CoreAudioInternal&);
  236215. CoreAudioInternal& operator= (const CoreAudioInternal&);
  236216. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  236217. const AudioTimeStamp* /*inNow*/,
  236218. const AudioBufferList* inInputData,
  236219. const AudioTimeStamp* /*inInputTime*/,
  236220. AudioBufferList* outOutputData,
  236221. const AudioTimeStamp* /*inOutputTime*/,
  236222. void* device)
  236223. {
  236224. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  236225. return noErr;
  236226. }
  236227. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236228. {
  236229. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236230. switch (pa->mSelector)
  236231. {
  236232. case kAudioDevicePropertyBufferSize:
  236233. case kAudioDevicePropertyBufferFrameSize:
  236234. case kAudioDevicePropertyNominalSampleRate:
  236235. case kAudioDevicePropertyStreamFormat:
  236236. case kAudioDevicePropertyDeviceIsAlive:
  236237. intern->deviceDetailsChanged();
  236238. break;
  236239. case kAudioDevicePropertyBufferSizeRange:
  236240. case kAudioDevicePropertyVolumeScalar:
  236241. case kAudioDevicePropertyMute:
  236242. case kAudioDevicePropertyPlayThru:
  236243. case kAudioDevicePropertyDataSource:
  236244. case kAudioDevicePropertyDeviceIsRunning:
  236245. break;
  236246. }
  236247. return noErr;
  236248. }
  236249. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236250. {
  236251. AudioObjectPropertyAddress pa;
  236252. pa.mSelector = kAudioDevicePropertyDataSources;
  236253. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236254. pa.mElement = kAudioObjectPropertyElementMaster;
  236255. UInt32 size = 0;
  236256. if (deviceID != 0
  236257. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236258. {
  236259. types.calloc (size, 1);
  236260. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236261. return size / (int) sizeof (OSType);
  236262. }
  236263. return 0;
  236264. }
  236265. };
  236266. class CoreAudioIODevice : public AudioIODevice
  236267. {
  236268. public:
  236269. CoreAudioIODevice (const String& deviceName,
  236270. AudioDeviceID inputDeviceId,
  236271. const int inputIndex_,
  236272. AudioDeviceID outputDeviceId,
  236273. const int outputIndex_)
  236274. : AudioIODevice (deviceName, "CoreAudio"),
  236275. inputIndex (inputIndex_),
  236276. outputIndex (outputIndex_),
  236277. isOpen_ (false),
  236278. isStarted (false)
  236279. {
  236280. CoreAudioInternal* device = 0;
  236281. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236282. {
  236283. jassert (inputDeviceId != 0);
  236284. device = new CoreAudioInternal (inputDeviceId);
  236285. }
  236286. else
  236287. {
  236288. device = new CoreAudioInternal (outputDeviceId);
  236289. if (inputDeviceId != 0)
  236290. {
  236291. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236292. device->inputDevice = secondDevice;
  236293. secondDevice->isSlaveDevice = true;
  236294. }
  236295. }
  236296. internal = device;
  236297. AudioObjectPropertyAddress pa;
  236298. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236299. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236300. pa.mElement = kAudioObjectPropertyElementWildcard;
  236301. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236302. }
  236303. ~CoreAudioIODevice()
  236304. {
  236305. AudioObjectPropertyAddress pa;
  236306. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236307. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236308. pa.mElement = kAudioObjectPropertyElementWildcard;
  236309. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236310. }
  236311. const StringArray getOutputChannelNames()
  236312. {
  236313. return internal->outChanNames;
  236314. }
  236315. const StringArray getInputChannelNames()
  236316. {
  236317. if (internal->inputDevice != 0)
  236318. return internal->inputDevice->inChanNames;
  236319. else
  236320. return internal->inChanNames;
  236321. }
  236322. int getNumSampleRates()
  236323. {
  236324. return internal->sampleRates.size();
  236325. }
  236326. double getSampleRate (int index)
  236327. {
  236328. return internal->sampleRates [index];
  236329. }
  236330. int getNumBufferSizesAvailable()
  236331. {
  236332. return internal->bufferSizes.size();
  236333. }
  236334. int getBufferSizeSamples (int index)
  236335. {
  236336. return internal->bufferSizes [index];
  236337. }
  236338. int getDefaultBufferSize()
  236339. {
  236340. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236341. if (getBufferSizeSamples(i) >= 512)
  236342. return getBufferSizeSamples(i);
  236343. return 512;
  236344. }
  236345. const String open (const BigInteger& inputChannels,
  236346. const BigInteger& outputChannels,
  236347. double sampleRate,
  236348. int bufferSizeSamples)
  236349. {
  236350. isOpen_ = true;
  236351. if (bufferSizeSamples <= 0)
  236352. bufferSizeSamples = getDefaultBufferSize();
  236353. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236354. isOpen_ = lastError.isEmpty();
  236355. return lastError;
  236356. }
  236357. void close()
  236358. {
  236359. isOpen_ = false;
  236360. internal->stop (false);
  236361. }
  236362. bool isOpen()
  236363. {
  236364. return isOpen_;
  236365. }
  236366. int getCurrentBufferSizeSamples()
  236367. {
  236368. return internal != 0 ? internal->getBufferSize() : 512;
  236369. }
  236370. double getCurrentSampleRate()
  236371. {
  236372. return internal != 0 ? internal->getSampleRate() : 0;
  236373. }
  236374. int getCurrentBitDepth()
  236375. {
  236376. return 32; // no way to find out, so just assume it's high..
  236377. }
  236378. const BigInteger getActiveOutputChannels() const
  236379. {
  236380. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236381. }
  236382. const BigInteger getActiveInputChannels() const
  236383. {
  236384. BigInteger chans;
  236385. if (internal != 0)
  236386. {
  236387. chans = internal->activeInputChans;
  236388. if (internal->inputDevice != 0)
  236389. chans |= internal->inputDevice->activeInputChans;
  236390. }
  236391. return chans;
  236392. }
  236393. int getOutputLatencyInSamples()
  236394. {
  236395. if (internal == 0)
  236396. return 0;
  236397. // this seems like a good guess at getting the latency right - comparing
  236398. // this with a round-trip measurement, it gets it to within a few millisecs
  236399. // for the built-in mac soundcard
  236400. return internal->outputLatency + internal->getBufferSize() * 2;
  236401. }
  236402. int getInputLatencyInSamples()
  236403. {
  236404. if (internal == 0)
  236405. return 0;
  236406. return internal->inputLatency + internal->getBufferSize() * 2;
  236407. }
  236408. void start (AudioIODeviceCallback* callback)
  236409. {
  236410. if (internal != 0 && ! isStarted)
  236411. {
  236412. if (callback != 0)
  236413. callback->audioDeviceAboutToStart (this);
  236414. isStarted = true;
  236415. internal->start (callback);
  236416. }
  236417. }
  236418. void stop()
  236419. {
  236420. if (isStarted && internal != 0)
  236421. {
  236422. AudioIODeviceCallback* const lastCallback = internal->callback;
  236423. isStarted = false;
  236424. internal->stop (true);
  236425. if (lastCallback != 0)
  236426. lastCallback->audioDeviceStopped();
  236427. }
  236428. }
  236429. bool isPlaying()
  236430. {
  236431. if (internal->callback == 0)
  236432. isStarted = false;
  236433. return isStarted;
  236434. }
  236435. const String getLastError()
  236436. {
  236437. return lastError;
  236438. }
  236439. int inputIndex, outputIndex;
  236440. juce_UseDebuggingNewOperator
  236441. private:
  236442. ScopedPointer<CoreAudioInternal> internal;
  236443. bool isOpen_, isStarted;
  236444. String lastError;
  236445. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236446. {
  236447. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236448. switch (pa->mSelector)
  236449. {
  236450. case kAudioHardwarePropertyDevices:
  236451. intern->deviceDetailsChanged();
  236452. break;
  236453. case kAudioHardwarePropertyDefaultOutputDevice:
  236454. case kAudioHardwarePropertyDefaultInputDevice:
  236455. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236456. break;
  236457. }
  236458. return noErr;
  236459. }
  236460. CoreAudioIODevice (const CoreAudioIODevice&);
  236461. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236462. };
  236463. class CoreAudioIODeviceType : public AudioIODeviceType
  236464. {
  236465. public:
  236466. CoreAudioIODeviceType()
  236467. : AudioIODeviceType ("CoreAudio"),
  236468. hasScanned (false)
  236469. {
  236470. }
  236471. ~CoreAudioIODeviceType()
  236472. {
  236473. }
  236474. void scanForDevices()
  236475. {
  236476. hasScanned = true;
  236477. inputDeviceNames.clear();
  236478. outputDeviceNames.clear();
  236479. inputIds.clear();
  236480. outputIds.clear();
  236481. UInt32 size;
  236482. AudioObjectPropertyAddress pa;
  236483. pa.mSelector = kAudioHardwarePropertyDevices;
  236484. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236485. pa.mElement = kAudioObjectPropertyElementMaster;
  236486. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236487. {
  236488. HeapBlock <AudioDeviceID> devs;
  236489. devs.calloc (size, 1);
  236490. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236491. {
  236492. const int num = size / (int) sizeof (AudioDeviceID);
  236493. for (int i = 0; i < num; ++i)
  236494. {
  236495. char name [1024];
  236496. size = sizeof (name);
  236497. pa.mSelector = kAudioDevicePropertyDeviceName;
  236498. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236499. {
  236500. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236501. const int numIns = getNumChannels (devs[i], true);
  236502. const int numOuts = getNumChannels (devs[i], false);
  236503. if (numIns > 0)
  236504. {
  236505. inputDeviceNames.add (nameString);
  236506. inputIds.add (devs[i]);
  236507. }
  236508. if (numOuts > 0)
  236509. {
  236510. outputDeviceNames.add (nameString);
  236511. outputIds.add (devs[i]);
  236512. }
  236513. }
  236514. }
  236515. }
  236516. }
  236517. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236518. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236519. }
  236520. const StringArray getDeviceNames (bool wantInputNames) const
  236521. {
  236522. jassert (hasScanned); // need to call scanForDevices() before doing this
  236523. if (wantInputNames)
  236524. return inputDeviceNames;
  236525. else
  236526. return outputDeviceNames;
  236527. }
  236528. int getDefaultDeviceIndex (bool forInput) const
  236529. {
  236530. jassert (hasScanned); // need to call scanForDevices() before doing this
  236531. AudioDeviceID deviceID;
  236532. UInt32 size = sizeof (deviceID);
  236533. // if they're asking for any input channels at all, use the default input, so we
  236534. // get the built-in mic rather than the built-in output with no inputs..
  236535. AudioObjectPropertyAddress pa;
  236536. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236537. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236538. pa.mElement = kAudioObjectPropertyElementMaster;
  236539. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236540. {
  236541. if (forInput)
  236542. {
  236543. for (int i = inputIds.size(); --i >= 0;)
  236544. if (inputIds[i] == deviceID)
  236545. return i;
  236546. }
  236547. else
  236548. {
  236549. for (int i = outputIds.size(); --i >= 0;)
  236550. if (outputIds[i] == deviceID)
  236551. return i;
  236552. }
  236553. }
  236554. return 0;
  236555. }
  236556. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236557. {
  236558. jassert (hasScanned); // need to call scanForDevices() before doing this
  236559. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236560. if (d == 0)
  236561. return -1;
  236562. return asInput ? d->inputIndex
  236563. : d->outputIndex;
  236564. }
  236565. bool hasSeparateInputsAndOutputs() const { return true; }
  236566. AudioIODevice* createDevice (const String& outputDeviceName,
  236567. const String& inputDeviceName)
  236568. {
  236569. jassert (hasScanned); // need to call scanForDevices() before doing this
  236570. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236571. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236572. String deviceName (outputDeviceName);
  236573. if (deviceName.isEmpty())
  236574. deviceName = inputDeviceName;
  236575. if (index >= 0)
  236576. return new CoreAudioIODevice (deviceName,
  236577. inputIds [inputIndex],
  236578. inputIndex,
  236579. outputIds [outputIndex],
  236580. outputIndex);
  236581. return 0;
  236582. }
  236583. juce_UseDebuggingNewOperator
  236584. private:
  236585. StringArray inputDeviceNames, outputDeviceNames;
  236586. Array <AudioDeviceID> inputIds, outputIds;
  236587. bool hasScanned;
  236588. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236589. {
  236590. int total = 0;
  236591. UInt32 size;
  236592. AudioObjectPropertyAddress pa;
  236593. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236594. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236595. pa.mElement = kAudioObjectPropertyElementMaster;
  236596. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236597. {
  236598. HeapBlock <AudioBufferList> bufList;
  236599. bufList.calloc (size, 1);
  236600. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236601. {
  236602. const int numStreams = bufList->mNumberBuffers;
  236603. for (int i = 0; i < numStreams; ++i)
  236604. {
  236605. const AudioBuffer& b = bufList->mBuffers[i];
  236606. total += b.mNumberChannels;
  236607. }
  236608. }
  236609. }
  236610. return total;
  236611. }
  236612. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236613. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236614. };
  236615. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236616. {
  236617. return new CoreAudioIODeviceType();
  236618. }
  236619. #undef log
  236620. #endif
  236621. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236622. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236623. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236624. // compiled on its own).
  236625. #if JUCE_INCLUDED_FILE
  236626. #if JUCE_MAC
  236627. namespace CoreMidiHelpers
  236628. {
  236629. static bool logError (const OSStatus err, const int lineNum)
  236630. {
  236631. if (err == noErr)
  236632. return true;
  236633. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236634. jassertfalse;
  236635. return false;
  236636. }
  236637. #undef CHECK_ERROR
  236638. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236639. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236640. {
  236641. String result;
  236642. CFStringRef str = 0;
  236643. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236644. if (str != 0)
  236645. {
  236646. result = PlatformUtilities::cfStringToJuceString (str);
  236647. CFRelease (str);
  236648. str = 0;
  236649. }
  236650. MIDIEntityRef entity = 0;
  236651. MIDIEndpointGetEntity (endpoint, &entity);
  236652. if (entity == 0)
  236653. return result; // probably virtual
  236654. if (result.isEmpty())
  236655. {
  236656. // endpoint name has zero length - try the entity
  236657. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236658. if (str != 0)
  236659. {
  236660. result += PlatformUtilities::cfStringToJuceString (str);
  236661. CFRelease (str);
  236662. str = 0;
  236663. }
  236664. }
  236665. // now consider the device's name
  236666. MIDIDeviceRef device = 0;
  236667. MIDIEntityGetDevice (entity, &device);
  236668. if (device == 0)
  236669. return result;
  236670. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236671. if (str != 0)
  236672. {
  236673. const String s (PlatformUtilities::cfStringToJuceString (str));
  236674. CFRelease (str);
  236675. // if an external device has only one entity, throw away
  236676. // the endpoint name and just use the device name
  236677. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236678. {
  236679. result = s;
  236680. }
  236681. else if (! result.startsWithIgnoreCase (s))
  236682. {
  236683. // prepend the device name to the entity name
  236684. result = (s + " " + result).trimEnd();
  236685. }
  236686. }
  236687. return result;
  236688. }
  236689. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236690. {
  236691. String result;
  236692. // Does the endpoint have connections?
  236693. CFDataRef connections = 0;
  236694. int numConnections = 0;
  236695. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236696. if (connections != 0)
  236697. {
  236698. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236699. if (numConnections > 0)
  236700. {
  236701. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236702. for (int i = 0; i < numConnections; ++i, ++pid)
  236703. {
  236704. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236705. MIDIObjectRef connObject;
  236706. MIDIObjectType connObjectType;
  236707. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236708. if (err == noErr)
  236709. {
  236710. String s;
  236711. if (connObjectType == kMIDIObjectType_ExternalSource
  236712. || connObjectType == kMIDIObjectType_ExternalDestination)
  236713. {
  236714. // Connected to an external device's endpoint (10.3 and later).
  236715. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236716. }
  236717. else
  236718. {
  236719. // Connected to an external device (10.2) (or something else, catch-all)
  236720. CFStringRef str = 0;
  236721. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236722. if (str != 0)
  236723. {
  236724. s = PlatformUtilities::cfStringToJuceString (str);
  236725. CFRelease (str);
  236726. }
  236727. }
  236728. if (s.isNotEmpty())
  236729. {
  236730. if (result.isNotEmpty())
  236731. result += ", ";
  236732. result += s;
  236733. }
  236734. }
  236735. }
  236736. }
  236737. CFRelease (connections);
  236738. }
  236739. if (result.isNotEmpty())
  236740. return result;
  236741. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236742. return getEndpointName (endpoint, false);
  236743. }
  236744. static MIDIClientRef getGlobalMidiClient()
  236745. {
  236746. static MIDIClientRef globalMidiClient = 0;
  236747. if (globalMidiClient == 0)
  236748. {
  236749. String name ("JUCE");
  236750. if (JUCEApplication::getInstance() != 0)
  236751. name = JUCEApplication::getInstance()->getApplicationName();
  236752. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236753. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236754. CFRelease (appName);
  236755. }
  236756. return globalMidiClient;
  236757. }
  236758. class MidiPortAndEndpoint
  236759. {
  236760. public:
  236761. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236762. : port (port_), endPoint (endPoint_)
  236763. {
  236764. }
  236765. ~MidiPortAndEndpoint()
  236766. {
  236767. if (port != 0)
  236768. MIDIPortDispose (port);
  236769. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236770. MIDIEndpointDispose (endPoint);
  236771. }
  236772. void send (const MIDIPacketList* const packets)
  236773. {
  236774. if (port != 0)
  236775. MIDISend (port, endPoint, packets);
  236776. else
  236777. MIDIReceived (endPoint, packets);
  236778. }
  236779. MIDIPortRef port;
  236780. MIDIEndpointRef endPoint;
  236781. };
  236782. class MidiPortAndCallback;
  236783. static CriticalSection callbackLock;
  236784. static Array<MidiPortAndCallback*> activeCallbacks;
  236785. class MidiPortAndCallback
  236786. {
  236787. public:
  236788. MidiPortAndCallback (MidiInputCallback& callback_)
  236789. : input (0), active (false), callback (callback_), concatenator (2048)
  236790. {
  236791. }
  236792. ~MidiPortAndCallback()
  236793. {
  236794. active = false;
  236795. {
  236796. const ScopedLock sl (callbackLock);
  236797. activeCallbacks.removeValue (this);
  236798. }
  236799. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236800. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236801. }
  236802. void handlePackets (const MIDIPacketList* const pktlist)
  236803. {
  236804. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236805. const ScopedLock sl (callbackLock);
  236806. if (activeCallbacks.contains (this) && active)
  236807. {
  236808. const MIDIPacket* packet = &pktlist->packet[0];
  236809. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236810. {
  236811. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236812. input, callback);
  236813. packet = MIDIPacketNext (packet);
  236814. }
  236815. }
  236816. }
  236817. MidiInput* input;
  236818. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236819. volatile bool active;
  236820. private:
  236821. MidiInputCallback& callback;
  236822. MidiDataConcatenator concatenator;
  236823. };
  236824. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236825. {
  236826. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236827. }
  236828. }
  236829. const StringArray MidiOutput::getDevices()
  236830. {
  236831. StringArray s;
  236832. const ItemCount num = MIDIGetNumberOfDestinations();
  236833. for (ItemCount i = 0; i < num; ++i)
  236834. {
  236835. MIDIEndpointRef dest = MIDIGetDestination (i);
  236836. if (dest != 0)
  236837. {
  236838. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236839. if (name.isEmpty())
  236840. name = "<error>";
  236841. s.add (name);
  236842. }
  236843. else
  236844. {
  236845. s.add ("<error>");
  236846. }
  236847. }
  236848. return s;
  236849. }
  236850. int MidiOutput::getDefaultDeviceIndex()
  236851. {
  236852. return 0;
  236853. }
  236854. MidiOutput* MidiOutput::openDevice (int index)
  236855. {
  236856. MidiOutput* mo = 0;
  236857. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236858. {
  236859. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236860. CFStringRef pname;
  236861. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236862. {
  236863. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236864. MIDIPortRef port;
  236865. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236866. {
  236867. mo = new MidiOutput();
  236868. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236869. }
  236870. CFRelease (pname);
  236871. }
  236872. }
  236873. return mo;
  236874. }
  236875. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236876. {
  236877. MidiOutput* mo = 0;
  236878. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236879. MIDIEndpointRef endPoint;
  236880. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236881. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236882. {
  236883. mo = new MidiOutput();
  236884. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236885. }
  236886. CFRelease (name);
  236887. return mo;
  236888. }
  236889. MidiOutput::~MidiOutput()
  236890. {
  236891. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236892. }
  236893. void MidiOutput::reset()
  236894. {
  236895. }
  236896. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236897. {
  236898. return false;
  236899. }
  236900. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236901. {
  236902. }
  236903. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236904. {
  236905. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236906. if (message.isSysEx())
  236907. {
  236908. const int maxPacketSize = 256;
  236909. int pos = 0, bytesLeft = message.getRawDataSize();
  236910. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236911. HeapBlock <MIDIPacketList> packets;
  236912. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236913. packets->numPackets = numPackets;
  236914. MIDIPacket* p = packets->packet;
  236915. for (int i = 0; i < numPackets; ++i)
  236916. {
  236917. p->timeStamp = 0;
  236918. p->length = jmin (maxPacketSize, bytesLeft);
  236919. memcpy (p->data, message.getRawData() + pos, p->length);
  236920. pos += p->length;
  236921. bytesLeft -= p->length;
  236922. p = MIDIPacketNext (p);
  236923. }
  236924. mpe->send (packets);
  236925. }
  236926. else
  236927. {
  236928. MIDIPacketList packets;
  236929. packets.numPackets = 1;
  236930. packets.packet[0].timeStamp = 0;
  236931. packets.packet[0].length = message.getRawDataSize();
  236932. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236933. mpe->send (&packets);
  236934. }
  236935. }
  236936. const StringArray MidiInput::getDevices()
  236937. {
  236938. StringArray s;
  236939. const ItemCount num = MIDIGetNumberOfSources();
  236940. for (ItemCount i = 0; i < num; ++i)
  236941. {
  236942. MIDIEndpointRef source = MIDIGetSource (i);
  236943. if (source != 0)
  236944. {
  236945. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236946. if (name.isEmpty())
  236947. name = "<error>";
  236948. s.add (name);
  236949. }
  236950. else
  236951. {
  236952. s.add ("<error>");
  236953. }
  236954. }
  236955. return s;
  236956. }
  236957. int MidiInput::getDefaultDeviceIndex()
  236958. {
  236959. return 0;
  236960. }
  236961. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236962. {
  236963. jassert (callback != 0);
  236964. using namespace CoreMidiHelpers;
  236965. MidiInput* newInput = 0;
  236966. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236967. {
  236968. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236969. if (endPoint != 0)
  236970. {
  236971. CFStringRef name;
  236972. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236973. {
  236974. MIDIClientRef client = getGlobalMidiClient();
  236975. if (client != 0)
  236976. {
  236977. MIDIPortRef port;
  236978. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236979. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236980. {
  236981. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236982. {
  236983. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236984. newInput = new MidiInput (getDevices() [index]);
  236985. mpc->input = newInput;
  236986. newInput->internal = mpc;
  236987. const ScopedLock sl (callbackLock);
  236988. activeCallbacks.add (mpc.release());
  236989. }
  236990. else
  236991. {
  236992. CHECK_ERROR (MIDIPortDispose (port));
  236993. }
  236994. }
  236995. }
  236996. }
  236997. CFRelease (name);
  236998. }
  236999. }
  237000. return newInput;
  237001. }
  237002. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  237003. {
  237004. jassert (callback != 0);
  237005. using namespace CoreMidiHelpers;
  237006. MidiInput* mi = 0;
  237007. MIDIClientRef client = getGlobalMidiClient();
  237008. if (client != 0)
  237009. {
  237010. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  237011. mpc->active = false;
  237012. MIDIEndpointRef endPoint;
  237013. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  237014. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  237015. {
  237016. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  237017. mi = new MidiInput (deviceName);
  237018. mpc->input = mi;
  237019. mi->internal = mpc;
  237020. const ScopedLock sl (callbackLock);
  237021. activeCallbacks.add (mpc.release());
  237022. }
  237023. CFRelease (name);
  237024. }
  237025. return mi;
  237026. }
  237027. MidiInput::MidiInput (const String& name_)
  237028. : name (name_)
  237029. {
  237030. }
  237031. MidiInput::~MidiInput()
  237032. {
  237033. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  237034. }
  237035. void MidiInput::start()
  237036. {
  237037. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237038. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  237039. }
  237040. void MidiInput::stop()
  237041. {
  237042. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237043. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  237044. }
  237045. #undef CHECK_ERROR
  237046. #else // Stubs for iOS...
  237047. MidiOutput::~MidiOutput() {}
  237048. void MidiOutput::reset() {}
  237049. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  237050. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  237051. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  237052. const StringArray MidiOutput::getDevices() { return StringArray(); }
  237053. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  237054. const StringArray MidiInput::getDevices() { return StringArray(); }
  237055. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  237056. #endif
  237057. #endif
  237058. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  237059. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  237060. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237061. // compiled on its own).
  237062. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  237063. #if ! JUCE_QUICKTIME
  237064. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  237065. #endif
  237066. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  237067. class QTCameraDeviceInteral;
  237068. END_JUCE_NAMESPACE
  237069. @interface QTCaptureCallbackDelegate : NSObject
  237070. {
  237071. @public
  237072. CameraDevice* owner;
  237073. QTCameraDeviceInteral* internal;
  237074. int64 firstPresentationTime;
  237075. int64 averageTimeOffset;
  237076. }
  237077. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  237078. - (void) dealloc;
  237079. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237080. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237081. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237082. fromConnection: (QTCaptureConnection*) connection;
  237083. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237084. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237085. fromConnection: (QTCaptureConnection*) connection;
  237086. @end
  237087. BEGIN_JUCE_NAMESPACE
  237088. class QTCameraDeviceInteral
  237089. {
  237090. public:
  237091. QTCameraDeviceInteral (CameraDevice* owner, int index)
  237092. {
  237093. const ScopedAutoReleasePool pool;
  237094. session = [[QTCaptureSession alloc] init];
  237095. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237096. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  237097. input = 0;
  237098. audioInput = 0;
  237099. audioDevice = 0;
  237100. fileOutput = 0;
  237101. imageOutput = 0;
  237102. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  237103. internalDev: this];
  237104. NSError* err = 0;
  237105. [device retain];
  237106. [device open: &err];
  237107. if (err == 0)
  237108. {
  237109. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237110. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237111. [session addInput: input error: &err];
  237112. if (err == 0)
  237113. {
  237114. resetFile();
  237115. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  237116. [imageOutput setDelegate: callbackDelegate];
  237117. if (err == 0)
  237118. {
  237119. [session startRunning];
  237120. return;
  237121. }
  237122. }
  237123. }
  237124. openingError = nsStringToJuce ([err description]);
  237125. DBG (openingError);
  237126. }
  237127. ~QTCameraDeviceInteral()
  237128. {
  237129. [session stopRunning];
  237130. [session removeOutput: imageOutput];
  237131. [session release];
  237132. [input release];
  237133. [device release];
  237134. [audioDevice release];
  237135. [audioInput release];
  237136. [fileOutput release];
  237137. [imageOutput release];
  237138. [callbackDelegate release];
  237139. }
  237140. void resetFile()
  237141. {
  237142. [fileOutput recordToOutputFileURL: nil];
  237143. [session removeOutput: fileOutput];
  237144. [fileOutput release];
  237145. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  237146. [session removeInput: audioInput];
  237147. [audioInput release];
  237148. audioInput = 0;
  237149. [audioDevice release];
  237150. audioDevice = 0;
  237151. [fileOutput setDelegate: callbackDelegate];
  237152. }
  237153. void addDefaultAudioInput()
  237154. {
  237155. NSError* err = nil;
  237156. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  237157. if ([audioDevice open: &err])
  237158. [audioDevice retain];
  237159. else
  237160. audioDevice = nil;
  237161. if (audioDevice != 0)
  237162. {
  237163. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  237164. [session addInput: audioInput error: &err];
  237165. }
  237166. }
  237167. void addListener (CameraDevice::Listener* listenerToAdd)
  237168. {
  237169. const ScopedLock sl (listenerLock);
  237170. if (listeners.size() == 0)
  237171. [session addOutput: imageOutput error: nil];
  237172. listeners.addIfNotAlreadyThere (listenerToAdd);
  237173. }
  237174. void removeListener (CameraDevice::Listener* listenerToRemove)
  237175. {
  237176. const ScopedLock sl (listenerLock);
  237177. listeners.removeValue (listenerToRemove);
  237178. if (listeners.size() == 0)
  237179. [session removeOutput: imageOutput];
  237180. }
  237181. void callListeners (CIImage* frame, int w, int h)
  237182. {
  237183. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  237184. Image image (cgImage);
  237185. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  237186. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  237187. CGContextFlush (cgImage->context);
  237188. const ScopedLock sl (listenerLock);
  237189. for (int i = listeners.size(); --i >= 0;)
  237190. {
  237191. CameraDevice::Listener* const l = listeners[i];
  237192. if (l != 0)
  237193. l->imageReceived (image);
  237194. }
  237195. }
  237196. QTCaptureDevice* device;
  237197. QTCaptureDeviceInput* input;
  237198. QTCaptureDevice* audioDevice;
  237199. QTCaptureDeviceInput* audioInput;
  237200. QTCaptureSession* session;
  237201. QTCaptureMovieFileOutput* fileOutput;
  237202. QTCaptureDecompressedVideoOutput* imageOutput;
  237203. QTCaptureCallbackDelegate* callbackDelegate;
  237204. String openingError;
  237205. Array<CameraDevice::Listener*> listeners;
  237206. CriticalSection listenerLock;
  237207. };
  237208. END_JUCE_NAMESPACE
  237209. @implementation QTCaptureCallbackDelegate
  237210. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  237211. internalDev: (QTCameraDeviceInteral*) d
  237212. {
  237213. [super init];
  237214. owner = owner_;
  237215. internal = d;
  237216. firstPresentationTime = 0;
  237217. averageTimeOffset = 0;
  237218. return self;
  237219. }
  237220. - (void) dealloc
  237221. {
  237222. [super dealloc];
  237223. }
  237224. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237225. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237226. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237227. fromConnection: (QTCaptureConnection*) connection
  237228. {
  237229. if (internal->listeners.size() > 0)
  237230. {
  237231. const ScopedAutoReleasePool pool;
  237232. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  237233. CVPixelBufferGetWidth (videoFrame),
  237234. CVPixelBufferGetHeight (videoFrame));
  237235. }
  237236. }
  237237. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237238. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237239. fromConnection: (QTCaptureConnection*) connection
  237240. {
  237241. const Time now (Time::getCurrentTime());
  237242. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  237243. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  237244. #else
  237245. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  237246. #endif
  237247. int64 presentationTime = (hosttime != nil)
  237248. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  237249. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  237250. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  237251. if (firstPresentationTime == 0)
  237252. {
  237253. firstPresentationTime = presentationTime;
  237254. averageTimeOffset = timeDiff;
  237255. }
  237256. else
  237257. {
  237258. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237259. }
  237260. }
  237261. @end
  237262. BEGIN_JUCE_NAMESPACE
  237263. class QTCaptureViewerComp : public NSViewComponent
  237264. {
  237265. public:
  237266. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237267. {
  237268. const ScopedAutoReleasePool pool;
  237269. captureView = [[QTCaptureView alloc] init];
  237270. [captureView setCaptureSession: internal->session];
  237271. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237272. setView (captureView);
  237273. }
  237274. ~QTCaptureViewerComp()
  237275. {
  237276. setView (0);
  237277. [captureView setCaptureSession: nil];
  237278. [captureView release];
  237279. }
  237280. QTCaptureView* captureView;
  237281. };
  237282. CameraDevice::CameraDevice (const String& name_, int index)
  237283. : name (name_)
  237284. {
  237285. isRecording = false;
  237286. internal = new QTCameraDeviceInteral (this, index);
  237287. }
  237288. CameraDevice::~CameraDevice()
  237289. {
  237290. stopRecording();
  237291. delete static_cast <QTCameraDeviceInteral*> (internal);
  237292. internal = 0;
  237293. }
  237294. Component* CameraDevice::createViewerComponent()
  237295. {
  237296. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237297. }
  237298. const String CameraDevice::getFileExtension()
  237299. {
  237300. return ".mov";
  237301. }
  237302. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237303. {
  237304. stopRecording();
  237305. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237306. d->callbackDelegate->firstPresentationTime = 0;
  237307. file.deleteFile();
  237308. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237309. // out wrong, so we'll put some audio in there too..,
  237310. d->addDefaultAudioInput();
  237311. [d->session addOutput: d->fileOutput error: nil];
  237312. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237313. for (;;)
  237314. {
  237315. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237316. if (connection == 0)
  237317. break;
  237318. QTCompressionOptions* options = 0;
  237319. NSString* mediaType = [connection mediaType];
  237320. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237321. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237322. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237323. : @"QTCompressionOptions240SizeH264Video"];
  237324. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237325. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237326. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237327. }
  237328. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237329. isRecording = true;
  237330. }
  237331. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237332. {
  237333. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237334. if (d->callbackDelegate->firstPresentationTime != 0)
  237335. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237336. return Time();
  237337. }
  237338. void CameraDevice::stopRecording()
  237339. {
  237340. if (isRecording)
  237341. {
  237342. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237343. isRecording = false;
  237344. }
  237345. }
  237346. void CameraDevice::addListener (Listener* listenerToAdd)
  237347. {
  237348. if (listenerToAdd != 0)
  237349. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237350. }
  237351. void CameraDevice::removeListener (Listener* listenerToRemove)
  237352. {
  237353. if (listenerToRemove != 0)
  237354. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237355. }
  237356. const StringArray CameraDevice::getAvailableDevices()
  237357. {
  237358. const ScopedAutoReleasePool pool;
  237359. StringArray results;
  237360. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237361. for (int i = 0; i < (int) [devs count]; ++i)
  237362. {
  237363. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237364. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237365. }
  237366. return results;
  237367. }
  237368. CameraDevice* CameraDevice::openDevice (int index,
  237369. int minWidth, int minHeight,
  237370. int maxWidth, int maxHeight)
  237371. {
  237372. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237373. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237374. return d.release();
  237375. return 0;
  237376. }
  237377. #endif
  237378. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237379. #endif
  237380. #endif
  237381. END_JUCE_NAMESPACE
  237382. #endif
  237383. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237384. #endif
  237385. #endif